rnwind 0.0.4 → 0.0.5
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.
- package/lib/cjs/core/normalize-classname.cjs +25 -0
- package/lib/cjs/core/normalize-classname.cjs.map +1 -0
- package/lib/cjs/core/normalize-classname.d.ts +10 -0
- package/lib/cjs/core/style-builder/build-style.cjs +258 -58
- package/lib/cjs/core/style-builder/build-style.cjs.map +1 -1
- package/lib/cjs/core/style-builder/build-style.d.ts +6 -1
- package/lib/cjs/core/style-builder/union-builder.cjs +37 -3
- package/lib/cjs/core/style-builder/union-builder.cjs.map +1 -1
- package/lib/cjs/core/style-builder/union-builder.d.ts +21 -1
- package/lib/cjs/metro/dts.cjs +7 -16
- package/lib/cjs/metro/dts.cjs.map +1 -1
- package/lib/cjs/metro/dts.d.ts +2 -4
- package/lib/cjs/metro/state.cjs +30 -78
- package/lib/cjs/metro/state.cjs.map +1 -1
- package/lib/cjs/metro/state.d.ts +8 -25
- package/lib/cjs/metro/transformer.cjs +193 -34
- package/lib/cjs/metro/transformer.cjs.map +1 -1
- package/lib/cjs/metro/with-config.cjs +2 -2
- package/lib/cjs/metro/with-config.cjs.map +1 -1
- package/lib/cjs/metro/with-config.d.ts +11 -26
- package/lib/cjs/metro/wrap-imports.cjs +273 -0
- package/lib/cjs/metro/wrap-imports.cjs.map +1 -0
- package/lib/cjs/metro/wrap-imports.d.ts +26 -0
- package/lib/cjs/runtime/components/rnwind-provider.cjs +0 -17
- package/lib/cjs/runtime/components/rnwind-provider.cjs.map +1 -1
- package/lib/cjs/runtime/components/rnwind-provider.d.ts +0 -14
- package/lib/cjs/runtime/hooks/use-css.cjs +16 -10
- package/lib/cjs/runtime/hooks/use-css.cjs.map +1 -1
- package/lib/cjs/runtime/hooks/use-css.d.ts +15 -9
- package/lib/cjs/runtime/index.cjs +11 -13
- package/lib/cjs/runtime/index.cjs.map +1 -1
- package/lib/cjs/runtime/index.d.ts +4 -9
- package/lib/cjs/runtime/lookup-css.cjs +10 -0
- package/lib/cjs/runtime/lookup-css.cjs.map +1 -1
- package/lib/cjs/runtime/lookup-css.d.ts +7 -0
- package/lib/cjs/runtime/resolve.cjs +348 -0
- package/lib/cjs/runtime/resolve.cjs.map +1 -0
- package/lib/cjs/runtime/resolve.d.ts +61 -0
- package/lib/cjs/runtime/wrap.cjs +254 -0
- package/lib/cjs/runtime/wrap.cjs.map +1 -0
- package/lib/cjs/runtime/wrap.d.ts +37 -0
- package/lib/cjs/testing/index.cjs +81 -50
- package/lib/cjs/testing/index.cjs.map +1 -1
- package/lib/esm/core/normalize-classname.d.ts +10 -0
- package/lib/esm/core/normalize-classname.mjs +23 -0
- package/lib/esm/core/normalize-classname.mjs.map +1 -0
- package/lib/esm/core/style-builder/build-style.d.ts +6 -1
- package/lib/esm/core/style-builder/build-style.mjs +258 -58
- package/lib/esm/core/style-builder/build-style.mjs.map +1 -1
- package/lib/esm/core/style-builder/union-builder.d.ts +21 -1
- package/lib/esm/core/style-builder/union-builder.mjs +37 -3
- package/lib/esm/core/style-builder/union-builder.mjs.map +1 -1
- package/lib/esm/metro/dts.d.ts +2 -4
- package/lib/esm/metro/dts.mjs +7 -16
- package/lib/esm/metro/dts.mjs.map +1 -1
- package/lib/esm/metro/state.d.ts +8 -25
- package/lib/esm/metro/state.mjs +30 -76
- package/lib/esm/metro/state.mjs.map +1 -1
- package/lib/esm/metro/transformer.mjs +194 -35
- package/lib/esm/metro/transformer.mjs.map +1 -1
- package/lib/esm/metro/with-config.d.ts +11 -26
- package/lib/esm/metro/with-config.mjs +2 -2
- package/lib/esm/metro/with-config.mjs.map +1 -1
- package/lib/esm/metro/wrap-imports.d.ts +26 -0
- package/lib/esm/metro/wrap-imports.mjs +250 -0
- package/lib/esm/metro/wrap-imports.mjs.map +1 -0
- package/lib/esm/runtime/components/rnwind-provider.d.ts +0 -14
- package/lib/esm/runtime/components/rnwind-provider.mjs +1 -17
- package/lib/esm/runtime/components/rnwind-provider.mjs.map +1 -1
- package/lib/esm/runtime/hooks/use-css.d.ts +15 -9
- package/lib/esm/runtime/hooks/use-css.mjs +16 -10
- package/lib/esm/runtime/hooks/use-css.mjs.map +1 -1
- package/lib/esm/runtime/index.d.ts +4 -9
- package/lib/esm/runtime/index.mjs +4 -4
- package/lib/esm/runtime/index.mjs.map +1 -1
- package/lib/esm/runtime/lookup-css.d.ts +7 -0
- package/lib/esm/runtime/lookup-css.mjs +10 -1
- package/lib/esm/runtime/lookup-css.mjs.map +1 -1
- package/lib/esm/runtime/resolve.d.ts +61 -0
- package/lib/esm/runtime/resolve.mjs +341 -0
- package/lib/esm/runtime/resolve.mjs.map +1 -0
- package/lib/esm/runtime/wrap.d.ts +37 -0
- package/lib/esm/runtime/wrap.mjs +251 -0
- package/lib/esm/runtime/wrap.mjs.map +1 -0
- package/lib/esm/testing/index.mjs +84 -53
- package/lib/esm/testing/index.mjs.map +1 -1
- package/package.json +2 -1
- package/src/core/normalize-classname.ts +19 -0
- package/src/core/style-builder/build-style.ts +286 -55
- package/src/core/style-builder/union-builder.ts +36 -3
- package/src/metro/dts.ts +7 -19
- package/src/metro/state.ts +29 -74
- package/src/metro/transformer.ts +190 -34
- package/src/metro/with-config.ts +13 -28
- package/src/metro/wrap-imports.ts +260 -0
- package/src/runtime/components/rnwind-provider.tsx +0 -17
- package/src/runtime/hooks/use-css.ts +17 -11
- package/src/runtime/index.ts +3 -26
- package/src/runtime/lookup-css.ts +10 -0
- package/src/runtime/resolve.ts +381 -0
- package/src/runtime/wrap.tsx +267 -0
- package/src/testing/index.ts +106 -56
- package/lib/cjs/core/parser/text-truncate.cjs +0 -78
- package/lib/cjs/core/parser/text-truncate.cjs.map +0 -1
- package/lib/cjs/metro/transform-ast.cjs +0 -1472
- package/lib/cjs/metro/transform-ast.cjs.map +0 -1
- package/lib/cjs/metro/transform-ast.d.ts +0 -88
- package/lib/cjs/runtime/haptics.cjs +0 -113
- package/lib/cjs/runtime/haptics.cjs.map +0 -1
- package/lib/cjs/runtime/haptics.d.ts +0 -48
- package/lib/cjs/runtime/interactive-box.cjs +0 -35
- package/lib/cjs/runtime/interactive-box.cjs.map +0 -1
- package/lib/cjs/runtime/interactive-box.d.ts +0 -40
- package/lib/esm/core/parser/text-truncate.mjs +0 -75
- package/lib/esm/core/parser/text-truncate.mjs.map +0 -1
- package/lib/esm/metro/transform-ast.d.ts +0 -88
- package/lib/esm/metro/transform-ast.mjs +0 -1451
- package/lib/esm/metro/transform-ast.mjs.map +0 -1
- package/lib/esm/runtime/haptics.d.ts +0 -48
- package/lib/esm/runtime/haptics.mjs +0 -110
- package/lib/esm/runtime/haptics.mjs.map +0 -1
- package/lib/esm/runtime/interactive-box.d.ts +0 -40
- package/lib/esm/runtime/interactive-box.mjs +0 -33
- package/lib/esm/runtime/interactive-box.mjs.map +0 -1
- package/src/metro/transform-ast.ts +0 -1729
- package/src/runtime/haptics.ts +0 -120
- package/src/runtime/interactive-box.tsx +0 -57
|
@@ -1,1729 +0,0 @@
|
|
|
1
|
-
import * as t from '@babel/types'
|
|
2
|
-
import type { File } from '@babel/types'
|
|
3
|
-
import traverseImport, { type NodePath } from '@babel/traverse'
|
|
4
|
-
import { createHash } from 'node:crypto'
|
|
5
|
-
import type { GradientAtomInfo, GradientDirection, HapticRequest, HapticTrigger } from '../core/parser'
|
|
6
|
-
import { detectTextTruncate, mayContainTextTruncate } from '../core/parser/text-truncate'
|
|
7
|
-
|
|
8
|
-
const traverse = (traverseImport as unknown as { default?: typeof traverseImport }).default ?? traverseImport
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Name of the internal rnwind context hook the transformer injects at
|
|
12
|
-
* each component top. Must start with `use` + uppercase letter so
|
|
13
|
-
* react-refresh's babel plugin folds it into each component's
|
|
14
|
-
* fast-refresh signature — otherwise stale signatures preserve fiber
|
|
15
|
-
* state across transformer changes and the rendered hook list shifts,
|
|
16
|
-
* which React surfaces as "change in the order of Hooks" runtime errors.
|
|
17
|
-
*/
|
|
18
|
-
const USE_RNWIND_INTERNAL = 'useR_'
|
|
19
|
-
/** Internal alias of `useMountHaptic` — emit `_hm` instead of the public name to dodge shadowing. */
|
|
20
|
-
const USE_MOUNT_HAPTIC = '_hm'
|
|
21
|
-
/** Internal alias of `triggerHaptic` — `_ht` so a user-defined `triggerHaptic` won't shadow it. */
|
|
22
|
-
const TRIGGER_HAPTIC = '_ht'
|
|
23
|
-
/** Internal alias of `lookupCss` — `_l` so user can't accidentally shadow at the JSX call sites. */
|
|
24
|
-
const LOOKUP_CSS = '_l'
|
|
25
|
-
/** Name of the runtime atom-registration entry point imported by the union style file. */
|
|
26
|
-
export const REGISTER_ATOMS = 'registerAtoms'
|
|
27
|
-
/** Package specifier rnwind runtime primitives import from. */
|
|
28
|
-
const RUNTIME_MODULE = 'rnwind'
|
|
29
|
-
/** Local binding name for the rnwind context hook result inside components. */
|
|
30
|
-
const CONTEXT_BINDING = '_t'
|
|
31
|
-
/**
|
|
32
|
-
* Name of the per-instance wrapper component rnwind substitutes for any
|
|
33
|
-
* JSX site that uses active: / focus: variants. One `useInteract()` lives
|
|
34
|
-
* INSIDE each InteractiveBox so siblings never share state — a previous
|
|
35
|
-
* design that called `useInteract()` once per enclosing component caused
|
|
36
|
-
* "press one button, all buttons glow" because every site read the same
|
|
37
|
-
* `_i.state` reference.
|
|
38
|
-
*/
|
|
39
|
-
const INTERACTIVE_BOX = '_ib'
|
|
40
|
-
/** Leading variant prefixes that trigger interact wiring. */
|
|
41
|
-
const INTERACTIVE_PREFIXES = ['active:', 'focus:']
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Regex matching the atom-name shape of every `*-safe` utility the
|
|
45
|
-
* rnwind preset ships. Used by the transformer to decide whether a
|
|
46
|
-
* file needs the `const _i = useInsets()` binding injected. Matches
|
|
47
|
-
* three families:
|
|
48
|
-
* - `*-safe` exactly (e.g. `pt-safe`, `inset-safe`).
|
|
49
|
-
* - `*-safe-or-<N>` / `*-safe-offset-<N>` (e.g. `mt-safe-or-4`).
|
|
50
|
-
* - `*-screen-safe` (e.g. `h-screen-safe`, `min-h-screen-safe`).
|
|
51
|
-
*
|
|
52
|
-
* Dynamic className expressions always inject `_i` — we can't inspect
|
|
53
|
-
* the string at build time, and the runtime slow path reads `SAFE_ATOMS`
|
|
54
|
-
* to pick up any user-defined safe utility the preset doesn't cover.
|
|
55
|
-
*/
|
|
56
|
-
const SAFE_ATOM_PATTERN = /(?:(?:^|-)safe(?:-or-|-offset-|$))|(?:-screen-safe$)/
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* RN host components that NEVER emit press / focus events — wrapping
|
|
60
|
-
* them in `<InteractiveBox>` buys nothing and costs `useInteract()`'s
|
|
61
|
-
* hooks per mount. When the JSX tag is in this set, we skip the
|
|
62
|
-
* wrapper even for dynamic `className={…}` expressions. On a list of
|
|
63
|
-
* 1000 `<View className={rowCls}>` rows this drops 6 × 1000 hook
|
|
64
|
-
* initialisations per mount.
|
|
65
|
-
*
|
|
66
|
-
* The set is intentionally conservative — anything not listed keeps
|
|
67
|
-
* the wrapper. Custom components, `Animated.View`, and
|
|
68
|
-
* `Pressable`/`TextInput` all still get interactive variants on
|
|
69
|
-
* dynamic className.
|
|
70
|
-
*/
|
|
71
|
-
const NON_INTERACTIVE_HOST_TAGS = new Set([
|
|
72
|
-
'View',
|
|
73
|
-
'Text',
|
|
74
|
-
'ScrollView',
|
|
75
|
-
'SafeAreaView',
|
|
76
|
-
'Image',
|
|
77
|
-
'ImageBackground',
|
|
78
|
-
'FlatList',
|
|
79
|
-
'SectionList',
|
|
80
|
-
'VirtualizedList',
|
|
81
|
-
'KeyboardAvoidingView',
|
|
82
|
-
'ActivityIndicator',
|
|
83
|
-
'RefreshControl',
|
|
84
|
-
'Fragment',
|
|
85
|
-
])
|
|
86
|
-
|
|
87
|
-
/** Per-file state returned by the transformer, for the caller to integrate with the atom ledger. */
|
|
88
|
-
export interface TransformAstResult {
|
|
89
|
-
/** `true` when the AST was mutated (any `className=` rewrite landed). */
|
|
90
|
-
touched: boolean
|
|
91
|
-
/** Atom-name arrays the transformer hoisted — one entry per unique atom set. */
|
|
92
|
-
hoistedArrays: ReadonlyMap<string, readonly string[]>
|
|
93
|
-
/** Candidate literal texts collected from every rewritten `className`. */
|
|
94
|
-
literals: readonly string[]
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Inputs to {@link transformAst}. */
|
|
98
|
-
export interface TransformAstOptions {
|
|
99
|
-
/**
|
|
100
|
-
* Module specifiers the transformer side-effect-imports at the top
|
|
101
|
-
* of each rewritten file. Today: the union `style.js` and
|
|
102
|
-
* `keyframes.js` (always two entries — see `STYLE_SPECIFIERS` in
|
|
103
|
-
* resolver.ts). Empty when the file has no atoms to register.
|
|
104
|
-
*/
|
|
105
|
-
styleSpecifiers: readonly string[]
|
|
106
|
-
/**
|
|
107
|
-
* Parser-surfaced gradient metadata per atom. The transformer reads
|
|
108
|
-
* this map when rewriting literal `className="..."` sites so it can
|
|
109
|
-
* strip gradient atoms out of the atom array fed to `lookupCss` and
|
|
110
|
-
* emit `colors={...} start={...} end={...}` JSX attributes consumed
|
|
111
|
-
* by `<LinearGradient>` (or any component with the expo prop shape).
|
|
112
|
-
*/
|
|
113
|
-
gradientAtoms?: ReadonlyMap<string, GradientAtomInfo>
|
|
114
|
-
/**
|
|
115
|
-
* Parser-surfaced haptic metadata per atom. Keys are the full class
|
|
116
|
-
* name (including any variant prefix — `haptic-light`,
|
|
117
|
-
* `active:haptic-medium`). Values are the structured
|
|
118
|
-
* {@link HapticRequest}. The transformer strips matched atoms from
|
|
119
|
-
* the className, aggregates mount requests per enclosing component,
|
|
120
|
-
* and wires press-in chains directly on the element.
|
|
121
|
-
*/
|
|
122
|
-
hapticAtoms?: ReadonlyMap<string, HapticRequest>
|
|
123
|
-
/**
|
|
124
|
-
* Extra prop-name prefixes that turn `<prefix>ClassName="…"` into
|
|
125
|
-
* `<prefix>Style={lookupCss(…)}` with the same plumbing as the plain
|
|
126
|
-
* `className` path. The built-in `'contentContainer'` prefix is always
|
|
127
|
-
* enabled (covers ScrollView / FlatList / SectionList) — entries here
|
|
128
|
-
* are additive, not a replacement. A user-supplied `['myFunny']` yields
|
|
129
|
-
* the effective set `['contentContainer', 'myFunny']`.
|
|
130
|
-
*
|
|
131
|
-
* Prefixed rewrites never go through `<InteractiveBox>`: the targeted
|
|
132
|
-
* sub-surfaces (scroll content containers, column wrappers, etc.)
|
|
133
|
-
* can't fire press / focus events, so we always emit the inline
|
|
134
|
-
* `lookupCss(…)` call regardless of whether the expression is static
|
|
135
|
-
* or dynamic.
|
|
136
|
-
*/
|
|
137
|
-
classNamePrefixes?: readonly string[]
|
|
138
|
-
/**
|
|
139
|
-
* Extra module specifiers whose JSX exports the transformer should
|
|
140
|
-
* treat as hosts (rewrite `className` → `style` at compile time).
|
|
141
|
-
* Merged with the built-in {@link DEFAULT_HOST_SOURCES} list. Use
|
|
142
|
-
* this for design-system packages whose primitives wrap RN hosts and
|
|
143
|
-
* accept `style` directly.
|
|
144
|
-
*/
|
|
145
|
-
hostSources?: readonly string[]
|
|
146
|
-
/**
|
|
147
|
-
* Extra component names (verbatim, including dotted member access
|
|
148
|
-
* like `'Animated.View'`) the transformer should treat as hosts. Use
|
|
149
|
-
* this for one-off escape-hatches that aren't matchable by source —
|
|
150
|
-
* e.g. you alias `View as MyBox` and want the compile-time path.
|
|
151
|
-
*/
|
|
152
|
-
hostComponents?: readonly string[]
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Built-in prefix that's always active — covers the React Native
|
|
157
|
-
* ecosystem's `contentContainerStyle` pattern on ScrollView / FlatList /
|
|
158
|
-
* SectionList. Users who pass `classNamePrefixes` get their list merged
|
|
159
|
-
* on top, never replacing this.
|
|
160
|
-
*/
|
|
161
|
-
const DEFAULT_CLASSNAME_PREFIXES: readonly string[] = ['contentContainer']
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Module specifiers whose JSX exports are "host-like" — they consume
|
|
165
|
-
* `style` directly (and own no opaque component logic that depends on
|
|
166
|
-
* receiving the raw `className` string). For tags imported from these
|
|
167
|
-
* sources the transformer rewrites `className="…"` → `style={lookupCss(…)}`
|
|
168
|
-
* at build time, so the runtime cost is zero.
|
|
169
|
-
*
|
|
170
|
-
* For tags from ANY other source the transformer leaves `className`
|
|
171
|
-
* alone — the importing component receives the raw string and decides
|
|
172
|
-
* what to do with it (forward to an inner host, reshape, route a slice
|
|
173
|
-
* to `contentContainerStyle`, …). This is what makes patterns like
|
|
174
|
-
* `<MyButton className="px-4 bg-primary" />` work without rnwind
|
|
175
|
-
* stealing the prop before the component sees it.
|
|
176
|
-
*
|
|
177
|
-
* Users extend the list via `withRnwindConfig`'s `hostSources` option.
|
|
178
|
-
*/
|
|
179
|
-
const DEFAULT_HOST_SOURCES: readonly string[] = [
|
|
180
|
-
'react-native',
|
|
181
|
-
'react-native-reanimated',
|
|
182
|
-
'react-native-svg',
|
|
183
|
-
'react-native-gesture-handler',
|
|
184
|
-
'react-native-safe-area-context',
|
|
185
|
-
'expo-linear-gradient',
|
|
186
|
-
'expo-image',
|
|
187
|
-
'expo-blur',
|
|
188
|
-
'expo-symbols',
|
|
189
|
-
'@shopify/flash-list',
|
|
190
|
-
'@shopify/react-native-skia',
|
|
191
|
-
'lottie-react-native',
|
|
192
|
-
]
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Whether a JSX tag name is lowercase. Lowercase tags don't appear in
|
|
196
|
-
* native React Native userland — but if one shows up (web target via
|
|
197
|
-
* `react-native-web`, mdx, etc.) treat it as a host so the rewrite
|
|
198
|
-
* engages instead of silently dropping the className.
|
|
199
|
-
* @param name JSX tag identifier text.
|
|
200
|
-
* @returns True for ASCII-lowercase first character.
|
|
201
|
-
*/
|
|
202
|
-
function isLowercaseTag(name: string): boolean {
|
|
203
|
-
const code = name.codePointAt(0)
|
|
204
|
-
return code !== undefined && code >= 97 && code <= 122
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Walk a JSX opening element's tag name node into a dotted string
|
|
209
|
-
* (`Animated.View`, `Foo.Bar.Baz`). Returns `null` for namespaced names
|
|
210
|
-
* (`<svg:rect>` — invalid in RN; we skip them).
|
|
211
|
-
* @param name JSXOpeningElement name node.
|
|
212
|
-
* @returns Dotted tag text, or null.
|
|
213
|
-
*/
|
|
214
|
-
function jsxTagText(name: t.JSXOpeningElement['name']): string | null {
|
|
215
|
-
if (t.isJSXIdentifier(name)) return name.name
|
|
216
|
-
if (t.isJSXMemberExpression(name)) {
|
|
217
|
-
const left = jsxTagText(name.object as t.JSXOpeningElement['name'])
|
|
218
|
-
return left ? `${left}.${name.property.name}` : null
|
|
219
|
-
}
|
|
220
|
-
return null
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Leftmost identifier of a (possibly dotted) tag — used to look up its import source.
|
|
225
|
-
* @param tagText
|
|
226
|
-
*/
|
|
227
|
-
function leftmostIdentifier(tagText: string): string {
|
|
228
|
-
const dot = tagText.indexOf('.')
|
|
229
|
-
return dot === -1 ? tagText : tagText.slice(0, dot)
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/** Resolves a tag-text to "is this a host?" using import sources + user-extended host names. */
|
|
233
|
-
type HostLookup = (tagText: string) => boolean
|
|
234
|
-
|
|
235
|
-
/**
|
|
236
|
-
* Build the per-file host lookup. Walks every `import` declaration once
|
|
237
|
-
* to map every locally-bound name to its source module. A JSX tag is a
|
|
238
|
-
* host when:
|
|
239
|
-
* 1. its full text matches an entry in `extraHostComponents` (verbatim),
|
|
240
|
-
* 2. its leftmost identifier was imported from a `hostSources` module,
|
|
241
|
-
* 3. it's a lowercase tag (web targets, defensive).
|
|
242
|
-
*
|
|
243
|
-
* Anything else is custom and the transformer leaves its className alone.
|
|
244
|
-
* @param ast File AST.
|
|
245
|
-
* @param extraHostSources User-supplied additional host module specifiers.
|
|
246
|
-
* @param extraHostComponents User-supplied additional host component names.
|
|
247
|
-
* @returns Lookup callback.
|
|
248
|
-
*/
|
|
249
|
-
function buildHostLookup(
|
|
250
|
-
ast: File,
|
|
251
|
-
extraHostSources: readonly string[] | undefined,
|
|
252
|
-
extraHostComponents: readonly string[] | undefined,
|
|
253
|
-
): HostLookup {
|
|
254
|
-
const importSourceByLocal = new Map<string, string>()
|
|
255
|
-
for (const node of ast.program.body) {
|
|
256
|
-
if (!t.isImportDeclaration(node)) continue
|
|
257
|
-
const source = node.source.value
|
|
258
|
-
for (const spec of node.specifiers) {
|
|
259
|
-
if (t.isImportDefaultSpecifier(spec) || t.isImportSpecifier(spec) || t.isImportNamespaceSpecifier(spec)) {
|
|
260
|
-
importSourceByLocal.set(spec.local.name, source)
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
// Recognise module-local host aliases — common pattern in React Native:
|
|
265
|
-
// const AnimatedTextInput = Animated.createAnimatedComponent(TextInput)
|
|
266
|
-
// const Animated = createAnimatedComponent(View)
|
|
267
|
-
// The local binding wraps a host underneath so its className must still
|
|
268
|
-
// be rewritten. Without this every `<AnimatedTextInput className="…" />`
|
|
269
|
-
// site looked custom and the className silently dropped.
|
|
270
|
-
const localHostAliases = collectCreateAnimatedComponentAliases(ast)
|
|
271
|
-
const hostSources = new Set<string>([...DEFAULT_HOST_SOURCES, ...(extraHostSources ?? [])])
|
|
272
|
-
const hostComponents = new Set<string>(extraHostComponents)
|
|
273
|
-
return (tagText: string): boolean => {
|
|
274
|
-
if (isLowercaseTag(tagText)) return true
|
|
275
|
-
if (hostComponents.has(tagText)) return true
|
|
276
|
-
const left = leftmostIdentifier(tagText)
|
|
277
|
-
if (localHostAliases.has(left)) return true
|
|
278
|
-
const source = importSourceByLocal.get(left)
|
|
279
|
-
return source !== undefined && hostSources.has(source)
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
* Walk top-level `const X = createAnimatedComponent(Y)` /
|
|
285
|
-
* `Animated.createAnimatedComponent(Y)` declarations and return the set
|
|
286
|
-
* of local names so the host-lookup recognises them. Reanimated +
|
|
287
|
-
* RN-core `Animated.createAnimatedComponent` are the only creators in
|
|
288
|
-
* common use; matching by callee-name covers both shapes without
|
|
289
|
-
* needing import-source resolution.
|
|
290
|
-
* @param ast File AST.
|
|
291
|
-
* @returns Set of locally-bound names that wrap a host component.
|
|
292
|
-
*/
|
|
293
|
-
function collectCreateAnimatedComponentAliases(ast: File): ReadonlySet<string> {
|
|
294
|
-
const aliases = new Set<string>()
|
|
295
|
-
for (const node of ast.program.body) {
|
|
296
|
-
const declaration = t.isExportNamedDeclaration(node) ? node.declaration : node
|
|
297
|
-
if (!t.isVariableDeclaration(declaration)) continue
|
|
298
|
-
for (const decl of declaration.declarations) {
|
|
299
|
-
if (!t.isIdentifier(decl.id) || !decl.init) continue
|
|
300
|
-
if (!isCreateAnimatedComponentCall(decl.init)) continue
|
|
301
|
-
aliases.add(decl.id.name)
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
return aliases
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* True for `createAnimatedComponent(...)` and `<x>.createAnimatedComponent(...)` calls.
|
|
309
|
-
* @param expr
|
|
310
|
-
*/
|
|
311
|
-
function isCreateAnimatedComponentCall(expr: t.Expression): boolean {
|
|
312
|
-
if (!t.isCallExpression(expr)) return false
|
|
313
|
-
const { callee } = expr
|
|
314
|
-
if (t.isIdentifier(callee) && callee.name === 'createAnimatedComponent') return true
|
|
315
|
-
if (t.isMemberExpression(callee) && t.isIdentifier(callee.property) && callee.property.name === 'createAnimatedComponent') return true
|
|
316
|
-
return false
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* Mutate an already-parsed Babel AST in place:
|
|
321
|
-
* - Rewrite every JSX `className="…"` / `className={expr}` attribute to
|
|
322
|
-
* `style={lookupCss(<ref|expr>, _s, <existingStyle>)}`. Static string
|
|
323
|
-
* literals get a module-scope `const _c_<hash> = Object.freeze(['a',
|
|
324
|
-
* 'b'])` hoist so React sees an identity-stable array across renders.
|
|
325
|
-
* - Preserve any adjacent `style={…}` prop — it becomes the third
|
|
326
|
-
* argument so user inline styles keep working (and trump atoms).
|
|
327
|
-
* - Inject `const _s = useScheme()` at the top of the enclosing
|
|
328
|
-
* function component (idempotent — one injection per component).
|
|
329
|
-
* - Prepend `import { lookupCss, useScheme } from 'rnwind'`.
|
|
330
|
-
* - Prepend a side-effect `import 'rnwind/__generated/style'` so the
|
|
331
|
-
* union registry is loaded before any hoist runs.
|
|
332
|
-
* @param ast Babel File AST (usually handed to us by Metro).
|
|
333
|
-
* @param options Extra inputs — side-effect import specifiers + parser metadata.
|
|
334
|
-
* @returns Transform outcome flags + the hoist table.
|
|
335
|
-
*/
|
|
336
|
-
export function transformAst(ast: File, options: TransformAstOptions): TransformAstResult {
|
|
337
|
-
const hoister = createHoister()
|
|
338
|
-
const gradientHoister = createGradientHoister()
|
|
339
|
-
const literals: string[] = []
|
|
340
|
-
const prefixSet = buildPrefixSet(options.classNamePrefixes)
|
|
341
|
-
const hapticHoister = createHapticHoister()
|
|
342
|
-
const isHostTag = buildHostLookup(ast, options.hostSources, options.hostComponents)
|
|
343
|
-
const rewriteCtx: RewriteContext = {
|
|
344
|
-
needsInsets: false,
|
|
345
|
-
gradientAtoms: options.gradientAtoms ?? EMPTY_GRADIENT_ATOMS,
|
|
346
|
-
gradientHoister,
|
|
347
|
-
hapticAtoms: options.hapticAtoms ?? EMPTY_HAPTIC_ATOMS,
|
|
348
|
-
hapticHoister,
|
|
349
|
-
mountByComponent: new Map(),
|
|
350
|
-
needsHapticsHook: false,
|
|
351
|
-
}
|
|
352
|
-
let touched = false
|
|
353
|
-
let usedLookupCss = false
|
|
354
|
-
let usedInteractiveBox = false
|
|
355
|
-
// Per-element host classification, captured the first time we see each
|
|
356
|
-
// JSXOpeningElement. Necessary because the InteractiveBox wrap mutates
|
|
357
|
-
// `parent.name` in-place from the original tag → `_ib`; sibling
|
|
358
|
-
// attributes processed AFTER the swap would otherwise re-classify off
|
|
359
|
-
// the now-meaningless `_ib` name and skip rewrites they should do
|
|
360
|
-
// (e.g. `contentContainerClassName` next to an `active:` className on
|
|
361
|
-
// the same `<ScrollView>`).
|
|
362
|
-
const customElements = new WeakSet<t.JSXOpeningElement>()
|
|
363
|
-
const classifiedElements = new WeakSet<t.JSXOpeningElement>()
|
|
364
|
-
|
|
365
|
-
traverse(ast, {
|
|
366
|
-
JSXAttribute(attributePath: NodePath<t.JSXAttribute>) {
|
|
367
|
-
const { node } = attributePath
|
|
368
|
-
if (!t.isJSXIdentifier(node.name)) return
|
|
369
|
-
const target = classifyAttributeName(node.name.name, prefixSet)
|
|
370
|
-
if (!target) return
|
|
371
|
-
// Skip className rewrite when the parent JSX tag is a custom
|
|
372
|
-
// component (not imported from a known host source). Custom
|
|
373
|
-
// components own their `className` prop — the transformer would
|
|
374
|
-
// steal the string from under them otherwise. The literal still
|
|
375
|
-
// appears in source text, so oxide still discovers its atoms via
|
|
376
|
-
// the project scan; the inner host that ultimately consumes the
|
|
377
|
-
// forwarded className gets rewritten by ITS file's transform.
|
|
378
|
-
const { parent } = attributePath
|
|
379
|
-
if (t.isJSXOpeningElement(parent)) {
|
|
380
|
-
if (!classifiedElements.has(parent)) {
|
|
381
|
-
classifiedElements.add(parent)
|
|
382
|
-
const tagText = jsxTagText(parent.name)
|
|
383
|
-
if (tagText !== null && !isHostTag(tagText)) customElements.add(parent)
|
|
384
|
-
}
|
|
385
|
-
if (customElements.has(parent)) return
|
|
386
|
-
}
|
|
387
|
-
const rewritten = rewriteClassNameAttribute(attributePath, hoister, literals, rewriteCtx, target)
|
|
388
|
-
if (!rewritten) return
|
|
389
|
-
touched = true
|
|
390
|
-
if (rewritten.injectedInteract) usedInteractiveBox = true
|
|
391
|
-
else usedLookupCss = true
|
|
392
|
-
},
|
|
393
|
-
})
|
|
394
|
-
|
|
395
|
-
if (!touched && options.styleSpecifiers.length === 0) return { touched: false, hoistedArrays: hoister.entries, literals }
|
|
396
|
-
|
|
397
|
-
// Inject `useMountHaptic(<hoisted>)` per component that had bare
|
|
398
|
-
// haptic atoms. Done post-traversal so we know every aggregated
|
|
399
|
-
// request up front and can hoist one frozen array per component.
|
|
400
|
-
injectMountHapticCalls(rewriteCtx)
|
|
401
|
-
const usedMountHaptic = rewriteCtx.mountByComponent.size > 0
|
|
402
|
-
prependRuntimeImports(
|
|
403
|
-
ast,
|
|
404
|
-
{
|
|
405
|
-
usedLookupCss,
|
|
406
|
-
usedInteractiveBox,
|
|
407
|
-
usedMountHaptic,
|
|
408
|
-
usedTriggerHaptic: rewriteCtx.needsHapticsHook,
|
|
409
|
-
touched,
|
|
410
|
-
},
|
|
411
|
-
options.styleSpecifiers,
|
|
412
|
-
)
|
|
413
|
-
if (hoister.entries.size > 0) injectHoistedConsts(ast, hoister.entries)
|
|
414
|
-
if (gradientHoister.entries.size > 0) injectGradientConsts(ast, gradientHoister.entries)
|
|
415
|
-
if (hapticHoister.entries.size > 0) injectHapticConsts(ast, hapticHoister.entries)
|
|
416
|
-
return { touched, hoistedArrays: hoister.entries, literals }
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
/** Default empty gradient-atoms map used when callers don't supply one. */
|
|
420
|
-
const EMPTY_GRADIENT_ATOMS: ReadonlyMap<string, GradientAtomInfo> = new Map()
|
|
421
|
-
/** Default empty haptic-atoms map used when callers don't supply one. */
|
|
422
|
-
const EMPTY_HAPTIC_ATOMS: ReadonlyMap<string, HapticRequest> = new Map()
|
|
423
|
-
|
|
424
|
-
/**
|
|
425
|
-
* Target of one rewrite — which JSX prop we replace and what name the
|
|
426
|
-
* replacement carries. `kind: 'className'` is the classic `className →
|
|
427
|
-
* style` path; `kind: 'prefix'` is `<prefix>ClassName → <prefix>Style`
|
|
428
|
-
* and skips the InteractiveBox wrapper (prefixed sub-surfaces can't
|
|
429
|
-
* fire press / focus events).
|
|
430
|
-
*/
|
|
431
|
-
type RewriteTarget =
|
|
432
|
-
| { readonly kind: 'className'; readonly styleProp: 'style' }
|
|
433
|
-
| { readonly kind: 'prefix'; readonly styleProp: string }
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* Merge the built-in default prefix with the caller-supplied list. The
|
|
437
|
-
* default (`contentContainer`) is always present; user entries are
|
|
438
|
-
* additive. Returned as a Set so the hot-path visitor classifies one
|
|
439
|
-
* attribute in O(1).
|
|
440
|
-
* @param userPrefixes Extra prefixes the caller wants active.
|
|
441
|
-
* @returns Sorted effective prefix set.
|
|
442
|
-
*/
|
|
443
|
-
function buildPrefixSet(userPrefixes: readonly string[] | undefined): ReadonlySet<string> {
|
|
444
|
-
const out = new Set<string>(DEFAULT_CLASSNAME_PREFIXES)
|
|
445
|
-
if (userPrefixes) for (const prefix of userPrefixes) out.add(prefix)
|
|
446
|
-
return out
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
* Decide whether a JSX attribute name is one the transformer should
|
|
451
|
-
* rewrite, and derive the replacement prop name when it is.
|
|
452
|
-
*
|
|
453
|
-
* `className` is the classic path. `<prefix>ClassName` where `prefix`
|
|
454
|
-
* is in the active set becomes `<prefix>Style`. Everything else returns
|
|
455
|
-
* `null` and the visitor moves on.
|
|
456
|
-
* @param name JSXAttribute's identifier text.
|
|
457
|
-
* @param prefixes Effective prefix set for this transform.
|
|
458
|
-
* @returns Rewrite target record, or `null` when the attribute is not ours.
|
|
459
|
-
*/
|
|
460
|
-
function classifyAttributeName(name: string, prefixes: ReadonlySet<string>): RewriteTarget | null {
|
|
461
|
-
if (name === 'className') return { kind: 'className', styleProp: 'style' }
|
|
462
|
-
if (!name.endsWith('ClassName')) return null
|
|
463
|
-
const prefix = name.slice(0, -'ClassName'.length)
|
|
464
|
-
if (prefix.length === 0 || !prefixes.has(prefix)) return null
|
|
465
|
-
return { kind: 'prefix', styleProp: `${prefix}Style` }
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
/**
|
|
469
|
-
* Rewrite-wide state threaded through every JSXAttribute visit. Right
|
|
470
|
-
* now it's just the insets-injection flag — flipped to `true` when any
|
|
471
|
-
* atom looks like a safe-area utility so the import writer knows to
|
|
472
|
-
* pull in `useInsets` alongside `useScheme`.
|
|
473
|
-
*/
|
|
474
|
-
interface RewriteContext {
|
|
475
|
-
/** Flipped on the first safe-area atom seen in the file. */
|
|
476
|
-
needsInsets: boolean
|
|
477
|
-
/** Parser-surfaced gradient metadata, keyed by atom name. */
|
|
478
|
-
gradientAtoms: ReadonlyMap<string, GradientAtomInfo>
|
|
479
|
-
/** Hoister for gradient spec consts (colours / start / end). */
|
|
480
|
-
gradientHoister: GradientHoister
|
|
481
|
-
/** Parser-surfaced haptic metadata, keyed by full class name. */
|
|
482
|
-
hapticAtoms: ReadonlyMap<string, HapticRequest>
|
|
483
|
-
/** Hoister for HapticRequest objects + mount-request arrays. */
|
|
484
|
-
hapticHoister: HapticHoister
|
|
485
|
-
/**
|
|
486
|
-
* Aggregates mount-haptic requests per enclosing component body.
|
|
487
|
-
* Populated as JSX is visited; consumed after traversal to inject
|
|
488
|
-
* one `useMountHaptic(...)` call per component.
|
|
489
|
-
*/
|
|
490
|
-
mountByComponent: Map<t.BlockStatement, HapticRequest[]>
|
|
491
|
-
/** Flipped on the first event (press / focus / hover) haptic that needs `_h`. */
|
|
492
|
-
needsHapticsHook: boolean
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
/** Per-attribute outcome from {@link rewriteClassNameAttribute}. */
|
|
496
|
-
interface RewriteOutcome {
|
|
497
|
-
/** `true` when the element was wired for active/focus interact state. */
|
|
498
|
-
injectedInteract: boolean
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Rewrite one `className` JSXAttribute node.
|
|
503
|
-
*
|
|
504
|
-
* Two paths:
|
|
505
|
-
* - **Non-interactive** (literal with no `active:` / `focus:` tokens):
|
|
506
|
-
* emit `style={lookupCss(<ref|expr>, _s [, userStyle])}` inline on
|
|
507
|
-
* the existing tag. The JSX site keeps its original component.
|
|
508
|
-
* - **Interactive** (literal with an interactive token OR any dynamic
|
|
509
|
-
* expression): replace the JSXElement's tag with `<InteractiveBox>`,
|
|
510
|
-
* move the original tag into a `_rw.as` spec prop, and forward all
|
|
511
|
-
* other attributes untouched. Each InteractiveBox instance calls
|
|
512
|
-
* `useInteract()` internally so sibling elements don't share state.
|
|
513
|
-
*
|
|
514
|
-
* If the element has a sibling `style={…}` attribute it's removed and
|
|
515
|
-
* its expression threads through as the user-style merge source.
|
|
516
|
-
* @param attributePath The JSXAttribute path.
|
|
517
|
-
* @param hoister Per-file hoist table.
|
|
518
|
-
* @param literals Output array — each static literal gets pushed so the
|
|
519
|
-
* caller can feed them into the parser / atom ledger.
|
|
520
|
-
* @param rewriteCtx
|
|
521
|
-
* @param target
|
|
522
|
-
* @returns Outcome flags, or `null` when the attribute was unrewritable.
|
|
523
|
-
*/
|
|
524
|
-
function rewriteClassNameAttribute(
|
|
525
|
-
attributePath: NodePath<t.JSXAttribute>,
|
|
526
|
-
hoister: Hoister,
|
|
527
|
-
literals: string[],
|
|
528
|
-
rewriteCtx: RewriteContext,
|
|
529
|
-
target: RewriteTarget,
|
|
530
|
-
): RewriteOutcome | null {
|
|
531
|
-
const { node } = attributePath
|
|
532
|
-
const { value } = node
|
|
533
|
-
if (!value) return null
|
|
534
|
-
const { parent } = attributePath
|
|
535
|
-
if (!t.isJSXOpeningElement(parent)) return null
|
|
536
|
-
// The rewrite emits references to `_t` (the `useR_()` binding). That
|
|
537
|
-
// binding can only live in a component body — so if this JSX site has
|
|
538
|
-
// no enclosing component (e.g. a top-level `const renderItem = (...) =>
|
|
539
|
-
// <View className=.../>` helper), bail and leave className untouched
|
|
540
|
-
// rather than emit a dangling `_t`. Checked BEFORE any mutation
|
|
541
|
-
// (hoist, sibling-style drop) so a bail leaves the AST pristine.
|
|
542
|
-
if (!hasComponentBody(attributePath)) return null
|
|
543
|
-
const buildResult = buildFirstArgument(value, hoister, literals, rewriteCtx)
|
|
544
|
-
if (!buildResult) return null
|
|
545
|
-
const userStyleExpr = extractAndDropSiblingStyle(parent, target.styleProp)
|
|
546
|
-
// Single context binding `_t = _r()` — carries scheme, fontScale,
|
|
547
|
-
// insets together so React tracks all three as render deps via one
|
|
548
|
-
// useContext read.
|
|
549
|
-
const ctxBinding = injectContextHook(attributePath)
|
|
550
|
-
applyDerivedJsxAttributes(attributePath, parent, buildResult, target, rewriteCtx)
|
|
551
|
-
// Prefixed rewrites (`<prefix>ClassName`) target a passive sub-surface
|
|
552
|
-
// that can't receive press / focus — skip the InteractiveBox wrapper
|
|
553
|
-
// even for dynamic expressions. Only the plain `className` path is
|
|
554
|
-
// eligible for InteractiveBox routing.
|
|
555
|
-
if (target.kind === 'className' && buildResult.mayBeInteractive && isTagInteractive(parent.name)) {
|
|
556
|
-
rewriteAsInteractiveBox(attributePath, parent, buildResult.expression, ctxBinding, userStyleExpr)
|
|
557
|
-
return { injectedInteract: true }
|
|
558
|
-
}
|
|
559
|
-
const args: t.Expression[] = [buildResult.expression, t.identifier(ctxBinding)]
|
|
560
|
-
// 3rd arg = userStyle (sibling style={…}). 4th arg = interactState
|
|
561
|
-
// (always undefined in the non-interactive branch).
|
|
562
|
-
if (userStyleExpr) args.push(userStyleExpr)
|
|
563
|
-
const call = t.callExpression(t.identifier(LOOKUP_CSS), args)
|
|
564
|
-
attributePath.replaceWith(t.jsxAttribute(t.jsxIdentifier(target.styleProp), t.jsxExpressionContainer(call)))
|
|
565
|
-
return { injectedInteract: false }
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
/**
|
|
569
|
-
* Apply every JSX attribute + side-effect derived from a parsed
|
|
570
|
-
* className literal: gradient props, truncate props, mount-haptic
|
|
571
|
-
* aggregation, and event-haptic handler chaining. Collected in one
|
|
572
|
-
* helper so {@link rewriteClassNameAttribute} stays under the
|
|
573
|
-
* complexity cap.
|
|
574
|
-
* @param attributePath Path of the className attribute being rewritten.
|
|
575
|
-
* @param parent Opening element to mutate.
|
|
576
|
-
* @param result Per-literal derived state.
|
|
577
|
-
* @param target Rewrite target (only `className`-kind gets derived attrs).
|
|
578
|
-
* @param rewriteCtx Rewrite-wide state.
|
|
579
|
-
*/
|
|
580
|
-
function applyDerivedJsxAttributes(
|
|
581
|
-
attributePath: NodePath<t.JSXAttribute>,
|
|
582
|
-
parent: t.JSXOpeningElement,
|
|
583
|
-
result: FirstArgumentResult,
|
|
584
|
-
target: RewriteTarget,
|
|
585
|
-
rewriteCtx: RewriteContext,
|
|
586
|
-
): void {
|
|
587
|
-
if (target.kind !== 'className') return
|
|
588
|
-
if (result.gradientAttrs) appendGradientAttributes(parent, result.gradientAttrs)
|
|
589
|
-
if (result.truncateAttrs) appendGradientAttributes(parent, result.truncateAttrs)
|
|
590
|
-
if (result.mountHaptics) recordMountHaptics(attributePath, result.mountHaptics, rewriteCtx)
|
|
591
|
-
if (result.eventHaptics) injectEventHapticHandlers(attributePath, parent, result.eventHaptics, rewriteCtx)
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
/**
|
|
595
|
-
* Splice class-derived JSX attributes (`colors={…}` / `start={…}` /
|
|
596
|
-
* `end={…}` for gradients; `numberOfLines=` / `ellipsizeMode=` for
|
|
597
|
-
* truncate) into a JSXOpeningElement's attribute list — but only when
|
|
598
|
-
* the developer hasn't already written that attribute themselves.
|
|
599
|
-
*
|
|
600
|
-
* **User attrs always win.** If a hand-written `colors={USER}` is
|
|
601
|
-
* present, the class-derived hoist is dropped on the floor for that
|
|
602
|
-
* specific attribute. Same rule for every derived prop, applied
|
|
603
|
-
* per-attribute so the user can override one slot (e.g. `start={…}`)
|
|
604
|
-
* and let rnwind fill in the others. Documented in
|
|
605
|
-
* `docs/architecture.md`.
|
|
606
|
-
* @param opening JSXOpeningElement to mutate.
|
|
607
|
-
* @param gradientAttributes Freshly built JSX attributes.
|
|
608
|
-
*/
|
|
609
|
-
function appendGradientAttributes(opening: t.JSXOpeningElement, gradientAttributes: readonly t.JSXAttribute[]): void {
|
|
610
|
-
const userAttributeNames = new Set<string>()
|
|
611
|
-
for (const attribute of opening.attributes) {
|
|
612
|
-
if (!t.isJSXAttribute(attribute)) continue
|
|
613
|
-
if (!t.isJSXIdentifier(attribute.name)) continue
|
|
614
|
-
userAttributeNames.add(attribute.name.name)
|
|
615
|
-
}
|
|
616
|
-
for (const derived of gradientAttributes) {
|
|
617
|
-
if (!t.isJSXIdentifier(derived.name)) continue
|
|
618
|
-
if (userAttributeNames.has(derived.name.name)) continue
|
|
619
|
-
opening.attributes.push(derived)
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
/**
|
|
624
|
-
* Whether a JSX tag can fire press / focus events. Pure host-tag check
|
|
625
|
-
* against {@link NON_INTERACTIVE_HOST_TAGS}: anything in the set is
|
|
626
|
-
* definitely non-interactive; anything else (custom component,
|
|
627
|
-
* `Animated.View`, etc.) is treated as potentially interactive so the
|
|
628
|
-
* InteractiveBox wrapper is still applied.
|
|
629
|
-
* @param name JSXOpeningElement name node.
|
|
630
|
-
* @returns `true` when the tag might emit press / focus events.
|
|
631
|
-
*/
|
|
632
|
-
function isTagInteractive(name: t.JSXOpeningElement['name']): boolean {
|
|
633
|
-
if (t.isJSXIdentifier(name)) return !NON_INTERACTIVE_HOST_TAGS.has(name.name)
|
|
634
|
-
// Member expressions (`Animated.View`, `Foo.Bar`): conservatively
|
|
635
|
-
// treat as interactive since the outer object's semantics are opaque.
|
|
636
|
-
return true
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Replace the JSXElement's tag with `<InteractiveBox>`, packing the
|
|
641
|
-
* original tag, the className ref / expression, the scheme binding, and
|
|
642
|
-
* any user style into a single `_rw` spec prop. All other attributes
|
|
643
|
-
* forward through unchanged.
|
|
644
|
-
*
|
|
645
|
-
* The replacement keeps the element's children — only the opening /
|
|
646
|
-
* closing tag name changes, plus the className attribute is replaced by
|
|
647
|
-
* `_rw` (and a preceding `style` attribute was already spliced out).
|
|
648
|
-
* @param attributePath JSXAttribute path for the className being rewritten.
|
|
649
|
-
* @param opening JSXOpeningElement the attribute lives on.
|
|
650
|
-
* @param classNameExpr The first-arg expression (hoisted ref or dynamic).
|
|
651
|
-
* @param schemeBinding Name of the `_s = useScheme()` binding.
|
|
652
|
-
* @param ctxBinding
|
|
653
|
-
* @param userStyleExpr Optional user style spliced from a sibling `style={…}`.
|
|
654
|
-
* @param insetsBinding `_i = useInsets()` binding name when the rewrite needs insets, else null.
|
|
655
|
-
* @param fontScaleBinding `_fs = useFontScale()` binding name — always present since every rewrite injects it.
|
|
656
|
-
*/
|
|
657
|
-
function rewriteAsInteractiveBox(
|
|
658
|
-
attributePath: NodePath<t.JSXAttribute>,
|
|
659
|
-
opening: t.JSXOpeningElement,
|
|
660
|
-
classNameExpr: t.Expression,
|
|
661
|
-
ctxBinding: string,
|
|
662
|
-
userStyleExpr: t.Expression | null,
|
|
663
|
-
): void {
|
|
664
|
-
const originalTagExpr = jsxNameToExpression(opening.name)
|
|
665
|
-
const rwProperties: t.ObjectProperty[] = [
|
|
666
|
-
t.objectProperty(t.identifier('as'), originalTagExpr),
|
|
667
|
-
t.objectProperty(t.identifier('cn'), classNameExpr),
|
|
668
|
-
t.objectProperty(t.identifier('t'), t.identifier(ctxBinding)),
|
|
669
|
-
]
|
|
670
|
-
if (userStyleExpr) rwProperties.push(t.objectProperty(t.identifier('us'), userStyleExpr))
|
|
671
|
-
const rwAttribute = t.jsxAttribute(t.jsxIdentifier('_rw'), t.jsxExpressionContainer(t.objectExpression(rwProperties)))
|
|
672
|
-
// Swap the className attribute out for `_rw`, keeping it at the
|
|
673
|
-
// attribute's original position so any surrounding spread attrs stay
|
|
674
|
-
// honouring the user's intended order.
|
|
675
|
-
attributePath.replaceWith(rwAttribute)
|
|
676
|
-
opening.name = t.jsxIdentifier(INTERACTIVE_BOX)
|
|
677
|
-
const jsxElement = findParentJsxElement(attributePath)
|
|
678
|
-
if (jsxElement?.closingElement) jsxElement.closingElement.name = t.jsxIdentifier(INTERACTIVE_BOX)
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
/**
|
|
682
|
-
* Walk from a JSXAttribute path up to its JSXElement ancestor.
|
|
683
|
-
* @param attributePath JSXAttribute path.
|
|
684
|
-
* @returns The enclosing JSXElement, or `null` when the shape is unexpected.
|
|
685
|
-
*/
|
|
686
|
-
function findParentJsxElement(attributePath: NodePath<t.JSXAttribute>): t.JSXElement | null {
|
|
687
|
-
const openingPath = attributePath.parentPath
|
|
688
|
-
if (!openingPath) return null
|
|
689
|
-
const elementPath = openingPath.parentPath
|
|
690
|
-
if (!elementPath) return null
|
|
691
|
-
const { node } = elementPath
|
|
692
|
-
return t.isJSXElement(node) ? node : null
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
/**
|
|
696
|
-
* Convert a JSX opening-element name (identifier or member expression)
|
|
697
|
-
* into a regular JS expression we can splice into the `_rw.as` object
|
|
698
|
-
* property. `<Animated.View>` → `Animated.View`, `<Pressable>` →
|
|
699
|
-
* `Pressable`.
|
|
700
|
-
* @param name JSXOpeningElement name node.
|
|
701
|
-
* @returns Equivalent identifier / member-expression node.
|
|
702
|
-
*/
|
|
703
|
-
function jsxNameToExpression(name: t.JSXOpeningElement['name']): t.Expression {
|
|
704
|
-
if (t.isJSXIdentifier(name)) return t.identifier(name.name)
|
|
705
|
-
if (t.isJSXMemberExpression(name)) {
|
|
706
|
-
return t.memberExpression(jsxNameToExpression(name.object), t.identifier(name.property.name))
|
|
707
|
-
}
|
|
708
|
-
throw new Error(
|
|
709
|
-
`rnwind: unsupported JSX tag shape "${(name as { type?: string }).type ?? 'unknown'}" for interactive className`,
|
|
710
|
-
)
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
/** Result from {@link buildFirstArgument} — the lookupCss first arg + flags. */
|
|
714
|
-
interface FirstArgumentResult {
|
|
715
|
-
/** Expression to splice in as `lookupCss`'s first argument. */
|
|
716
|
-
expression: t.Expression
|
|
717
|
-
/**
|
|
718
|
-
* Whether this className might engage active/focus variants at runtime.
|
|
719
|
-
* `true` for every dynamic (non-literal) expression — we can't know
|
|
720
|
-
* the eventual string. For literals, `true` only if any token carries
|
|
721
|
-
* a recognised interactive prefix.
|
|
722
|
-
*/
|
|
723
|
-
mayBeInteractive: boolean
|
|
724
|
-
/**
|
|
725
|
-
* Whether this particular rewrite needs the safe-area insets
|
|
726
|
-
* argument passed to `lookupCss`. Set to `true` for dynamic
|
|
727
|
-
* expressions (can't inspect tokens at build time) and for literals
|
|
728
|
-
* that include any `*-safe` utility. When `false` the rewrite emits
|
|
729
|
-
* the compact 2-arg call so the runtime fast path stays engaged.
|
|
730
|
-
*/
|
|
731
|
-
needsInsets: boolean
|
|
732
|
-
/**
|
|
733
|
-
* Extra JSX attributes the rewrite should inject alongside the
|
|
734
|
-
* `style={...}` prop. Non-null only when the literal carried gradient
|
|
735
|
-
* atoms: `colors={_g_x}`, `start={_gs_x}`, `end={_ge_x}`, optionally
|
|
736
|
-
* `locations={_gl_x}` — stable consts hoisted at module scope.
|
|
737
|
-
*/
|
|
738
|
-
gradientAttrs?: readonly t.JSXAttribute[]
|
|
739
|
-
/**
|
|
740
|
-
* Extra JSX attributes derived from text-truncate atoms (`truncate`,
|
|
741
|
-
* `line-clamp-<N>`, `text-ellipsis`, `text-clip`). Emitted as inline
|
|
742
|
-
* literals — `numberOfLines={N}` and/or `ellipsizeMode="tail"` — so
|
|
743
|
-
* `<Text>` (and any `Text`-prop-shaped component) gets the right
|
|
744
|
-
* native truncation without the user hand-wiring props.
|
|
745
|
-
*/
|
|
746
|
-
truncateAttrs?: readonly t.JSXAttribute[]
|
|
747
|
-
/**
|
|
748
|
-
* Mount-haptic requests collected from this literal (bare `haptic-*`
|
|
749
|
-
* atoms, no variant prefix). Aggregated per-component by the caller.
|
|
750
|
-
*/
|
|
751
|
-
mountHaptics?: readonly HapticRequest[]
|
|
752
|
-
/**
|
|
753
|
-
* Event-haptic entries (`active:haptic-*` / `focus:haptic-*` /
|
|
754
|
-
* `hover:haptic-*`). Caller splices the chained event handlers onto
|
|
755
|
-
* the opening element.
|
|
756
|
-
*/
|
|
757
|
-
eventHaptics?: readonly { readonly request: HapticRequest; readonly trigger: Exclude<HapticTrigger, 'mount'> }[]
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
/**
|
|
761
|
-
* Decide what the first arg of the rewritten `lookupCss(...)` call
|
|
762
|
-
* should be:
|
|
763
|
-
* - Static string literal (`"…"` or `{"…"}` or static template): tokenize,
|
|
764
|
-
* push literal text for the ledger, return a hoisted const reference.
|
|
765
|
-
* - Dynamic expression: forward the expression unchanged; runtime
|
|
766
|
-
* tokenizes the string result at render time.
|
|
767
|
-
* @param value Attribute's value node (StringLiteral or JSXExpressionContainer).
|
|
768
|
-
* @param hoister Hoist table.
|
|
769
|
-
* @param literals Output array for static literals.
|
|
770
|
-
* @param rewriteCtx
|
|
771
|
-
* @returns The first-arg expression + interact-eligibility flag, or `null`.
|
|
772
|
-
*/
|
|
773
|
-
function buildFirstArgument(
|
|
774
|
-
value: t.JSXAttribute['value'],
|
|
775
|
-
hoister: Hoister,
|
|
776
|
-
literals: string[],
|
|
777
|
-
rewriteCtx: RewriteContext,
|
|
778
|
-
): FirstArgumentResult | null {
|
|
779
|
-
if (t.isStringLiteral(value)) return literalResult(value.value, hoister, literals, rewriteCtx)
|
|
780
|
-
if (!t.isJSXExpressionContainer(value)) return null
|
|
781
|
-
const { expression } = value
|
|
782
|
-
if (t.isJSXEmptyExpression(expression)) return null
|
|
783
|
-
if (t.isStringLiteral(expression)) return literalResult(expression.value, hoister, literals, rewriteCtx)
|
|
784
|
-
if (t.isTemplateLiteral(expression) && expression.expressions.length === 0 && expression.quasis[0]) {
|
|
785
|
-
const text = expression.quasis[0].value.cooked ?? expression.quasis[0].value.raw
|
|
786
|
-
return literalResult(text, hoister, literals, rewriteCtx)
|
|
787
|
-
}
|
|
788
|
-
// Dynamic expression — can't inspect atoms at build time. Assume safe
|
|
789
|
-
// is possible and pull in `_i` so the runtime can resolve any
|
|
790
|
-
// `*-safe` class a consumer composes at runtime. The runtime fast
|
|
791
|
-
// path is still taken when the dynamic string resolves to a plain
|
|
792
|
-
// non-safe atom list (SAFE_ATOMS index check gates the slow path).
|
|
793
|
-
rewriteCtx.needsInsets = true
|
|
794
|
-
return { expression: expression as t.Expression, mayBeInteractive: true, needsInsets: true }
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
/**
|
|
798
|
-
* Package a literal classname into a hoisted atom-array ref and scan it
|
|
799
|
-
* for interactive prefixes (`active:`, `focus:`) + safe-area patterns.
|
|
800
|
-
* Pre-scanned literals without any interactive tokens skip the (small
|
|
801
|
-
* but measurable) cost of injecting a `useInteract()` hook; literals
|
|
802
|
-
* without any `*-safe` token skip the insets arg, keeping the runtime
|
|
803
|
-
* fast path engaged.
|
|
804
|
-
* @param text Raw classname string.
|
|
805
|
-
* @param hoister Hoist table.
|
|
806
|
-
* @param literals Output array for literal-text sink.
|
|
807
|
-
* @param rewriteCtx Rewrite-wide state; updated when any atom needs insets.
|
|
808
|
-
* @returns The expression + per-rewrite flags.
|
|
809
|
-
*/
|
|
810
|
-
function literalResult(text: string, hoister: Hoister, literals: string[], rewriteCtx: RewriteContext): FirstArgumentResult {
|
|
811
|
-
literals.push(text)
|
|
812
|
-
const atoms = tokenize(text)
|
|
813
|
-
const { gradientAttrs, remaining: afterGradient } = extractGradientSpec(atoms, rewriteCtx)
|
|
814
|
-
const { truncateAttrs, remaining: afterTruncate } = extractTextTruncateSpec(afterGradient)
|
|
815
|
-
const { mountHaptics, eventHaptics, remaining } = extractHapticSpec(afterTruncate, rewriteCtx)
|
|
816
|
-
const mayBeInteractive = remaining.some((atom) => INTERACTIVE_PREFIXES.some((prefix) => atom.startsWith(prefix)))
|
|
817
|
-
const needsInsets = remaining.some((atom) => SAFE_ATOM_PATTERN.test(atom))
|
|
818
|
-
if (needsInsets) rewriteCtx.needsInsets = true
|
|
819
|
-
return {
|
|
820
|
-
expression: hoister.refFor(remaining),
|
|
821
|
-
mayBeInteractive,
|
|
822
|
-
needsInsets,
|
|
823
|
-
gradientAttrs: gradientAttrs.length > 0 ? gradientAttrs : undefined,
|
|
824
|
-
truncateAttrs: truncateAttrs.length > 0 ? truncateAttrs : undefined,
|
|
825
|
-
mountHaptics: mountHaptics.length > 0 ? mountHaptics : undefined,
|
|
826
|
-
eventHaptics: eventHaptics.length > 0 ? eventHaptics : undefined,
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
/**
|
|
831
|
-
* Scan the atom list for gradient roles (direction + from/via/to
|
|
832
|
-
* colours), strip those atoms out, and produce the JSX attributes the
|
|
833
|
-
* rewrite will splice onto the opening element:
|
|
834
|
-
* colors={_g_<hash>} start={_gs_<hash>} end={_ge_<hash>}
|
|
835
|
-
* When the atom list doesn't contain a complete gradient (no direction
|
|
836
|
-
* OR no colour stops), the gradient atoms pass through untouched —
|
|
837
|
-
* they'd resolve to `{}` in the runtime anyway. This keeps the
|
|
838
|
-
* transform conservative.
|
|
839
|
-
* @param atoms Tokenised atom list from the literal.
|
|
840
|
-
* @param rewriteCtx Rewrite-wide state (for the hoister).
|
|
841
|
-
* @returns The gradient JSX attrs (possibly empty) and the non-gradient remainder.
|
|
842
|
-
*/
|
|
843
|
-
function extractGradientSpec(
|
|
844
|
-
atoms: readonly string[],
|
|
845
|
-
rewriteCtx: RewriteContext,
|
|
846
|
-
): { gradientAttrs: readonly t.JSXAttribute[]; remaining: readonly string[] } {
|
|
847
|
-
const {gradientAtoms} = rewriteCtx
|
|
848
|
-
if (gradientAtoms.size === 0) return { gradientAttrs: [], remaining: atoms }
|
|
849
|
-
|
|
850
|
-
let direction: GradientDirection | null = null
|
|
851
|
-
let from: string | null = null
|
|
852
|
-
let via: string | null = null
|
|
853
|
-
let to: string | null = null
|
|
854
|
-
const remaining: string[] = []
|
|
855
|
-
for (const atom of atoms) {
|
|
856
|
-
const info = gradientAtoms.get(atom)
|
|
857
|
-
if (!info) {
|
|
858
|
-
remaining.push(atom)
|
|
859
|
-
continue
|
|
860
|
-
}
|
|
861
|
-
switch (info.role) {
|
|
862
|
-
case 'direction': {
|
|
863
|
-
direction = info.dir
|
|
864
|
-
break;
|
|
865
|
-
}
|
|
866
|
-
case 'from': {
|
|
867
|
-
from = info.color
|
|
868
|
-
break;
|
|
869
|
-
}
|
|
870
|
-
case 'via': {
|
|
871
|
-
via = info.color
|
|
872
|
-
break;
|
|
873
|
-
}
|
|
874
|
-
case 'to': { {
|
|
875
|
-
to = info.color
|
|
876
|
-
// No default
|
|
877
|
-
}
|
|
878
|
-
break;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
// Gradient atoms deliberately drop from `remaining` — they're
|
|
882
|
-
// consumed at build time and don't need a runtime style slot.
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
if (direction === null || direction === 'unknown' || (from === null && to === null)) {
|
|
886
|
-
// No recognisable gradient — put atoms back so they at least
|
|
887
|
-
// attempt to resolve through lookupCss.
|
|
888
|
-
return { gradientAttrs: [], remaining: atoms }
|
|
889
|
-
}
|
|
890
|
-
const colors = gradientColors(from, via, to)
|
|
891
|
-
const points = directionToPoints(direction)
|
|
892
|
-
const colorsRef = rewriteCtx.gradientHoister.refForColors(colors)
|
|
893
|
-
const startRef = rewriteCtx.gradientHoister.refForPoint(points.start, 'start')
|
|
894
|
-
const endRef = rewriteCtx.gradientHoister.refForPoint(points.end, 'end')
|
|
895
|
-
const attributes: t.JSXAttribute[] = [
|
|
896
|
-
t.jsxAttribute(t.jsxIdentifier('colors'), t.jsxExpressionContainer(colorsRef)),
|
|
897
|
-
t.jsxAttribute(t.jsxIdentifier('start'), t.jsxExpressionContainer(startRef)),
|
|
898
|
-
t.jsxAttribute(t.jsxIdentifier('end'), t.jsxExpressionContainer(endRef)),
|
|
899
|
-
]
|
|
900
|
-
return { gradientAttrs: attributes, remaining }
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
/**
|
|
904
|
-
* Scan the atom list for text-truncate utilities (`truncate`,
|
|
905
|
-
* `line-clamp-<N>`, `line-clamp-none`, `text-ellipsis`, `text-clip`),
|
|
906
|
-
* strip them out, and produce the JSX attributes the rewrite will
|
|
907
|
-
* splice onto the opening element: `numberOfLines={N}` and/or
|
|
908
|
-
* `ellipsizeMode="tail"|"clip"`.
|
|
909
|
-
*
|
|
910
|
-
* Merge rule mirrors Tailwind's cascade — later atoms override earlier
|
|
911
|
-
* ones. `numberOfLines: 0` (the `line-clamp-none` reset) suppresses
|
|
912
|
-
* emission entirely; a standalone `text-ellipsis` / `text-clip` with no
|
|
913
|
-
* companion line count also emits nothing because `ellipsizeMode`
|
|
914
|
-
* alone has no effect on RN `<Text>`.
|
|
915
|
-
* @param atoms Tokenised atom list.
|
|
916
|
-
* @returns The truncate JSX attrs (possibly empty) and the non-truncate remainder.
|
|
917
|
-
*/
|
|
918
|
-
function extractTextTruncateSpec(
|
|
919
|
-
atoms: readonly string[],
|
|
920
|
-
): { truncateAttrs: readonly t.JSXAttribute[]; remaining: readonly string[] } {
|
|
921
|
-
if (!mayContainTextTruncate(atoms)) return { truncateAttrs: [], remaining: atoms }
|
|
922
|
-
let numberOfLines: number | undefined
|
|
923
|
-
let ellipsizeMode: 'tail' | 'clip' | undefined
|
|
924
|
-
const remaining: string[] = []
|
|
925
|
-
for (const atom of atoms) {
|
|
926
|
-
const info = detectTextTruncate(atom)
|
|
927
|
-
if (!info) {
|
|
928
|
-
remaining.push(atom)
|
|
929
|
-
continue
|
|
930
|
-
}
|
|
931
|
-
const { numberOfLines: infoLines, ellipsizeMode: infoMode } = info
|
|
932
|
-
if (infoLines !== undefined) numberOfLines = infoLines
|
|
933
|
-
if (infoMode !== undefined) ellipsizeMode = infoMode
|
|
934
|
-
}
|
|
935
|
-
const attributes = buildTruncateAttributes(numberOfLines, ellipsizeMode)
|
|
936
|
-
return { truncateAttrs: attributes, remaining }
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
/**
|
|
940
|
-
* Assemble JSXAttribute nodes for the resolved truncate props. Drops
|
|
941
|
-
* `numberOfLines` when zero (reset) and drops `ellipsizeMode` when not
|
|
942
|
-
* paired with a positive line count — matching RN's behaviour where
|
|
943
|
-
* `ellipsizeMode` needs `numberOfLines` to do anything.
|
|
944
|
-
* @param numberOfLines Resolved clamp count, or undefined.
|
|
945
|
-
* @param ellipsizeMode Resolved ellipsize mode, or undefined.
|
|
946
|
-
* @returns Zero, one, or two JSX attributes.
|
|
947
|
-
*/
|
|
948
|
-
function buildTruncateAttributes(
|
|
949
|
-
numberOfLines: number | undefined,
|
|
950
|
-
ellipsizeMode: 'tail' | 'clip' | undefined,
|
|
951
|
-
): readonly t.JSXAttribute[] {
|
|
952
|
-
const attributes: t.JSXAttribute[] = []
|
|
953
|
-
if (numberOfLines !== undefined && numberOfLines > 0) {
|
|
954
|
-
attributes.push(
|
|
955
|
-
t.jsxAttribute(t.jsxIdentifier('numberOfLines'), t.jsxExpressionContainer(t.numericLiteral(numberOfLines))),
|
|
956
|
-
)
|
|
957
|
-
if (ellipsizeMode !== undefined) {
|
|
958
|
-
attributes.push(t.jsxAttribute(t.jsxIdentifier('ellipsizeMode'), t.stringLiteral(ellipsizeMode)))
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
return attributes
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
/**
|
|
965
|
-
* Map of variant-prefix → trigger. Bare atoms (no colon) resolve to
|
|
966
|
-
* `'mount'` through {@link extractHapticSpec}; these entries cover the
|
|
967
|
-
* explicit `active:` / `focus:` / `hover:` cases.
|
|
968
|
-
*/
|
|
969
|
-
const HAPTIC_VARIANT_TRIGGER: Record<string, Exclude<HapticTrigger, 'mount'>> = {
|
|
970
|
-
active: 'pressIn',
|
|
971
|
-
focus: 'focus',
|
|
972
|
-
hover: 'hover',
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
/** Map a non-mount haptic trigger to the JSX event prop it chains onto. */
|
|
976
|
-
const HAPTIC_EVENT_PROP: Record<Exclude<HapticTrigger, 'mount'>, string> = {
|
|
977
|
-
pressIn: 'onPressIn',
|
|
978
|
-
pressOut: 'onPressOut',
|
|
979
|
-
focus: 'onFocus',
|
|
980
|
-
hover: 'onMouseEnter',
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
/**
|
|
984
|
-
* Scan atom list for haptic utilities. Bare `haptic-*` → mount trigger;
|
|
985
|
-
* `active:haptic-*` / `focus:haptic-*` / `hover:haptic-*` → the matching
|
|
986
|
-
* event trigger. Matched atoms are stripped from the remainder so the
|
|
987
|
-
* runtime style resolver never tries to look up `--rnwind-haptic`.
|
|
988
|
-
* @param atoms Post-gradient, post-truncate atom list.
|
|
989
|
-
* @param rewriteCtx Rewrite-wide state (for the haptic-atom map).
|
|
990
|
-
* @returns Mount + event haptic entries, plus the non-haptic remainder.
|
|
991
|
-
*/
|
|
992
|
-
function extractHapticSpec(
|
|
993
|
-
atoms: readonly string[],
|
|
994
|
-
rewriteCtx: RewriteContext,
|
|
995
|
-
): {
|
|
996
|
-
mountHaptics: readonly HapticRequest[]
|
|
997
|
-
eventHaptics: readonly { readonly request: HapticRequest; readonly trigger: Exclude<HapticTrigger, 'mount'> }[]
|
|
998
|
-
remaining: readonly string[]
|
|
999
|
-
} {
|
|
1000
|
-
const { hapticAtoms } = rewriteCtx
|
|
1001
|
-
if (hapticAtoms.size === 0) return { mountHaptics: [], eventHaptics: [], remaining: atoms }
|
|
1002
|
-
const mountHaptics: HapticRequest[] = []
|
|
1003
|
-
const eventHaptics: { request: HapticRequest; trigger: Exclude<HapticTrigger, 'mount'> }[] = []
|
|
1004
|
-
const remaining: string[] = []
|
|
1005
|
-
for (const atom of atoms) {
|
|
1006
|
-
const resolved = resolveHapticAtom(atom, hapticAtoms)
|
|
1007
|
-
if (!resolved) {
|
|
1008
|
-
remaining.push(atom)
|
|
1009
|
-
continue
|
|
1010
|
-
}
|
|
1011
|
-
if (resolved.trigger === 'mount') mountHaptics.push(resolved.request)
|
|
1012
|
-
else eventHaptics.push({ request: resolved.request, trigger: resolved.trigger })
|
|
1013
|
-
}
|
|
1014
|
-
return { mountHaptics, eventHaptics, remaining }
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
/**
|
|
1018
|
-
* Classify one atom against the parser's haptic map. A colon-free atom
|
|
1019
|
-
* maps to `'mount'`; `active:` / `focus:` / `hover:` prefixes map to
|
|
1020
|
-
* the matching event trigger. Other prefixes return `null` so they
|
|
1021
|
-
* fall through to the regular style path.
|
|
1022
|
-
* @param atom Atom name, possibly variant-prefixed.
|
|
1023
|
-
* @param hapticAtoms Parser-surfaced haptic metadata.
|
|
1024
|
-
* @returns `{request, trigger}` on match, null otherwise.
|
|
1025
|
-
*/
|
|
1026
|
-
function resolveHapticAtom(
|
|
1027
|
-
atom: string,
|
|
1028
|
-
hapticAtoms: ReadonlyMap<string, HapticRequest>,
|
|
1029
|
-
): { readonly request: HapticRequest; readonly trigger: HapticTrigger } | null {
|
|
1030
|
-
// Direct lookup first — Tailwind v4 registers the variant-prefixed
|
|
1031
|
-
// class (e.g. `active:haptic-medium`) as its own rule, and the
|
|
1032
|
-
// parser's nested-rule walk surfaces the marker under that key.
|
|
1033
|
-
const direct = hapticAtoms.get(atom)
|
|
1034
|
-
if (direct) {
|
|
1035
|
-
const colon = atom.indexOf(':')
|
|
1036
|
-
if (colon === -1) return { request: direct, trigger: 'mount' }
|
|
1037
|
-
const trigger = HAPTIC_VARIANT_TRIGGER[atom.slice(0, colon)]
|
|
1038
|
-
if (trigger) return { request: direct, trigger }
|
|
1039
|
-
return null
|
|
1040
|
-
}
|
|
1041
|
-
// Fallback — try stripping a known variant prefix and looking up
|
|
1042
|
-
// the bare class. Handles cases where the parser only registered
|
|
1043
|
-
// the base utility (the variant rule may be missing if only the
|
|
1044
|
-
// bare class is otherwise used in the theme).
|
|
1045
|
-
const colon = atom.indexOf(':')
|
|
1046
|
-
if (colon === -1) return null
|
|
1047
|
-
const prefix = atom.slice(0, colon)
|
|
1048
|
-
const trigger = HAPTIC_VARIANT_TRIGGER[prefix]
|
|
1049
|
-
if (!trigger) return null
|
|
1050
|
-
const bare = hapticAtoms.get(atom.slice(colon + 1))
|
|
1051
|
-
if (!bare) return null
|
|
1052
|
-
return { request: bare, trigger }
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
/**
|
|
1056
|
-
* Append mount-haptic requests to the aggregate keyed by the JSX site's
|
|
1057
|
-
* enclosing component body. Post-traversal the transformer injects one
|
|
1058
|
-
* `useMountHaptic(<hoisted>)` call per component.
|
|
1059
|
-
* @param attributePath The JSXAttribute path the haptic came from.
|
|
1060
|
-
* @param requests Mount requests gathered from this literal.
|
|
1061
|
-
* @param rewriteCtx Rewrite-wide state.
|
|
1062
|
-
*/
|
|
1063
|
-
function recordMountHaptics(
|
|
1064
|
-
attributePath: NodePath<t.JSXAttribute>,
|
|
1065
|
-
requests: readonly HapticRequest[],
|
|
1066
|
-
rewriteCtx: RewriteContext,
|
|
1067
|
-
): void {
|
|
1068
|
-
const body = findComponentBody(attributePath)
|
|
1069
|
-
if (!body) return
|
|
1070
|
-
const bucket = rewriteCtx.mountByComponent.get(body.node)
|
|
1071
|
-
if (bucket) {
|
|
1072
|
-
bucket.push(...requests)
|
|
1073
|
-
return
|
|
1074
|
-
}
|
|
1075
|
-
rewriteCtx.mountByComponent.set(body.node, [...requests])
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
/**
|
|
1079
|
-
* Splice one chained event handler per event-haptic entry onto the
|
|
1080
|
-
* JSXOpeningElement. Each handler calls `triggerHaptic(_h, <request>,
|
|
1081
|
-
* '<trigger>')` and then forwards to any pre-existing user handler.
|
|
1082
|
-
* @param attributePath Path of the className attribute being rewritten.
|
|
1083
|
-
* @param opening Opening element to mutate.
|
|
1084
|
-
* @param entries Event-haptic entries.
|
|
1085
|
-
* @param rewriteCtx Rewrite-wide state (for the hoister).
|
|
1086
|
-
*/
|
|
1087
|
-
function injectEventHapticHandlers(
|
|
1088
|
-
attributePath: NodePath<t.JSXAttribute>,
|
|
1089
|
-
opening: t.JSXOpeningElement,
|
|
1090
|
-
entries: readonly { readonly request: HapticRequest; readonly trigger: Exclude<HapticTrigger, 'mount'> }[],
|
|
1091
|
-
rewriteCtx: RewriteContext,
|
|
1092
|
-
): void {
|
|
1093
|
-
// Make sure `_t = _r()` is in scope — haptic dispatcher reads `_t.onHaptics`.
|
|
1094
|
-
injectContextHook(attributePath)
|
|
1095
|
-
rewriteCtx.needsHapticsHook = true
|
|
1096
|
-
const byTrigger = new Map<Exclude<HapticTrigger, 'mount'>, HapticRequest[]>()
|
|
1097
|
-
for (const { request, trigger } of entries) {
|
|
1098
|
-
const list = byTrigger.get(trigger)
|
|
1099
|
-
if (list) list.push(request)
|
|
1100
|
-
else byTrigger.set(trigger, [request])
|
|
1101
|
-
}
|
|
1102
|
-
for (const [trigger, requests] of byTrigger) {
|
|
1103
|
-
const eventProperty = HAPTIC_EVENT_PROP[trigger]
|
|
1104
|
-
const existing = extractAndDropSiblingStyle(opening, eventProperty)
|
|
1105
|
-
const handler = buildChainedHapticHandler(rewriteCtx, requests, trigger, existing)
|
|
1106
|
-
opening.attributes.push(t.jsxAttribute(t.jsxIdentifier(eventProperty), t.jsxExpressionContainer(handler)))
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
/**
|
|
1111
|
-
* Build the inline arrow body for one chained handler — dispatch every
|
|
1112
|
-
* request in `requests` via `triggerHaptic`, then forward the event to
|
|
1113
|
-
* the user-supplied handler (if any) via `existing?.(event)`.
|
|
1114
|
-
* @param rewriteCtx Rewrite-wide state.
|
|
1115
|
-
* @param requests Requests that share this trigger.
|
|
1116
|
-
* @param trigger Lifecycle trigger this handler fires on.
|
|
1117
|
-
* @param existing User-supplied event handler expression, or null.
|
|
1118
|
-
* @returns ArrowFunctionExpression ready to splice into a JSXAttribute.
|
|
1119
|
-
*/
|
|
1120
|
-
function buildChainedHapticHandler(
|
|
1121
|
-
rewriteCtx: RewriteContext,
|
|
1122
|
-
requests: readonly HapticRequest[],
|
|
1123
|
-
trigger: Exclude<HapticTrigger, 'mount'>,
|
|
1124
|
-
existing: t.Expression | null,
|
|
1125
|
-
): t.ArrowFunctionExpression {
|
|
1126
|
-
const eventId = t.identifier('_e')
|
|
1127
|
-
const body: t.Statement[] = []
|
|
1128
|
-
for (const request of requests) {
|
|
1129
|
-
const ref = rewriteCtx.hapticHoister.refForRequest(request)
|
|
1130
|
-
body.push(
|
|
1131
|
-
t.expressionStatement(
|
|
1132
|
-
t.callExpression(t.identifier(TRIGGER_HAPTIC), [
|
|
1133
|
-
t.memberExpression(t.identifier(CONTEXT_BINDING), t.identifier('onHaptics')),
|
|
1134
|
-
ref,
|
|
1135
|
-
t.stringLiteral(trigger),
|
|
1136
|
-
]),
|
|
1137
|
-
),
|
|
1138
|
-
)
|
|
1139
|
-
}
|
|
1140
|
-
if (existing) {
|
|
1141
|
-
body.push(
|
|
1142
|
-
t.expressionStatement(
|
|
1143
|
-
t.optionalCallExpression(existing, [eventId], true),
|
|
1144
|
-
),
|
|
1145
|
-
)
|
|
1146
|
-
}
|
|
1147
|
-
return t.arrowFunctionExpression([eventId], t.blockStatement(body))
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
/**
|
|
1151
|
-
* Walk the aggregated `mountByComponent` map and inject a single
|
|
1152
|
-
* `useMountHaptic(<hoisted requests>)` call per component body.
|
|
1153
|
-
* The hoist yields a stable `const _hm_<hash>` referencing a frozen
|
|
1154
|
-
* array of request objects.
|
|
1155
|
-
* @param rewriteCtx Rewrite-wide state.
|
|
1156
|
-
*/
|
|
1157
|
-
function injectMountHapticCalls(rewriteCtx: RewriteContext): void {
|
|
1158
|
-
for (const [body, requests] of rewriteCtx.mountByComponent) {
|
|
1159
|
-
const ref = rewriteCtx.hapticHoister.refForRequestList(requests)
|
|
1160
|
-
const declaration = t.expressionStatement(
|
|
1161
|
-
t.callExpression(t.identifier(USE_MOUNT_HAPTIC), [ref]),
|
|
1162
|
-
)
|
|
1163
|
-
body.body.unshift(declaration)
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
/** One hoisted haptic entry — either a single request or a frozen list. */
|
|
1168
|
-
type HapticEntry =
|
|
1169
|
-
| { readonly kind: 'request'; readonly request: HapticRequest }
|
|
1170
|
-
| { readonly kind: 'list'; readonly requests: readonly HapticRequest[] }
|
|
1171
|
-
|
|
1172
|
-
/** Hoister for haptic request objects + mount-request arrays. */
|
|
1173
|
-
interface HapticHoister {
|
|
1174
|
-
/** Hoist (or fetch) a single request const (`_hr_<hash>`). */
|
|
1175
|
-
refForRequest: (request: HapticRequest) => t.Identifier
|
|
1176
|
-
/** Hoist (or fetch) a frozen array of requests (`_hm_<hash>`). */
|
|
1177
|
-
refForRequestList: (requests: readonly HapticRequest[]) => t.Identifier
|
|
1178
|
-
/** All hoisted entries in insertion order. */
|
|
1179
|
-
entries: ReadonlyMap<string, HapticEntry>
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
/**
|
|
1183
|
-
* Derive a stable cache key for one {@link HapticRequest}. Keys are
|
|
1184
|
-
* used both for hoister interning and mount-list digesting.
|
|
1185
|
-
* @param request Haptic request.
|
|
1186
|
-
* @returns Canonical key text.
|
|
1187
|
-
*/
|
|
1188
|
-
function keyForHapticRequest(request: HapticRequest): string {
|
|
1189
|
-
if (request.kind === 'impact') return `impact:${request.style}`
|
|
1190
|
-
if (request.kind === 'notification') return `notification:${request.type}`
|
|
1191
|
-
return 'selection'
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
/**
|
|
1195
|
-
* Build the haptic hoist table. Single requests and mount-request
|
|
1196
|
-
* lists each get their own module-scope frozen const so component
|
|
1197
|
-
* bodies only reference stable identifiers — no per-render allocation.
|
|
1198
|
-
* @returns HapticHoister API.
|
|
1199
|
-
*/
|
|
1200
|
-
function createHapticHoister(): HapticHoister {
|
|
1201
|
-
const pool = createInternPool<HapticEntry>()
|
|
1202
|
-
const refForRequest = (request: HapticRequest): t.Identifier =>
|
|
1203
|
-
pool.intern('_hr', `req:${keyForHapticRequest(request)}`, { kind: 'request', request })
|
|
1204
|
-
const refForRequestList = (requests: readonly HapticRequest[]): t.Identifier =>
|
|
1205
|
-
pool.intern('_hm', `list:${requests.map((request) => keyForHapticRequest(request)).join('|')}`, {
|
|
1206
|
-
kind: 'list',
|
|
1207
|
-
requests,
|
|
1208
|
-
})
|
|
1209
|
-
return { refForRequest, refForRequestList, entries: pool.entries }
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
/**
|
|
1213
|
-
* Generic intern-pool: one shared cache for module-scope consts keyed
|
|
1214
|
-
* by an arbitrary string. Returns a stable `t.Identifier` per key and
|
|
1215
|
-
* records `{name → entry}` for the emitter pass.
|
|
1216
|
-
* @returns Intern API.
|
|
1217
|
-
*/
|
|
1218
|
-
function createInternPool<Entry>(): {
|
|
1219
|
-
intern: (prefix: string, key: string, entry: Entry) => t.Identifier
|
|
1220
|
-
entries: ReadonlyMap<string, Entry>
|
|
1221
|
-
} {
|
|
1222
|
-
const byKey = new Map<string, t.Identifier>()
|
|
1223
|
-
const entries = new Map<string, Entry>()
|
|
1224
|
-
const intern = (prefix: string, key: string, entry: Entry): t.Identifier => {
|
|
1225
|
-
const existing = byKey.get(key)
|
|
1226
|
-
if (existing) return existing
|
|
1227
|
-
const hash = createHash('sha256').update(key).digest('hex').slice(0, 12)
|
|
1228
|
-
const name = `${prefix}_${hash}`
|
|
1229
|
-
const ident = t.identifier(name)
|
|
1230
|
-
byKey.set(key, ident)
|
|
1231
|
-
entries.set(name, entry)
|
|
1232
|
-
return ident
|
|
1233
|
-
}
|
|
1234
|
-
return { intern, entries }
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
/**
|
|
1238
|
-
* Emit `const _hr_<hash> = Object.freeze({...})` and `const _hm_<hash>
|
|
1239
|
-
* = Object.freeze([{...}, ...])` statements at module scope — one per
|
|
1240
|
-
* hoister entry.
|
|
1241
|
-
* @param ast Babel File AST.
|
|
1242
|
-
* @param entries Hoister entries.
|
|
1243
|
-
*/
|
|
1244
|
-
function injectHapticConsts(ast: File, entries: ReadonlyMap<string, HapticEntry>): void {
|
|
1245
|
-
const declarations: t.Statement[] = []
|
|
1246
|
-
for (const [name, entry] of entries) {
|
|
1247
|
-
if (entry.kind === 'request') {
|
|
1248
|
-
declarations.push(
|
|
1249
|
-
t.variableDeclaration('const', [
|
|
1250
|
-
t.variableDeclarator(t.identifier(name), freezeExpression(requestLiteral(entry.request))),
|
|
1251
|
-
]),
|
|
1252
|
-
)
|
|
1253
|
-
} else {
|
|
1254
|
-
declarations.push(
|
|
1255
|
-
t.variableDeclaration('const', [
|
|
1256
|
-
t.variableDeclarator(
|
|
1257
|
-
t.identifier(name),
|
|
1258
|
-
freezeExpression(t.arrayExpression(entry.requests.map((request) => freezeExpression(requestLiteral(request))))),
|
|
1259
|
-
),
|
|
1260
|
-
]),
|
|
1261
|
-
)
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
ast.program.body.unshift(...declarations)
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
/**
|
|
1268
|
-
* Build an `Object.freeze(...)` call around the given expression.
|
|
1269
|
-
* @param value Expression to freeze.
|
|
1270
|
-
* @returns CallExpression node.
|
|
1271
|
-
*/
|
|
1272
|
-
function freezeExpression(value: t.Expression): t.CallExpression {
|
|
1273
|
-
return t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [value])
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
/**
|
|
1277
|
-
* Build an object-literal representation of a {@link HapticRequest} —
|
|
1278
|
-
* `{kind: 'impact', style: 'Light'}` etc.
|
|
1279
|
-
* @param request Haptic request.
|
|
1280
|
-
* @returns ObjectExpression node.
|
|
1281
|
-
*/
|
|
1282
|
-
function requestLiteral(request: HapticRequest): t.ObjectExpression {
|
|
1283
|
-
const properties: t.ObjectProperty[] = [
|
|
1284
|
-
t.objectProperty(t.identifier('kind'), t.stringLiteral(request.kind)),
|
|
1285
|
-
]
|
|
1286
|
-
if (request.kind === 'impact') properties.push(t.objectProperty(t.identifier('style'), t.stringLiteral(request.style)))
|
|
1287
|
-
else if (request.kind === 'notification') properties.push(t.objectProperty(t.identifier('type'), t.stringLiteral(request.type)))
|
|
1288
|
-
return t.objectExpression(properties)
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
/**
|
|
1292
|
-
* Normalise the `from/via/to` triple into the array
|
|
1293
|
-
* `<LinearGradient colors={…}>` expects: drop `null` entries while
|
|
1294
|
-
* keeping the source order.
|
|
1295
|
-
* @param from Hex colour for `from-*`, or null.
|
|
1296
|
-
* @param via Hex colour for `via-*`, or null.
|
|
1297
|
-
* @param to Hex colour for `to-*`, or null.
|
|
1298
|
-
* @returns Colour array (at least one entry guaranteed by the caller).
|
|
1299
|
-
*/
|
|
1300
|
-
function gradientColors(from: string | null, via: string | null, to: string | null): readonly string[] {
|
|
1301
|
-
const out: string[] = []
|
|
1302
|
-
if (from !== null) out.push(from)
|
|
1303
|
-
if (via !== null) out.push(via)
|
|
1304
|
-
if (to !== null) out.push(to)
|
|
1305
|
-
return out
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
/**
|
|
1309
|
-
* Map Tailwind's stock direction tag to the `(start, end)` pair of
|
|
1310
|
-
* unit-square points expo-linear-gradient expects. Pure constants —
|
|
1311
|
-
* the same as NativeWind and the wider RN-gradient community.
|
|
1312
|
-
* @param dir Compact direction tag from the parser.
|
|
1313
|
-
* @returns Start + end point records.
|
|
1314
|
-
*/
|
|
1315
|
-
function directionToPoints(dir: GradientDirection): {
|
|
1316
|
-
start: { x: number; y: number }
|
|
1317
|
-
end: { x: number; y: number }
|
|
1318
|
-
} {
|
|
1319
|
-
switch (dir) {
|
|
1320
|
-
case 'to-r': {
|
|
1321
|
-
return { start: { x: 0, y: 0.5 }, end: { x: 1, y: 0.5 } }
|
|
1322
|
-
}
|
|
1323
|
-
case 'to-l': {
|
|
1324
|
-
return { start: { x: 1, y: 0.5 }, end: { x: 0, y: 0.5 } }
|
|
1325
|
-
}
|
|
1326
|
-
case 'to-t': {
|
|
1327
|
-
return { start: { x: 0.5, y: 1 }, end: { x: 0.5, y: 0 } }
|
|
1328
|
-
}
|
|
1329
|
-
case 'to-b': {
|
|
1330
|
-
return { start: { x: 0.5, y: 0 }, end: { x: 0.5, y: 1 } }
|
|
1331
|
-
}
|
|
1332
|
-
case 'to-tr': {
|
|
1333
|
-
return { start: { x: 0, y: 1 }, end: { x: 1, y: 0 } }
|
|
1334
|
-
}
|
|
1335
|
-
case 'to-tl': {
|
|
1336
|
-
return { start: { x: 1, y: 1 }, end: { x: 0, y: 0 } }
|
|
1337
|
-
}
|
|
1338
|
-
case 'to-br': {
|
|
1339
|
-
return { start: { x: 0, y: 0 }, end: { x: 1, y: 1 } }
|
|
1340
|
-
}
|
|
1341
|
-
case 'to-bl': {
|
|
1342
|
-
return { start: { x: 1, y: 0 }, end: { x: 0, y: 1 } }
|
|
1343
|
-
}
|
|
1344
|
-
default: {
|
|
1345
|
-
return { start: { x: 0, y: 0.5 }, end: { x: 1, y: 0.5 } }
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
|
|
1350
|
-
/**
|
|
1351
|
-
* Look for a sibling style attribute on the same JSXOpeningElement, drop
|
|
1352
|
-
* it, and return its expression for the caller to pass as the `lookupCss`
|
|
1353
|
-
* third arg. The attribute name is parameterised so the prefix path can
|
|
1354
|
-
* pull `contentContainerStyle` (et al.) instead of plain `style`.
|
|
1355
|
-
* @param parent JSXOpeningElement containing the className we're rewriting.
|
|
1356
|
-
* @param styleProp The exact sibling attribute name to look for.
|
|
1357
|
-
* @param styleProperty
|
|
1358
|
-
* @returns Expression from the dropped attribute, or `null`.
|
|
1359
|
-
*/
|
|
1360
|
-
function extractAndDropSiblingStyle(parent: t.JSXOpeningElement, styleProperty: string): t.Expression | null {
|
|
1361
|
-
const { attributes } = parent
|
|
1362
|
-
for (let index = 0; index < attributes.length; index += 1) {
|
|
1363
|
-
const attribute = attributes[index]
|
|
1364
|
-
if (!t.isJSXAttribute(attribute)) continue
|
|
1365
|
-
if (!t.isJSXIdentifier(attribute.name) || attribute.name.name !== styleProperty) continue
|
|
1366
|
-
const { value } = attribute
|
|
1367
|
-
if (!value || !t.isJSXExpressionContainer(value)) return null
|
|
1368
|
-
const { expression } = value
|
|
1369
|
-
if (t.isJSXEmptyExpression(expression)) return null
|
|
1370
|
-
attributes.splice(index, 1)
|
|
1371
|
-
return expression as t.Expression
|
|
1372
|
-
}
|
|
1373
|
-
return null
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
const INJECTED = new WeakSet<t.BlockStatement>()
|
|
1377
|
-
/**
|
|
1378
|
-
* Walk up from the rewrite site to the nearest enclosing function
|
|
1379
|
-
* component and inject `const _t = _r()` at the top of its body. This
|
|
1380
|
-
* is the SINGLE rnwind context binding — `_t` carries scheme,
|
|
1381
|
-
* fontScale, insets, etc. Idempotent per component.
|
|
1382
|
-
* @param path Path of any node inside the component's JSX.
|
|
1383
|
-
* @returns The binding name (`_t`).
|
|
1384
|
-
*/
|
|
1385
|
-
function injectContextHook(path: NodePath): string {
|
|
1386
|
-
const componentBody = findComponentBody(path)
|
|
1387
|
-
if (!componentBody) return CONTEXT_BINDING
|
|
1388
|
-
if (INJECTED.has(componentBody.node)) return CONTEXT_BINDING
|
|
1389
|
-
INJECTED.add(componentBody.node)
|
|
1390
|
-
const declaration = t.variableDeclaration('const', [
|
|
1391
|
-
t.variableDeclarator(t.identifier(CONTEXT_BINDING), t.callExpression(t.identifier(USE_RNWIND_INTERNAL), [])),
|
|
1392
|
-
])
|
|
1393
|
-
componentBody.unshiftContainer('body', declaration)
|
|
1394
|
-
return CONTEXT_BINDING
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
/**
|
|
1398
|
-
* Whether `path` sits inside a recognised function component — i.e.
|
|
1399
|
-
* {@link injectContextHook} would find a body to host `const _t =
|
|
1400
|
-
* useR_()`. Pure lookup that mirrors {@link findComponentBody}'s walk
|
|
1401
|
-
* but performs NO body promotion, so a caller can bail before mutating
|
|
1402
|
-
* when the answer is no.
|
|
1403
|
-
* @param path Rewrite-site path.
|
|
1404
|
-
* @returns True when an enclosing component function exists.
|
|
1405
|
-
*/
|
|
1406
|
-
function hasComponentBody(path: NodePath): boolean {
|
|
1407
|
-
let current: NodePath | null = path
|
|
1408
|
-
while (current) {
|
|
1409
|
-
const fn = current.findParent((parent) => parent.isFunction())
|
|
1410
|
-
if (!fn) return false
|
|
1411
|
-
if (isComponentFunction(fn)) return true
|
|
1412
|
-
current = fn
|
|
1413
|
-
}
|
|
1414
|
-
return false
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
/**
|
|
1418
|
-
* Walk up from `path` to the nearest recognised function component.
|
|
1419
|
-
* Accepts:
|
|
1420
|
-
* - `function Capital() {}` declarations.
|
|
1421
|
-
* - `const Capital = () => …` / `const Capital = function () {}` bindings.
|
|
1422
|
-
* - `forwardRef(…)` / `memo(…)` argument callbacks.
|
|
1423
|
-
* - `export default function () {}`.
|
|
1424
|
-
*
|
|
1425
|
-
* Arrow components with expression bodies get promoted to block bodies
|
|
1426
|
-
* so the hook can be `unshift`ed.
|
|
1427
|
-
* @param path Starting path.
|
|
1428
|
-
* @returns BlockStatement path of the component's body, or `null`.
|
|
1429
|
-
*/
|
|
1430
|
-
function findComponentBody(path: NodePath): NodePath<t.BlockStatement> | null {
|
|
1431
|
-
let current: NodePath | null = path
|
|
1432
|
-
while (current) {
|
|
1433
|
-
const fn = current.findParent((parent) => parent.isFunction())
|
|
1434
|
-
if (!fn) return null
|
|
1435
|
-
if (isComponentFunction(fn))
|
|
1436
|
-
return ensureBlockBody(fn as NodePath<t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression>)
|
|
1437
|
-
current = fn
|
|
1438
|
-
}
|
|
1439
|
-
return null
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
/**
|
|
1443
|
-
* Classify a function path as a React component per the three accepted
|
|
1444
|
-
* shapes (PascalCase decl, PascalCase var assignment, forwardRef/memo
|
|
1445
|
-
* argument, default export).
|
|
1446
|
-
* @param fn Function-like path.
|
|
1447
|
-
* @returns Whether the path is a React function component.
|
|
1448
|
-
*/
|
|
1449
|
-
function isComponentFunction(fn: NodePath): boolean {
|
|
1450
|
-
if (fn.isFunctionDeclaration()) {
|
|
1451
|
-
const { id } = fn.node
|
|
1452
|
-
if (!id) return isExportDefaultValue(fn)
|
|
1453
|
-
return isPascalCase(id.name)
|
|
1454
|
-
}
|
|
1455
|
-
if (fn.isArrowFunctionExpression() || fn.isFunctionExpression()) {
|
|
1456
|
-
return isAssignedToPascalCase(fn) || isHocArgument(fn) || isExportDefaultValue(fn)
|
|
1457
|
-
}
|
|
1458
|
-
return false
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
/**
|
|
1462
|
-
* Whether this function is the value of an `export default`.
|
|
1463
|
-
* @param fn Babel path pointing at the function node.
|
|
1464
|
-
* @returns True when the node is directly the default export value.
|
|
1465
|
-
*/
|
|
1466
|
-
function isExportDefaultValue(fn: NodePath): boolean {
|
|
1467
|
-
const { parent } = fn
|
|
1468
|
-
if (t.isExportDefaultDeclaration(parent)) return parent.declaration === fn.node
|
|
1469
|
-
return false
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
/**
|
|
1473
|
-
* Whether this arrow/function-expression is the init of `const Capital = …`.
|
|
1474
|
-
* @param fn Babel path pointing at the function node.
|
|
1475
|
-
* @returns True when the enclosing declarator's id starts with an uppercase letter.
|
|
1476
|
-
*/
|
|
1477
|
-
function isAssignedToPascalCase(fn: NodePath): boolean {
|
|
1478
|
-
const { parent } = fn
|
|
1479
|
-
if (!t.isVariableDeclarator(parent)) return false
|
|
1480
|
-
if (!t.isIdentifier(parent.id)) return false
|
|
1481
|
-
return isPascalCase(parent.id.name)
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
/**
|
|
1485
|
-
* Whether this fn is the first argument to `forwardRef(...)` / `memo(...)`.
|
|
1486
|
-
* @param fn Babel path pointing at the function node.
|
|
1487
|
-
* @returns True when wrapped by a recognized React HOC call.
|
|
1488
|
-
*/
|
|
1489
|
-
function isHocArgument(fn: NodePath): boolean {
|
|
1490
|
-
const { parent } = fn
|
|
1491
|
-
if (!t.isCallExpression(parent)) return false
|
|
1492
|
-
if (parent.arguments[0] !== fn.node) return false
|
|
1493
|
-
const { callee } = parent
|
|
1494
|
-
if (!t.isIdentifier(callee)) return false
|
|
1495
|
-
return callee.name === 'forwardRef' || callee.name === 'memo'
|
|
1496
|
-
}
|
|
1497
|
-
|
|
1498
|
-
/**
|
|
1499
|
-
* Identifier-starts-with-uppercase — Conventional React component marker.
|
|
1500
|
-
* @param name Identifier text.
|
|
1501
|
-
* @returns True when the first character is `A`–`Z`.
|
|
1502
|
-
*/
|
|
1503
|
-
function isPascalCase(name: string): boolean {
|
|
1504
|
-
const first = name.charAt(0)
|
|
1505
|
-
return first >= 'A' && first <= 'Z'
|
|
1506
|
-
}
|
|
1507
|
-
|
|
1508
|
-
/**
|
|
1509
|
-
* Promote an expression-bodied arrow to a block so we can unshift statements in.
|
|
1510
|
-
* @param fn Babel path at the function / arrow whose body should be a block.
|
|
1511
|
-
* @returns The path, mutated in place when the body was an expression.
|
|
1512
|
-
*/
|
|
1513
|
-
function ensureBlockBody(
|
|
1514
|
-
fn: NodePath<t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression>,
|
|
1515
|
-
): NodePath<t.BlockStatement> {
|
|
1516
|
-
const bodyPath = fn.get('body')
|
|
1517
|
-
if (Array.isArray(bodyPath)) throw new Error('rnwind: unexpected multi-body function node')
|
|
1518
|
-
if (bodyPath.isBlockStatement()) return bodyPath as NodePath<t.BlockStatement>
|
|
1519
|
-
const node = bodyPath.node as t.Expression
|
|
1520
|
-
bodyPath.replaceWith(t.blockStatement([t.returnStatement(node)]))
|
|
1521
|
-
return bodyPath as NodePath<t.BlockStatement>
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
type Hoister = {
|
|
1525
|
-
/** Return an identifier referencing the hoisted const for this atom list. */
|
|
1526
|
-
refFor: (atoms: readonly string[]) => t.Identifier
|
|
1527
|
-
/** Read-only view of every (const name → atoms) pair the hoister built. */
|
|
1528
|
-
entries: ReadonlyMap<string, readonly string[]>
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
/**
|
|
1532
|
-
* Build a per-file hoist table. Every unique source-order atom list gets
|
|
1533
|
-
* one module-scope `const _c_<hash> = Object.freeze(['a', 'b'])`. Order
|
|
1534
|
-
* is part of the hash key — `className="a b"` and `className="b a"`
|
|
1535
|
-
* intentionally produce different hoisted consts because RN's style
|
|
1536
|
-
* flatten is order-dependent (later atoms override earlier ones for
|
|
1537
|
-
* conflicting props). Canonicalizing by sort would collapse
|
|
1538
|
-
* `opacity-100 opacity-0` and `opacity-0 opacity-100` to the same atom
|
|
1539
|
-
* list and silently break the user's intended last-wins override.
|
|
1540
|
-
* @returns Hoister API.
|
|
1541
|
-
*/
|
|
1542
|
-
function createHoister(): Hoister {
|
|
1543
|
-
const byKey = new Map<string, { name: string; atoms: readonly string[] }>()
|
|
1544
|
-
const entries = new Map<string, readonly string[]>()
|
|
1545
|
-
|
|
1546
|
-
const refFor = (atoms: readonly string[]): t.Identifier => {
|
|
1547
|
-
const ordered = [...atoms]
|
|
1548
|
-
const canonical = ordered.join('\0')
|
|
1549
|
-
const hit = byKey.get(canonical)
|
|
1550
|
-
if (hit) return t.identifier(hit.name)
|
|
1551
|
-
const hash = createHash('sha256').update(canonical).digest('hex').slice(0, 12)
|
|
1552
|
-
const name = `_c_${hash}`
|
|
1553
|
-
byKey.set(canonical, { name, atoms: ordered })
|
|
1554
|
-
entries.set(name, ordered)
|
|
1555
|
-
return t.identifier(name)
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
return { refFor, entries }
|
|
1559
|
-
}
|
|
1560
|
-
|
|
1561
|
-
/** One gradient-hoist entry — either a colour array or a single {x,y} point. */
|
|
1562
|
-
type GradientEntry = { readonly kind: 'colors'; readonly colors: readonly string[] } | { readonly kind: 'point'; readonly point: { x: number; y: number } }
|
|
1563
|
-
|
|
1564
|
-
type GradientHoister = {
|
|
1565
|
-
/** Hoist (or fetch) the colour-array const for a gradient. */
|
|
1566
|
-
refForColors: (colors: readonly string[]) => t.Identifier
|
|
1567
|
-
/** Hoist (or fetch) a start/end point const — role only affects prefix. */
|
|
1568
|
-
refForPoint: (point: { x: number; y: number }, role: 'start' | 'end') => t.Identifier
|
|
1569
|
-
/** All hoisted entries in insertion order. */
|
|
1570
|
-
entries: ReadonlyMap<string, GradientEntry>
|
|
1571
|
-
}
|
|
1572
|
-
|
|
1573
|
-
/**
|
|
1574
|
-
* Build the gradient hoist table. Colour arrays and `(x,y)` point
|
|
1575
|
-
* records each get their own module-scope `const _g_<hash>` so the
|
|
1576
|
-
* JSX site references a stable identity — `<LinearGradient
|
|
1577
|
-
* colors={_g_hash}>`'s prop never changes across renders, which lets
|
|
1578
|
-
* React's prop-diff short-circuit and keeps native-side gradient
|
|
1579
|
-
* rebuilds off the hot path.
|
|
1580
|
-
* @returns GradientHoister API.
|
|
1581
|
-
*/
|
|
1582
|
-
function createGradientHoister(): GradientHoister {
|
|
1583
|
-
const pool = createInternPool<GradientEntry>()
|
|
1584
|
-
const refForColors = (colors: readonly string[]): t.Identifier =>
|
|
1585
|
-
pool.intern('_g', `colors:${colors.join('|')}`, { kind: 'colors', colors })
|
|
1586
|
-
const refForPoint = (point: { x: number; y: number }, role: 'start' | 'end'): t.Identifier => {
|
|
1587
|
-
const prefix = role === 'start' ? '_gs' : '_ge'
|
|
1588
|
-
return pool.intern(prefix, `point:${point.x},${point.y}`, { kind: 'point', point })
|
|
1589
|
-
}
|
|
1590
|
-
return { refForColors, refForPoint, entries: pool.entries }
|
|
1591
|
-
}
|
|
1592
|
-
|
|
1593
|
-
/**
|
|
1594
|
-
* Prepend the runtime + style imports to the file's program body.
|
|
1595
|
-
* Runtime primitives `{lookupCss, useScheme}` are
|
|
1596
|
-
* only added when the rewritten code references them. Side-effect
|
|
1597
|
-
* imports go first so the atom registry is populated before any
|
|
1598
|
-
* module-init hoist runs.
|
|
1599
|
-
/** Per-file flags telling the import builder what runtime symbols are in use.
|
|
1600
|
-
*/
|
|
1601
|
-
interface RuntimeImportFlags {
|
|
1602
|
-
/** Any className rewrite ran — always pulls in `_r` (rnwind context hook). */
|
|
1603
|
-
touched: boolean
|
|
1604
|
-
/** At least one rewrite emitted an inline `lookupCss(...)` call. */
|
|
1605
|
-
usedLookupCss: boolean
|
|
1606
|
-
/** At least one rewrite swapped the tag for `<InteractiveBox>`. */
|
|
1607
|
-
usedInteractiveBox: boolean
|
|
1608
|
-
/** At least one component accumulated bare `haptic-*` mount requests. */
|
|
1609
|
-
usedMountHaptic: boolean
|
|
1610
|
-
/** At least one event-haptic chain emitted a `triggerHaptic(...)` call. */
|
|
1611
|
-
usedTriggerHaptic: boolean
|
|
1612
|
-
}
|
|
1613
|
-
|
|
1614
|
-
/**
|
|
1615
|
-
* Prepend the runtime + style imports to the file's program body.
|
|
1616
|
-
* Only the specifiers actually used by the rewritten code are added
|
|
1617
|
-
* — a file with only interactive rewrites skips `lookupCss` entirely
|
|
1618
|
-
* (it lives inside InteractiveBox) and vice versa.
|
|
1619
|
-
* @param ast File AST.
|
|
1620
|
-
* @param flags Which runtime symbols the rewritten code references.
|
|
1621
|
-
* @param styleSpecifiers Side-effect import specifiers (style.js + keyframes.js).
|
|
1622
|
-
*/
|
|
1623
|
-
function prependRuntimeImports(ast: File, flags: RuntimeImportFlags, styleSpecifiers: readonly string[]): void {
|
|
1624
|
-
const heads: t.Statement[] = []
|
|
1625
|
-
for (const specifier of styleSpecifiers) {
|
|
1626
|
-
heads.push(t.importDeclaration([], t.stringLiteral(specifier)))
|
|
1627
|
-
}
|
|
1628
|
-
if (flags.touched) {
|
|
1629
|
-
heads.push(t.importDeclaration(buildRuntimeSpecifiers(flags), t.stringLiteral(RUNTIME_MODULE)))
|
|
1630
|
-
}
|
|
1631
|
-
if (heads.length > 0) ast.program.body.unshift(...heads)
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
/**
|
|
1635
|
-
* Build the import specifiers for the `rnwind` runtime module — only
|
|
1636
|
-
* symbols the rewritten code actually references. Extracted from
|
|
1637
|
-
* {@link prependRuntimeImports} to keep cognitive complexity low.
|
|
1638
|
-
* @param flags Per-file usage flags.
|
|
1639
|
-
* @returns The import specifiers to splice into the runtime import.
|
|
1640
|
-
*/
|
|
1641
|
-
function buildRuntimeSpecifiers(flags: RuntimeImportFlags): t.ImportSpecifier[] {
|
|
1642
|
-
const specifiers: t.ImportSpecifier[] = []
|
|
1643
|
-
const named = (name: string): void => {
|
|
1644
|
-
specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name)))
|
|
1645
|
-
}
|
|
1646
|
-
if (flags.usedLookupCss) named(LOOKUP_CSS)
|
|
1647
|
-
named(USE_RNWIND_INTERNAL)
|
|
1648
|
-
if (flags.usedMountHaptic) named(USE_MOUNT_HAPTIC)
|
|
1649
|
-
if (flags.usedTriggerHaptic) named(TRIGGER_HAPTIC)
|
|
1650
|
-
if (flags.usedInteractiveBox) named(INTERACTIVE_BOX)
|
|
1651
|
-
return specifiers
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
/**
|
|
1655
|
-
* Splice hoisted `const _c_<hash> = ['flex-1', 'bg-primary', ...]`
|
|
1656
|
-
* atom-list declarations into the file right after the imports so
|
|
1657
|
-
* every JSX rewrite site sees them in scope.
|
|
1658
|
-
*
|
|
1659
|
-
* The JSX site references the const as `lookupCss(_c0, _s, userStyle,
|
|
1660
|
-
* …)`. The runtime caches its resolved style array per
|
|
1661
|
-
* (hoist, scheme, stateIndex) against a global version counter, so
|
|
1662
|
-
* subsequent renders return the SAME array reference — zero
|
|
1663
|
-
* allocation on the hot path.
|
|
1664
|
-
* @param ast File AST.
|
|
1665
|
-
* @param entries Hoist table (const name → atom names).
|
|
1666
|
-
*/
|
|
1667
|
-
function injectHoistedConsts(ast: File, entries: ReadonlyMap<string, readonly string[]>): void {
|
|
1668
|
-
const decls: t.Statement[] = []
|
|
1669
|
-
for (const [name, atoms] of entries) {
|
|
1670
|
-
const array = t.arrayExpression(atoms.map((atom) => t.stringLiteral(atom)))
|
|
1671
|
-
decls.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), array)]))
|
|
1672
|
-
}
|
|
1673
|
-
spliceAfterImports(ast, decls)
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
/**
|
|
1677
|
-
* Splice gradient const declarations after the imports. Each entry is
|
|
1678
|
-
* either `colors` (frozen string array) or a `point` ({x, y} object
|
|
1679
|
-
* literal) so `<LinearGradient>` gets a stable ref for every gradient
|
|
1680
|
-
* shape.
|
|
1681
|
-
* @param ast File AST to mutate.
|
|
1682
|
-
* @param entries Gradient-hoister entries.
|
|
1683
|
-
*/
|
|
1684
|
-
function injectGradientConsts(ast: File, entries: ReadonlyMap<string, GradientEntry>): void {
|
|
1685
|
-
const decls: t.Statement[] = []
|
|
1686
|
-
for (const [name, entry] of entries) {
|
|
1687
|
-
const init =
|
|
1688
|
-
entry.kind === 'colors'
|
|
1689
|
-
? t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [
|
|
1690
|
-
t.arrayExpression(entry.colors.map((c) => t.stringLiteral(c))),
|
|
1691
|
-
])
|
|
1692
|
-
: t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [
|
|
1693
|
-
t.objectExpression([
|
|
1694
|
-
t.objectProperty(t.identifier('x'), t.numericLiteral(entry.point.x)),
|
|
1695
|
-
t.objectProperty(t.identifier('y'), t.numericLiteral(entry.point.y)),
|
|
1696
|
-
]),
|
|
1697
|
-
])
|
|
1698
|
-
decls.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), init)]))
|
|
1699
|
-
}
|
|
1700
|
-
spliceAfterImports(ast, decls)
|
|
1701
|
-
}
|
|
1702
|
-
|
|
1703
|
-
/**
|
|
1704
|
-
* Insert a block of declarations right after the last import in the
|
|
1705
|
-
* program body. Shared helper for atom-hoist and gradient-hoist.
|
|
1706
|
-
* @param ast File AST.
|
|
1707
|
-
* @param decls Declarations to splice in (already-built statements).
|
|
1708
|
-
*/
|
|
1709
|
-
function spliceAfterImports(ast: File, decls: readonly t.Statement[]): void {
|
|
1710
|
-
if (decls.length === 0) return
|
|
1711
|
-
const { body } = ast.program
|
|
1712
|
-
let index = 0
|
|
1713
|
-
while (index < body.length && t.isImportDeclaration(body[index])) index += 1
|
|
1714
|
-
body.splice(index, 0, ...decls)
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
/**
|
|
1718
|
-
* Tokenize a classname literal — split on whitespace, drop empties.
|
|
1719
|
-
* Mirrors what Tailwind + the runtime tokenizer expect.
|
|
1720
|
-
* @param literal Raw classname text.
|
|
1721
|
-
* @returns Atom names in document order.
|
|
1722
|
-
*/
|
|
1723
|
-
function tokenize(literal: string): string[] {
|
|
1724
|
-
const out: string[] = []
|
|
1725
|
-
for (const piece of literal.split(/\s+/)) {
|
|
1726
|
-
if (piece.length > 0) out.push(piece)
|
|
1727
|
-
}
|
|
1728
|
-
return out
|
|
1729
|
-
}
|