Skip to content

Commit 7ba3366

Browse files
authored
Merge pull request #2373 from didi/feat-style-compile-251012
merge feat-style-compile-251012 into fix-drn-2.10.17
2 parents 570a962 + b2d2ee3 commit 7ba3366

File tree

9 files changed

+105
-63
lines changed

9 files changed

+105
-63
lines changed

packages/api-proxy/src/platform/api/route/index.ios.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,10 @@ function navigateBack (options = {}) {
104104
}
105105
if (delta >= routeLength && global.__mpx?.config.rnConfig.onAppBack?.(delta - routeLength + 1)) {
106106
nextTick(() => {
107-
navigationHelper.lastSuccessCallback()
108-
navigationHelper.lastSuccessCallback = null
107+
if (navigationHelper.lastSuccessCallback) {
108+
navigationHelper.lastSuccessCallback()
109+
navigationHelper.lastSuccessCallback = null
110+
}
109111
})
110112
} else {
111113
navigation.pop(delta)

packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isObject, isArray, dash2hump, cached, isEmptyObject, hasOwn, getFocusedNavigation, noop } from '@mpxjs/utils'
1+
import { isObject, isArray, dash2hump, cached, isEmptyObject, hasOwn, getFocusedNavigation } from '@mpxjs/utils'
22
import { StyleSheet, Dimensions } from 'react-native'
33
import { reactive } from '../../observer/reactive'
44
import Mpx from '../../index'
@@ -12,7 +12,7 @@ global.__mpxPageSizeCountMap = reactive({})
1212

1313
global.__GCC = function (className, classMap, classMapValueCache) {
1414
if (!classMapValueCache.has(className)) {
15-
const styleObj = classMap[className]?.()
15+
const styleObj = classMap[className]?.(global.__formatValue)
1616
styleObj && classMapValueCache.set(className, styleObj)
1717
}
1818
return classMapValueCache.get(className)
@@ -271,13 +271,13 @@ export default function styleHelperMixin () {
271271
if (localStyle._media?.length) {
272272
mergeResult(localStyle._default, getMediaStyle(localStyle._media))
273273
} else {
274-
mergeResult(localStyle._default)
274+
mergeResult(localStyle)
275275
}
276-
} else if (appStyle = getAppClassStyle(className)) {
276+
} else if (appStyle = global.__getAppClassStyle?.(className)) {
277277
if (appStyle._media?.length) {
278278
mergeResult(appStyle._default, getMediaStyle(appStyle._media))
279279
} else {
280-
mergeResult(appStyle._default)
280+
mergeResult(appStyle)
281281
}
282282
} else if (isObject(this.__props[className])) {
283283
// externalClasses必定以对象形式传递下来

packages/webpack-plugin/lib/platform/style/wx/index.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,15 @@ module.exports = function getSpec ({ warn, error }) {
549549
return { prop, value: values[0].trim() }
550550
}
551551

552+
const formatZIndex = ({ prop, value, selector }, { mode }) => {
553+
// z-index auto 报错
554+
if (value === 'auto') {
555+
error(`Property [${prop}] does not supported [${value}] on ${selector} in ${mode} environment, please check again!`)
556+
return { prop, value: 0 }
557+
}
558+
return { prop, value: value }
559+
}
560+
552561
// const formatBoxShadow = ({ prop, value, selector }, { mode }) => {
553562
// value = value.trim()
554563
// if (value === 'none') {
@@ -614,6 +623,12 @@ module.exports = function getSpec ({ warn, error }) {
614623
android: formatFontFamily,
615624
harmony: formatFontFamily
616625
},
626+
{
627+
test: 'z-index',
628+
ios: formatZIndex,
629+
android: formatZIndex,
630+
harmony: formatZIndex
631+
},
617632
// {
618633
// test: 'box-shadow',
619634
// ios: formatBoxShadow,

packages/webpack-plugin/lib/react/processStyles.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,26 +48,29 @@ module.exports = function (styles, {
4848
}, (err) => {
4949
if (err) return callback(err)
5050
try {
51+
output += `
52+
global.__classCaches = global.__classCaches || []
53+
var __classCache = new Map()
54+
global.__classCaches.push(__classCache)`
55+
const formatValueName = '_f'
5156
const classMap = getClassMap({
5257
content,
5358
filename: loaderContext.resourcePath,
5459
mode,
5560
srcMode,
5661
ctorType,
5762
warn,
58-
error
63+
error,
64+
formatValueName
5965
})
6066
const classMapCode = Object.entries(classMap).reduce((result, [key, value]) => {
6167
result !== '' && (result += ',')
62-
result += `${isValidIdentifierStr(key) ? `${key}` : `['${key}']`}: () => (${shallowStringify(value)})`
68+
result += `${isValidIdentifierStr(key) ? `${key}` : `['${key}']`}: function(${formatValueName}){return ${shallowStringify(value)};}`
6369
return result
6470
}, '')
6571
if (ctorType === 'app') {
6672
output += `
67-
global.__classCaches = global.__classCaches || []
68-
const __classCache = new Map()
69-
global.__classCaches.push(__classCache)
70-
let __appClassMap
73+
var __appClassMap
7174
global.__getAppClassStyle = function(className) {
7275
if(!__appClassMap) {
7376
__appClassMap = {${classMapCode}};
@@ -76,10 +79,7 @@ module.exports = function (styles, {
7679
};\n`
7780
} else {
7881
output += `
79-
global.__classCaches = global.__classCaches || []
80-
const __classCache = new Map()
81-
global.__classCaches.push(__classCache)
82-
let __classMap
82+
var __classMap
8383
global.currentInject.injectMethods = {
8484
__getClassStyle: function(className) {
8585
if(!__classMap) {

packages/webpack-plugin/lib/react/style-helper.js

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,9 @@ const unitRegExp = /^\s*(-?\d+(?:\.\d+)?)(rpx|vw|vh|px)?\s*$/
88
const hairlineRegExp = /^\s*hairlineWidth\s*$/
99
const varRegExp = /^--/
1010
const cssPrefixExp = /^-(webkit|moz|ms|o)-/
11-
function getClassMap ({ content, filename, mode, srcMode, ctorType, warn, error }) {
11+
function getClassMap ({ content, filename, mode, srcMode, ctorType, formatValueName, warn, error }) {
1212
const classMap = ctorType === 'page'
13-
? {
14-
[MPX_TAG_PAGE_SELECTOR]: {
15-
_media: [],
16-
_default: { flex: 1, height: "'100%'" }
17-
}
18-
}
13+
? { [MPX_TAG_PAGE_SELECTOR]: { flex: 1, height: "'100%'" } }
1914
: {}
2015

2116
const root = postcss.parse(content, {
@@ -30,12 +25,12 @@ function getClassMap ({ content, filename, mode, srcMode, ctorType, warn, error
3025
value = matched[1]
3126
needStringify = false
3227
} else {
33-
value = `global.__formatValue(${+matched[1]}, '${matched[2]}')`
28+
value = `${formatValueName}(${+matched[1]}, '${matched[2]}')`
3429
needStringify = false
3530
}
3631
}
3732
if (hairlineRegExp.test(value)) {
38-
value = `global.__formatValue(${JSON.stringify(value)}, 'hairlineWidth')`
33+
value = `${formatValueName}(${JSON.stringify(value)}, 'hairlineWidth')`
3934
needStringify = false
4035
}
4136
return needStringify ? JSON.stringify(value) : value
@@ -93,7 +88,7 @@ function getClassMap ({ content, filename, mode, srcMode, ctorType, warn, error
9388
root.walkRules(rule => {
9489
const classMapValue = {}
9590
rule.walkDecls(({ prop, value }) => {
96-
if (cssPrefixExp.test(prop) || cssPrefixExp.test(value)) return
91+
if (value === 'undefined' || cssPrefixExp.test(prop) || cssPrefixExp.test(value)) return
9792
let newData = rulesRunner({ prop, value, selector: rule.selector })
9893
if (!newData) return
9994
if (!Array.isArray(newData)) {
@@ -140,19 +135,27 @@ function getClassMap ({ content, filename, mode, srcMode, ctorType, warn, error
140135
if (classMapKeys.length) {
141136
classMapKeys.forEach((key) => {
142137
if (Object.keys(classMapValue).length) {
143-
const _default = classMap[key]?._default || {}
144-
const _media = classMap[key]?._media || []
138+
let _default = classMap[key]?._default
139+
let _media = classMap[key]?._media
145140
if (isMedia) {
141+
// 当前是媒体查询
142+
_default = _default || {}
143+
_media = _media || []
146144
_media.push({
147145
options,
148146
value: classMapValue
149147
})
150-
} else {
148+
classMap[key] = {
149+
_media,
150+
_default
151+
}
152+
} else if (_default) {
153+
// 已有媒体查询数据,此次非媒体查询
151154
Object.assign(_default, classMapValue)
152-
}
153-
classMap[key] = {
154-
_media,
155-
_default
155+
} else {
156+
// 无媒体查询
157+
const val = classMap[key] || {}
158+
classMap[key] = Object.assign(val, classMapValue)
156159
}
157160
}
158161
})

packages/webpack-plugin/lib/resolver/AddModePlugin.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,21 +44,31 @@ module.exports = class AddModePlugin {
4444
if (!extname || !matchCondition(resourcePath, fileConditionRules)) return callback()
4545

4646
const queryInfix = queryObj.infix
47-
if (!implicitMode) queryObj.mode = mode
48-
queryObj.infix = `${queryInfix || ''}.${mode}`
4947

5048
// 如果已经确认是mode后缀的文件,添加query与mode后直接返回
5149
if (modePattern.test(path.basename(resourcePath))) {
52-
request.query = stringifyQuery(queryObj)
53-
request.mode = obj.mode
50+
// 已经被resolved到对应mode的文件,避免重复添加mode
51+
const isResolved = (implicitMode || queryObj.mode === mode) && modePattern.test(queryObj.infix)
52+
if (!isResolved) {
53+
queryObj.infix = `${queryInfix || ''}.${mode}`
54+
if (!implicitMode) queryObj.mode = mode
55+
request.query = stringifyQuery(queryObj)
56+
request.mode = obj.mode
57+
}
5458
return callback()
5559
} else if (defaultMode && defaultModePattern.test(path.basename(resourcePath))) {
56-
queryObj.infix = `${queryInfix || ''}.${defaultMode}`
57-
request.query = stringifyQuery(queryObj)
58-
request.mode = obj.mode
60+
const isResolved = (implicitMode || queryObj.mode === mode) && defaultModePattern.test(queryObj.infix)
61+
if (!isResolved) {
62+
queryObj.infix = `${queryInfix || ''}.${defaultMode}`
63+
if (!implicitMode) queryObj.mode = mode
64+
request.query = stringifyQuery(queryObj)
65+
request.mode = obj.mode
66+
}
5967
return callback()
6068
}
6169

70+
if (!implicitMode) queryObj.mode = mode
71+
queryObj.infix = `${queryInfix || ''}.${mode}`
6272
obj.query = stringifyQuery(queryObj)
6373
obj.path = addInfix(resourcePath, mode, extname)
6474
obj.relativePath = request.relativePath && addInfix(request.relativePath, mode, extname)

packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ function backgroundSize (imageProps: ImageProps, preImageInfo: PreImageInfo, ima
287287
} else { // 数值类型 ImageStyle
288288
// 数值类型设置为 stretch
289289
imageProps.resizeMode = 'stretch'
290-
if (type === 'linear' && (!layoutWidth || !layoutHeight)) {
290+
if (type === 'linear' && (!layoutWidth || !layoutHeight) && (isPercent(width) || isPercent(height))) {
291291
// ios 上 linear 组件只要重新触发渲染,在渲染过程中外层容器 width 或者 height 被设置为 0,通过设置 % 的方式会渲染不出来,即使后面再更新为正常宽高也渲染不出来
292292
// 所以 hack 手动先将 linear 宽高也设置为 0,后面再更新为正确的数值或 %。
293293
dimensions = {

packages/webpack-plugin/lib/runtime/components/react/utils.tsx

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { useEffect, useCallback, useMemo, useRef, ReactNode, ReactElement, isValidElement, useContext, useState, Dispatch, SetStateAction, Children, cloneElement, createElement, MutableRefObject } from 'react'
22
import { LayoutChangeEvent, TextStyle, ImageProps, Image } from 'react-native'
3-
import { isObject, isFunction, isNumber, hasOwn, diffAndCloneA, error, warn } from '@mpxjs/utils'
3+
import { isObject, isFunction, isNumber, hasOwn, diffAndCloneA, error, warn, isEmptyObject } from '@mpxjs/utils'
44
import { VarContext, ScrollViewContext, RouteContext } from './context'
55
import { ExpressionParser, parseFunc, ReplaceSource } from './parser'
66
import { initialWindowMetrics } from 'react-native-safe-area-context'
@@ -238,7 +238,7 @@ function transformVar (styleObj: Record<string, any>, varKeyPaths: Array<Array<s
238238
const resolved = resolveVar(value, varContext)
239239
if (resolved === undefined) {
240240
delete target[key]
241-
error(`Can not resolve css var at ${varKeyPath.join('.')}:${value}.`)
241+
// error(`Can not resolve css var at ${varKeyPath.join('.')}:${value}.`)
242242
return
243243
}
244244
target[key] = resolved
@@ -390,6 +390,14 @@ function transformBoxShadow (styleObj: Record<string, any>) {
390390
}, '')
391391
}
392392

393+
function transformZIndex (styleObj: Record<string, any>) {
394+
if (!styleObj.zIndex || typeof styleObj.zIndex === 'number') return
395+
if (styleObj.zIndex === 'auto') {
396+
error('Property [z-index] does not supported [auto], please check again!')
397+
styleObj.zIndex = 0
398+
}
399+
}
400+
393401
interface TransformStyleConfig {
394402
enableVar?: boolean
395403
externalVarContext?: Record<string, any>
@@ -446,17 +454,20 @@ export function useTransformStyle (styleObj: Record<string, any> = {}, { enableV
446454
}
447455
}
448456

449-
function calcVisitor ({ value, keyPath }: VisitorArg) {
457+
function calcVisitor ({ key, value, keyPath }: VisitorArg) {
450458
if (calcUseRegExp.test(value)) {
459+
// calc translate & border-radius 的百分比计算
460+
if (hasOwn(selfPercentRule, key) && /%/.test(value)) {
461+
hasSelfPercent = true
462+
percentKeyPaths.push(keyPath.slice())
463+
}
451464
calcKeyPaths.push(keyPath.slice())
452465
}
453466
}
454467

455468
function percentVisitor ({ key, value, keyPath }: VisitorArg) {
456-
if (hasOwn(selfPercentRule, key) && PERCENT_REGEX.test(value)) {
457-
hasSelfPercent = true
458-
percentKeyPaths.push(keyPath.slice())
459-
} else if ((key === 'fontSize' || key === 'lineHeight') && PERCENT_REGEX.test(value)) {
469+
// fixme 去掉 translate & border-radius 的百分比计算
470+
if ((key === 'fontSize' || key === 'lineHeight') && PERCENT_REGEX.test(value)) {
460471
percentKeyPaths.push(keyPath.slice())
461472
}
462473
}
@@ -466,10 +477,10 @@ export function useTransformStyle (styleObj: Record<string, any> = {}, { enableV
466477
[envVisitor, percentVisitor, calcVisitor].forEach(visitor => visitor({ target, key, value, keyPath }))
467478
}
468479
}
469-
480+
// transform 字符串格式转化数组格式(先转数组再处理css var)
481+
transformTransform(styleObj)
470482
// traverse var & generate normalStyle
471483
traverseStyle(styleObj, [varVisitor])
472-
473484
hasVarDec = hasVarDec || !!externalVarContext
474485
enableVar = enableVar || hasVarDec || hasVarUse
475486
const enableVarRef = useRef(enableVar)
@@ -533,10 +544,11 @@ export function useTransformStyle (styleObj: Record<string, any> = {}, { enableV
533544
transformStringify(normalStyle)
534545
// transform rpx to px
535546
transformBoxShadow(normalStyle)
536-
537-
// transform 字符串格式转化数组格式
538-
transformTransform(normalStyle)
539-
547+
// transform z-index auto to 0
548+
transformZIndex(normalStyle)
549+
if (Array.isArray(normalStyle.transform)) {
550+
normalStyle.transform = normalStyle.transform.filter(item => !isEmptyObject(item))
551+
}
540552
return {
541553
hasVarDec,
542554
varContextRef,

0 commit comments

Comments
 (0)