@mpxjs/webpack-plugin 2.10.22 → 2.10.24-test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/lib/loader.js +2 -0
  2. package/lib/platform/style/wx/index.js +395 -104
  3. package/lib/react/index.js +3 -1
  4. package/lib/react/processTemplate.js +3 -1
  5. package/lib/react/style-helper.js +6 -6
  6. package/lib/runtime/components/react/animationHooks/index.ts +7 -3
  7. package/lib/runtime/components/react/dist/animationHooks/index.d.ts +0 -2
  8. package/lib/runtime/components/react/dist/animationHooks/index.js +6 -1
  9. package/lib/runtime/components/react/dist/event.config.d.ts +2 -6
  10. package/lib/runtime/components/react/dist/event.config.js +28 -24
  11. package/lib/runtime/components/react/dist/getInnerListeners.d.ts +1 -1
  12. package/lib/runtime/components/react/dist/getInnerListeners.js +74 -56
  13. package/lib/runtime/components/react/dist/mpx-button.d.ts +1 -1
  14. package/lib/runtime/components/react/dist/mpx-button.jsx +16 -9
  15. package/lib/runtime/components/react/dist/mpx-camera.d.ts +0 -1
  16. package/lib/runtime/components/react/dist/mpx-camera.jsx +1 -2
  17. package/lib/runtime/components/react/dist/mpx-canvas/index.d.ts +0 -1
  18. package/lib/runtime/components/react/dist/mpx-canvas/index.jsx +1 -2
  19. package/lib/runtime/components/react/dist/mpx-canvas/utils.d.ts +1 -1
  20. package/lib/runtime/components/react/dist/mpx-checkbox-group.d.ts +0 -1
  21. package/lib/runtime/components/react/dist/mpx-checkbox-group.jsx +3 -4
  22. package/lib/runtime/components/react/dist/mpx-checkbox.d.ts +1 -1
  23. package/lib/runtime/components/react/dist/mpx-checkbox.jsx +8 -9
  24. package/lib/runtime/components/react/dist/mpx-form.d.ts +1 -1
  25. package/lib/runtime/components/react/dist/mpx-form.jsx +5 -5
  26. package/lib/runtime/components/react/dist/mpx-icon/index.d.ts +0 -1
  27. package/lib/runtime/components/react/dist/mpx-icon/index.jsx +2 -2
  28. package/lib/runtime/components/react/dist/mpx-image.d.ts +0 -1
  29. package/lib/runtime/components/react/dist/mpx-image.jsx +59 -43
  30. package/lib/runtime/components/react/dist/mpx-input.d.ts +0 -1
  31. package/lib/runtime/components/react/dist/mpx-input.jsx +2 -2
  32. package/lib/runtime/components/react/dist/mpx-label.d.ts +1 -1
  33. package/lib/runtime/components/react/dist/mpx-label.jsx +5 -6
  34. package/lib/runtime/components/react/dist/mpx-movable-area.d.ts +0 -1
  35. package/lib/runtime/components/react/dist/mpx-movable-area.jsx +3 -3
  36. package/lib/runtime/components/react/dist/mpx-movable-view.d.ts +1 -1
  37. package/lib/runtime/components/react/dist/mpx-movable-view.jsx +6 -6
  38. package/lib/runtime/components/react/dist/mpx-picker-view/index.d.ts +1 -1
  39. package/lib/runtime/components/react/dist/mpx-picker-view/index.jsx +5 -7
  40. package/lib/runtime/components/react/dist/mpx-picker-view-column/index.d.ts +0 -1
  41. package/lib/runtime/components/react/dist/mpx-picker-view-column/index.jsx +2 -2
  42. package/lib/runtime/components/react/dist/mpx-progress.d.ts +0 -1
  43. package/lib/runtime/components/react/dist/mpx-progress.jsx +1 -2
  44. package/lib/runtime/components/react/dist/mpx-radio-group.d.ts +0 -1
  45. package/lib/runtime/components/react/dist/mpx-radio-group.jsx +3 -4
  46. package/lib/runtime/components/react/dist/mpx-radio.d.ts +1 -1
  47. package/lib/runtime/components/react/dist/mpx-radio.jsx +8 -9
  48. package/lib/runtime/components/react/dist/mpx-rich-text/index.d.ts +0 -1
  49. package/lib/runtime/components/react/dist/mpx-rich-text/index.jsx +1 -2
  50. package/lib/runtime/components/react/dist/mpx-scroll-view.d.ts +1 -1
  51. package/lib/runtime/components/react/dist/mpx-scroll-view.jsx +6 -6
  52. package/lib/runtime/components/react/dist/mpx-simple-text.jsx +36 -31
  53. package/lib/runtime/components/react/dist/mpx-simple-view.d.ts +4 -2
  54. package/lib/runtime/components/react/dist/mpx-simple-view.jsx +24 -17
  55. package/lib/runtime/components/react/dist/mpx-slider.d.ts +0 -1
  56. package/lib/runtime/components/react/dist/mpx-slider.jsx +6 -6
  57. package/lib/runtime/components/react/dist/mpx-sticky-header.d.ts +1 -1
  58. package/lib/runtime/components/react/dist/mpx-sticky-header.jsx +5 -5
  59. package/lib/runtime/components/react/dist/mpx-sticky-section.d.ts +1 -1
  60. package/lib/runtime/components/react/dist/mpx-sticky-section.jsx +6 -6
  61. package/lib/runtime/components/react/dist/mpx-swiper-item.d.ts +1 -1
  62. package/lib/runtime/components/react/dist/mpx-swiper-item.jsx +5 -5
  63. package/lib/runtime/components/react/dist/mpx-swiper.d.ts +1 -1
  64. package/lib/runtime/components/react/dist/mpx-swiper.jsx +4 -7
  65. package/lib/runtime/components/react/dist/mpx-switch.d.ts +0 -1
  66. package/lib/runtime/components/react/dist/mpx-switch.jsx +1 -2
  67. package/lib/runtime/components/react/dist/mpx-text.d.ts +0 -1
  68. package/lib/runtime/components/react/dist/mpx-text.jsx +44 -40
  69. package/lib/runtime/components/react/dist/mpx-video.d.ts +0 -1
  70. package/lib/runtime/components/react/dist/mpx-video.jsx +4 -4
  71. package/lib/runtime/components/react/dist/mpx-view.d.ts +2 -1
  72. package/lib/runtime/components/react/dist/mpx-view.jsx +229 -128
  73. package/lib/runtime/components/react/dist/mpx-web-view.jsx +5 -1
  74. package/lib/runtime/components/react/dist/namedColorSet.d.ts +2 -0
  75. package/lib/runtime/components/react/dist/namedColorSet.js +149 -0
  76. package/lib/runtime/components/react/dist/utils.d.ts +73 -69
  77. package/lib/runtime/components/react/dist/utils.jsx +1295 -442
  78. package/lib/runtime/components/react/event.config.ts +32 -25
  79. package/lib/runtime/components/react/getInnerListeners.ts +84 -60
  80. package/lib/runtime/components/react/mpx-button.tsx +18 -16
  81. package/lib/runtime/components/react/mpx-camera.tsx +0 -3
  82. package/lib/runtime/components/react/mpx-canvas/index.tsx +1 -3
  83. package/lib/runtime/components/react/mpx-canvas/utils.tsx +3 -1
  84. package/lib/runtime/components/react/mpx-checkbox-group.tsx +2 -6
  85. package/lib/runtime/components/react/mpx-checkbox.tsx +9 -11
  86. package/lib/runtime/components/react/mpx-form.tsx +6 -6
  87. package/lib/runtime/components/react/mpx-icon/index.tsx +1 -3
  88. package/lib/runtime/components/react/mpx-image.tsx +65 -54
  89. package/lib/runtime/components/react/mpx-input.tsx +1 -3
  90. package/lib/runtime/components/react/mpx-label.tsx +6 -8
  91. package/lib/runtime/components/react/mpx-movable-area.tsx +3 -4
  92. package/lib/runtime/components/react/mpx-movable-view.tsx +7 -7
  93. package/lib/runtime/components/react/mpx-picker-view/index.tsx +6 -8
  94. package/lib/runtime/components/react/mpx-picker-view-column/index.tsx +2 -4
  95. package/lib/runtime/components/react/mpx-progress.tsx +0 -3
  96. package/lib/runtime/components/react/mpx-radio-group.tsx +2 -6
  97. package/lib/runtime/components/react/mpx-radio.tsx +9 -11
  98. package/lib/runtime/components/react/mpx-rich-text/index.tsx +0 -3
  99. package/lib/runtime/components/react/mpx-scroll-view.tsx +7 -7
  100. package/lib/runtime/components/react/mpx-simple-text.tsx +36 -38
  101. package/lib/runtime/components/react/mpx-simple-view.tsx +29 -17
  102. package/lib/runtime/components/react/mpx-slider.tsx +15 -10
  103. package/lib/runtime/components/react/mpx-sticky-header.tsx +6 -6
  104. package/lib/runtime/components/react/mpx-sticky-section.tsx +7 -7
  105. package/lib/runtime/components/react/mpx-swiper-item.tsx +6 -6
  106. package/lib/runtime/components/react/mpx-swiper.tsx +5 -8
  107. package/lib/runtime/components/react/mpx-switch.tsx +0 -3
  108. package/lib/runtime/components/react/mpx-text.tsx +46 -49
  109. package/lib/runtime/components/react/mpx-video.tsx +3 -5
  110. package/lib/runtime/components/react/mpx-view.tsx +250 -141
  111. package/lib/runtime/components/react/mpx-web-view.tsx +8 -3
  112. package/lib/runtime/components/react/namedColorSet.ts +150 -0
  113. package/lib/runtime/components/react/types/getInnerListeners.d.ts +21 -1
  114. package/lib/runtime/components/react/types/global.d.ts +1 -0
  115. package/lib/runtime/components/react/utils.tsx +1347 -539
  116. package/lib/runtime/i18n.wxs +15 -9
  117. package/lib/style-compiler/strip-conditional.js +19 -4
  118. package/lib/template-compiler/compiler.js +5 -1
  119. package/lib/utils/source-location.js +9 -13
  120. package/lib/web/index.js +3 -1
  121. package/lib/web/processTemplate.js +3 -1
  122. package/package.json +5 -4
  123. package/LICENSE +0 -433
@@ -1,46 +1,53 @@
1
1
  import { useEffect, useCallback, useMemo, useRef, isValidElement, useContext, useState, createElement } from 'react';
2
2
  import { Image } from 'react-native';
3
- import { isObject, isFunction, isNumber, hasOwn, diffAndCloneA, error, warn } from '@mpxjs/utils';
3
+ import { isObject, isFunction, isNumber, hasOwn, diffAndCloneA, shallowEqual, error, warn } from '@mpxjs/utils';
4
4
  import { VarContext, ScrollViewContext, RouteContext, TextPassThroughContext } from './context';
5
5
  import { ExpressionParser, parseFunc, ReplaceSource } from './parser';
6
6
  import { initialWindowMetrics } from 'react-native-safe-area-context';
7
7
  import { Gesture } from 'react-native-gesture-handler';
8
- export const TEXT_STYLE_MAP = {
8
+ export const percentRegExp = /^\s*-?\d+(\.\d+)?%\s*$/;
9
+ export const svgRegExp = /\.svg(?:[?#].*)?$/i;
10
+ export const hiddenStyle = {
11
+ opacity: 0
12
+ };
13
+ export const isIOS = __mpx_mode__ === 'ios';
14
+ export const isAndroid = __mpx_mode__ === 'android';
15
+ export const isHarmony = __mpx_mode__ === 'harmony';
16
+ export const extendObject = Object.assign;
17
+ const textStyleMap = {
9
18
  color: true,
10
19
  letterSpacing: true,
11
20
  lineHeight: true,
12
21
  includeFontPadding: true,
13
22
  writingDirection: true
14
23
  };
15
- export const PERCENT_REGEX = /^\s*-?\d+(\.\d+)?%\s*$/;
16
- export const URL_REGEX = /^\s*url\(["']?(.*?)["']?\)\s*$/;
17
- export const SVG_REGEXP = /\.svg(?:[?#].*)?$/i;
18
- export const BACKGROUND_STYLE_MAP = {
24
+ const urlRegExp = /^\s*url\(["']?(.*?)["']?\)\s*$/;
25
+ const linearGradientRegExp = /^\s*linear-gradient\(.*\)\s*$/;
26
+ const digitStartRegExp = /^\d/;
27
+ const varDecRegExp = /^--/;
28
+ const varUseRegExp = /var\(/;
29
+ const unoVarDecRegExp = /^--un-/;
30
+ const unoVarUseRegExp = /var\(--un-/;
31
+ const lengthValueRegExp = /^(-?(?:\d+(?:\.\d+)?|\.\d+)(?:rpx|px|%|vw|vh)?|hairlineWidth)$/;
32
+ // transform: 'rotateX(45deg) ...' 单段拆出 fn 名与括号内值
33
+ const transformFnRegExp = /([/\w]+)\((.+)\)/;
34
+ // boxShadow 子值识别 rpx 单位(仅 rpx 需要换算为 px,其它单位保留原样)
35
+ const rpxSuffixRegExp = /\d+rpx$/;
36
+ // font-family / font 简写解析时统一去掉单/双引号
37
+ const quoteCharRegExp = /["']/g;
38
+ const defaultBoxSizingStyle = {
39
+ boxSizing: 'content-box'
40
+ };
41
+ const backgroundStyleMap = {
19
42
  backgroundImage: true,
20
43
  backgroundSize: true,
21
44
  backgroundRepeat: true,
22
45
  backgroundPosition: true
23
46
  };
24
- export const TEXT_PROPS_MAP = {
47
+ const textPropsMap = {
25
48
  ellipsizeMode: true,
26
49
  numberOfLines: true
27
50
  };
28
- export const DEFAULT_FONT_SIZE = 16;
29
- export const HIDDEN_STYLE = {
30
- opacity: 0
31
- };
32
- export const DEFAULT_BOX_SIZING_STYLE = {
33
- boxSizing: 'content-box'
34
- };
35
- export const isIOS = __mpx_mode__ === 'ios';
36
- export const isAndroid = __mpx_mode__ === 'android';
37
- export const isHarmony = __mpx_mode__ === 'harmony';
38
- const varDecRegExp = /^--/;
39
- const varUseRegExp = /var\(/;
40
- const unoVarDecRegExp = /^--un-/;
41
- const unoVarUseRegExp = /var\(--un-/;
42
- const calcUseRegExp = /calc\(/;
43
- const envUseRegExp = /env\(/;
44
51
  const boxSizingAffectingStyleMap = {
45
52
  padding: true,
46
53
  paddingTop: true,
@@ -51,7 +58,139 @@ const boxSizingAffectingStyleMap = {
51
58
  borderTopWidth: true,
52
59
  borderRightWidth: true,
53
60
  borderBottomWidth: true,
54
- borderLeftWidth: true
61
+ borderLeftWidth: true,
62
+ border: true,
63
+ borderTop: true,
64
+ borderRight: true,
65
+ borderBottom: true,
66
+ borderLeft: true
67
+ };
68
+ const runtimeAbbreviationMap = {
69
+ margin: ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'],
70
+ padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],
71
+ borderRadius: ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius'],
72
+ borderWidth: ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'],
73
+ borderColor: ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'],
74
+ border: ['borderWidth', 'borderStyle', 'borderColor'],
75
+ // RN 不支持单边 border-*-style,统一展开到 borderStyle
76
+ // 实测 RN 上当 borderStyle 不为 solid 时单边 border-*-color 不生效,
77
+ // 这里把单边 color 也统一展开到 borderColor 规避(width 不能这样做,否则会覆盖其它三边)
78
+ borderTop: ['borderTopWidth', 'borderStyle', 'borderColor'],
79
+ borderRight: ['borderRightWidth', 'borderStyle', 'borderColor'],
80
+ borderBottom: ['borderBottomWidth', 'borderStyle', 'borderColor'],
81
+ borderLeft: ['borderLeftWidth', 'borderStyle', 'borderColor'],
82
+ flexFlow: ['flexDirection', 'flexWrap'],
83
+ textShadow: ['textShadowOffset.width', 'textShadowOffset.height', 'textShadowRadius', 'textShadowColor'],
84
+ textDecoration: ['textDecorationLine', 'textDecorationStyle', 'textDecorationColor'],
85
+ // gap:CSS 2 槽位(row-gap / column-gap),单值复制行列。RN 原生支持但要求 number。
86
+ // 单值串在 __getStyle 的 transformStyleObj / 编译期 formatValue 已被 __formatValue 换算为 number;
87
+ // 真正以字符串形态进 transformShorthand 的是多值串(如 '10px 20px')—— unitRegExp 不命中、原样透传。
88
+ // 因此进入 runtimeForceExpandCompositeMap,避免「单值透传」捷径放过这类多值串残留。
89
+ // 百分比(`gap: 50%` / `gap: 10px 50%`)由 transformShorthand 写回阶段就地 resolvePercent 落成 number
90
+ gap: ['rowGap', 'columnGap'],
91
+ // inset:4 槽位等价 margin 四值语法;RN inset 长属性非稳定,单值也必须展开到 top/right/bottom/left
92
+ inset: ['top', 'right', 'bottom', 'left'],
93
+ // outline: <outline-width> || <outline-style> || <outline-color>,顺序不敏感
94
+ outline: ['outlineWidth', 'outlineStyle', 'outlineColor']
95
+ };
96
+ const runtimeCompositeStyleMap = {
97
+ margin: true,
98
+ padding: true,
99
+ borderRadius: true,
100
+ borderWidth: true,
101
+ borderColor: true,
102
+ gap: true,
103
+ inset: true
104
+ };
105
+ // 即使单值也必须展开(不走「单值透传」捷径):
106
+ // - inset:RN inset 长属性不稳定,单值透传会留下不可靠的 inset key
107
+ // - gap:RN gap / rowGap / columnGap 严格要求 number;单值串虽已在 __getStyle 阶段被 __formatValue 换算,
108
+ // 但多值串(如 '10px 20px')会原样透传到这里,需展开后逐 token 再过 __formatValue 才能落成 number;
109
+ // `%` 在写回阶段由 transformShorthand 调 resolvePercent 落成 number(rowGap 基 parentHeight、columnGap 基 parentWidth)
110
+ const runtimeForceExpandCompositeMap = {
111
+ inset: true,
112
+ gap: true
113
+ };
114
+ const runtimeUnorderedAbbreviationMap = {
115
+ border: true,
116
+ borderTop: true,
117
+ borderRight: true,
118
+ borderBottom: true,
119
+ borderLeft: true,
120
+ flexFlow: true,
121
+ textShadow: true,
122
+ textDecoration: true,
123
+ // outline 与 border 简写共享同一套缺省值处理
124
+ outline: true
125
+ };
126
+ const runtimeBorderLikeShorthandMap = {
127
+ border: true,
128
+ borderTop: true,
129
+ borderRight: true,
130
+ borderBottom: true,
131
+ borderLeft: true,
132
+ outline: true
133
+ };
134
+ // CSS border-width: medium 的实测值(各主流浏览器一致取 3px)
135
+ // 与编译期 wx/index.js 同名常量保持一致;调整需两侧一起改
136
+ const BORDER_MEDIUM_WIDTH = 3;
137
+ // 运行时简写槽位缺省值表(与编译期 ShorthandDefaultMap 镜像,仅 CSS quote 形式不同)
138
+ // 值即槽位缺省时追加的补齐值;borderColor / textShadowRadius 因 RN 有内置缺省值不补,不进此表
139
+ // none 清除语义统一保留到 useTransformStyle 末尾处理
140
+ const runtimeShorthandDefaultMap = {
141
+ border: { borderWidth: BORDER_MEDIUM_WIDTH, borderStyle: 'none' },
142
+ borderTop: { borderTopWidth: BORDER_MEDIUM_WIDTH, borderStyle: 'none' },
143
+ borderRight: { borderRightWidth: BORDER_MEDIUM_WIDTH, borderStyle: 'none' },
144
+ borderBottom: { borderBottomWidth: BORDER_MEDIUM_WIDTH, borderStyle: 'none' },
145
+ borderLeft: { borderLeftWidth: BORDER_MEDIUM_WIDTH, borderStyle: 'none' },
146
+ // outline 与 border 缺省值完全对齐:缺 width → BORDER_MEDIUM_WIDTH;
147
+ // 缺 style → outlineStyle: none,末尾统一转换为 outlineWidth: 0
148
+ outline: { outlineWidth: BORDER_MEDIUM_WIDTH, outlineStyle: 'none' },
149
+ textShadow: { textShadowColor: '#000' }
150
+ // textDecoration / flexFlow 暂不配置,与 RN 默认一致
151
+ };
152
+ const borderStyleMap = {
153
+ // RN 实测仅支持 solid/dotted/dashed;none 作为 CSS 合法值保留到末尾统一转换为 borderWidth: 0
154
+ solid: true,
155
+ dotted: true,
156
+ dashed: true,
157
+ none: true
158
+ };
159
+ const textDecorationLineMap = {
160
+ none: true,
161
+ underline: true,
162
+ 'line-through': true
163
+ };
164
+ const textDecorationStyleMap = {
165
+ solid: true,
166
+ double: true,
167
+ dotted: true,
168
+ dashed: true
169
+ };
170
+ // font 简写 <font-weight> 槽位允许的关键字 / 数值(CSS 子集,与 RN 支持一致)
171
+ const fontWeightMap = {
172
+ bold: true,
173
+ normal: true,
174
+ 100: true,
175
+ 200: true,
176
+ 300: true,
177
+ 400: true,
178
+ 500: true,
179
+ 600: true,
180
+ 700: true,
181
+ 800: true,
182
+ 900: true
183
+ };
184
+ const flexDirectionMap = {
185
+ row: true,
186
+ 'row-reverse': true,
187
+ column: true,
188
+ 'column-reverse': true
189
+ };
190
+ const flexWrapMap = {
191
+ wrap: true,
192
+ nowrap: true,
193
+ 'wrap-reverse': true
55
194
  };
56
195
  const safeAreaInsetMap = {
57
196
  'safe-area-inset-top': 'top',
@@ -59,30 +198,42 @@ const safeAreaInsetMap = {
59
198
  'safe-area-inset-bottom': 'bottom',
60
199
  'safe-area-inset-left': 'left'
61
200
  };
62
- export const extendObject = Object.assign;
63
- export function getDefaultAllowFontScaling() {
64
- return global.__mpx?.config?.rnConfig?.allowFontScaling ?? false;
65
- }
66
- export function transformBoxSizing(style = {}, hasBoxSizingAffectingStyle = false) {
67
- if (hasBoxSizingAffectingStyle && style.boxSizing === undefined) {
68
- style.boxSizing = global.__mpx?.config?.rnConfig?.defaultBoxSizing ?? DEFAULT_BOX_SIZING_STYLE.boxSizing;
69
- }
70
- return style;
71
- }
72
- export function isBoxSizingAffectingStyle(key) {
73
- return hasOwn(boxSizingAffectingStyleMap, key);
74
- }
75
- function isTextStyle(key) {
76
- return hasOwn(TEXT_STYLE_MAP, key) || key.startsWith('font') || key.startsWith('text');
77
- }
78
- function getSafeAreaInset(name, navigation) {
79
- const insets = extendObject({}, initialWindowMetrics?.insets, navigation?.insets);
80
- return insets[safeAreaInsetMap[name]];
81
- }
82
- export function useNavigation() {
83
- const { navigation } = useContext(RouteContext) || {};
84
- return navigation;
85
- }
201
+ const radiusPercentRule = {
202
+ borderTopLeftRadius: 'width',
203
+ borderBottomLeftRadius: 'width',
204
+ borderBottomRightRadius: 'width',
205
+ borderTopRightRadius: 'width',
206
+ borderRadius: 'width'
207
+ };
208
+ const selfPercentRule = extendObject({
209
+ translateX: 'width',
210
+ translateY: 'height'
211
+ }, radiusPercentRule);
212
+ const parentHeightPercentRule = {
213
+ height: true,
214
+ minHeight: true,
215
+ maxHeight: true,
216
+ top: true,
217
+ bottom: true,
218
+ // row-gap 百分比按 CSS 规范基于容器内容区高度;columnGap 不入此表,落默认 parentWidth 分支
219
+ rowGap: true
220
+ };
221
+ const bgRepeatMap = {
222
+ repeat: true,
223
+ 'repeat-x': true,
224
+ 'repeat-y': true,
225
+ 'no-repeat': true
226
+ };
227
+ const bgPositionMap = {
228
+ left: true,
229
+ right: true,
230
+ top: true,
231
+ bottom: true,
232
+ center: true
233
+ };
234
+ // ============================================================
235
+ // generic utility functions
236
+ // ============================================================
86
237
  export function omit(obj, fields) {
87
238
  const shallowCopy = extendObject({}, obj);
88
239
  for (let i = 0; i < fields.length; i += 1) {
@@ -91,35 +242,18 @@ export function omit(obj, fields) {
91
242
  }
92
243
  return shallowCopy;
93
244
  }
94
- /**
95
- * 用法等同于 useEffect,但是会忽略首次执行,只在依赖更新时执行
96
- */
97
- export const useUpdateEffect = (effect, deps) => {
98
- const isMounted = useRef(false);
99
- // for react-refresh
100
- useEffect(() => {
101
- return () => {
102
- isMounted.current = false;
103
- };
104
- }, []);
105
- useEffect(() => {
106
- if (!isMounted.current) {
107
- isMounted.current = true;
108
- }
109
- else {
110
- return effect();
111
- }
112
- }, deps);
113
- };
114
245
  export const parseUrl = (cssUrl = '') => {
115
246
  if (!cssUrl)
116
247
  return;
117
- const match = cssUrl.match(URL_REGEX);
248
+ const match = cssUrl.match(urlRegExp);
118
249
  return match?.[1];
119
250
  };
120
251
  export const getRestProps = (transferProps = {}, originProps = {}, deletePropsKey = []) => {
121
252
  return extendObject({}, transferProps, omit(originProps, deletePropsKey));
122
253
  };
254
+ export function getDefaultAllowFontScaling() {
255
+ return global.__mpx?.config?.rnConfig?.allowFontScaling ?? false;
256
+ }
123
257
  export function isText(ele) {
124
258
  if (isValidElement(ele)) {
125
259
  const displayName = ele.type?.displayName;
@@ -135,86 +269,148 @@ export function isStringChildren(children) {
135
269
  return false;
136
270
  return children.every((child) => typeof child === 'string');
137
271
  }
138
- export function groupBy(obj, callback, group = {}) {
139
- Object.entries(obj).forEach(([key, val]) => {
140
- const groupKey = callback(key, val);
141
- group[groupKey] = group[groupKey] || {};
142
- group[groupKey][key] = val;
143
- });
144
- return group;
272
+ // 多value解析
273
+ export function parseValues(str, char = ' ') {
274
+ let stack = 0;
275
+ let temp = '';
276
+ const result = [];
277
+ for (let i = 0; i < str.length; i++) {
278
+ if (str[i] === '(') {
279
+ stack++;
280
+ }
281
+ else if (str[i] === ')') {
282
+ stack--;
283
+ }
284
+ // 非括号内 或者 非分隔字符且非空
285
+ if (stack !== 0 || str[i] !== char) {
286
+ temp += str[i];
287
+ }
288
+ if ((stack === 0 && str[i] === char) || i === str.length - 1) {
289
+ result.push(temp.trim());
290
+ temp = '';
291
+ }
292
+ }
293
+ return result;
294
+ }
295
+ export const debounce = (func, delay) => {
296
+ let timer;
297
+ const wrapper = (...args) => {
298
+ timer && clearTimeout(timer);
299
+ timer = setTimeout(() => {
300
+ func(...args);
301
+ }, delay);
302
+ };
303
+ wrapper.clear = () => {
304
+ timer && clearTimeout(timer);
305
+ timer = null;
306
+ };
307
+ return wrapper;
308
+ };
309
+ // ============================================================
310
+ // style classification & splitting
311
+ // ============================================================
312
+ function isTextStyle(key) {
313
+ return hasOwn(textStyleMap, key) || key.startsWith('font') || key.startsWith('text');
314
+ }
315
+ function isColorValue(token) {
316
+ if (token.startsWith('#') || token.startsWith('rgb(') || token.startsWith('rgba(') || token.startsWith('hsl(') || token.startsWith('hsla('))
317
+ return true;
318
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
319
+ return hasOwn(require('./namedColorSet').default, token.toLowerCase());
320
+ }
321
+ function isLengthValue(token) {
322
+ return lengthValueRegExp.test(token);
323
+ }
324
+ export function isBoxSizingAffectingStyle(key) {
325
+ return hasOwn(boxSizingAffectingStyleMap, key);
326
+ }
327
+ // 仅在调用侧已确认存在 padding / border 等 box-sizing 影响项时调用:
328
+ // 给样式补默认 boxSizing(用户未显式设置时)。是否需要进入由调用侧决定,
329
+ // useTransformStyle / mpx-simple-view / mpx-simple-text 都按 hasBoxSizingAffectingStyle 短路。
330
+ export function transformBoxSizing(style = {}) {
331
+ if (style.boxSizing === undefined) {
332
+ style.boxSizing = global.__mpx?.config?.rnConfig?.defaultBoxSizing ?? defaultBoxSizingStyle.boxSizing;
333
+ }
145
334
  }
146
335
  export function splitStyle(styleObj, sideEffect) {
147
- return groupBy(styleObj, (key, val) => {
336
+ const keys = Object.keys(styleObj);
337
+ let textStyle;
338
+ let backgroundStyle;
339
+ let innerStyle;
340
+ let firstSpecialIdx = -1;
341
+ for (let i = 0; i < keys.length; i++) {
342
+ const key = keys[i];
343
+ const val = styleObj[key];
148
344
  sideEffect && sideEffect(key, val);
149
345
  if (isTextStyle(key)) {
150
- return 'textStyle';
346
+ if (firstSpecialIdx < 0)
347
+ firstSpecialIdx = i;
348
+ textStyle = textStyle || {};
349
+ textStyle[key] = val;
151
350
  }
152
- else if (hasOwn(BACKGROUND_STYLE_MAP, key)) {
153
- return 'backgroundStyle';
351
+ else if (hasOwn(backgroundStyleMap, key)) {
352
+ if (firstSpecialIdx < 0)
353
+ firstSpecialIdx = i;
354
+ backgroundStyle = backgroundStyle || {};
355
+ backgroundStyle[key] = val;
154
356
  }
155
- else {
156
- return 'innerStyle';
357
+ else if (firstSpecialIdx >= 0) {
358
+ innerStyle = innerStyle || {};
359
+ innerStyle[key] = val;
157
360
  }
158
- });
159
- }
160
- const radiusPercentRule = {
161
- borderTopLeftRadius: 'width',
162
- borderBottomLeftRadius: 'width',
163
- borderBottomRightRadius: 'width',
164
- borderTopRightRadius: 'width',
165
- borderRadius: 'width'
166
- };
167
- const selfPercentRule = extendObject({
168
- translateX: 'width',
169
- translateY: 'height'
170
- }, radiusPercentRule);
171
- const parentHeightPercentRule = {
172
- height: true,
173
- minHeight: true,
174
- maxHeight: true,
175
- top: true,
176
- bottom: true
177
- };
178
- function resolvePercent(value, key, percentConfig) {
179
- if (!(typeof value === 'string' && PERCENT_REGEX.test(value)))
180
- return value;
181
- let base;
182
- let reason;
183
- if (key === 'fontSize') {
184
- base = percentConfig.parentFontSize;
185
- reason = 'parent-font-size';
186
361
  }
187
- else if (key === 'lineHeight') {
188
- base = resolvePercent(percentConfig.fontSize, 'fontSize', percentConfig);
189
- reason = 'font-size';
190
- }
191
- else if (selfPercentRule[key]) {
192
- base = percentConfig[selfPercentRule[key]];
193
- reason = selfPercentRule[key];
194
- }
195
- else if (parentHeightPercentRule[key]) {
196
- base = percentConfig.parentHeight;
197
- reason = 'parent-height';
198
- }
199
- else {
200
- base = percentConfig.parentWidth;
201
- reason = 'parent-width';
362
+ if (firstSpecialIdx < 0)
363
+ return { innerStyle: styleObj };
364
+ if (firstSpecialIdx > 0) {
365
+ innerStyle = innerStyle || {};
366
+ for (let i = 0; i < firstSpecialIdx; i++) {
367
+ const key = keys[i];
368
+ innerStyle[key] = styleObj[key];
369
+ }
202
370
  }
203
- if (typeof base !== 'number') {
204
- error(`[${key}] can not contain % unit unless you set [${reason}] with a number for the percent calculation.`);
205
- return value;
371
+ return { textStyle, backgroundStyle, innerStyle };
372
+ }
373
+ export function splitProps(props) {
374
+ const keys = Object.keys(props);
375
+ let textProps;
376
+ let innerProps;
377
+ let firstTextIdx = -1;
378
+ for (let i = 0; i < keys.length; i++) {
379
+ const key = keys[i];
380
+ if (hasOwn(textPropsMap, key)) {
381
+ if (firstTextIdx < 0)
382
+ firstTextIdx = i;
383
+ textProps = textProps || {};
384
+ textProps[key] = props[key];
385
+ }
386
+ else if (firstTextIdx >= 0) {
387
+ innerProps = innerProps || {};
388
+ innerProps[key] = props[key];
389
+ }
206
390
  }
207
- else {
208
- return parseFloat(value) / 100 * base;
391
+ if (firstTextIdx < 0)
392
+ return { innerProps: props };
393
+ if (firstTextIdx > 0) {
394
+ innerProps = innerProps || {};
395
+ for (let i = 0; i < firstTextIdx; i++) {
396
+ const key = keys[i];
397
+ innerProps[key] = props[key];
398
+ }
209
399
  }
400
+ return { textProps, innerProps };
210
401
  }
211
- function transformPercent(styleObj, percentKeyPaths, percentConfig) {
212
- percentKeyPaths.forEach((percentKeyPath) => {
213
- setStyle(styleObj, percentKeyPath, ({ target, key, value }) => {
214
- target[key] = resolvePercent(value, key, percentConfig);
215
- });
216
- });
402
+ export function pickStyle(styleObj = {}, pickedKeys, callback) {
403
+ return pickedKeys.reduce((acc, key) => {
404
+ if (key in styleObj) {
405
+ acc[key] = callback ? callback(key, styleObj[key]) : styleObj[key];
406
+ }
407
+ return acc;
408
+ }, {});
217
409
  }
410
+ // ============================================================
411
+ // style transform pipeline
412
+ // ============================================================
413
+ // --- var ---
218
414
  function resolveVar(input, varContext) {
219
415
  const parsed = parseFunc(input, 'var');
220
416
  const replaced = new ReplaceSource(input);
@@ -253,7 +449,9 @@ function transformVar(styleObj, varKeyPaths, varContext, visitOther) {
253
449
  });
254
450
  });
255
451
  }
452
+ // --- env ---
256
453
  function transformEnv(styleObj, envKeyPaths, navigation) {
454
+ const insets = extendObject({}, initialWindowMetrics?.insets, navigation?.insets);
257
455
  envKeyPaths.forEach((envKeyPath) => {
258
456
  setStyle(styleObj, envKeyPath, ({ target, key, value }) => {
259
457
  const parsed = parseFunc(value, 'env');
@@ -261,13 +459,56 @@ function transformEnv(styleObj, envKeyPaths, navigation) {
261
459
  parsed.forEach(({ start, end, args }) => {
262
460
  const name = args[0];
263
461
  const fallback = args[1] || '';
264
- const value = '' + (getSafeAreaInset(name, navigation) ?? global.__formatValue(fallback));
265
- replaced.replace(start, end - 1, value);
462
+ const inset = insets[safeAreaInsetMap[name]];
463
+ const next = '' + (inset ?? global.__formatValue(fallback));
464
+ replaced.replace(start, end - 1, next);
266
465
  });
267
466
  target[key] = global.__formatValue(replaced.source());
268
467
  });
269
468
  });
270
469
  }
470
+ // --- percent ---
471
+ function resolvePercent(value, key, percentConfig) {
472
+ if (!(typeof value === 'string' && percentRegExp.test(value)))
473
+ return value;
474
+ let base;
475
+ let reason;
476
+ if (key === 'fontSize') {
477
+ base = percentConfig.parentFontSize;
478
+ reason = 'parent-font-size';
479
+ }
480
+ else if (key === 'lineHeight') {
481
+ base = resolvePercent(percentConfig.fontSize, 'fontSize', percentConfig);
482
+ reason = 'font-size';
483
+ }
484
+ else if (selfPercentRule[key]) {
485
+ base = percentConfig[selfPercentRule[key]];
486
+ reason = selfPercentRule[key];
487
+ }
488
+ else if (parentHeightPercentRule[key]) {
489
+ base = percentConfig.parentHeight;
490
+ reason = 'parent-height';
491
+ }
492
+ else {
493
+ base = percentConfig.parentWidth;
494
+ reason = 'parent-width';
495
+ }
496
+ if (typeof base !== 'number') {
497
+ error(`[${key}] can not contain % unit unless you set [${reason}] with a number for the percent calculation.`);
498
+ return value;
499
+ }
500
+ else {
501
+ return parseFloat(value) / 100 * base;
502
+ }
503
+ }
504
+ function transformPercent(styleObj, percentKeyPaths, percentConfig) {
505
+ percentKeyPaths.forEach((percentKeyPath) => {
506
+ setStyle(styleObj, percentKeyPath, ({ target, key, value }) => {
507
+ target[key] = resolvePercent(value, key, percentConfig);
508
+ });
509
+ });
510
+ }
511
+ // --- calc ---
271
512
  function transformCalc(styleObj, calcKeyPaths, formatter) {
272
513
  calcKeyPaths.forEach((calcKeyPath) => {
273
514
  setStyle(styleObj, calcKeyPath, ({ target, key, value }) => {
@@ -289,6 +530,7 @@ function transformCalc(styleObj, calcKeyPaths, formatter) {
289
530
  });
290
531
  });
291
532
  }
533
+ // --- misc ---
292
534
  function transformStringify(styleObj) {
293
535
  if (isNumber(styleObj.fontWeight)) {
294
536
  styleObj.fontWeight = '' + styleObj.fontWeight;
@@ -298,35 +540,7 @@ function transformStringify(styleObj) {
298
540
  styleObj.transformOrigin = '' + styleObj.transformOrigin;
299
541
  }
300
542
  }
301
- function transformPosition(styleObj, meta) {
302
- if (styleObj.position === 'fixed') {
303
- styleObj.position = 'absolute';
304
- meta.hasPositionFixed = true;
305
- }
306
- }
307
- // 多value解析
308
- export function parseValues(str, char = ' ') {
309
- let stack = 0;
310
- let temp = '';
311
- const result = [];
312
- for (let i = 0; i < str.length; i++) {
313
- if (str[i] === '(') {
314
- stack++;
315
- }
316
- else if (str[i] === ')') {
317
- stack--;
318
- }
319
- // 非括号内 或者 非分隔字符且非空
320
- if (stack !== 0 || str[i] !== char) {
321
- temp += str[i];
322
- }
323
- if ((stack === 0 && str[i] === char) || i === str.length - 1) {
324
- result.push(temp.trim());
325
- temp = '';
326
- }
327
- }
328
- return result;
329
- }
543
+ // --- transform / shadow ---
330
544
  // parse string transform, eg: transform: 'rotateX(45deg) rotateZ(0.785398rad)'
331
545
  function parseTransform(transformStr) {
332
546
  const values = parseValues(transformStr);
@@ -334,51 +548,109 @@ function parseTransform(transformStr) {
334
548
  // Todo 1 transform 排序不一致时,transform动画会闪烁,故这里同样的排序输出 transform
335
549
  // values.sort()
336
550
  const transform = [];
551
+ // 与编译期 wx/index.js 同 transform formatter 口径对齐:
552
+ // 「整条 transform 声明」绝不会因单个子项失败而丢弃,被丢的只有那一个子项,其余 transform 项仍输出。
553
+ // 因此本 forEach 内所有「丢这一项」的提示一律用 warn(编译期同名分支注释:「仅丢这一 transform 项,其它项仍输出,按规范使用 warn」)。
337
554
  values.forEach(item => {
338
- const match = item.match(/([/\w]+)\((.+)\)/);
339
- if (match && match.length >= 3) {
340
- let key = match[1];
341
- const val = match[2];
342
- switch (key) {
343
- case 'translateX':
344
- case 'translateY':
345
- case 'scaleX':
346
- case 'scaleY':
347
- case 'rotateX':
348
- case 'rotateY':
349
- case 'rotateZ':
350
- case 'rotate':
351
- case 'skewX':
352
- case 'skewY':
353
- case 'perspective':
354
- // rotate 处理成 rotateZ
355
- key = key === 'rotate' ? 'rotateZ' : key;
356
- // 单个值处理
357
- transform.push({ [key]: global.__formatValue(val) });
555
+ const match = item.match(transformFnRegExp);
556
+ if (!match || match.length < 3) {
557
+ warn(`Transform value [${item}] is not a valid fn(value) form, dropped.`);
558
+ return;
559
+ }
560
+ let key = match[1];
561
+ const val = match[2];
562
+ switch (key) {
563
+ case 'rotateX':
564
+ case 'rotateY':
565
+ case 'rotateZ':
566
+ case 'rotate':
567
+ case 'skewX':
568
+ case 'skewY':
569
+ key = key === 'rotate' ? 'rotateZ' : key;
570
+ transform.push({ [key]: val });
571
+ break;
572
+ case 'translateX':
573
+ case 'translateY':
574
+ case 'scaleX':
575
+ case 'scaleY':
576
+ case 'perspective':
577
+ transform.push({ [key]: global.__formatValue(val) });
578
+ break;
579
+ case 'matrix': {
580
+ // parseValues 内部已 trim
581
+ const matrixValues = parseValues(val, ',').map(v => +v);
582
+ if (matrixValues.length === 6) {
583
+ const [a, b, c, d, tx, ty] = matrixValues;
584
+ transform.push({ matrix: [a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1] });
585
+ }
586
+ else {
587
+ warn(`Transform matrix only supports 6 values in React Native, got ${matrixValues.length}`);
588
+ }
589
+ break;
590
+ }
591
+ case 'matrix3d': {
592
+ // parseValues 内部已 trim
593
+ const matrixValues = parseValues(val, ',').map(v => +v);
594
+ if (matrixValues.length === 16) {
595
+ transform.push({ matrix: matrixValues });
596
+ }
597
+ else {
598
+ warn(`Transform matrix only supports 16 values in React Native, got ${matrixValues.length}`);
599
+ }
600
+ break;
601
+ }
602
+ case 'translate':
603
+ case 'scale':
604
+ case 'skew':
605
+ case 'translate3d': // x y 支持 z不支持
606
+ case 'scale3d': // x y 支持 z不支持
607
+ {
608
+ // 2 个以上的值处理
609
+ key = key.replace('3d', '');
610
+ const vals = parseValues(val, ',').splice(0, 3);
611
+ // scale(.5) === scaleX(.5) scaleY(.5)
612
+ if (vals.length === 1 && key === 'scale') {
613
+ vals.push(vals[0]);
614
+ }
615
+ const xyz = ['X', 'Y', 'Z'];
616
+ vals.forEach((v, index) => {
617
+ if (key !== 'rotate' && index > 1) {
618
+ warn(`Transform [${key}Z] is not supported in React Native, dropped.`);
619
+ return;
620
+ }
621
+ // parseValues 内部已 trim
622
+ transform.push({ [`${key}${xyz[index] || ''}`]: global.__formatValue(v) });
623
+ });
358
624
  break;
359
- case 'matrix':
360
- transform.push({ [key]: parseValues(val, ',').map(val => +val) });
625
+ }
626
+ case 'rotate3d': {
627
+ const parts = parseValues(val, ',');
628
+ if (parts.length !== 4) {
629
+ warn(`Transform rotate3d only supports 4 values, got ${parts.length}`);
361
630
  break;
362
- case 'translate':
363
- case 'scale':
364
- case 'skew':
365
- case 'translate3d': // x y 支持 z不支持
366
- case 'scale3d': // x y 支持 z不支持
367
- {
368
- // 2 个以上的值处理
369
- key = key.replace('3d', '');
370
- const vals = parseValues(val, ',').splice(0, 3);
371
- // scale(.5) === scaleX(.5) scaleY(.5)
372
- if (vals.length === 1 && key === 'scale') {
373
- vals.push(vals[0]);
374
- }
375
- const xyz = ['X', 'Y', 'Z'];
376
- transform.push(...vals.map((v, index) => {
377
- return { [`${key}${xyz[index] || ''}`]: global.__formatValue(v.trim()) };
378
- }));
379
- break;
380
- }
631
+ }
632
+ // parseValues 内部已 trim
633
+ const x = +parts[0];
634
+ const y = +parts[1];
635
+ const z = +parts[2];
636
+ const angle = parts[3];
637
+ if (x && !y && !z)
638
+ transform.push({ rotateX: angle });
639
+ else if (!x && y && !z)
640
+ transform.push({ rotateY: angle });
641
+ else if (!x && !y && z)
642
+ transform.push({ rotateZ: angle });
643
+ else
644
+ warn(`Transform rotate3d(${val}) only supports single-axis vector (1,0,0) / (0,1,0) / (0,0,1) in React Native, dropped.`);
645
+ break;
381
646
  }
647
+ case 'translateZ':
648
+ case 'scaleZ':
649
+ // RN 不支持 Z 轴 translate/scale,丢该子项;编译期同分支用 warn(unsupportedPropError isError=false)
650
+ warn(`Transform [${key}] is not supported in React Native, dropped.`);
651
+ break;
652
+ default:
653
+ warn(`Transform fn [${key}] is not supported in React Native, dropped.`);
382
654
  }
383
655
  });
384
656
  return transform;
@@ -389,14 +661,522 @@ function transformTransform(style) {
389
661
  return;
390
662
  style.transform = parseTransform(style.transform);
391
663
  }
392
- function transformBoxShadow(styleObj) {
393
- if (!styleObj.boxShadow)
394
- return;
395
- styleObj.boxShadow = parseValues(styleObj.boxShadow).reduce((res, i, idx) => {
396
- return `${res}${idx === 0 ? '' : ' '}${global.__formatValue(i)}`;
397
- }, '');
664
+ function transformBoxShadow(styleObj) {
665
+ if (!styleObj.boxShadow)
666
+ return;
667
+ styleObj.boxShadow = parseValues(styleObj.boxShadow).reduce((res, i, idx) => {
668
+ let formatted;
669
+ // 需要保留 px 关键字,这里仅处理 rpx 转 px
670
+ if (rpxSuffixRegExp.test(i)) {
671
+ formatted = global.__formatValue(i) + 'px';
672
+ }
673
+ else {
674
+ formatted = i;
675
+ }
676
+ return `${res}${idx === 0 ? '' : ' '}${formatted}`;
677
+ }, '');
678
+ }
679
+ // --- shorthand ---
680
+ function expandCompositeValues(values) {
681
+ const v = values.slice(0, 4);
682
+ switch (v.length) {
683
+ case 1:
684
+ return [v[0], v[0], v[0], v[0]];
685
+ case 2:
686
+ return [v[0], v[1], v[0], v[1]];
687
+ case 3:
688
+ return [v[0], v[1], v[2], v[1]];
689
+ default:
690
+ return v;
691
+ }
692
+ }
693
+ function expandAbbreviation(values, props) {
694
+ const result = [];
695
+ for (let i = 0; i < props.length && i < values.length; i++) {
696
+ pushExpandedPair(result, props[i], global.__formatValue(values[i]));
697
+ }
698
+ return result;
699
+ }
700
+ function pushExpandedPair(result, prop, value) {
701
+ if (prop.includes('.')) {
702
+ const [main, sub] = prop.split('.');
703
+ let entry = result.find(item => item[0] === main);
704
+ if (!entry) {
705
+ entry = [main, {}];
706
+ result.push(entry);
707
+ }
708
+ entry[1][sub] = value;
709
+ }
710
+ else {
711
+ result.push([prop, value]);
712
+ }
713
+ }
714
+ function getUnorderedShorthandProp(key, token, used) {
715
+ const props = runtimeAbbreviationMap[key];
716
+ for (const prop of props) {
717
+ if (used[prop])
718
+ continue;
719
+ if (matchRuntimeShorthandProp(prop, token))
720
+ return prop;
721
+ }
722
+ }
723
+ function matchRuntimeShorthandProp(prop, token) {
724
+ if (prop === 'textShadowOffset.width' || prop === 'textShadowOffset.height' || prop === 'textShadowRadius')
725
+ return isLengthValue(token);
726
+ if (prop === 'textShadowColor')
727
+ return isColorValue(token);
728
+ if (prop.endsWith('Width'))
729
+ return isLengthValue(token);
730
+ if (prop === 'textDecorationStyle')
731
+ return hasOwn(textDecorationStyleMap, token);
732
+ if (prop.endsWith('Style'))
733
+ return hasOwn(borderStyleMap, token);
734
+ if (prop.endsWith('Color'))
735
+ return isColorValue(token);
736
+ if (prop === 'flexDirection')
737
+ return hasOwn(flexDirectionMap, token);
738
+ if (prop === 'flexWrap')
739
+ return hasOwn(flexWrapMap, token);
740
+ return false;
741
+ }
742
+ // 通用补齐:扫描完所有 token 后,将 runtimeShorthandDefaultMap 中未被占用(不在 used)的槽位追加到 pairs
743
+ // used 即主循环的占用记录,key 是完整目标 prop 名(含 textShadowOffset.width 这类 dot 路径)
744
+ function applyRuntimeShorthandDefaults(key, pairs, used) {
745
+ const defaults = runtimeShorthandDefaultMap[key];
746
+ if (!defaults)
747
+ return pairs;
748
+ for (const target in defaults) {
749
+ if (!used[target]) {
750
+ pushExpandedPair(pairs, target, defaults[target]);
751
+ }
752
+ }
753
+ return pairs;
754
+ }
755
+ function expandUnorderedAbbreviation(key, values) {
756
+ const result = [];
757
+ const used = {};
758
+ let hasTextDecorationNone = false;
759
+ let hasUnderline = false;
760
+ let hasLineThrough = false;
761
+ for (const value of values) {
762
+ if (key === 'textDecoration' && hasOwn(textDecorationLineMap, value)) {
763
+ switch (value) {
764
+ case 'underline':
765
+ hasUnderline = true;
766
+ continue;
767
+ case 'line-through':
768
+ hasLineThrough = true;
769
+ continue;
770
+ case 'none':
771
+ hasTextDecorationNone = true;
772
+ continue;
773
+ // textDecorationLineMap 命中但分支未处理的 line token:落到通用 getUnorderedShorthandProp 流程
774
+ }
775
+ }
776
+ const prop = getUnorderedShorthandProp(key, value, used);
777
+ if (!prop) {
778
+ // 该 token 与 key 下任何空闲槽位都不匹配(未知类型 / 槽位已占满),静默丢弃可能让用户难以察觉
779
+ warn(`Token [${value}] in [${key}: ${values.join(' ')}] is not a valid value or has no available slot, dropped.`);
780
+ continue;
781
+ }
782
+ used[prop] = true;
783
+ pushExpandedPair(result, prop, global.__formatValue(value));
784
+ }
785
+ if (hasUnderline || hasLineThrough) {
786
+ result.push(['textDecorationLine', hasUnderline && hasLineThrough ? 'underline line-through' : hasUnderline ? 'underline' : 'line-through']);
787
+ }
788
+ else if (hasTextDecorationNone) {
789
+ result.push(['textDecorationLine', 'none']);
790
+ }
791
+ // text-shadow 至少需要 offset-x / offset-y;缺省 height 时按 CSS 默认补 0 并发出 warn
792
+ if (key === 'textShadow') {
793
+ const offsetEntry = result.find(item => item[0] === 'textShadowOffset')?.[1];
794
+ if (offsetEntry && offsetEntry.width !== undefined && offsetEntry.height === undefined) {
795
+ warn(`Value of [textShadow:${values.join(' ')}] is missing offset-y, fallback to 0, please check again!`);
796
+ offsetEntry.height = 0;
797
+ }
798
+ }
799
+ return applyRuntimeShorthandDefaults(key, result, used);
800
+ }
801
+ function expandFlex(value) {
802
+ const values = parseValues(value);
803
+ if (values.length === 0)
804
+ return null;
805
+ if (values.length === 1) {
806
+ if (values[0] === 'none') {
807
+ return [['flexGrow', 0], ['flexShrink', 0]];
808
+ }
809
+ if (values[0] === 'initial') {
810
+ return [['flexGrow', 0], ['flexShrink', 1]];
811
+ }
812
+ }
813
+ const result = [];
814
+ let i = 0;
815
+ const isNum = (v) => !isNaN(+v);
816
+ if (isNum(values[i])) {
817
+ result.push(['flexGrow', +values[i++]]);
818
+ }
819
+ else {
820
+ result.push(['flexGrow', 1]);
821
+ }
822
+ if (i < values.length && isNum(values[i])) {
823
+ result.push(['flexShrink', +values[i++]]);
824
+ }
825
+ else {
826
+ result.push(['flexShrink', 1]);
827
+ }
828
+ if (i < values.length) {
829
+ if (values[i] !== 'auto') {
830
+ result.push(['flexBasis', global.__formatValue(values[i])]);
831
+ }
832
+ }
833
+ else {
834
+ result.push(['flexBasis', 0]);
835
+ }
836
+ return result;
837
+ }
838
+ // font 简写专用 transform,仿 transformFlex 的标志位模式。
839
+ // RN 等效子集语法:font: [ <font-style> ] [ <font-variant-css2> ] [ <font-weight> ] <font-size> [ / <line-height> ] <font-family>
840
+ // - 必填项:font-size 与 font-family;缺其一整条 font 声明丢弃(error)
841
+ // - 非必填 token(font-stretch / 数字型 font-variant-numeric / system 关键字等):warn 提示并忽略,保留其余槽位
842
+ function transformFont(styleObj, percentConfig) {
843
+ const value = styleObj.font;
844
+ if (typeof value !== 'string')
845
+ return;
846
+ const tokens = parseValues(value);
847
+ let sizeIdx = -1;
848
+ let lineHeight;
849
+ const result = [];
850
+ // 1. 定位 font-size(第一个 length,可能带 /<line-height>)
851
+ // 注意:unit-less 数字也命中 length 正则,需要先排除 font-weight 数字(100..900 / bold / normal),
852
+ // 否则 `font: 500 16px Arial` 会把 500 误判为 fontSize。
853
+ // fontSize 自身可能是 %(如 `font: 50% Arial`),就地用 resolvePercent 按 parentFontSize 解析;
854
+ // fontSize % 校验通过的是 `isLengthValue`(length 正则含 %),主流程已用 length 分支接住,无需特判
855
+ for (let i = 0; i < tokens.length; i++) {
856
+ let t = tokens[i];
857
+ if (t.endsWith('/') && tokens[i + 1]) {
858
+ t += tokens[i + 1];
859
+ tokens.splice(i + 1, 1);
860
+ }
861
+ else if (tokens[i + 1] === '/' && tokens[i + 2]) {
862
+ t += `/${tokens[i + 2]}`;
863
+ tokens.splice(i + 1, 2);
864
+ }
865
+ else if (tokens[i + 1]?.startsWith('/') && tokens[i + 1].length > 1) {
866
+ t += tokens[i + 1];
867
+ tokens.splice(i + 1, 1);
868
+ }
869
+ const [sizePart, lhPart] = parseValues(t, '/');
870
+ if (hasOwn(fontWeightMap, sizePart))
871
+ continue;
872
+ if (isLengthValue(sizePart)) {
873
+ sizeIdx = i;
874
+ const sizeVal = percentRegExp.test(sizePart)
875
+ ? resolvePercent(sizePart, 'fontSize', percentConfig)
876
+ : global.__formatValue(sizePart);
877
+ result.push(['fontSize', sizeVal]);
878
+ if (lhPart)
879
+ lineHeight = lhPart;
880
+ break;
881
+ }
882
+ }
883
+ if (sizeIdx === -1) {
884
+ // 缺必填 font-size 整体丢弃;与 transformFlex「Flex shorthand value [...] ..., dropped.」同口径
885
+ error(`Font shorthand value [${value}] is missing required <font-size>, dropped.`);
886
+ delete styleObj.font;
887
+ return;
888
+ }
889
+ // 2. 前导段 font-style / font-variant(small-caps) / font-weight,顺序不敏感
890
+ for (let i = 0; i < sizeIdx; i++) {
891
+ const t = tokens[i];
892
+ if (t === 'normal')
893
+ continue;
894
+ if (t === 'italic') {
895
+ result.push(['fontStyle', t]);
896
+ }
897
+ else if (t === 'small-caps') {
898
+ // RN processFontVariant 接受字符串,内部 split 归一为数组,与 font-variant 长属性同口径
899
+ result.push(['fontVariant', t]);
900
+ }
901
+ else if (hasOwn(fontWeightMap, t)) {
902
+ result.push(['fontWeight', t]);
903
+ }
904
+ else {
905
+ // 其余(font-stretch / 数字型 font-variant-numeric / system 关键字等)→ 非必填:
906
+ // 与 transformBackground「Token [...] in [background: ...] ..., dropped.」同口径,warn + 忽略该 token、保留其余
907
+ warn(`Token [${t}] in [font: ${value}] is not supported (only font-style / small-caps / font-weight are valid before <font-size>), dropped.`);
908
+ }
909
+ }
910
+ // 3. line-height:RN lineHeight 不接受百分比字符串,必须当场数值化。
911
+ // - unit-less 数字(1.5)→ '150%' 后走 resolvePercent
912
+ // - 显式百分比(120%)→ 直接走 resolvePercent
913
+ // - 带单位(40px / 40rpx)→ __formatValue
914
+ // 基数 fontSize 取值(「长属性不覆盖简写」一致):
915
+ // - user 已显式写 fontSize 长属性 → 优先(先经 __formatValue 归一 '24px' → 24)
916
+ // - 否则用 font 简写解析出的 fontSize(result[0][1],已可能是 number / 解析后的 % 值)
917
+ if (lineHeight !== undefined) {
918
+ // percentConfig.fontSize 用于 resolvePercent 的 base:
919
+ // - user 已显式写 fontSize 长属性 → 外层用 normalStyle.fontSize 初始化,已被前置 styleHelperMixin
920
+ // 的 transformStyleObj 经 __formatValue 归一为 number,可直接用,不覆盖(「长属性优先」一致)
921
+ // - 否则用 font 简写解析出的 fontSize(result[0][1],本身已 number 或解析后的 % 值)回填
922
+ if (percentConfig.fontSize === undefined)
923
+ percentConfig.fontSize = result[0][1];
924
+ let lh;
925
+ if (percentRegExp.test(lineHeight)) {
926
+ lh = resolvePercent(lineHeight, 'lineHeight', percentConfig);
927
+ }
928
+ else if (!isNaN(+lineHeight)) {
929
+ lh = resolvePercent(`${+lineHeight * 100}%`, 'lineHeight', percentConfig);
930
+ }
931
+ else {
932
+ lh = global.__formatValue(lineHeight);
933
+ }
934
+ // lh 仍是字符串说明 resolvePercent 因 base 非 number 原样返回(已 error 过)或带单位 __formatValue
935
+ // 未能换算成 number(如 fontSize 是未解析的 var())。RN lineHeight 不接受字符串,丢弃避免运行时报错
936
+ if (typeof lh === 'number') {
937
+ result.push(['lineHeight', lh]);
938
+ }
939
+ else {
940
+ warn(`Line-height [${lineHeight}] in [font: ${value}] could not be resolved to a number (font-size unresolved?), dropped.`);
941
+ }
942
+ }
943
+ // 4. font-family(font-size 之后剩余部分;多字体取首值、去引号)
944
+ const familyStr = tokens.slice(sizeIdx + 1).join(' ').trim();
945
+ if (!familyStr) {
946
+ error(`Font shorthand value [${value}] is missing required <font-family>, dropped.`);
947
+ delete styleObj.font;
948
+ return;
949
+ }
950
+ // parseValues 内部已 trim
951
+ const family = parseValues(familyStr.replace(quoteCharRegExp, ''), ',')[0];
952
+ if (family)
953
+ result.push(['fontFamily', family]);
954
+ delete styleObj.font;
955
+ for (const [prop, val] of result) {
956
+ if (!hasOwn(styleObj, prop))
957
+ styleObj[prop] = val;
958
+ }
959
+ }
960
+ function transformFlex(styleObj) {
961
+ const value = styleObj.flex;
962
+ if (typeof value !== 'string')
963
+ return;
964
+ delete styleObj.flex;
965
+ const flexResult = expandFlex(value);
966
+ if (!flexResult) {
967
+ // expandFlex 仅在 parseValues 出空数组时返回 null(空字符串 / 纯空白),属于明确非法,整段丢弃
968
+ error(`Flex shorthand value [${value}] is not a valid CSS flex value, dropped.`);
969
+ return;
970
+ }
971
+ for (const [prop, val] of flexResult) {
972
+ if (!hasOwn(styleObj, prop))
973
+ styleObj[prop] = val;
974
+ }
975
+ }
976
+ export function transformShorthand(styleObj, shorthandKeys, percentConfig) {
977
+ for (const key of shorthandKeys) {
978
+ const value = styleObj[key];
979
+ // —— 以下为公共链路(与 textDecoration / flexFlow / textShadow / 四值简写共用)——
980
+ let values;
981
+ if (typeof value === 'string') {
982
+ values = parseValues(value);
983
+ }
984
+ else if (value === 0 && hasOwn(runtimeBorderLikeShorthandMap, key)) {
985
+ values = ['0'];
986
+ }
987
+ else {
988
+ continue;
989
+ }
990
+ const props = runtimeAbbreviationMap[key];
991
+ if (!props)
992
+ continue;
993
+ // 单值短路:composite 且单值通常透传(RN 原生支持 margin / padding 单值 DimensionValue);
994
+ // 但 inset / gap 必须展开(理由见 runtimeForceExpandCompositeMap 注释)
995
+ if (hasOwn(runtimeCompositeStyleMap, key) &&
996
+ values.length === 1 &&
997
+ !hasOwn(runtimeForceExpandCompositeMap, key))
998
+ continue;
999
+ let expandedValues = values;
1000
+ let pairs;
1001
+ if (hasOwn(runtimeCompositeStyleMap, key)) {
1002
+ expandedValues = expandCompositeValues(values);
1003
+ }
1004
+ if (hasOwn(runtimeUnorderedAbbreviationMap, key)) {
1005
+ // expandUnorderedAbbreviation 末尾已内部调用 applyRuntimeShorthandDefaults 补齐
1006
+ pairs = expandUnorderedAbbreviation(key, values);
1007
+ }
1008
+ else {
1009
+ pairs = expandAbbreviation(expandedValues, props);
1010
+ }
1011
+ delete styleObj[key];
1012
+ for (const [prop, val] of pairs) {
1013
+ if (hasOwn(styleObj, prop))
1014
+ continue;
1015
+ // gap 简写展开后的 rowGap / columnGap 仍可能是 `%` 字符串(如 `gap: 50%` / `gap: 10px 50%`),
1016
+ // RN 类型严格要求 number,这里就地用 resolvePercent 落成数字(rowGap 基 parentHeight、columnGap 基 parentWidth)
1017
+ if ((prop === 'rowGap' || prop === 'columnGap') && typeof val === 'string' && percentRegExp.test(val)) {
1018
+ styleObj[prop] = resolvePercent(val, prop, percentConfig);
1019
+ }
1020
+ else {
1021
+ styleObj[prop] = val;
1022
+ }
1023
+ }
1024
+ }
1025
+ }
1026
+ // --- runtime alignment ---
1027
+ function transformFontFamily(styleObj) {
1028
+ const value = styleObj.fontFamily;
1029
+ if (typeof value !== 'string')
1030
+ return;
1031
+ const stripped = value.replace(quoteCharRegExp, '').trim();
1032
+ if (!stripped)
1033
+ return;
1034
+ const values = parseValues(stripped, ',');
1035
+ // parseValues 内部已 trim
1036
+ styleObj.fontFamily = values[0];
1037
+ }
1038
+ function transformBorderStyleNone(styleObj) {
1039
+ if (styleObj.borderStyle === 'none') {
1040
+ delete styleObj.borderStyle;
1041
+ delete styleObj.borderTopWidth;
1042
+ delete styleObj.borderRightWidth;
1043
+ delete styleObj.borderBottomWidth;
1044
+ delete styleObj.borderLeftWidth;
1045
+ styleObj.borderWidth = 0;
1046
+ }
1047
+ if (styleObj.outlineStyle === 'none') {
1048
+ delete styleObj.outlineStyle;
1049
+ styleObj.outlineWidth = 0;
1050
+ }
1051
+ }
1052
+ function transformPosition(styleObj) {
1053
+ if (styleObj.position === 'fixed') {
1054
+ styleObj.position = 'absolute';
1055
+ return true;
1056
+ }
1057
+ return false;
1058
+ }
1059
+ function transOrderXY(values) {
1060
+ if (values.length === 2 && ['top', 'bottom'].includes(values[0])) {
1061
+ [values[0], values[1]] = [values[1], values[0]];
1062
+ }
1063
+ return values;
1064
+ }
1065
+ function transformBackground(styleObj) {
1066
+ if (typeof styleObj.backgroundSize === 'string') {
1067
+ styleObj.backgroundSize = parseValues(styleObj.backgroundSize);
1068
+ }
1069
+ if (typeof styleObj.backgroundPosition === 'string') {
1070
+ const parts = parseValues(styleObj.backgroundPosition);
1071
+ styleObj.backgroundPosition = transOrderXY(parts.map(v => v === 'center' ? '50%' : v));
1072
+ }
1073
+ const value = styleObj.background;
1074
+ if (typeof value !== 'string')
1075
+ return;
1076
+ delete styleObj.background;
1077
+ if (value === 'none') {
1078
+ styleObj.backgroundImage = 'none';
1079
+ styleObj.backgroundColor = 'transparent';
1080
+ return;
1081
+ }
1082
+ const tokens = parseValues(value);
1083
+ const positionValues = [];
1084
+ const sizeValues = [];
1085
+ let isSize = false;
1086
+ for (const token of tokens) {
1087
+ if (urlRegExp.test(token)) {
1088
+ styleObj.backgroundImage = token;
1089
+ }
1090
+ else if (linearGradientRegExp.test(token)) {
1091
+ styleObj.backgroundImage = token;
1092
+ }
1093
+ else if (hasOwn(bgRepeatMap, token)) {
1094
+ styleObj.backgroundRepeat = token;
1095
+ }
1096
+ else if (isColorValue(token)) {
1097
+ styleObj.backgroundColor = token;
1098
+ }
1099
+ else if (token === '/') {
1100
+ isSize = true;
1101
+ }
1102
+ else {
1103
+ const slashParts = parseValues(token, '/');
1104
+ if (slashParts.length > 1) {
1105
+ const posPart = slashParts[0];
1106
+ if (posPart)
1107
+ positionValues.push(posPart === 'center' ? '50%' : posPart);
1108
+ isSize = true;
1109
+ for (let i = 1; i < slashParts.length; i++) {
1110
+ if (slashParts[i])
1111
+ sizeValues.push(slashParts[i]);
1112
+ }
1113
+ }
1114
+ else if (isSize) {
1115
+ sizeValues.push(token);
1116
+ }
1117
+ else if (hasOwn(bgPositionMap, token) || percentRegExp.test(token) || digitStartRegExp.test(token)) {
1118
+ positionValues.push(token === 'center' ? '50%' : token);
1119
+ }
1120
+ else {
1121
+ // background-attachment / background-origin / background-clip 及拼写错误等:RN 均不支持,提示用户避免静默丢值
1122
+ warn(`Token [${token}] in [background: ${value}] is not a recognized background sub-value, dropped.`);
1123
+ }
1124
+ }
1125
+ }
1126
+ if (positionValues.length)
1127
+ styleObj.backgroundPosition = transOrderXY(positionValues);
1128
+ if (sizeValues.length)
1129
+ styleObj.backgroundSize = sizeValues;
1130
+ }
1131
+ // ============================================================
1132
+ // style traversal
1133
+ // ============================================================
1134
+ export function traverseStyle(styleObj, visitor) {
1135
+ const keyPath = [];
1136
+ function traverse(target) {
1137
+ if (Array.isArray(target)) {
1138
+ for (let i = 0; i < target.length; i++) {
1139
+ const key = String(i);
1140
+ const value = target[i];
1141
+ keyPath.push(key);
1142
+ visitor({ target, key, value, keyPath });
1143
+ traverse(value);
1144
+ keyPath.pop();
1145
+ }
1146
+ }
1147
+ else if (isObject(target)) {
1148
+ const keys = Object.keys(target);
1149
+ for (let i = 0; i < keys.length; i++) {
1150
+ const key = keys[i];
1151
+ const value = target[key];
1152
+ keyPath.push(key);
1153
+ visitor({ target, key, value, keyPath });
1154
+ traverse(value);
1155
+ keyPath.pop();
1156
+ }
1157
+ }
1158
+ }
1159
+ traverse(styleObj);
1160
+ }
1161
+ export function setStyle(styleObj, keyPath, setter) {
1162
+ let target = styleObj;
1163
+ const lastKey = keyPath[keyPath.length - 1];
1164
+ for (let i = 0; i < keyPath.length - 1; i++) {
1165
+ target = target[keyPath[i]];
1166
+ if (!target)
1167
+ return;
1168
+ }
1169
+ setter({
1170
+ target,
1171
+ key: lastKey,
1172
+ value: target[lastKey],
1173
+ keyPath
1174
+ });
398
1175
  }
399
- export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPercent, externalVarContext, parentFontSize, parentWidth, parentHeight }) {
1176
+ // ============================================================
1177
+ // core style hook
1178
+ // ============================================================
1179
+ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPercent, parentFontSize, parentWidth, parentHeight, defaultStyle }) {
400
1180
  const varStyle = {};
401
1181
  const unoVarStyle = {};
402
1182
  const normalStyle = {};
@@ -404,15 +1184,85 @@ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPer
404
1184
  let hasVarUse = false;
405
1185
  let hasSelfPercent = false;
406
1186
  let hasBoxSizingAffectingStyle = false;
1187
+ // 顶层 transform* 标志位:在 styleVisitor 阶段从原始 styleObj 收集,
1188
+ // 调用侧据此决定是否进入对应 transform 函数。
1189
+ let hasTransform = false;
1190
+ let hasBoxShadow = false;
1191
+ let hasFontFamily = false;
1192
+ let hasFlex = false;
1193
+ let hasFont = false;
1194
+ let needTransformBackground = false;
1195
+ let needStringify = false;
407
1196
  const varKeyPaths = [];
408
1197
  const unoVarKeyPaths = [];
409
1198
  const percentKeyPaths = [];
410
1199
  const calcKeyPaths = [];
411
1200
  const envKeyPaths = [];
1201
+ const shorthandKeys = [];
412
1202
  const [width, setWidth] = useState(0);
413
1203
  const [height, setHeight] = useState(0);
414
1204
  const navigation = useNavigation();
415
- function varVisitor({ target, key, value, keyPath }) {
1205
+ function collectTopLevelFlags(key, value) {
1206
+ switch (key) {
1207
+ case 'transform':
1208
+ hasTransform = true;
1209
+ break;
1210
+ case 'boxShadow':
1211
+ hasBoxShadow = true;
1212
+ break;
1213
+ case 'fontFamily':
1214
+ hasFontFamily = true;
1215
+ break;
1216
+ case 'flex':
1217
+ hasFlex = true;
1218
+ break;
1219
+ case 'font':
1220
+ hasFont = true;
1221
+ break;
1222
+ case 'background':
1223
+ case 'backgroundSize':
1224
+ case 'backgroundPosition':
1225
+ needTransformBackground = true;
1226
+ break;
1227
+ case 'fontWeight':
1228
+ case 'transformOrigin':
1229
+ needStringify = true;
1230
+ break;
1231
+ }
1232
+ }
1233
+ function visitOther({ key, value, keyPath }) {
1234
+ if (typeof value !== 'string')
1235
+ return;
1236
+ const hasPercent = value.includes('%');
1237
+ const hasCalc = value.includes('calc(');
1238
+ const hasEnv = value.includes('env(');
1239
+ if (!(hasPercent || hasCalc || hasEnv))
1240
+ return;
1241
+ let resolvedKeyPath;
1242
+ if (hasEnv) {
1243
+ resolvedKeyPath = keyPath.slice();
1244
+ envKeyPaths.push(resolvedKeyPath);
1245
+ }
1246
+ if (hasPercent) {
1247
+ // fixme 去掉 translate & border-radius 的百分比计算
1248
+ // fixme Image 组件 borderRadius 仅支持 number
1249
+ const needRadiusPercent = transformRadiusPercent && hasOwn(radiusPercentRule, key);
1250
+ const needFontPercent = key === 'fontSize' || key === 'lineHeight';
1251
+ // RN gap / rowGap / columnGap 不支持 %,需要运行时换算为 number 喂给 RN
1252
+ const needGapPercent = key === 'rowGap' || key === 'columnGap';
1253
+ if ((needRadiusPercent || needFontPercent || needGapPercent) && percentRegExp.test(value)) {
1254
+ if (needRadiusPercent)
1255
+ hasSelfPercent = true;
1256
+ resolvedKeyPath = resolvedKeyPath ?? keyPath.slice();
1257
+ percentKeyPaths.push(resolvedKeyPath);
1258
+ }
1259
+ }
1260
+ if (hasCalc) {
1261
+ resolvedKeyPath = resolvedKeyPath ?? keyPath.slice();
1262
+ calcKeyPaths.push(resolvedKeyPath);
1263
+ }
1264
+ }
1265
+ function styleVisitor({ target, key, value, keyPath }) {
416
1266
  if (keyPath.length === 1) {
417
1267
  if (unoVarDecRegExp.test(key)) {
418
1268
  unoVarStyle[key] = value;
@@ -424,57 +1274,32 @@ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPer
424
1274
  else {
425
1275
  // clone对象避免set值时改写到props
426
1276
  normalStyle[key] = isObject(value) ? diffAndCloneA(value).clone : value;
1277
+ if (!hasBoxSizingAffectingStyle && isBoxSizingAffectingStyle(key)) {
1278
+ hasBoxSizingAffectingStyle = true;
1279
+ }
1280
+ if (hasOwn(runtimeAbbreviationMap, key)) {
1281
+ shorthandKeys.push(key);
1282
+ }
1283
+ collectTopLevelFlags(key, value);
427
1284
  }
428
1285
  }
429
- // 对于var定义中使用的var无需替换值,可以通过resolveVar递归解析出值
430
- if (!varDecRegExp.test(key)) {
431
- // 一般情况下一个样式属性中不会混用unocss var和普通css var,可分开进行互斥处理
432
- if (unoVarUseRegExp.test(value)) {
433
- unoVarKeyPaths.push(keyPath.slice());
434
- }
435
- else if (varUseRegExp.test(value)) {
436
- hasVarUse = true;
437
- varKeyPaths.push(keyPath.slice());
438
- }
439
- else {
440
- visitOther({ target, key, value, keyPath });
441
- }
442
- }
443
- }
444
- function boxSizingVisitor({ key, keyPath }) {
445
- if (keyPath.length === 1 && !hasBoxSizingAffectingStyle && isBoxSizingAffectingStyle(key)) {
446
- hasBoxSizingAffectingStyle = true;
447
- }
448
- }
449
- function envVisitor({ value, keyPath }) {
450
- if (envUseRegExp.test(value)) {
451
- envKeyPaths.push(keyPath.slice());
452
- }
453
- }
454
- function calcVisitor({ value, keyPath }) {
455
- if (calcUseRegExp.test(value)) {
456
- calcKeyPaths.push(keyPath.slice());
457
- }
458
- }
459
- function percentVisitor({ key, value, keyPath }) {
460
- // fixme 去掉 translate & border-radius 的百分比计算
461
- // fixme Image 组件 borderRadius 仅支持 number
462
- if (transformRadiusPercent && hasOwn(radiusPercentRule, key) && PERCENT_REGEX.test(value)) {
463
- hasSelfPercent = true;
464
- percentKeyPaths.push(keyPath.slice());
1286
+ // var 定义中使用的 var 无需替换值,可以通过 resolveVar 递归解析出值
1287
+ if (varDecRegExp.test(key) || typeof value !== 'string')
1288
+ return;
1289
+ // 一般情况下一个样式属性中不会混用 unocss var 和普通 css var,可分开互斥处理
1290
+ if (unoVarUseRegExp.test(value)) {
1291
+ unoVarKeyPaths.push(keyPath.slice());
465
1292
  }
466
- else if ((key === 'fontSize' || key === 'lineHeight') && PERCENT_REGEX.test(value)) {
467
- percentKeyPaths.push(keyPath.slice());
1293
+ else if (varUseRegExp.test(value)) {
1294
+ hasVarUse = true;
1295
+ varKeyPaths.push(keyPath.slice());
468
1296
  }
469
- }
470
- function visitOther({ target, key, value, keyPath }) {
471
- if (typeof value === 'string' && (value.includes('%') || value.includes('calc(') || value.includes('env('))) {
472
- [envVisitor, percentVisitor, calcVisitor].forEach(visitor => visitor({ target, key, value, keyPath }));
1297
+ else {
1298
+ visitOther({ target, key, value, keyPath });
473
1299
  }
474
1300
  }
475
1301
  // traverse var & generate normalStyle
476
- traverseStyle(styleObj, [varVisitor, boxSizingVisitor]);
477
- hasVarDec = hasVarDec || !!externalVarContext;
1302
+ traverseStyle(styleObj, styleVisitor);
478
1303
  enableVar = enableVar || hasVarDec || hasVarUse;
479
1304
  const enableVarRef = useRef(enableVar);
480
1305
  if (enableVarRef.current !== enableVar) {
@@ -485,17 +1310,27 @@ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPer
485
1310
  if (enableVarRef.current) {
486
1311
  // eslint-disable-next-line react-hooks/rules-of-hooks
487
1312
  const varContext = useContext(VarContext);
488
- const newVarContext = extendObject({}, varContext, externalVarContext, varStyle);
489
- // 缓存比较newVarContext是否发生变化
490
- if (diffAndCloneA(varContextRef.current, newVarContext).diff) {
491
- varContextRef.current = newVarContext;
1313
+ // 无声明节点:直接用父 varContext 解析,跳过 merge / 比对 / ref 维护。
1314
+ // 有声明节点:浅合并出 newVarContext,仅在内容变化时替换 ref 维持引用稳定,
1315
+ // 供 wrapChildren 的 <VarContext.Provider> 使用。
1316
+ let resolvedVarContext = varContext;
1317
+ if (hasVarDec) {
1318
+ const newVarContext = extendObject({}, varContext, varStyle);
1319
+ if (!shallowEqual(varContextRef.current, newVarContext)) {
1320
+ varContextRef.current = newVarContext;
1321
+ }
1322
+ resolvedVarContext = varContextRef.current;
492
1323
  }
493
- transformVar(normalStyle, varKeyPaths, varContextRef.current, visitOther);
1324
+ if (varKeyPaths.length)
1325
+ transformVar(normalStyle, varKeyPaths, resolvedVarContext, visitOther);
494
1326
  }
495
1327
  // apply unocss var
496
- if (unoVarKeyPaths.length) {
1328
+ if (unoVarKeyPaths.length)
497
1329
  transformVar(normalStyle, unoVarKeyPaths, unoVarStyle, visitOther);
498
- }
1330
+ // apply env
1331
+ if (envKeyPaths.length)
1332
+ transformEnv(normalStyle, envKeyPaths, navigation);
1333
+ // apply percent / calc
499
1334
  const percentConfig = {
500
1335
  width,
501
1336
  height,
@@ -504,42 +1339,70 @@ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPer
504
1339
  parentHeight,
505
1340
  parentFontSize
506
1341
  };
507
- const positionMeta = {
508
- hasPositionFixed: false
509
- };
510
- // apply env
511
- transformEnv(normalStyle, envKeyPaths, navigation);
512
- // apply percent
513
- transformPercent(normalStyle, percentKeyPaths, percentConfig);
514
- // apply calc
515
- transformCalc(normalStyle, calcKeyPaths, (value, key) => {
516
- if (PERCENT_REGEX.test(value)) {
517
- if (hasOwn(selfPercentRule, key)) {
518
- hasSelfPercent = true;
519
- }
520
- const resolved = resolvePercent(value, key, percentConfig);
521
- return typeof resolved === 'number' ? resolved : 0;
522
- }
523
- else {
524
- const formatted = global.__formatValue(value);
525
- if (typeof formatted === 'number') {
526
- return formatted;
1342
+ // transformFont 可能会更新 percentConfig 配置,必须在 transformPercent 之前执行,保证 fontSize / lineHeight 的百分比能被正确解析
1343
+ if (hasFont)
1344
+ transformFont(normalStyle, percentConfig);
1345
+ if (percentKeyPaths.length)
1346
+ transformPercent(normalStyle, percentKeyPaths, percentConfig);
1347
+ if (calcKeyPaths.length) {
1348
+ transformCalc(normalStyle, calcKeyPaths, (value, key) => {
1349
+ if (percentRegExp.test(value)) {
1350
+ if (hasOwn(selfPercentRule, key)) {
1351
+ hasSelfPercent = true;
1352
+ }
1353
+ const resolved = resolvePercent(value, key, percentConfig);
1354
+ return typeof resolved === 'number' ? resolved : 0;
527
1355
  }
528
1356
  else {
529
- warn('calc() only support number, px, rpx, % temporarily.');
530
- return 0;
1357
+ const formatted = global.__formatValue(value);
1358
+ if (typeof formatted === 'number') {
1359
+ return formatted;
1360
+ }
1361
+ else {
1362
+ warn('calc() only support number, px, rpx, % temporarily.');
1363
+ return 0;
1364
+ }
531
1365
  }
532
- }
533
- });
534
- // apply position
535
- transformPosition(normalStyle, positionMeta);
1366
+ });
1367
+ }
536
1368
  // transform number enum stringify
537
- transformStringify(normalStyle);
538
- // transform rpx to px
539
- transformBoxShadow(normalStyle);
540
- // transform 字符串格式转化数组格式(先转数组再处理css var)
541
- transformTransform(normalStyle);
542
- transformBoxSizing(normalStyle, hasBoxSizingAffectingStyle);
1369
+ if (needStringify)
1370
+ transformStringify(normalStyle);
1371
+ // transform unit
1372
+ if (hasBoxShadow)
1373
+ transformBoxShadow(normalStyle);
1374
+ // transform 字符串格式转化数组格式
1375
+ if (hasTransform)
1376
+ transformTransform(normalStyle);
1377
+ // apply runtime style processing alignment
1378
+ if (hasFontFamily)
1379
+ transformFontFamily(normalStyle);
1380
+ if (hasFlex)
1381
+ transformFlex(normalStyle);
1382
+ if (shorthandKeys.length)
1383
+ transformShorthand(normalStyle, shorthandKeys, percentConfig);
1384
+ if (needTransformBackground)
1385
+ transformBackground(normalStyle);
1386
+ // borderStyle / outlineStyle: 'none' 的清除语义放到变量解析、简写展开之后统一处理。
1387
+ transformBorderStyleNone(normalStyle);
1388
+ // transform position: fixed
1389
+ const hasPositionFixed = transformPosition(normalStyle);
1390
+ // 合并组件默认样式:默认样式在 user transform 之后兜底写入,需完全符合 RN style 规范
1391
+ // 命中 user 已存在 key(含简写展开后的长属性)则跳过。
1392
+ // 复用同一次循环顺带补 hasBoxSizingAffectingStyle,避免独立扫一遍 default。
1393
+ if (defaultStyle) {
1394
+ for (const k in defaultStyle) {
1395
+ if (!hasOwn(defaultStyle, k))
1396
+ continue;
1397
+ if (!hasOwn(normalStyle, k))
1398
+ normalStyle[k] = defaultStyle[k];
1399
+ if (!hasBoxSizingAffectingStyle && isBoxSizingAffectingStyle(k)) {
1400
+ hasBoxSizingAffectingStyle = true;
1401
+ }
1402
+ }
1403
+ }
1404
+ if (hasBoxSizingAffectingStyle)
1405
+ transformBoxSizing(normalStyle);
543
1406
  return {
544
1407
  hasVarDec,
545
1408
  varContextRef,
@@ -547,61 +1410,41 @@ export function useTransformStyle(styleObj = {}, { enableVar, transformRadiusPer
547
1410
  setHeight,
548
1411
  normalStyle,
549
1412
  hasSelfPercent,
550
- hasPositionFixed: positionMeta.hasPositionFixed
1413
+ hasPositionFixed
551
1414
  };
552
1415
  }
553
- export function traverseStyle(styleObj, visitors) {
554
- const keyPath = [];
555
- function traverse(target) {
556
- if (Array.isArray(target)) {
557
- target.forEach((value, index) => {
558
- const key = String(index);
559
- keyPath.push(key);
560
- visitors.forEach(visitor => visitor({ target, key, value, keyPath }));
561
- traverse(value);
562
- keyPath.pop();
563
- });
564
- }
565
- else if (isObject(target)) {
566
- Object.entries(target).forEach(([key, value]) => {
567
- keyPath.push(key);
568
- visitors.forEach(visitor => visitor({ target, key, value, keyPath }));
569
- traverse(value);
570
- keyPath.pop();
571
- });
572
- }
573
- }
574
- traverse(styleObj);
575
- }
576
- export function setStyle(styleObj, keyPath, setter) {
577
- let target = styleObj;
578
- const lastKey = keyPath[keyPath.length - 1];
579
- for (let i = 0; i < keyPath.length - 1; i++) {
580
- target = target[keyPath[i]];
581
- if (!target)
582
- return;
583
- }
584
- setter({
585
- target,
586
- key: lastKey,
587
- value: target[lastKey],
588
- keyPath
589
- });
1416
+ // ============================================================
1417
+ // other React hooks
1418
+ // ============================================================
1419
+ export function useNavigation() {
1420
+ const { navigation } = useContext(RouteContext) || {};
1421
+ return navigation;
590
1422
  }
591
- export function splitProps(props) {
592
- return groupBy(props, (key) => {
593
- if (hasOwn(TEXT_PROPS_MAP, key)) {
594
- return 'textProps';
1423
+ /**
1424
+ * 用法等同于 useEffect,但是会忽略首次执行,只在依赖更新时执行
1425
+ */
1426
+ export const useUpdateEffect = (effect, deps) => {
1427
+ const isMounted = useRef(false);
1428
+ // for react-refresh
1429
+ useEffect(() => {
1430
+ return () => {
1431
+ isMounted.current = false;
1432
+ };
1433
+ }, []);
1434
+ useEffect(() => {
1435
+ if (!isMounted.current) {
1436
+ isMounted.current = true;
595
1437
  }
596
1438
  else {
597
- return 'innerProps';
1439
+ return effect();
598
1440
  }
599
- });
600
- }
1441
+ }, deps);
1442
+ };
601
1443
  export const useLayout = ({ props, hasSelfPercent, setWidth, setHeight, onLayout, nodeRef }) => {
602
1444
  const layoutRef = useRef({});
603
1445
  const hasLayoutRef = useRef(false);
604
- const layoutStyle = useMemo(() => { return !hasLayoutRef.current && hasSelfPercent ? HIDDEN_STYLE : {}; }, [hasLayoutRef.current]);
1446
+ // 固定首次 layout 前是否需要隐藏,避免 hasSelfPercent 后续变化时重新隐藏组件
1447
+ const layoutStyle = useMemo(() => { return !hasLayoutRef.current && hasSelfPercent ? hiddenStyle : undefined; }, [hasLayoutRef.current]);
605
1448
  const layoutProps = {};
606
1449
  const navigation = useNavigation();
607
1450
  const enableOffset = props['enable-offset'];
@@ -629,21 +1472,26 @@ export const useLayout = ({ props, hasSelfPercent, setWidth, setHeight, onLayout
629
1472
  layoutProps
630
1473
  };
631
1474
  };
632
- export function useTextPassThroughValue(textStyle, textProps, { inheritTextProps = true, disabled = false } = {}) {
1475
+ export function useTextPassThrough(textStyle, textProps, { enableTextPassThrough = false } = {}) {
1476
+ const shouldEnableTextPassThrough = (enableTextPassThrough ||
1477
+ !!textStyle ||
1478
+ !!textProps);
1479
+ const enableTextPassThroughRef = useRef(shouldEnableTextPassThrough);
1480
+ if (enableTextPassThroughRef.current !== shouldEnableTextPassThrough) {
1481
+ error('[Mpx runtime error]: text style/props use should be stable in the component lifecycle, or you can set [enable-text-pass-through] with true.');
1482
+ }
1483
+ if (!enableTextPassThroughRef.current)
1484
+ return null;
1485
+ // eslint-disable-next-line react-hooks/rules-of-hooks
633
1486
  const parent = useContext(TextPassThroughContext);
1487
+ // eslint-disable-next-line react-hooks/rules-of-hooks
634
1488
  const valueRef = useRef(null);
635
- if (disabled)
636
- return null;
637
- if (!textStyle && !textProps && (inheritTextProps || !parent?.pendingTextProps))
638
- return null;
639
1489
  const nextTextStyle = textStyle
640
1490
  ? extendObject({}, parent?.textStyle, textStyle)
641
1491
  : parent?.textStyle;
642
- const nextTextProps = inheritTextProps
643
- ? textProps
644
- ? extendObject({}, parent?.pendingTextProps, textProps)
645
- : parent?.pendingTextProps
646
- : textProps;
1492
+ const nextTextProps = textProps
1493
+ ? extendObject({}, parent?.pendingTextProps, textProps)
1494
+ : parent?.pendingTextProps;
647
1495
  const nextValue = {
648
1496
  textStyle: nextTextStyle,
649
1497
  pendingTextProps: nextTextProps
@@ -653,76 +1501,25 @@ export function useTextPassThroughValue(textStyle, textProps, { inheritTextProps
653
1501
  }
654
1502
  return valueRef.current;
655
1503
  }
656
- export function wrapChildren(props = {}, { hasVarDec, varContext, textPassThrough }) {
657
- let { children } = props;
658
- if (textPassThrough) {
659
- children = <TextPassThroughContext.Provider value={textPassThrough} key='textPassThroughWrap'>{children}</TextPassThroughContext.Provider>;
660
- }
661
- if (hasVarDec && varContext) {
662
- children = <VarContext.Provider value={varContext} key='varContextWrap'>{children}</VarContext.Provider>;
1504
+ export function useTextPassThroughText(textStyle) {
1505
+ const inheritedText = useContext(TextPassThroughContext);
1506
+ const valueRef = useRef(null);
1507
+ if (!textStyle) {
1508
+ return {
1509
+ inheritedText,
1510
+ textPassThrough: null
1511
+ };
663
1512
  }
664
- return children;
665
- }
666
- export const debounce = (func, delay) => {
667
- let timer;
668
- const wrapper = (...args) => {
669
- timer && clearTimeout(timer);
670
- timer = setTimeout(() => {
671
- func(...args);
672
- }, delay);
673
- };
674
- wrapper.clear = () => {
675
- timer && clearTimeout(timer);
676
- timer = null;
1513
+ const nextValue = {
1514
+ textStyle: extendObject({}, inheritedText?.textStyle, textStyle)
677
1515
  };
678
- return wrapper;
679
- };
680
- export const useDebounceCallback = (func, delay) => {
681
- const debounced = useMemo(() => debounce(func, delay), [func]);
682
- return debounced;
683
- };
684
- export const useStableCallback = (callback) => {
685
- const ref = useRef(callback);
686
- ref.current = callback;
687
- return useCallback((...args) => ref.current?.(...args), []);
688
- };
689
- export function usePrevious(value) {
690
- const ref = useRef();
691
- const prev = ref.current;
692
- ref.current = value;
693
- return prev;
694
- }
695
- export function flatGesture(gestures = []) {
696
- return (gestures && gestures.flatMap((gesture) => {
697
- if (gesture && gesture.nodeRefs) {
698
- return gesture.nodeRefs
699
- .map((item) => item.getNodeInstance()?.instance?.gestureRef || {});
700
- }
701
- return gesture?.current ? [gesture] : [];
702
- })) || [];
703
- }
704
- export function getCurrentPage(pageId) {
705
- if (!global.getCurrentPages)
706
- return;
707
- const pages = global.getCurrentPages();
708
- return pages.find((page) => isFunction(page.getPageId) && page.getPageId() === pageId);
709
- }
710
- export function renderImage(imageProps, enableFastImage = true) {
711
- let Component = Image;
712
- if (enableFastImage) {
713
- // eslint-disable-next-line @typescript-eslint/no-var-requires
714
- const fastImageModule = require('@d11/react-native-fast-image');
715
- Component = fastImageModule.default || fastImageModule;
1516
+ if (diffAndCloneA(valueRef.current, nextValue).diff) {
1517
+ valueRef.current = nextValue;
716
1518
  }
717
- return createElement(Component, imageProps);
718
- }
719
- export function pickStyle(styleObj = {}, pickedKeys, callback) {
720
- return pickedKeys.reduce((acc, key) => {
721
- if (key in styleObj) {
722
- acc[key] = callback ? callback(key, styleObj[key]) : styleObj[key];
723
- }
724
- return acc;
725
- }, {});
1519
+ return {
1520
+ inheritedText,
1521
+ textPassThrough: valueRef.current
1522
+ };
726
1523
  }
727
1524
  export function useHover({ enableHover, hoverStartTime, hoverStayTime, disabled }) {
728
1525
  const enableHoverRef = useRef(enableHover);
@@ -736,33 +1533,38 @@ export function useHover({ enableHover, hoverStartTime, hoverStayTime, disabled
736
1533
  // eslint-disable-next-line react-hooks/rules-of-hooks
737
1534
  const [isHover, setIsHover] = useState(false);
738
1535
  // eslint-disable-next-line react-hooks/rules-of-hooks
739
- const dataRef = useRef({});
1536
+ const hoverRef = useRef({ hoverStartTime, hoverStayTime, disabled });
1537
+ hoverRef.current.hoverStartTime = hoverStartTime;
1538
+ hoverRef.current.hoverStayTime = hoverStayTime;
1539
+ hoverRef.current.disabled = disabled;
740
1540
  // eslint-disable-next-line react-hooks/rules-of-hooks
741
1541
  useEffect(() => {
742
1542
  return () => {
743
- dataRef.current.startTimer && clearTimeout(dataRef.current.startTimer);
744
- dataRef.current.stayTimer && clearTimeout(dataRef.current.stayTimer);
1543
+ hoverRef.current.startTimer && clearTimeout(hoverRef.current.startTimer);
1544
+ hoverRef.current.stayTimer && clearTimeout(hoverRef.current.stayTimer);
745
1545
  };
746
1546
  }, []);
747
- const setStartTimer = () => {
748
- if (disabled)
749
- return;
750
- dataRef.current.startTimer && clearTimeout(dataRef.current.startTimer);
751
- dataRef.current.startTimer = setTimeout(() => {
752
- setIsHover(true);
753
- }, +hoverStartTime);
754
- };
755
- const setStayTimer = () => {
756
- if (disabled)
757
- return;
758
- dataRef.current.stayTimer && clearTimeout(dataRef.current.stayTimer);
759
- dataRef.current.startTimer && clearTimeout(dataRef.current.startTimer);
760
- dataRef.current.stayTimer = setTimeout(() => {
761
- setIsHover(false);
762
- }, +hoverStayTime);
763
- };
764
1547
  // eslint-disable-next-line react-hooks/rules-of-hooks
765
1548
  const gesture = useMemo(() => {
1549
+ const setStartTimer = () => {
1550
+ const data = hoverRef.current;
1551
+ if (data.disabled)
1552
+ return;
1553
+ data.startTimer && clearTimeout(data.startTimer);
1554
+ data.startTimer = setTimeout(() => {
1555
+ setIsHover(true);
1556
+ }, +data.hoverStartTime);
1557
+ };
1558
+ const setStayTimer = () => {
1559
+ const data = hoverRef.current;
1560
+ if (data.disabled)
1561
+ return;
1562
+ data.stayTimer && clearTimeout(data.stayTimer);
1563
+ data.startTimer && clearTimeout(data.startTimer);
1564
+ data.stayTimer = setTimeout(() => {
1565
+ setIsHover(false);
1566
+ }, +data.hoverStayTime);
1567
+ };
766
1568
  return Gesture.Pan()
767
1569
  .onTouchesDown(() => {
768
1570
  setStartTimer();
@@ -793,3 +1595,54 @@ export function useRunOnJSCallback(callbackMapRef) {
793
1595
  }, []);
794
1596
  return invokeCallback;
795
1597
  }
1598
+ export const useDebounceCallback = (func, delay) => {
1599
+ const debounced = useMemo(() => debounce(func, delay), [func]);
1600
+ return debounced;
1601
+ };
1602
+ export const useStableCallback = (callback) => {
1603
+ const ref = useRef(callback);
1604
+ ref.current = callback;
1605
+ return useCallback((...args) => ref.current?.(...args), []);
1606
+ };
1607
+ export function usePrevious(value) {
1608
+ const ref = useRef();
1609
+ const prev = ref.current;
1610
+ ref.current = value;
1611
+ return prev;
1612
+ }
1613
+ // ============================================================
1614
+ // component helpers
1615
+ // ============================================================
1616
+ export function wrapChildren(children, { hasVarDec, varContext, textPassThrough }) {
1617
+ if (textPassThrough) {
1618
+ children = <TextPassThroughContext.Provider value={textPassThrough} key='textPassThroughWrap'>{children}</TextPassThroughContext.Provider>;
1619
+ }
1620
+ if (hasVarDec && varContext) {
1621
+ children = <VarContext.Provider value={varContext} key='varContextWrap'>{children}</VarContext.Provider>;
1622
+ }
1623
+ return children;
1624
+ }
1625
+ export function renderImage(imageProps, enableFastImage = true) {
1626
+ let Component = Image;
1627
+ if (enableFastImage) {
1628
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1629
+ const fastImageModule = require('@d11/react-native-fast-image');
1630
+ Component = fastImageModule.default || fastImageModule;
1631
+ }
1632
+ return createElement(Component, imageProps);
1633
+ }
1634
+ export function flatGesture(gestures = []) {
1635
+ return (gestures && gestures.flatMap((gesture) => {
1636
+ if (gesture && gesture.nodeRefs) {
1637
+ return gesture.nodeRefs
1638
+ .map((item) => item.getNodeInstance()?.instance?.gestureRef || {});
1639
+ }
1640
+ return gesture?.current ? [gesture] : [];
1641
+ })) || [];
1642
+ }
1643
+ export function getCurrentPage(pageId) {
1644
+ if (!global.getCurrentPages)
1645
+ return;
1646
+ const pages = global.getCurrentPages();
1647
+ return pages.find((page) => isFunction(page.getPageId) && page.getPageId() === pageId);
1648
+ }