提交 72ad6aef 编写于 作者: fxy060608's avatar fxy060608

wip(mp): css

上级 0eb7ff2b
......@@ -16,13 +16,13 @@ function hasCallback(args: unknown) {
}
export function handlePromise(promise: Promise<unknown>) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data]
})
.catch((err) => [err])
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise
}
......
......@@ -1064,6 +1064,13 @@ var serviceContext = (function (vue) {
return false;
}
function handlePromise(promise) {
// if (false) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
function promisify(name, fn) {
......
import fs from 'fs'
import path from 'path'
import { extend } from '@vue/shared'
import { once, defaultRpx2Unit } from '@dcloudio/uni-shared'
import {
once,
defaultRpx2Unit,
defaultMiniProgramRpx2Unit,
} from '@dcloudio/uni-shared'
import { parseJson } from './json'
......@@ -13,10 +17,19 @@ export const parseManifestJson = (inputDir: string) => {
export const parseManifestJsonOnce = once(parseManifestJson)
export const parseRpx2UnitOnce = once((inputDir: string) => {
const { h5 } = parseManifestJsonOnce(inputDir)
return extend({}, defaultRpx2Unit, (h5 && h5.rpx) || {})
})
export const parseRpx2UnitOnce = once(
(inputDir: string, platform: UniApp.PLATFORM) => {
const rpx2unit =
platform === 'h5' || platform === 'app'
? defaultRpx2Unit
: defaultMiniProgramRpx2Unit
const platformOptions = parseManifestJsonOnce(inputDir)[platform]
if (platformOptions && platformOptions.rpx) {
return extend({}, rpx2unit, platformOptions)
}
return extend({}, rpx2unit)
}
)
interface CompilerCompatConfig {
MODE?: 2 | 3
......
......@@ -101,7 +101,7 @@ const uniapp = (opts?: UniAppCssProcessorOptions) => {
return {
OnceExit(root) {
root.walkDecls(walkDecls(rpx2unit))
root.walkRules(walkRules(page))
page && root.walkRules(walkRules(page))
},
}
},
......
......@@ -55,7 +55,10 @@ export function uniSSRPlugin(): Plugin {
chunk.code =
generateSsrDefineCode(
resolvedConfig,
parseRpx2UnitOnce(process.env.UNI_INPUT_DIR)
parseRpx2UnitOnce(
process.env.UNI_INPUT_DIR,
process.env.UNI_PLATFORM
)
) +
'\n' +
chunk.code
......
......@@ -132,7 +132,7 @@ export function rewriteSsrNativeTag() {
}
export function rewriteSsrRenderStyle(inputDir: string) {
const { unit, unitRatio, unitPrecision } = parseRpx2UnitOnce(inputDir)
const { unit, unitRatio, unitPrecision } = parseRpx2UnitOnce(inputDir, 'h5')
const rpx2unit = createRpx2Unit(unit, unitRatio, unitPrecision)
const shared = require('@vue/shared')
const oldStringifyStyle = shared.stringifyStyle
......
......@@ -1243,11 +1243,6 @@ function hasCallback(args) {
return false;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise.then((data) => {
return [null, data];
}).catch((err) => [err]);
}
return promise;
}
function promisify(name, fn) {
......
......@@ -2522,11 +2522,6 @@ function hasCallback(args) {
return false;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise.then((data) => {
return [null, data];
}).catch((err) => [err]);
}
return promise;
}
function promisify(name, fn) {
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -58,10 +58,10 @@ describe('compiler: transform class', () => {
})
test('v-bind:class object syntax', () => {
assert(
`<view :class="{ red: isRed }"/>`,
`<view :class="{ red: \`\${isRed}\` }"/>`,
`<view class="{{[a && 'red']}}"/>`,
`(_ctx, _cache) => {
return { a: _ctx.isRed }
return { a: \`\${_ctx.isRed}\` }
}`
)
assert(
......@@ -103,6 +103,13 @@ describe('compiler: transform class', () => {
)
})
test('v-bind:class array syntax', () => {
assert(
`<view :class="[classA, \`\${classB}\`]"/>`,
`<view class="{{[a, b]}}"/>`,
`(_ctx, _cache) => {
return { a: _normalizeClass(_ctx.classA), b: _normalizeClass(\`\${_ctx.classB}\`) }
}`
)
assert(
`<view :class="[classA, classB]"/>`,
`<view class="{{[a, b]}}"/>`,
......
......@@ -50,6 +50,13 @@ describe('compiler: transform style', () => {
)
})
test('v-bind:style object syntax', () => {
assert(
`<view :style="{ color: \`\${green}px\` }"/>`,
`<view style="{{'color:' + a}}"/>`,
`(_ctx, _cache) => {
return { a: \`\${_ctx.green}px\` }
}`
)
assert(
`<view :style="{ color: 'green' }"/>`,
`<view style="{{'color:' + 'green'}}"/>`,
......@@ -98,6 +105,13 @@ describe('compiler: transform style', () => {
)
})
test('v-bind:style array syntax', () => {
assert(
`<view :style="[styleA, \`\${styleB}\`]"/>`,
`<view style="{{a + ';' + b}}"/>`,
`(_ctx, _cache) => {
return { a: _normalizeStyle(_ctx.styleA), b: _normalizeStyle(\`\${_ctx.styleB}\`) }
}`
)
assert(
`<view :style="[styleA, styleB]"/>`,
`<view style="{{a + ';' + b}}"/>`,
......
......@@ -34,10 +34,10 @@ function assert(
describe('compiler', () => {
test('scope', () => {
assert(
`<view v-for="(item,weekIndex) in weeks" :key="weekIndex" :data-id="item.id"><view v-for="(weeks,weeksIndex) in item" :key="weeksIndex" :data-id="weeks.id"/></view>`,
`<view wx:for="{{a}}" wx:for-item="item" wx:key="b" data-id="{{item.c}}"><view wx:for="{{item.a}}" wx:for-item="weeks" wx:key="a" data-id="{{weeks.b}}"/></view>`,
`<view :style="{ color: \`\${green}px\` }"/>`,
`<view style="{{'color:' + a}}"/>`,
`(_ctx, _cache) => {
return { a: _vFor(_ctx.weeks, (item, weekIndex) => { return { a: _vFor(item, (weeks, weeksIndex) => { return { a: weeksIndex, b: weeks.id }; }), b: weekIndex, c: item.id }; }) }
return { a: \`\${_ctx.green}px\` }
}`
)
})
......
......@@ -18,6 +18,7 @@ import {
LogicalExpression,
logicalExpression,
StringLiteral,
isTemplateLiteral,
} from '@babel/types'
import {
DirectiveNode,
......@@ -156,7 +157,7 @@ function rewriteClassObjectExpression(
key as Expression
) as Identifier
}
if (isLiteral(value)) {
if (isLiteral(value) && !isTemplateLiteral(value)) {
return
} else {
const newExpr = parseExprWithRewrite(
......
......@@ -13,6 +13,7 @@ import {
isObjectProperty,
binaryExpression,
isIdentifier,
isTemplateLiteral,
} from '@babel/types'
import {
DirectiveNode,
......@@ -159,7 +160,8 @@ function rewriteStyleObjectExpression(
prop.key = parseStringLiteral(prop.key)
prop.key.value = hyphenate(prop.key.value) + ':'
}
if (isLiteral(value)) {
// {fontSize:`${fontSize}px`} => {'font-size':a}
if (isLiteral(value) && !isTemplateLiteral(value)) {
return
} else {
const newExpr = parseExprWithRewrite(
......
......@@ -2,6 +2,7 @@ import {
ConditionalExpression,
isConditionalExpression,
isLiteral,
isTemplateLiteral,
isSpreadElement,
ObjectExpression,
} from '@babel/types'
......@@ -55,7 +56,7 @@ export const transformIf = createStructuralDirectiveTransform(
condition,
})
if (condition) {
if (!isLiteral(condition)) {
if (!isLiteral(condition) || isTemplateLiteral(condition)) {
ifOptions.condition = rewriteExpression(
dir.exp!,
context,
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
import { extend } from '@vue/shared'
import { initProvide, uniViteInjectPlugin } from '@dcloudio/uni-cli-shared'
import { uniMiniProgramPlugin, UniMiniProgramPluginOptions } from './plugin'
import { uniUsingComponentsPlugin } from './plugins/usingComponents'
import { uniMainJsPlugin } from './plugins/mainJs'
......@@ -5,6 +7,8 @@ import { uniManifestJsonPlugin } from './plugins/manifestJson'
import { uniPagesJsonPlugin } from './plugins/pagesJson'
import { uniEntryPlugin } from './plugins/entry'
import { SFCScriptCompileOptions } from '@vue/compiler-sfc'
import { uniRenderjsPlugin } from './plugins/renderjs'
export { UniMiniProgramPluginOptions } from './plugin'
export default (options: UniMiniProgramPluginOptions) => {
return [
......@@ -12,6 +16,8 @@ export default (options: UniMiniProgramPluginOptions) => {
uniManifestJsonPlugin(options),
uniPagesJsonPlugin(options),
uniEntryPlugin(options),
uniViteInjectPlugin(extend({}, options.vite.inject, initProvide())),
uniRenderjsPlugin(),
uniMiniProgramPlugin(options),
(options: {
vueOptions?: { script?: Partial<SFCScriptCompileOptions> }
......
......@@ -20,6 +20,9 @@ export interface UniMiniProgramPluginOptions {
vite: {
alias: AliasOptions
copyOptions: CopyOptions
inject: {
[name: string]: [string, string]
}
}
global: string
app: {
......
import debug from 'debug'
import { Plugin } from 'vite'
import { missingModuleName, parseRenderjs } from '@dcloudio/uni-cli-shared'
const debugRenderjs = debug('vite:uni:renderjs')
export function uniRenderjsPlugin(): Plugin {
return {
name: 'vite:uni-mp-renderjs',
transform(code, id) {
const { type, name } = parseRenderjs(id)
if (!type) {
return
}
debugRenderjs(id)
if (!name) {
this.error(missingModuleName(type, code))
}
if (type === 'wxs') {
console.log('wxs', id, code)
// this.emitFile({
// type: 'asset',
// fileName: '',
// source: code,
// })
}
return {
code: 'export default {}',
}
},
}
}
......@@ -4684,7 +4684,6 @@ function setupRenderEffect(instance) {
patch(instance, renderComponentRoot(instance));
}
else {
instance.render && instance.render.call(instance.proxy);
// updateComponent
const { bu, u } = instance;
effect.allowRecurse = false;
......
......@@ -4616,7 +4616,6 @@ function setupRenderEffect(instance) {
patch(instance, renderComponentRoot(instance));
}
else {
instance.render && instance.render.call(instance.proxy);
// updateComponent
const { bu, u } = instance;
effect.allowRecurse = false;
......
......@@ -253,13 +253,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -69,6 +69,12 @@ const uniMiniProgramWeixinPlugin = {
const projectConfigFilename = 'project.config.json';
const options = {
vite: {
inject: {
uni: [
uniCliShared.resolveBuiltIn('@dcloudio/uni-mp-weixin/dist/uni.api.esm.js'),
'default',
],
},
alias: {
'uni-mp-runtime': uniCliShared.resolveBuiltIn('@dcloudio/uni-mp-weixin/dist/uni.mp.esm.js'),
},
......
......@@ -21,6 +21,12 @@ const projectConfigFilename = 'project.config.json'
const options: UniMiniProgramPluginOptions = {
vite: {
inject: {
uni: [
resolveBuiltIn('@dcloudio/uni-mp-weixin/dist/uni.api.esm.js'),
'default',
],
},
alias: {
'uni-mp-runtime': resolveBuiltIn(
'@dcloudio/uni-mp-weixin/dist/uni.mp.esm.js'
......
......@@ -289,13 +289,13 @@ function invokeApi(method, api, options, ...params) {
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
......
......@@ -168,12 +168,20 @@ const defaultRpx2Unit = {
unitRatio: 10 / 320,
unitPrecision: 5,
};
const defaultMiniProgramRpx2Unit = {
unit: 'rpx',
unitRatio: 1,
unitPrecision: 1,
};
function createRpx2Unit(unit, unitRatio, unitPrecision) {
// ignore: rpxCalcIncludeWidth
return (val) => val.replace(unitRE, (m, $1) => {
if (!$1) {
return m;
}
if (unitRatio === 1) {
return `${$1}${unit}`;
}
const value = toFixed(parseFloat($1) * unitRatio, unitPrecision);
return value === 0 ? '0' : `${value}${unit}`;
});
......@@ -1212,6 +1220,7 @@ exports.createUniEvent = createUniEvent;
exports.debounce = debounce;
exports.decode = decode;
exports.decodedQuery = decodedQuery;
exports.defaultMiniProgramRpx2Unit = defaultMiniProgramRpx2Unit;
exports.defaultRpx2Unit = defaultRpx2Unit;
exports.formatAppLog = formatAppLog;
exports.formatDateTime = formatDateTime;
......
......@@ -132,6 +132,12 @@ export declare function decode(text: string | number): string;
export declare function decodedQuery(query?: Record<string, any>): Record<string, string>;
export declare const defaultMiniProgramRpx2Unit: {
unit: string;
unitRatio: number;
unitPrecision: number;
};
export declare const defaultRpx2Unit: {
unit: string;
unitRatio: number;
......
......@@ -164,12 +164,20 @@ const defaultRpx2Unit = {
unitRatio: 10 / 320,
unitPrecision: 5,
};
const defaultMiniProgramRpx2Unit = {
unit: 'rpx',
unitRatio: 1,
unitPrecision: 1,
};
function createRpx2Unit(unit, unitRatio, unitPrecision) {
// ignore: rpxCalcIncludeWidth
return (val) => val.replace(unitRE, (m, $1) => {
if (!$1) {
return m;
}
if (unitRatio === 1) {
return `${$1}${unit}`;
}
const value = toFixed(parseFloat($1) * unitRatio, unitPrecision);
return value === 0 ? '0' : `${value}${unit}`;
});
......@@ -1107,4 +1115,4 @@ function getEnvLocale() {
return (lang && lang.replace(/[.:].*/, '')) || 'en';
}
export { ACTION_TYPE_ADD_EVENT, ACTION_TYPE_ADD_WXS_EVENT, ACTION_TYPE_CREATE, ACTION_TYPE_EVENT, ACTION_TYPE_INSERT, ACTION_TYPE_PAGE_CREATE, ACTION_TYPE_PAGE_CREATED, ACTION_TYPE_PAGE_SCROLL, ACTION_TYPE_REMOVE, ACTION_TYPE_REMOVE_ATTRIBUTE, ACTION_TYPE_REMOVE_EVENT, ACTION_TYPE_SET_ATTRIBUTE, ACTION_TYPE_SET_TEXT, ATTR_CHANGE_PREFIX, ATTR_CLASS, ATTR_INNER_HTML, ATTR_STYLE, ATTR_TEXT_CONTENT, ATTR_V_OWNER_ID, ATTR_V_RENDERJS, ATTR_V_SHOW, BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, EventChannel, EventModifierFlags, I18N_JSON_DELIMITERS, JSON_PROTOCOL, LINEFEED, NAVBAR_HEIGHT, NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_PAGE, NODE_TYPE_TEXT, ON_ADD_TO_FAVORITES, ON_APP_ENTER_BACKGROUND, ON_APP_ENTER_FOREGROUND, ON_BACK_PRESS, ON_ERROR, ON_HIDE, ON_KEYBOARD_HEIGHT_CHANGE, ON_LAUNCH, ON_LOAD, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_PAGE_NOT_FOUND, ON_PAGE_SCROLL, ON_PULL_DOWN_REFRESH, ON_REACH_BOTTOM, ON_REACH_BOTTOM_DISTANCE, ON_READY, ON_RESIZE, ON_SHARE_APP_MESSAGE, ON_SHARE_TIMELINE, ON_SHOW, ON_TAB_ITEM_TAP, ON_THEME_CHANGE, ON_UNHANDLE_REJECTION, ON_UNLOAD, ON_WEB_INVOKE_APP_SERVICE, ON_WXS_INVOKE_CALL_METHOD, PLUS_RE, PRIMARY_COLOR, RENDERJS_MODULES, RESPONSIVE_MIN_WIDTH, SCHEME_RE, SELECTED_COLOR, TABBAR_HEIGHT, TAGS, UNI_SSR, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR_STORE, UNI_SSR_TITLE, UniBaseNode, UniCommentNode, UniElement, UniEvent, UniInputElement, UniLifecycleHooks, UniNode, UniTextAreaElement, UniTextNode, WEB_INVOKE_APPSERVICE, WXS_MODULES, WXS_PROTOCOL, addFont, cache, cacheStringFunction, callOptions, createRpx2Unit, createUniEvent, debounce, decode, decodedQuery, defaultRpx2Unit, formatAppLog, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, getValueByDataPath, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isRootHook, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeEventType, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, resolveOwnerEl, resolveOwnerVm, sanitise, scrollTo, stringifyQuery, updateElementStyle };
export { ACTION_TYPE_ADD_EVENT, ACTION_TYPE_ADD_WXS_EVENT, ACTION_TYPE_CREATE, ACTION_TYPE_EVENT, ACTION_TYPE_INSERT, ACTION_TYPE_PAGE_CREATE, ACTION_TYPE_PAGE_CREATED, ACTION_TYPE_PAGE_SCROLL, ACTION_TYPE_REMOVE, ACTION_TYPE_REMOVE_ATTRIBUTE, ACTION_TYPE_REMOVE_EVENT, ACTION_TYPE_SET_ATTRIBUTE, ACTION_TYPE_SET_TEXT, ATTR_CHANGE_PREFIX, ATTR_CLASS, ATTR_INNER_HTML, ATTR_STYLE, ATTR_TEXT_CONTENT, ATTR_V_OWNER_ID, ATTR_V_RENDERJS, ATTR_V_SHOW, BACKGROUND_COLOR, BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, EventChannel, EventModifierFlags, I18N_JSON_DELIMITERS, JSON_PROTOCOL, LINEFEED, NAVBAR_HEIGHT, NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_PAGE, NODE_TYPE_TEXT, ON_ADD_TO_FAVORITES, ON_APP_ENTER_BACKGROUND, ON_APP_ENTER_FOREGROUND, ON_BACK_PRESS, ON_ERROR, ON_HIDE, ON_KEYBOARD_HEIGHT_CHANGE, ON_LAUNCH, ON_LOAD, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_PAGE_NOT_FOUND, ON_PAGE_SCROLL, ON_PULL_DOWN_REFRESH, ON_REACH_BOTTOM, ON_REACH_BOTTOM_DISTANCE, ON_READY, ON_RESIZE, ON_SHARE_APP_MESSAGE, ON_SHARE_TIMELINE, ON_SHOW, ON_TAB_ITEM_TAP, ON_THEME_CHANGE, ON_UNHANDLE_REJECTION, ON_UNLOAD, ON_WEB_INVOKE_APP_SERVICE, ON_WXS_INVOKE_CALL_METHOD, PLUS_RE, PRIMARY_COLOR, RENDERJS_MODULES, RESPONSIVE_MIN_WIDTH, SCHEME_RE, SELECTED_COLOR, TABBAR_HEIGHT, TAGS, UNI_SSR, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR_STORE, UNI_SSR_TITLE, UniBaseNode, UniCommentNode, UniElement, UniEvent, UniInputElement, UniLifecycleHooks, UniNode, UniTextAreaElement, UniTextNode, WEB_INVOKE_APPSERVICE, WXS_MODULES, WXS_PROTOCOL, addFont, cache, cacheStringFunction, callOptions, createRpx2Unit, createUniEvent, debounce, decode, decodedQuery, defaultMiniProgramRpx2Unit, defaultRpx2Unit, formatAppLog, formatDateTime, formatLog, getCustomDataset, getEnvLocale, getLen, getValueByDataPath, initCustomDataset, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, isRootHook, isServiceCustomElement, isServiceNativeTag, normalizeDataset, normalizeEventType, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, resolveOwnerEl, resolveOwnerVm, sanitise, scrollTo, stringifyQuery, updateElementStyle };
......@@ -15,6 +15,12 @@ export const defaultRpx2Unit = {
unitPrecision: 5,
}
export const defaultMiniProgramRpx2Unit = {
unit: 'rpx',
unitRatio: 1,
unitPrecision: 1,
}
export type Rpx2UnitOptions = typeof defaultRpx2Unit
export function createRpx2Unit(
......@@ -28,6 +34,9 @@ export function createRpx2Unit(
if (!$1) {
return m
}
if (unitRatio === 1) {
return `${$1}${unit}`
}
const value = toFixed(parseFloat($1) * unitRatio, unitPrecision)
return value === 0 ? '0' : `${value}${unit}`
})
......
export * from './ast'
export * from './filter'
export * from './plugin'
export * from './postcss'
import { extend } from '@vue/shared'
import { rule, Rule, Declaration, Plugin } from 'postcss'
import selectorParser from 'postcss-selector-parser'
import {
createRpx2Unit,
defaultRpx2Unit,
isBuiltInComponent,
COMPONENT_SELECTOR_PREFIX,
} from '@dcloudio/uni-shared'
interface UniAppCssProcessorOptions {
page?: string
unit?: string // 目标单位,默认rem
unitRatio?: number // 单位转换比例,默认10/320
unitPrecision?: number // 单位精度,默认5
}
const defaultUniAppCssProcessorOptions = extend(
{
page: 'body',
},
defaultRpx2Unit
)
const BG_PROPS = [
'background',
'background-clip',
'background-color',
'background-image',
'background-origin',
'background-position',
'background-repeat',
'background-size',
'background-attachment',
]
function transform(
selector: selectorParser.Node,
page: string,
state: { bg: boolean }
) {
if (selector.type !== 'tag') {
return
}
const { value } = selector
if (isBuiltInComponent(value)) {
selector.value = COMPONENT_SELECTOR_PREFIX + value
} else if (value === 'page') {
if (!page) {
return
}
selector.value = page
if (page !== 'body') {
state.bg = true
}
}
}
function createBodyBackgroundRule(origRule: Rule) {
const bgDecls: Declaration[] = []
origRule.walkDecls((decl) => {
if (BG_PROPS.indexOf(decl.prop) !== -1) {
bgDecls.push(decl.clone())
}
})
if (bgDecls.length) {
origRule.after(rule({ selector: 'body' }).append(bgDecls))
}
}
function walkRules(page: string) {
return (rule: Rule) => {
const state = { bg: false }
rule.selector = selectorParser((selectors) =>
selectors.walk((selector) => transform(selector, page, state))
).processSync(rule.selector)
state.bg && createBodyBackgroundRule(rule)
}
}
function walkDecls(rpx2unit: ReturnType<typeof createRpx2Unit>) {
return (decl: Declaration) => {
const { value } = decl
if (value.indexOf('rpx') === -1 && value.indexOf('upx') === -1) {
return
}
decl.value = rpx2unit(decl.value)
}
}
export const uniapp = (opts?: UniAppCssProcessorOptions) => {
const { page, unit, unitRatio, unitPrecision } = extend(
{},
defaultUniAppCssProcessorOptions,
opts || {}
)
const rpx2unit = createRpx2Unit(unit, unitRatio, unitPrecision)
return {
postcssPlugin: 'uni-app',
prepare() {
return {
OnceExit(root) {
root.walkDecls(walkDecls(rpx2unit))
root.walkRules(walkRules(page))
},
}
},
} as Plugin
}
uniapp.postcss = true
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册