embedded-react 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +922 -0
  4. package/aot/compiler/boot.mjs +441 -0
  5. package/aot/compiler/branch-merge.mjs +319 -0
  6. package/aot/compiler/c/animations.mjs +362 -0
  7. package/aot/compiler/c/boot.mjs +127 -0
  8. package/aot/compiler/c/expressions.mjs +270 -0
  9. package/aot/compiler/c/functions.mjs +268 -0
  10. package/aot/compiler/c/keyboard.mjs +96 -0
  11. package/aot/compiler/c/nodes.mjs +294 -0
  12. package/aot/compiler/c/pan-responder.mjs +136 -0
  13. package/aot/compiler/c/statements.mjs +271 -0
  14. package/aot/compiler/c/text.mjs +83 -0
  15. package/aot/compiler/c/vectors.mjs +381 -0
  16. package/aot/compiler/c-syntax.mjs +127 -0
  17. package/aot/compiler/check.mjs +165 -0
  18. package/aot/compiler/collect.mjs +785 -0
  19. package/aot/compiler/control-flow.mjs +696 -0
  20. package/aot/compiler/diagnostics.mjs +137 -0
  21. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  22. package/aot/compiler/elements/dial.mjs +346 -0
  23. package/aot/compiler/elements/flat-list.mjs +139 -0
  24. package/aot/compiler/elements/image.mjs +151 -0
  25. package/aot/compiler/elements/modal.mjs +158 -0
  26. package/aot/compiler/elements/props.mjs +474 -0
  27. package/aot/compiler/elements/switch.mjs +183 -0
  28. package/aot/compiler/elements/text-input.mjs +171 -0
  29. package/aot/compiler/expressions.mjs +1579 -0
  30. package/aot/compiler/handlers.mjs +1072 -0
  31. package/aot/compiler/ir/animations.mjs +16 -0
  32. package/aot/compiler/ir/app.mjs +16 -0
  33. package/aot/compiler/ir/boot.mjs +16 -0
  34. package/aot/compiler/ir/expressions.mjs +16 -0
  35. package/aot/compiler/ir/functions.mjs +16 -0
  36. package/aot/compiler/ir/keyboard.mjs +16 -0
  37. package/aot/compiler/ir/nodes.mjs +107 -0
  38. package/aot/compiler/ir/pan-responder.mjs +16 -0
  39. package/aot/compiler/ir/reads.mjs +351 -0
  40. package/aot/compiler/ir/source.mjs +16 -0
  41. package/aot/compiler/ir/statements.mjs +16 -0
  42. package/aot/compiler/ir/text.mjs +16 -0
  43. package/aot/compiler/ir/types.mjs +185 -0
  44. package/aot/compiler/ir/vectors.mjs +16 -0
  45. package/aot/compiler/keyboard.mjs +152 -0
  46. package/aot/compiler/lower.mjs +311 -0
  47. package/aot/compiler/nodes.mjs +688 -0
  48. package/aot/compiler/options.mjs +55 -0
  49. package/aot/compiler/out.mjs +94 -0
  50. package/aot/compiler/pan-responder.mjs +354 -0
  51. package/aot/compiler/parse.mjs +300 -0
  52. package/aot/compiler/static-eval.mjs +454 -0
  53. package/aot/compiler/style-text.mjs +807 -0
  54. package/aot/compiler/svg.mjs +1167 -0
  55. package/aot/compiler/types.mjs +16 -0
  56. package/aot/screenshot-smoke.mjs +95 -55
  57. package/aot/style-map.mjs +366 -304
  58. package/cli.mjs +5 -8
  59. package/package.json +14 -6
  60. package/sim/embedded-react.wasm +0 -0
  61. package/src/embedded-react/FlatList.js +4 -4
  62. package/src/props.js +1 -1
@@ -0,0 +1,474 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { RN_PLATFORM_NO_OPS } from '../../../src/embedded-react/warn-props.js';
20
+ import { isStyleKey } from '../../style-map.mjs';
21
+ import { aotError } from '../diagnostics.mjs';
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Constants
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ /** A JSX event prop → the engine event it registers a handler for. */
26
+ export const EVENT_TYPES = {
27
+ onPress: 'ER_EVENT_PRESS',
28
+ onLongPress: 'ER_EVENT_LONG_PRESS',
29
+ onPressIn: 'ER_EVENT_PRESS_IN',
30
+ onPressOut: 'ER_EVENT_PRESS_OUT',
31
+ onTouchStart: 'ER_EVENT_TOUCH_START',
32
+ onTouchMove: 'ER_EVENT_TOUCH_MOVE',
33
+ onTouchEnd: 'ER_EVENT_TOUCH_END',
34
+ onLayout: 'ER_EVENT_LAYOUT',
35
+ };
36
+ /** Style keys every node lays out by, and `transform`, which every node draws through. */
37
+ const LAYOUT_STYLE = [
38
+ 'width',
39
+ 'height',
40
+ 'flexBasis',
41
+ 'minWidth',
42
+ 'maxWidth',
43
+ 'minHeight',
44
+ 'maxHeight',
45
+ 'padding',
46
+ 'paddingHorizontal',
47
+ 'paddingVertical',
48
+ 'paddingLeft',
49
+ 'paddingTop',
50
+ 'paddingRight',
51
+ 'paddingBottom',
52
+ 'margin',
53
+ 'marginHorizontal',
54
+ 'marginVertical',
55
+ 'marginLeft',
56
+ 'marginTop',
57
+ 'marginRight',
58
+ 'marginBottom',
59
+ 'gap',
60
+ 'rowGap',
61
+ 'columnGap',
62
+ 'flex',
63
+ 'flexGrow',
64
+ 'flexShrink',
65
+ 'flexDirection',
66
+ 'alignItems',
67
+ 'alignSelf',
68
+ 'justifyContent',
69
+ 'position',
70
+ 'display',
71
+ 'left',
72
+ 'top',
73
+ 'right',
74
+ 'bottom',
75
+ 'zIndex',
76
+ 'transform',
77
+ ];
78
+ /** What the engine draws a View, ScrollView or Pressable with. */
79
+ const VIEW_STYLE = [
80
+ 'backgroundColor',
81
+ 'borderRadius',
82
+ 'borderTopLeftRadius',
83
+ 'borderTopRightRadius',
84
+ 'borderBottomRightRadius',
85
+ 'borderBottomLeftRadius',
86
+ 'borderWidth',
87
+ 'borderColor',
88
+ 'opacity',
89
+ ];
90
+ /** What the engine draws a Text with. */
91
+ const TEXT_STYLE = [
92
+ 'color',
93
+ 'fontSize',
94
+ 'fontWeight',
95
+ 'lineHeight',
96
+ 'letterSpacing',
97
+ ];
98
+ /** What the engine draws a Modal's own box with. */
99
+ const MODAL_STYLE = [
100
+ 'backgroundColor',
101
+ 'borderRadius',
102
+ 'borderWidth',
103
+ 'borderColor',
104
+ 'opacity',
105
+ ];
106
+ /** What the engine draws a TextInput with. */
107
+ const TEXT_INPUT_STYLE = [...MODAL_STYLE, 'color', 'fontSize'];
108
+ /** The style keys the engine animates on a View, ScrollView, Pressable or Modal; `transform` animates anywhere. */
109
+ const VIEW_ANIMATED = ['opacity', 'backgroundColor', 'transform'];
110
+ /** The style keys the engine animates on a Text. */
111
+ const TEXT_ANIMATED = ['color', 'transform'];
112
+ /** What a span of a multi-span <Text> carries; the rest of its look comes from the outer <Text>. */
113
+ const SPAN_STYLE = ['color', 'fontSize', 'fontWeight', 'letterSpacing'];
114
+ /** The paint a vector shape or group takes. */
115
+ const SVG_PAINT = [
116
+ 'fill',
117
+ 'stroke',
118
+ 'strokeWidth',
119
+ 'strokeLinecap',
120
+ 'strokeLinejoin',
121
+ 'strokeMiterlimit',
122
+ 'fillRule',
123
+ 'fillGrad',
124
+ 'strokeGrad',
125
+ ];
126
+ /** The attributes every host node lowers: style, visibility, a node ref, and its events. */
127
+ const HOST_PROPS = [
128
+ 'style',
129
+ 'visible',
130
+ 'ref',
131
+ 'delayLongPress',
132
+ ...Object.keys(EVENT_TYPES),
133
+ ];
134
+ /** Why the engine's TextInput refuses a React Native prop it has no field for. */
135
+ const NO_TEXT_INPUT_FIELD = "the engine's TextInput has no such setting, so the device would ignore it. Remove it.";
136
+ /** Why an <Svg> refuses an event: its node is a drawing, not a touch target of its own. */
137
+ const SVG_EVENT = 'wrap it in a <Pressable> (or a <View>) that takes the event: <Pressable onPress={…}><Svg …/></Pressable>.';
138
+ /** Why an <Svg> refuses paint on itself: Flow A does not inherit it either. */
139
+ const SVG_ROOT_PAINT = 'paint goes on the shapes, or on a <G> around them; the <Svg> itself passes none down.';
140
+ /** The built-in elements, by tag. `Animated.X` resolves to X. */
141
+ const ELEMENTS = {
142
+ View: element('View', HOST_PROPS, [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
143
+ ScrollView: element('ScrollView', HOST_PROPS, [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {
144
+ onScroll: 'scroll events are not lowered yet. Read the position another way, or keep this screen Flow A only.',
145
+ horizontal: "the engine's ScrollView scrolls vertically; lay a horizontal strip out with flexDirection: 'row'.",
146
+ }, VIEW_ANIMATED),
147
+ Pressable: element('Pressable', [...HOST_PROPS, 'disabled'], [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
148
+ TouchableOpacity: element('TouchableOpacity', [...HOST_PROPS, 'disabled', 'activeOpacity'], [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
149
+ Text: element('Text', [...HOST_PROPS, 'numberOfLines', 'ellipsizeMode'], [...LAYOUT_STYLE, ...TEXT_STYLE], 'text', {}, TEXT_ANIMATED),
150
+ Image: element('Image', [...HOST_PROPS, 'source', 'imageName', 'resizeMode', 'tintColor'], LAYOUT_STYLE, 'none'),
151
+ Switch: element('Switch', [
152
+ 'style',
153
+ 'ref',
154
+ 'value',
155
+ 'onValueChange',
156
+ 'trackColor',
157
+ 'thumbColor',
158
+ 'disabled',
159
+ ], LAYOUT_STYLE, 'none'),
160
+ TextInput: element('TextInput', [
161
+ 'style',
162
+ 'ref',
163
+ 'value',
164
+ 'defaultValue',
165
+ 'onChangeText',
166
+ 'onSubmitEditing',
167
+ 'onFocus',
168
+ 'onBlur',
169
+ 'placeholder',
170
+ 'placeholderTextColor',
171
+ 'cursorColor',
172
+ 'editable',
173
+ 'secureTextEntry',
174
+ ], [...LAYOUT_STYLE, ...TEXT_INPUT_STYLE], 'none', Object.fromEntries([
175
+ 'autoFocus',
176
+ 'keyboardType',
177
+ 'maxLength',
178
+ 'multiline',
179
+ 'autoCapitalize',
180
+ 'autoCorrect',
181
+ 'returnKeyType',
182
+ ].map(name => [name, NO_TEXT_INPUT_FIELD]))),
183
+ ActivityIndicator: element('ActivityIndicator', ['style', 'ref', 'color', 'size', 'animating'], [...LAYOUT_STYLE, 'color'], 'none'),
184
+ Modal: element('Modal', [
185
+ 'style',
186
+ 'ref',
187
+ 'visible',
188
+ 'backdropColor',
189
+ 'animationType',
190
+ 'onRequestClose',
191
+ 'statusBarTranslucent',
192
+ ], [...LAYOUT_STYLE, ...MODAL_STYLE], 'nodes', {
193
+ transparent: 'the engine always draws a backdrop behind a Modal, in backdropColor; set backdropColor="transparent" for none.',
194
+ }, VIEW_ANIMATED),
195
+ Dial: element('Dial', [
196
+ 'style',
197
+ 'ref',
198
+ 'value',
199
+ 'min',
200
+ 'max',
201
+ 'startAngle',
202
+ 'sweepAngle',
203
+ 'step',
204
+ 'thickness',
205
+ 'bandThickness',
206
+ 'trackColor',
207
+ 'indicatorColor',
208
+ 'indicatorGradient',
209
+ 'bandColor',
210
+ 'cap',
211
+ 'segments',
212
+ 'gapAngle',
213
+ 'knob',
214
+ 'knobSize',
215
+ 'minSpan',
216
+ 'knobColor',
217
+ 'knobBorderColor',
218
+ 'knobBorderWidth',
219
+ 'knobImage',
220
+ 'adjustable',
221
+ 'range',
222
+ 'valueStart',
223
+ 'onChange',
224
+ ], LAYOUT_STYLE, 'nodes'),
225
+ FlatList: {
226
+ ...element('FlatList', ['data', 'renderItem', 'keyExtractor', 'style'], [...LAYOUT_STYLE, ...VIEW_STYLE], 'none', {
227
+ ref: 'Flow A cannot pass a ref through <FlatList> either; use <ScrollView ref={…}> with .map.',
228
+ }),
229
+ // The Flow A wrapper warns about these too, so a list that runs in the simulator also compiles.
230
+ platformNoOps: false,
231
+ },
232
+ Svg: element('Svg', ['style', 'ref', 'width', 'height', 'viewBox', 'source'], LAYOUT_STYLE, 'shapes', {
233
+ visible: 'wrap it: <View visible={…}><Svg …/></View> — the View carries the hide and the whole subtree goes with it.',
234
+ ...Object.fromEntries(Object.keys(EVENT_TYPES).map(name => [name, SVG_EVENT])),
235
+ ...Object.fromEntries(SVG_PAINT.map(name => [name, SVG_ROOT_PAINT])),
236
+ }),
237
+ };
238
+ /** The shapes inside an <Svg>, by tag; they are drawing data, so they take no ref, style or events. */
239
+ const SVG_SHAPES = {
240
+ Path: shape('Path', ['d']),
241
+ Circle: shape('Circle', ['cx', 'cy', 'r']),
242
+ Ellipse: shape('Ellipse', ['cx', 'cy', 'rx', 'ry']),
243
+ Rect: shape('Rect', ['x', 'y', 'width', 'height', 'rx', 'ry']),
244
+ Line: shape('Line', ['x1', 'y1', 'x2', 'y2']),
245
+ Arc: shape('Arc', ['cx', 'cy', 'r', 'startAngle', 'endAngle']),
246
+ G: {
247
+ ...shape('G', ['x', 'y', 'translateX', 'translateY', 'scale']),
248
+ children: 'shapes',
249
+ },
250
+ };
251
+ /** A <Text> nested in a <Text>: one inline span of the outer one. */
252
+ export const TEXT_SPAN = element('Text', ['style'], SPAN_STYLE, 'text', {}, []);
253
+ /*----------------------------------------------------------------------------------------------------------------------
254
+ - Implementation
255
+ ---------------------------------------------------------------------------------------------------------------------*/
256
+ /**
257
+ * Declares an element.
258
+ *
259
+ * @param tag The tag.
260
+ * @param props The attributes it lowers.
261
+ * @param styleKeys The style keys it lays out or draws with.
262
+ * @param children What it may hold.
263
+ * @param refused Known attributes it refuses, with what to do instead.
264
+ * @param animatedStyleKeys The style keys the engine animates on it.
265
+ *
266
+ * @returns The declaration.
267
+ */
268
+ function element(tag, props, styleKeys, children, refused = {}, animatedStyleKeys = ['transform']) {
269
+ return {
270
+ tag,
271
+ props: new Set(props),
272
+ refused,
273
+ platformNoOps: true,
274
+ styleKeys: new Set(styleKeys),
275
+ animatedStyleKeys: new Set(animatedStyleKeys),
276
+ children,
277
+ };
278
+ }
279
+ /**
280
+ * Declares a vector shape: its geometry plus the paint every shape takes.
281
+ *
282
+ * @param tag The tag.
283
+ * @param geometry The attributes that place it.
284
+ *
285
+ * @returns The declaration.
286
+ */
287
+ function shape(tag, geometry) {
288
+ return {
289
+ tag,
290
+ props: new Set([...geometry, ...SVG_PAINT]),
291
+ refused: {},
292
+ platformNoOps: false,
293
+ styleKeys: null,
294
+ animatedStyleKeys: new Set(),
295
+ children: 'none',
296
+ };
297
+ }
298
+ /** Every built-in element's tag. */
299
+ export const ELEMENT_TAGS = Object.keys(ELEMENTS);
300
+ /** Every shape's tag. */
301
+ export const SVG_SHAPE_TAGS = Object.keys(SVG_SHAPES);
302
+ /**
303
+ * The declaration of a built-in element.
304
+ *
305
+ * @param tag The resolved tag.
306
+ *
307
+ * @returns The declaration, or undefined when `tag` is not a built-in element.
308
+ */
309
+ export const elementSpec = (tag) => Object.hasOwn(ELEMENTS, tag) ? ELEMENTS[tag] : undefined;
310
+ /**
311
+ * The declaration of a shape inside an <Svg>.
312
+ *
313
+ * @param tag The tag.
314
+ *
315
+ * @returns The declaration, or undefined when `tag` is not a shape.
316
+ */
317
+ export const svgShapeSpec = (tag) => Object.hasOwn(SVG_SHAPES, tag) ? SVG_SHAPES[tag] : undefined;
318
+ /**
319
+ * An attribute's name as written, a namespaced one (`xlink:href`) included.
320
+ *
321
+ * @param attr The attribute.
322
+ *
323
+ * @returns Its name.
324
+ */
325
+ export const attrName = (attr) => attr.name.type === 'JSXNamespacedName'
326
+ ? `${attr.name.namespace.name}:${attr.name.name.name}`
327
+ : attr.name.name;
328
+ /**
329
+ * Pins an error to a construct's location.
330
+ *
331
+ * @param error The error.
332
+ * @param node The construct.
333
+ *
334
+ * @returns The error, for the caller to throw.
335
+ */
336
+ export function at(error, node) {
337
+ if (node.loc) {
338
+ error.aotLoc = node.loc.start;
339
+ }
340
+ return error;
341
+ }
342
+ /**
343
+ * Whether an element takes an attribute: `key`, a declared prop, or a platform no-op it accepts.
344
+ *
345
+ * @param spec The element.
346
+ * @param name The attribute's name.
347
+ *
348
+ * @returns Whether it is declared.
349
+ */
350
+ const declares = (spec, name) => name === 'key' ||
351
+ spec.props.has(name) ||
352
+ (spec.platformNoOps && RN_PLATFORM_NO_OPS.includes(name));
353
+ /**
354
+ * Whether `attr` sits on a built-in element or shape that does not declare it. A component's props are its own,
355
+ * so an attribute on one is never undeclared.
356
+ *
357
+ * @param openingElement The element's opening tag.
358
+ * @param attr One of its attributes.
359
+ *
360
+ * @returns Whether the element would refuse it.
361
+ */
362
+ export function isUndeclaredAttribute(openingElement, attr) {
363
+ const nameNode = openingElement.name;
364
+ const tag = nameNode.type === 'JSXIdentifier'
365
+ ? nameNode.name
366
+ : nameNode.type === 'JSXMemberExpression' &&
367
+ nameNode.object.type === 'JSXIdentifier' &&
368
+ nameNode.object.name === 'Animated'
369
+ ? nameNode.property.name
370
+ : null;
371
+ const spec = tag == null ? undefined : (elementSpec(tag) ?? svgShapeSpec(tag));
372
+ return spec != null && !declares(spec, attrName(attr));
373
+ }
374
+ /**
375
+ * Refuses every attribute `spec` does not declare, at the attribute. Spreads are left to the element's
376
+ * emitter, which knows the one spread it may take.
377
+ *
378
+ * @param spec The element.
379
+ * @param openingElement Its opening tag.
380
+ */
381
+ export function checkAttributes(spec, openingElement) {
382
+ for (const attr of openingElement.attributes) {
383
+ if (attr.type !== 'JSXAttribute')
384
+ continue;
385
+ const name = attrName(attr);
386
+ if (declares(spec, name))
387
+ continue;
388
+ const refusal = Object.hasOwn(spec.refused, name)
389
+ ? spec.refused[name]
390
+ : undefined;
391
+ throw at(aotError(`AOT: <${spec.tag}> prop "${name}" is not supported`, refusal ?? `supported props: ${[...spec.props].join(', ')}.`), attr);
392
+ }
393
+ }
394
+ /**
395
+ * `element` without the platform no-op props its declaration accepts, so no emitter has to know them. A copy
396
+ * is returned only when one is dropped.
397
+ *
398
+ * @param spec The element.
399
+ * @param element The element, its attributes already checked.
400
+ *
401
+ * @returns The element, or a copy of it without those attributes.
402
+ */
403
+ export function withoutPlatformNoOps(spec, element) {
404
+ if (!spec.platformNoOps)
405
+ return element;
406
+ const attrs = element.openingElement.attributes;
407
+ const kept = attrs.filter(attr => attr.type !== 'JSXAttribute' ||
408
+ !RN_PLATFORM_NO_OPS.includes(attrName(attr)));
409
+ return kept.length === attrs.length
410
+ ? element
411
+ : {
412
+ ...element,
413
+ openingElement: { ...element.openingElement, attributes: kept },
414
+ };
415
+ }
416
+ /**
417
+ * Refuses a style key the element's node neither lays out nor draws with. A key no element lowers is left to
418
+ * the style lowering, which says so in its own words.
419
+ *
420
+ * @param spec The element.
421
+ * @param key The style key.
422
+ * @param node Where the key is written, for the error's location.
423
+ */
424
+ export function checkStyleKey(spec, key, node) {
425
+ if (key !== 'transform' && !isStyleKey(key))
426
+ return;
427
+ if (spec.styleKeys?.has(key))
428
+ return;
429
+ const drawn = [...(spec.styleKeys ?? [])].filter(styleKey => !LAYOUT_STYLE.includes(styleKey));
430
+ throw at(aotError(`AOT: style "${key}" has no effect on <${spec.tag}>`, `the engine lays a <${spec.tag}> out like any node` +
431
+ (drawn.length ? ` and draws it with ${drawn.join(', ')}` : '') +
432
+ ', so the device would ignore it. Move it to a wrapping <View>, or remove it.'), node);
433
+ }
434
+ /**
435
+ * Refuses a style key bound to an animated value where the engine does not animate it on this element's node.
436
+ *
437
+ * @param spec The element.
438
+ * @param key The style key.
439
+ * @param node Where the key is written, for the error's location.
440
+ */
441
+ export function checkAnimatedStyleKey(spec, key, node) {
442
+ checkStyleKey(spec, key, node);
443
+ if (spec.animatedStyleKeys.has(key))
444
+ return;
445
+ throw at(aotError(`AOT: an animated "${key}" has no effect on <${spec.tag}>`, 'the engine animates opacity and backgroundColor on a View, ScrollView, Pressable or Modal, color on ' +
446
+ 'a Text, and transform anywhere. Animate a wrapping <View>, or drive the value from state.'), node);
447
+ }
448
+ /**
449
+ * Refuses children on an element that holds none. Whitespace between tags and JSX comments are not children.
450
+ *
451
+ * @param spec The element.
452
+ * @param children Its children.
453
+ */
454
+ export function checkNoChildren(spec, children) {
455
+ for (const child of children) {
456
+ if (child.type === 'JSXText' && !child.value.trim())
457
+ continue;
458
+ if (child.type === 'JSXExpressionContainer' &&
459
+ child.expression.type === 'JSXEmptyExpression') {
460
+ continue;
461
+ }
462
+ throw at(aotError(`AOT: <${spec.tag}> takes no children`, `the engine draws a <${spec.tag}> on its own; put what belongs beside it in a wrapping <View>.`), child);
463
+ }
464
+ }
465
+ /**
466
+ * `children` with each `<>…</>` replaced by its own children, at any depth: a fragment adds no node of its own.
467
+ *
468
+ * @param children An element's children.
469
+ *
470
+ * @returns The children, fragments inlined.
471
+ */
472
+ export function inlineFragments(children) {
473
+ return children.flatMap(child => child.type === 'JSXFragment' ? inlineFragments(child.children) : [child]);
474
+ }
@@ -0,0 +1,183 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { colorLiteral } from '../../style-map.mjs';
20
+ import { aotError } from '../diagnostics.mjs';
21
+ import { evalStatic } from '../static-eval.mjs';
22
+ import { asCond, emitExpr, lowerExpr } from '../expressions.mjs';
23
+ import { isFn } from '../collect.mjs';
24
+ import { attrExpr, styleWrites, collectStyleAssigns } from '../style-text.mjs';
25
+ import { lowerValueHandler } from '../handlers.mjs';
26
+ import { checkInterpolations, lowerRefBinds } from '../nodes.mjs';
27
+ import { at, elementSpec } from './props.mjs';
28
+ /*----------------------------------------------------------------------------------------------------------------------
29
+ - Implementation
30
+ ---------------------------------------------------------------------------------------------------------------------*/
31
+ /**
32
+ * <Switch value={on} onValueChange={(v) => setOn(v)} trackColor={{false,true}} thumbColor=… style=… />
33
+ * → ER_NODE_SWITCH. The engine flips its own value on press (+ animates the thumb), then fires ER_EVENT_PRESS,
34
+ * so onValueChange maps to PRESS, and its `v` param is the TOGGLED value (!value). `value` drives switch_value
35
+ * (state → dynamic). Default RN 51×31 box (the renderer scales the track/thumb to it); style can override.
36
+ *
37
+ * @param element The <Switch>.
38
+ * @param scope Compile-time constants in reach.
39
+ * @param out Everything emitted so far.
40
+ * @param env The expression environment.
41
+ * @param state The component's state table.
42
+ *
43
+ * @returns The node's variable.
44
+ */
45
+ export function emitSwitch(element, scope, out, env, state) {
46
+ // get node id
47
+ const nodeId = `n${out.allocateNodeId()}`;
48
+ // collect style assignments
49
+ const { staticAssigns, dynAssigns, binds } = collectStyleAssigns(element.openingElement, scope, env, elementSpec('Switch'));
50
+ const hasField = (f) => styleWrites(staticAssigns, dynAssigns, f);
51
+ if (!hasField('width')) {
52
+ staticAssigns.push({ field: 'width', expr: '51' });
53
+ }
54
+ if (!hasField('height')) {
55
+ staticAssigns.push({ field: 'height', expr: '31' });
56
+ }
57
+ // process element attributes
58
+ let valueNode = null;
59
+ let onChangeFn = null;
60
+ for (const attr of element.openingElement.attributes) {
61
+ // Ensure all props are explicit named attributes.
62
+ // Spread props cannot be analyzed statically
63
+ if (attr.type !== 'JSXAttribute') {
64
+ throw aotError('AOT: spread props on <Switch> are not supported');
65
+ }
66
+ // skip non-props
67
+ const name = attr.name.name;
68
+ if (name === 'style' || name === 'ref' || name === 'key')
69
+ continue;
70
+ // process props
71
+ const node = attrExpr(attr);
72
+ if (name === 'value') {
73
+ valueNode = node;
74
+ }
75
+ else if (name === 'onValueChange') {
76
+ onChangeFn = node;
77
+ }
78
+ else if (name === 'thumbColor') {
79
+ staticAssigns.push({
80
+ field: 'thumb_color',
81
+ expr: colorLiteral(String(evalStatic(node, scope))),
82
+ });
83
+ }
84
+ else if (name === 'trackColor') {
85
+ const trackColor = evalStatic(node, scope);
86
+ if (trackColor == null ||
87
+ typeof trackColor !== 'object' ||
88
+ Object.keys(trackColor).some(key => key !== 'false' && key !== 'true')) {
89
+ throw at(aotError('AOT: <Switch trackColor> must be an object of two colors', "trackColor={{false: '#767577', true: '#81b0ff'}}"), attr);
90
+ }
91
+ if (trackColor.false != null) {
92
+ staticAssigns.push({
93
+ field: 'track_color_false',
94
+ expr: colorLiteral(String(trackColor.false)),
95
+ });
96
+ }
97
+ if (trackColor.true != null) {
98
+ staticAssigns.push({
99
+ field: 'track_color_true',
100
+ expr: colorLiteral(String(trackColor.true)),
101
+ });
102
+ }
103
+ }
104
+ else if (name === 'disabled') {
105
+ // The engine flips a Switch on every press, so only a Switch that is never disabled lowers.
106
+ let disabled = true;
107
+ try {
108
+ disabled = evalStatic(node, scope);
109
+ }
110
+ catch {
111
+ /* state-driven: refused below */
112
+ }
113
+ if (disabled !== false) {
114
+ throw at(aotError('AOT: a disabled <Switch> is not supported', 'the engine flips a Switch on every press and has no disabled state. Leave it enabled and ' +
115
+ 'ignore the change in onValueChange while it should not move.'), attr);
116
+ }
117
+ }
118
+ else {
119
+ throw aotError(`AOT: <Switch> prop "${name}" is not supported`, 'supported props: value, onValueChange, trackColor, thumbColor, style.');
120
+ }
121
+ }
122
+ // value → switch_value (static or, when state-driven, recomputed in app_update).
123
+ if (valueNode) {
124
+ try {
125
+ staticAssigns.push({
126
+ field: 'switch_value',
127
+ expr: evalStatic(valueNode, scope) ? '1' : '0',
128
+ });
129
+ }
130
+ catch {
131
+ dynAssigns.push({
132
+ field: 'switch_value',
133
+ value: {
134
+ kind: 'flag',
135
+ test: lowerExpr(valueNode, env),
136
+ truthiness: 'condition',
137
+ negate: false,
138
+ whenTrue: 1,
139
+ },
140
+ });
141
+ }
142
+ }
143
+ const node = {
144
+ id: nodeId,
145
+ type: 'ER_NODE_SWITCH',
146
+ constantProps: staticAssigns,
147
+ stateProps: dynAssigns,
148
+ placeholder: null,
149
+ text: null,
150
+ image: null,
151
+ spans: null,
152
+ children: [],
153
+ wiring: binds.map((bind, index) => ({ kind: 'bind', bind, index })),
154
+ };
155
+ // Compile onValueChange into a press handler that receives the toggled switch value.
156
+ if (onChangeFn) {
157
+ // Require a controlled switch so onValueChange can receive the next value.
158
+ if (!isFn(onChangeFn)) {
159
+ throw aotError('AOT: onValueChange must be an inline function', 'onValueChange={(v) => setX(v)}');
160
+ }
161
+ if (!valueNode) {
162
+ throw aotError('AOT: a <Switch> with onValueChange needs a value prop', 'controlled switch: <Switch value={on} onValueChange={(v) => setOn(v)} />');
163
+ }
164
+ // Compile onValueChange into an ER_EVENT_PRESS handler, passing the next switch value.
165
+ const handlerName = `er_handler_${out.handlers.length}`;
166
+ const toggled = `(!(${asCond(emitExpr(valueNode, env))}))`; // the engine toggles on press → param is !value
167
+ out.handlers.push({
168
+ kind: 'callback',
169
+ name: handlerName,
170
+ callback: lowerValueHandler(onChangeFn, toggled, env, state, out, 'int', null, true),
171
+ });
172
+ node.wiring.push({
173
+ kind: 'event',
174
+ event: 'ER_EVENT_PRESS',
175
+ handler: handlerName,
176
+ });
177
+ }
178
+ for (const slot of lowerRefBinds(element.openingElement, env)) {
179
+ node.wiring.push({ kind: 'ref', slot });
180
+ }
181
+ checkInterpolations(node);
182
+ return node;
183
+ }