Skip to content

Commit

Permalink
Merge branch 'master' into feat-lyf-pickerview
Browse files Browse the repository at this point in the history
  • Loading branch information
luyongfang committed Oct 11, 2024
2 parents 72e0f6b + 3ed8d82 commit 68f05ec
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
hump2dash,
isArray
} from '@mpxjs/utils'
import { StyleSheet } from 'react-native'

const flushRefFns = (nodeInstances, fns, single) => {
// wx的数据格式:对于具体方法接受到的回调传参,如果获取的 nodeRef 只有一个,那么只需要返回一条数据而不是数组,但是 exec 里面统一都是数组
Expand Down Expand Up @@ -61,18 +60,18 @@ const getMeasureProps = (measureProps = []) => {
}

const getDataset = (props) => {
return wrapFn((nodeRef, resolve) => {
props = nodeRef.props.current
return wrapFn((nodeInstance, resolve) => {
props = nodeInstance.props.current
resolve({
dataset: collectDataset(props)
})
})
}

const getPlainProps = (config) => {
return wrapFn((nodeRef, resolve) => {
return wrapFn((nodeInstance, resolve) => {
const res = {}
const props = nodeRef.props.current
const props = nodeInstance.props.current
config.forEach((key) => {
// props 属性默认不转驼峰,用户写什么格式不会变化,取值做兼容
res[key] = props[key] || props[hump2dash(key)] || ''
Expand All @@ -82,12 +81,15 @@ const getPlainProps = (config) => {
}

const getComputedStyle = (config = []) => {
return wrapFn((nodeRef, resolve) => {
return wrapFn((nodeInstance, resolve) => {
config = new Set(config)
const res = {}
const styles = nodeRef.props.current.style || []
const defaultStyle = nodeRef.instance.defaultStyle || {}
const computedStyle = StyleSheet.flatten([defaultStyle, ...styles])
const styles = nodeInstance.props.current.style || {}
const defaultStyle = nodeInstance.instance.defaultStyle || {}
const computedStyle = {
...defaultStyle,
...styles
}
config.forEach((key) => {
const humpKey = dash2hump(key)
// 取 style 的 key 是根据传入的 key 来设置,传什么设置什么 key,只不过取值需要做兼容
Expand All @@ -99,8 +101,8 @@ const getComputedStyle = (config = []) => {
}

const getInstanceConfig = (config) => {
return wrapFn((nodeRef, resolve) => {
const instance = nodeRef.instance
return wrapFn((nodeInstance, resolve) => {
const instance = nodeInstance.instance
resolve({ [config]: instance[config] || {} })
})
}
Expand All @@ -113,8 +115,8 @@ const defaultScrollOffset = {
}

const getScrollOffset = () => {
return wrapFn((nodeRef, resolve) => {
const instance = nodeRef.instance
return wrapFn((nodeInstance, resolve) => {
const instance = nodeInstance.instance
resolve(
(instance.scrollOffset && instance.scrollOffset.current) ||
defaultScrollOffset
Expand Down
12 changes: 7 additions & 5 deletions packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isObject, isArray, dash2hump, isFunction, cached } from '@mpxjs/utils'
import { Dimensions } from 'react-native'
import { Dimensions, StyleSheet } from 'react-native'

function rpx (value) {
const { width } = Dimensions.get('screen')
Expand All @@ -9,6 +9,7 @@ function rpx (value) {
}

global.__rpx = rpx
global.__hairlineWidth = StyleSheet.hairlineWidth

const escapeReg = /[()[\]{}#!.:,%'"+$]/g
const escapeMap = {
Expand All @@ -25,7 +26,7 @@ const escapeMap = {
':': '_c_',
',': '_2c_',
'%': '_p_',
"'": '_q_',
'\'': '_q_',
'"': '_dq_',
'+': '_a_',
$: '_si_'
Expand Down Expand Up @@ -81,7 +82,8 @@ const listDelimiter = /;(?![^(]*[)])/g
const propertyDelimiter = /:(.+)/
const rpxRegExp = /^\s*(-?\d+(\.\d+)?)rpx\s*$/
const pxRegExp = /^\s*(-?\d+(\.\d+)?)(px)?\s*$/
const varRegExp = /^--.*/
const hairlineRegExp = /^\s*hairlineWidth\s*$/
const varRegExp = /^--/

const parseStyleText = cached((cssText = '') => {
const res = {}
Expand Down Expand Up @@ -123,15 +125,15 @@ function transformStyleObj (styleObj) {
const keys = Object.keys(styleObj)
const transformed = {}
keys.forEach((prop) => {
// todo 检测不支持的prop
let value = styleObj[prop]
let matched
if ((matched = pxRegExp.exec(value))) {
value = +matched[1]
} else if ((matched = rpxRegExp.exec(value))) {
value = rpx(+matched[1])
} else if (hairlineRegExp.test(value)) {
value = StyleSheet.hairlineWidth
}
// todo 检测不支持的value
transformed[prop] = value
})
return transformed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ const triggerResizeEvent = (mpxProxy) => {
}

function usePageContext (mpxProxy, instance) {
const { pageId } = useContext(routeContext) || {}
const pageId = useContext(routeContext)

instance.getPageId = () => {
return pageId
Expand Down Expand Up @@ -447,13 +447,12 @@ export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) {
null,
createElement(routeContext.Provider,
{
value: { pageId: currentPageId }
value: currentPageId
},
createElement(defaultOptions,
{
navigation,
route,
pageConfig
route
}
)
)
Expand Down
6 changes: 3 additions & 3 deletions packages/webpack-plugin/lib/platform/style/wx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = function getSpec ({ warn, error }) {
// React Native android 不支持的 CSS property
android: /^(text-decoration-style|text-decoration-color|shadow-offset|shadow-opacity|shadow-radius)$/
}
const cssVariableExp = /var\((.*?)\)/
const cssVariableExp = /^var\((.+)\)$/
// 不支持的属性提示
const unsupportedPropError = ({ prop, mode }) => {
error(`Property [${prop}] is not supported in React Native ${mode} environment!`)
Expand Down Expand Up @@ -91,15 +91,15 @@ module.exports = function getSpec ({ warn, error }) {
// css variable 类型校验
const newVal = (value.match(cssVariableExp)?.[1] || '').split(',')
const variable = newVal?.[0]
if (!variable || !/^--.+$/.test(variable)) {
if (!variable || !/^--/.test(variable)) {
tips(`The css variable [${prop}:${value}] is invalid, please check again`)
return false
}
return true
}
const namedColor = ['transparent', 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen']
const valueExp = {
number: /^(-?\d+(\.\d+)?)(rpx|px|%)?$/,
number: /^((-?\d+(\.\d+)?)(rpx|px|%)?|hairlineWidth)$/,
color: new RegExp(('^(' + namedColor.join('|') + ')$') + '|(^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$)|^(rgb|rgba|hsl|hsla|hwb)\\(.+\\)$')
}
const type = getValueType(prop)
Expand Down
6 changes: 5 additions & 1 deletion packages/webpack-plugin/lib/react/style-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const getRulesRunner = require('../platform/index')
const dash2hump = require('../utils/hump-dash').dash2hump
const rpxRegExp = /^\s*(-?\d+(\.\d+)?)rpx\s*$/
const pxRegExp = /^\s*(-?\d+(\.\d+)?)(px)?\s*$/
const varRegExp = /^--.*/
const hairlineRegExp = /^\s*hairlineWidth\s*$/
const varRegExp = /^--/
const cssPrefixExp = /^-(webkit|moz|ms|o)-/
function getClassMap ({ content, filename, mode, srcMode, warn, error }) {
const classMap = {}
Expand All @@ -22,6 +23,9 @@ function getClassMap ({ content, filename, mode, srcMode, warn, error }) {
} else if ((matched = rpxRegExp.exec(value))) {
value = `global.__rpx(${matched[1]})`
needStringify = false
} else if (hairlineRegExp.test(value)) {
value = 'global.__hairlineWidth'
needStringify = false
}
return needStringify ? JSON.stringify(value) : value
}
Expand Down
32 changes: 19 additions & 13 deletions packages/webpack-plugin/lib/runtime/components/react/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useRef, ReactNode, ReactElement, FunctionComponent, isValidElement, useContext, useState } from 'react'
import { TextStyle, Dimensions } from 'react-native'
import { Dimensions, StyleSheet } from 'react-native'
import { isObject, hasOwn, diffAndCloneA, noop } from '@mpxjs/utils'
import { VarContext } from './context'

Expand All @@ -8,10 +8,16 @@ export const PERCENT_REGEX = /^\s*-?\d+(\.\d+)?%\s*$/
export const BACKGROUND_REGEX = /^background(Image|Size|Repeat|Position)$/
export const TEXT_PROPS_REGEX = /ellipsizeMode|numberOfLines/
export const VAR_DEC_REGEX = /^--.*/
export const VAR_USE_REGEX = /var\(([^,]+)(?:,([^)]+))?\)/
export const URL_REGEX = /url\(["']?(.*?)["']?\)/
export const VAR_USE_REGEX = /^\s*var\(([^,]+)(?:,(.+))?\)\s*$/
export const URL_REGEX = /^\s*url\(["']?(.*?)["']?\)\s*$/
export const DEFAULT_FONT_SIZE = 16

export const throwReactWarning = (message: string) => {
setTimeout(() => {
console.warn(message)
}, 0)
}

export function rpx (value: number) {
const { width } = Dimensions.get('screen')
// rn 单位 dp = 1(css)px = 1 物理像素 * pixelRatio(像素比)
Expand All @@ -21,13 +27,16 @@ export function rpx (value: number) {

const rpxRegExp = /^\s*(-?\d+(\.\d+)?)rpx\s*$/
const pxRegExp = /^\s*(-?\d+(\.\d+)?)(px)?\s*$/
const hairlineRegExp = /^\s*hairlineWidth\s*$/

export function formatValue (value: string) {
let matched
if ((matched = pxRegExp.exec(value))) {
return +matched[1]
} else if ((matched = rpxRegExp.exec(value))) {
return rpx(+matched[1])
} else if (hairlineRegExp.test(value)) {
return StyleSheet.hairlineWidth
}
return value
}
Expand Down Expand Up @@ -79,9 +88,7 @@ export const parseInlineStyle = (inlineStyle = ''): Record<string, string> => {

export const parseUrl = (cssUrl = '') => {
if (!cssUrl) return

const match = cssUrl.match(URL_REGEX)

return match?.[1]
}

Expand Down Expand Up @@ -182,7 +189,12 @@ function transformVar (styleObj: Record<string, any>, varKeyPaths: Array<Array<s
function transformLineHeight (styleObj: Record<string, any>) {
let { lineHeight } = styleObj
if (typeof lineHeight === 'string' && PERCENT_REGEX.test(lineHeight)) {
lineHeight = (parseFloat(lineHeight) / 100) * (styleObj.fontSize || DEFAULT_FONT_SIZE)
const hasFontSize = hasOwn(styleObj, 'fontSize')
if (!hasFontSize) {
throwReactWarning('[Mpx runtime 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
}
}
Expand All @@ -194,7 +206,7 @@ interface TransformStyleConfig {
enableLineHeight?: boolean
}

export function useTransformStyle (styleObj: Record<string, any>, { enableVar, externalVarContext, enablePercent = true, enableLineHeight = true }: TransformStyleConfig) {
export function useTransformStyle (styleObj: Record<string, any> = {}, { enableVar, externalVarContext, enablePercent = true, enableLineHeight = true }: TransformStyleConfig) {
const varStyle: Record<string, any> = {}
const normalStyle: Record<string, any> = {}
let hasVarDec = false
Expand Down Expand Up @@ -342,9 +354,3 @@ export function splitProps<T extends Record<string, any>> (props: T) {
}
})
}

export const throwReactWarning = (message: string) => {
setTimeout(() => {
console.warn(message)
}, 0)
}

0 comments on commit 68f05ec

Please sign in to comment.