Skip to content

Commit

Permalink
fix(*): merge code.
Browse files Browse the repository at this point in the history
  • Loading branch information
shangqunfeng committed Oct 18, 2024
2 parents 890e513 + c117f28 commit e8bf428
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 87 deletions.
5 changes: 0 additions & 5 deletions packages/webpack-plugin/lib/platform/style/wx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,6 @@ module.exports = function getSpec ({ warn, error }) {
suffix = ['Top', 'Right', 'Bottom', 'Left']
break
}
if (values.length === 1 && (calcExp.test(value) || cssVariableExp.test(value))) {
// calc() or var() 则分开输出
suffix = ['Vertical', 'Horizontal']
values.push(values[0])
}
return values.map((value, index) => {
const newProp = `${prop}${suffix[index] || ''}`
// validate
Expand Down
27 changes: 20 additions & 7 deletions packages/webpack-plugin/lib/runtime/components/react/mpx-text.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ interface _TextProps extends TextProps {
style?: TextStyle
children?: ReactNode
selectable?: boolean
'user-select'?: boolean
'enable-var'?: boolean
'external-var-context'?: Record<string, any>
'user-select'?: boolean
userSelect?: boolean
'disable-default-style'?: boolean
'parent-font-size'?: number
'parent-width'?: number
'parent-height'?: number
}

interface WrapChildrenConfig {
Expand All @@ -41,7 +42,10 @@ const _Text = forwardRef<HandlerRef<Text, _TextProps>, _TextProps>((props, ref):
selectable,
'enable-var': enableVar,
'external-var-context': externalVarContext,
'user-select': userSelect
'user-select': userSelect,
'parent-font-size': parentFontSize,
'parent-width': parentWidth,
'parent-height': parentHeight
} = props

const layoutRef = useRef({})
Expand All @@ -50,7 +54,13 @@ const _Text = forwardRef<HandlerRef<Text, _TextProps>, _TextProps>((props, ref):
normalStyle,
hasVarDec,
varContextRef
} = useTransformStyle(style, { enableVar, externalVarContext })
} = useTransformStyle(style, {
enableVar,
externalVarContext,
parentFontSize,
parentWidth,
parentHeight
})

const { nodeRef } = useNodesRef<Text, _TextProps>(props, ref)

Expand All @@ -61,8 +71,11 @@ const _Text = forwardRef<HandlerRef<Text, _TextProps>, _TextProps>((props, ref):
'children',
'selectable',
'user-select',
'useInherit',
'enable-offset'
'enable-var',
'external-var-context',
'parent-font-size',
'parent-width',
'parent-height'
], {
layoutRef
})
Expand Down
40 changes: 29 additions & 11 deletions packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export interface _ViewProps extends ViewProps {
'enable-background'?: boolean
'enable-var'?: boolean
'external-var-context'?: Record<string, any>
'parent-font-size'?: number
'parent-width'?: number
'parent-height'?: number
bindtouchstart?: (event: NativeSyntheticEvent<TouchEvent> | unknown) => void
bindtouchmove?: (event: NativeSyntheticEvent<TouchEvent> | unknown) => void
bindtouchend?: (event: NativeSyntheticEvent<TouchEvent> | unknown) => void
Expand Down Expand Up @@ -599,7 +602,7 @@ function wrapImage (imageStyle?: ExtendedViewStyle) {
}
}

return <View key='viewBgImg' {...needLayout ? { onLayout } : null} style={{ ...StyleSheet.absoluteFillObject, width: '100%', height: '100%', overflow: 'hidden' }}>
return <View key='backgroundImage' {...needLayout ? { onLayout } : null} style={{ ...StyleSheet.absoluteFillObject, width: '100%', height: '100%', overflow: 'hidden' }}>
{show && type === 'linear' && <LinearGradient useAngle={true} {...imageStyleToProps(preImageInfo, sizeInfo.current as Size, layoutInfo.current as Size, linearInfo)} /> }
{show && type === 'image' && <Image {...imageStyleToProps(preImageInfo, sizeInfo.current as Size, layoutInfo.current as Size)} />}
</View>
Expand Down Expand Up @@ -646,7 +649,10 @@ const _View = forwardRef<HandlerRef<View, _ViewProps>, _ViewProps>((props, ref):
'enable-offset': enableOffset,
'enable-var': enableVar,
'external-var-context': externalVarContext,
'enable-background': enableBackground
'enable-background': enableBackground,
'parent-font-size': parentFontSize,
'parent-width': parentWidth,
'parent-height': parentHeight
} = props

const [isHover, setIsHover] = useState(false)
Expand All @@ -671,12 +677,18 @@ const _View = forwardRef<HandlerRef<View, _ViewProps>, _ViewProps>((props, ref):

const {
normalStyle,
hasPercent,
hasSelfPercent,
hasVarDec,
varContextRef,
setContainerWidth,
setContainerHeight
} = useTransformStyle(styleObj, { enableVar, externalVarContext })
setWidth,
setHeight
} = useTransformStyle(styleObj, {
enableVar,
externalVarContext,
parentFontSize,
parentWidth,
parentHeight
})

const { textStyle, backgroundStyle, innerStyle } = splitStyle(normalStyle)

Expand Down Expand Up @@ -730,10 +742,11 @@ const _View = forwardRef<HandlerRef<View, _ViewProps>, _ViewProps>((props, ref):
}

const onLayout = (res: LayoutChangeEvent) => {
if (hasPercent) {
props.onLayout && props.onLayout(res)
if (hasSelfPercent) {
const { width, height } = res?.nativeEvent?.layout || {}
setContainerWidth(width || 0)
setContainerHeight(height || 0)
setWidth(width || 0)
setHeight(height || 0)
}
if (enableOffset) {
nodeRef.current?.measure((x: number, y: number, width: number, height: number, offsetLeft: number, offsetTop: number) => {
Expand All @@ -742,7 +755,7 @@ const _View = forwardRef<HandlerRef<View, _ViewProps>, _ViewProps>((props, ref):
}
}

const needLayout = enableOffset || hasPercent
const needLayout = enableOffset || hasSelfPercent

const innerProps = useInnerProps(props, {
ref: nodeRef,
Expand All @@ -759,7 +772,12 @@ const _View = forwardRef<HandlerRef<View, _ViewProps>, _ViewProps>((props, ref):
'hover-style',
'hover-class',
'enable-offset',
'enable-background-image'
'enable-background-image',
'enable-var',
'external-var-context',
'parent-font-size',
'parent-width',
'parent-height'
], {
layoutRef
})
Expand Down
133 changes: 69 additions & 64 deletions packages/webpack-plugin/lib/runtime/components/react/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function splitStyle (styleObj: Object) {
})
}

const percentRule: Record<string, string> = {
const selfPercentRule: Record<string, 'height' | 'width'> = {
translateX: 'width',
translateY: 'height',
borderTopLeftRadius: 'width',
Expand All @@ -142,16 +142,10 @@ const percentRule: Record<string, string> = {
borderRadius: 'width'
}

const heightPercentRule: Record<string, boolean> = {
translateY: true,
const parentHeightPercentRule: Record<string, boolean> = {
height: true,
top: true,
bottom: true,
marginTop: true,
marginBottom: true,
marginVertical: true,
paddingTop: true,
paddingBottom: true,
paddingVertical: true
bottom: true
}

// todo calc时处理角度和时间等单位
Expand All @@ -167,18 +161,47 @@ function formatValue (value: string) {
return value
}

function transformPercent (styleObj: Record<string, any>, percentKeyPaths: Array<Array<string>>, { width, height }: { width?: number, height?: number }) {
interface PercentConfig {
fontSize?: number | string
width?: number
height?: number
parentFontSize?: number
parentWidth?: number
parentHeight?: number
}

function resolvePercent (value: string | number | undefined, key: string, percentConfig: PercentConfig): string | number | undefined {
if (!(typeof value === 'string' && PERCENT_REGEX.test(value))) return value
let base
let reason
if (key === 'fontSize') {
base = percentConfig.parentFontSize
reason = 'parent-font-size'
} else if (key === 'lineHeight') {
base = resolvePercent(percentConfig.fontSize, 'fontSize', percentConfig)
reason = 'font-size'
} else if (selfPercentRule[key]) {
base = percentConfig[selfPercentRule[key]]
reason = selfPercentRule[key]
} else if (parentHeightPercentRule[key]) {
base = percentConfig.parentHeight
reason = 'parent-height'
} else {
base = percentConfig.parentWidth
reason = 'parent-width'
}
if (typeof base !== 'number') {
error(`[${key}] can not contain % unit unless you set [${reason}] with a number for the percent calculation.`)
return value
} else {
return parseFloat(value) / 100 * base
}
}

function transformPercent (styleObj: Record<string, any>, percentKeyPaths: Array<Array<string>>, percentConfig: PercentConfig) {
percentKeyPaths.forEach((percentKeyPath) => {
setStyle(styleObj, percentKeyPath, ({ target, key, value }) => {
const percentage = parseFloat(value) / 100
const type = percentRule[key]
if (type === 'height' && height) {
target[key] = percentage * height
} else if (type === 'width' && width) {
target[key] = percentage * width
} else {
target[key] = 0
}
target[key] = resolvePercent(value, key, percentConfig)
})
})
}
Expand Down Expand Up @@ -230,38 +253,25 @@ function transformCalc (styleObj: Record<string, any>, calcKeyPaths: Array<Array
})
}

function transformLineHeight (styleObj: Record<string, any>) {
let { lineHeight } = styleObj
if (typeof lineHeight === 'string' && PERCENT_REGEX.test(lineHeight)) {
const hasFontSize = hasOwn(styleObj, 'fontSize')
if (!hasFontSize) {
warn('The fontSize property could not be read correctly, so the default fontSize of 16 will be used as the basis for calculating the lineHeight!')
}
const fontSize = hasFontSize ? styleObj.fontSize : DEFAULT_FONT_SIZE
lineHeight = (parseFloat(lineHeight) / 100) * fontSize
styleObj.lineHeight = lineHeight
}
}

interface TransformStyleConfig {
enableVar?: boolean
externalVarContext?: Record<string, any>
parentFontSize?: number
parentWidth?: number
parentHeight?: number
}

export function useTransformStyle (styleObj: Record<string, any> = {}, { enableVar, externalVarContext }: TransformStyleConfig) {
export function useTransformStyle (styleObj: Record<string, any> = {}, { enableVar, externalVarContext, parentFontSize, parentWidth, parentHeight }: TransformStyleConfig) {
const varStyle: Record<string, any> = {}
const normalStyle: Record<string, any> = {}
let hasVarDec = false
let hasVarUse = false
let hasPercent = false
let hasCalcUse = false
let hasSelfPercent = false
const varKeyPaths: Array<Array<string>> = []
const percentKeyPaths: Array<Array<string>> = []
const calcKeyPaths: Array<Array<string>> = []
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const setContainerWidth = setWidth
const setContainerHeight = setHeight

function varVisitor ({ key, value, keyPath }: VisitorArg) {
if (keyPath.length === 1) {
Expand Down Expand Up @@ -301,36 +311,38 @@ export function useTransformStyle (styleObj: Record<string, any> = {}, { enableV

function calcVisitor ({ value, keyPath }: VisitorArg) {
if (calcUseRegExp.test(value)) {
hasCalcUse = true
calcKeyPaths.push(keyPath.slice())
}
}

function percentVisitor ({ key, value, keyPath }: VisitorArg) {
if (hasOwn(percentRule, key) && PERCENT_REGEX.test(value)) {
hasPercent = true
if (hasOwn(selfPercentRule, key) && PERCENT_REGEX.test(value)) {
hasSelfPercent = true
percentKeyPaths.push(keyPath.slice())
} else if (key === 'fontSize' || key === 'lineHeight') {
percentKeyPaths.push(keyPath.slice())
}
}

// traverse calc & percent
traverseStyle(normalStyle, [percentVisitor, calcVisitor])

// apply percent
if (hasPercent) {
transformPercent(normalStyle, percentKeyPaths, { width, height })
const percentConfig = {
width,
height,
fontSize: normalStyle.fontSize,
parentWidth,
parentHeight,
parentFontSize
}

function calcFormatter (value: string, key: string) {
// apply percent
transformPercent(normalStyle, percentKeyPaths, percentConfig)
// apply calc
transformCalc(normalStyle, calcKeyPaths, (value: string, key: string) => {
if (PERCENT_REGEX.test(value)) {
if (key === 'width' || key === 'height') {
error(`calc() can not use % in ${key}.`)
return 0
}
hasPercent = true
const percentage = parseFloat(value) / 100
const isHeight = heightPercentRule[key]
return percentage * (isHeight ? height : width)
const resolved = resolvePercent(value, key, percentConfig)
return typeof resolved === 'number' ? resolved : 0
} else {
const formatted = formatValue(value)
if (typeof formatted === 'number') {
Expand All @@ -340,23 +352,16 @@ export function useTransformStyle (styleObj: Record<string, any> = {}, { enableV
return 0
}
}
}
// apply calc
if (hasCalcUse) {
transformCalc(normalStyle, calcKeyPaths, calcFormatter)
}
// transform lineHeight
transformLineHeight(normalStyle)
})

return {
normalStyle,
hasPercent,
hasSelfPercent,
hasVarDec,
hasVarUse,
enableVarRef,
varContextRef,
setContainerWidth,
setContainerHeight
setWidth,
setHeight
}
}

Expand Down

0 comments on commit e8bf428

Please sign in to comment.