embedded-react 0.15.0 → 0.16.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 (57) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +806 -0
  4. package/aot/compiler/c/animations.mjs +362 -0
  5. package/aot/compiler/c/expressions.mjs +215 -0
  6. package/aot/compiler/c/functions.mjs +268 -0
  7. package/aot/compiler/c/keyboard.mjs +96 -0
  8. package/aot/compiler/c/nodes.mjs +282 -0
  9. package/aot/compiler/c/pan-responder.mjs +136 -0
  10. package/aot/compiler/c/statements.mjs +242 -0
  11. package/aot/compiler/c/text.mjs +83 -0
  12. package/aot/compiler/c/vectors.mjs +381 -0
  13. package/aot/compiler/c-syntax.mjs +127 -0
  14. package/aot/compiler/check.mjs +165 -0
  15. package/aot/compiler/collect.mjs +743 -0
  16. package/aot/compiler/control-flow.mjs +683 -0
  17. package/aot/compiler/diagnostics.mjs +137 -0
  18. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  19. package/aot/compiler/elements/dial.mjs +343 -0
  20. package/aot/compiler/elements/flat-list.mjs +139 -0
  21. package/aot/compiler/elements/image.mjs +151 -0
  22. package/aot/compiler/elements/modal.mjs +158 -0
  23. package/aot/compiler/elements/props.mjs +474 -0
  24. package/aot/compiler/elements/switch.mjs +183 -0
  25. package/aot/compiler/elements/text-input.mjs +171 -0
  26. package/aot/compiler/expressions.mjs +1479 -0
  27. package/aot/compiler/handlers.mjs +1072 -0
  28. package/aot/compiler/ir/animations.mjs +16 -0
  29. package/aot/compiler/ir/app.mjs +16 -0
  30. package/aot/compiler/ir/expressions.mjs +16 -0
  31. package/aot/compiler/ir/functions.mjs +16 -0
  32. package/aot/compiler/ir/keyboard.mjs +16 -0
  33. package/aot/compiler/ir/nodes.mjs +83 -0
  34. package/aot/compiler/ir/pan-responder.mjs +16 -0
  35. package/aot/compiler/ir/source.mjs +16 -0
  36. package/aot/compiler/ir/statements.mjs +16 -0
  37. package/aot/compiler/ir/text.mjs +16 -0
  38. package/aot/compiler/ir/types.mjs +185 -0
  39. package/aot/compiler/ir/vectors.mjs +16 -0
  40. package/aot/compiler/keyboard.mjs +152 -0
  41. package/aot/compiler/lower.mjs +282 -0
  42. package/aot/compiler/nodes.mjs +683 -0
  43. package/aot/compiler/options.mjs +55 -0
  44. package/aot/compiler/out.mjs +94 -0
  45. package/aot/compiler/pan-responder.mjs +354 -0
  46. package/aot/compiler/parse.mjs +300 -0
  47. package/aot/compiler/static-eval.mjs +228 -0
  48. package/aot/compiler/style-text.mjs +648 -0
  49. package/aot/compiler/svg.mjs +1167 -0
  50. package/aot/compiler/types.mjs +16 -0
  51. package/aot/screenshot-smoke.mjs +95 -55
  52. package/aot/style-map.mjs +366 -304
  53. package/cli.mjs +5 -8
  54. package/package.json +14 -6
  55. package/sim/embedded-react.wasm +0 -0
  56. package/src/embedded-react/FlatList.js +4 -4
  57. package/src/props.js +1 -1
@@ -0,0 +1,648 @@
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 { check } from './check.mjs';
20
+ import { lowerStyle, isStyleKey, STYLE_KEYS, DYN_FIELDS, colorLiteral, } from '../style-map.mjs';
21
+ import { parseColor } from '../../src/embedded-react/svg-ops.js';
22
+ import { aotError } from './diagnostics.mjs';
23
+ import { at, checkAnimatedStyleKey, checkAttributes, checkStyleKey, inlineFragments, TEXT_SPAN, } from './elements/props.mjs';
24
+ import { evalStatic, foldScope, withUndefined } from './static-eval.mjs';
25
+ import { cstr } from './c-syntax.mjs';
26
+ import { jsxChildText, lowerExpr, lowerText } from './expressions.mjs';
27
+ import { printPropValue } from './c/nodes.mjs';
28
+ import { ANIM_STYLE_PROPS, ANIM_TRANSFORM_PROPS, parseInterp, } from './animations.mjs';
29
+ /*----------------------------------------------------------------------------------------------------------------------
30
+ - Implementation
31
+ ---------------------------------------------------------------------------------------------------------------------*/
32
+ /**
33
+ * A JSX attribute's value as an expression: a bare `name` is `true`, `name="x"` the string, `name={expr}` the
34
+ * expression.
35
+ *
36
+ * @param attr The attribute.
37
+ *
38
+ * @returns Its value.
39
+ */
40
+ export function attrExpr(attr) {
41
+ const attrValue = attr.value;
42
+ if (!attrValue)
43
+ return { type: 'BooleanLiteral', value: true };
44
+ if (attrValue.type === 'StringLiteral')
45
+ return attrValue;
46
+ if (attrValue.type === 'JSXExpressionContainer')
47
+ return attrValue.expression;
48
+ return attrValue;
49
+ }
50
+ /**
51
+ * A static ARGB8888 C literal (`0xAARRGGBBu`) from a CSS color string or number.
52
+ *
53
+ * @param value The color.
54
+ *
55
+ * @returns Its C literal.
56
+ */
57
+ export function argbLiteral(value) {
58
+ return ('0x' +
59
+ (parseColor(String(value)) >>> 0)
60
+ .toString(16)
61
+ .padStart(8, '0')
62
+ .toUpperCase() +
63
+ 'u');
64
+ }
65
+ /**
66
+ * Lowers a dynamic (state-referencing) color expression to an ARGB value: a color, or a ternary of them.
67
+ *
68
+ * @param node The color expression.
69
+ * @param env The expression environment.
70
+ *
71
+ * @returns The value.
72
+ */
73
+ export function lowerColorValue(node, env) {
74
+ if (node.type === 'StringLiteral') {
75
+ return { kind: 'constant', code: colorLiteral(node.value) };
76
+ }
77
+ if (node.type === 'ConditionalExpression') {
78
+ return {
79
+ kind: 'select',
80
+ test: lowerExpr(node.test, env),
81
+ whenTrue: lowerColorValue(node.consequent, env),
82
+ whenFalse: lowerColorValue(node.alternate, env),
83
+ };
84
+ }
85
+ // A statically resolvable color (a const string, or a theme token like `theme.card`) folds to a literal.
86
+ try {
87
+ const color = evalStatic(node, foldScope(env, env.consts ?? {}));
88
+ if (typeof color === 'string') {
89
+ return { kind: 'constant', code: colorLiteral(color) };
90
+ }
91
+ }
92
+ catch {
93
+ /* not static — fall through to the error below */
94
+ }
95
+ throw new Error('AOT: a dynamic color must be a color string literal or a ternary of them');
96
+ }
97
+ /**
98
+ * A dynamic color expression as C for its ARGB value (see lowerColorValue).
99
+ *
100
+ * @param node The color expression.
101
+ * @param env The expression environment.
102
+ *
103
+ * @returns The C.
104
+ */
105
+ export const emitColorExpr = (node, env) => printPropValue(lowerColorValue(node, env));
106
+ /**
107
+ * Lowers a dynamic enum-style expression (e.g. `flexDirection: row ? 'row' : 'column'`) to its ER_* constant
108
+ * (or a ternary of them), looking values up in the style key's enum `table`.
109
+ *
110
+ * @param node The enum expression.
111
+ * @param table The RN value → ER_* constant table.
112
+ * @param env The expression environment.
113
+ *
114
+ * @returns The value.
115
+ */
116
+ export function lowerEnumValue(node, table, env) {
117
+ if (node.type === 'StringLiteral') {
118
+ const enumConstant = table[node.value];
119
+ if (!enumConstant) {
120
+ throw aotError(`AOT: unsupported enum value "${node.value}"`, `one of: ${Object.keys(table).join(', ')}`);
121
+ }
122
+ return { kind: 'constant', code: enumConstant };
123
+ }
124
+ if (node.type === 'ConditionalExpression') {
125
+ return {
126
+ kind: 'select',
127
+ test: lowerExpr(node.test, env),
128
+ whenTrue: lowerEnumValue(node.consequent, table, env),
129
+ whenFalse: lowerEnumValue(node.alternate, table, env),
130
+ };
131
+ }
132
+ // A statically resolvable enum (a const string) folds to its constant.
133
+ try {
134
+ const enumValue = evalStatic(node, foldScope(env, env.consts ?? {}));
135
+ if (typeof enumValue === 'string' && table[enumValue]) {
136
+ return { kind: 'constant', code: table[enumValue] };
137
+ }
138
+ }
139
+ catch {
140
+ /* not static — fall through */
141
+ }
142
+ throw aotError('AOT: a state-driven enum style must be a string literal or a ternary of them', "e.g. flexDirection: wide ? 'row' : 'column'");
143
+ }
144
+ /**
145
+ * A dynamic enum-style expression as C for its ER_* value (see lowerEnumValue).
146
+ *
147
+ * @param node The enum expression.
148
+ * @param table The RN value → ER_* constant table.
149
+ * @param env The expression environment.
150
+ *
151
+ * @returns The C.
152
+ */
153
+ export const emitEnumExpr = (node, table, env) => printPropValue(lowerEnumValue(node, table, env));
154
+ /**
155
+ * The diagnostic for a style key the AOT has no lowering for, static or dynamic.
156
+ *
157
+ * @param key The style key.
158
+ *
159
+ * @returns The error, for the caller to throw.
160
+ */
161
+ const unknownStyleKey = (key) => aotError(`AOT: style "${key}" is not supported by the AOT (no ERProps lowering)`, `Flow A may accept it; Flow B lowers these: ${STYLE_KEYS.join(', ')}.`);
162
+ /**
163
+ * Lowers one STATIC style key/value, telling the two failures apart: a key the AOT has no lowering for
164
+ * at all, and a known key whose value it rejects. Neither is reported as a state-driven value.
165
+ *
166
+ * @param key The style key.
167
+ * @param value Its folded value.
168
+ *
169
+ * @returns The ERProps writes; none for an undefined or null value.
170
+ */
171
+ function lowerStyleChecked(key, value) {
172
+ // A null or undefined value is a no-op, as in Flow A, so the key is judged only when there is a value to lower.
173
+ if (value === undefined || value === null)
174
+ return [];
175
+ if (!isStyleKey(key)) {
176
+ throw unknownStyleKey(key);
177
+ }
178
+ try {
179
+ return lowerStyle({ [key]: value });
180
+ }
181
+ catch (error) {
182
+ // style-map's own value errors already name the key in some cases — don't say it twice.
183
+ const message = String(error.message);
184
+ const reason = message.startsWith(`${key}: `)
185
+ ? message.slice(key.length + 2)
186
+ : message;
187
+ throw aotError(`AOT: unsupported value for style "${key}": ${reason}`);
188
+ }
189
+ }
190
+ /**
191
+ * Lowers one dynamic inline-style value to ERProps field assignment(s).
192
+ *
193
+ * @param key The style key.
194
+ * @param valueNode Its state-driven value.
195
+ * @param env The expression environment.
196
+ *
197
+ * @returns The ERProps writes.
198
+ */
199
+ function lowerDynamicStyleValue(key, valueNode, env) {
200
+ // Own properties only, so a key like `toString` cannot resolve to Object.prototype and emit `p.undefined`.
201
+ const dynamicField = Object.hasOwn(DYN_FIELDS, key)
202
+ ? DYN_FIELDS[key]
203
+ : undefined;
204
+ // Report an unknown key as such; advising "make it static" would only lead to the unknown-key error next.
205
+ if (!dynamicField && !isStyleKey(key)) {
206
+ throw unknownStyleKey(key);
207
+ }
208
+ if (!dynamicField) {
209
+ throw aotError(`AOT: a state-driven value for style "${key}" is not supported (static only)`, `state-driven styles supported: colors, opacity, sizes/margins/padding, and the ` +
210
+ `layout enums (flexDirection, alignItems, alignSelf, justifyContent, position, ` +
211
+ `display). Make "${key}" static, or drive the change another way.`);
212
+ }
213
+ // Colors and enums lower to a constant or a C ternary of constants.
214
+ if (dynamicField.kind === 'color') {
215
+ return [
216
+ { field: dynamicField.field, value: lowerColorValue(valueNode, env) },
217
+ ];
218
+ }
219
+ if (dynamicField.kind === 'enum') {
220
+ return [
221
+ {
222
+ field: dynamicField.field,
223
+ value: lowerEnumValue(valueNode, dynamicField.table, env),
224
+ },
225
+ ];
226
+ }
227
+ // Opacity and every size are numbers; C would take a char[] here as its address or refuse it.
228
+ const valueExpr = lowerExpr(valueNode, env);
229
+ if (valueExpr.type.kind === 'string') {
230
+ const error = aotError(`AOT: style "${key}" needs a number, but the value is a string`, "JS would coerce the string; C cannot. Keep the state numeric — useState(10), not useState('10').");
231
+ if (valueNode.loc) {
232
+ error.aotLoc = valueNode.loc.start;
233
+ }
234
+ throw error;
235
+ }
236
+ if (dynamicField.kind === 'opacity') {
237
+ return [
238
+ { field: dynamicField.field, value: { kind: 'opacity', value: valueExpr } },
239
+ ];
240
+ }
241
+ return [
242
+ { field: dynamicField.field, value: { kind: 'dimension', value: valueExpr } },
243
+ ];
244
+ }
245
+ /**
246
+ * Whether a style already writes `field`, counting its percentage twin: `width: '50%'` lowers to
247
+ * `width_pct`, and the author has still set the width. Used by the components that fall back to a
248
+ * built-in size or inset when the style leaves one out — without the twin they inject a pixel default
249
+ * ALONGSIDE the percentage, and the engine prefers the pixel value for a size.
250
+ *
251
+ * @param staticAssigns Static field writes from collectStyleAssigns().
252
+ * @param dynAssigns State-driven field writes from collectStyleAssigns().
253
+ * @param field ERProps field to look for.
254
+ *
255
+ * @returns Whether either list writes the field or its `_pct` twin.
256
+ */
257
+ export const styleWrites = (staticAssigns, dynAssigns, field) => [field, `${field}_pct`].some(fieldName => staticAssigns.some(assign => assign.field === fieldName) ||
258
+ dynAssigns.some(assign => assign.field === fieldName));
259
+ /**
260
+ * Collects an element's merged style into static field assigns and dynamic (state-driven) field assigns.
261
+ * Inline object values are tried statically first; a value that references state becomes a dynAssign.
262
+ * Later style sources override earlier ones per field (RN merge), kept in `fields` by ERProps field. A key the
263
+ * element's node neither lays out nor draws with is refused.
264
+ *
265
+ * @param openingElement The element's opening tag.
266
+ * @param scope Compile-time constants in reach.
267
+ * @param env The expression environment.
268
+ * @param spec The element, for the style keys it takes.
269
+ *
270
+ * @returns The style's constant writes, state-driven writes, and animated-value binds.
271
+ */
272
+ export function collectStyleAssigns(openingElement, scope, env, spec) {
273
+ // ERProps field → its last write: a constant's C, or a state-driven value.
274
+ const fields = new Map();
275
+ const binds = []; // animated values bound to node properties (native driver)
276
+ // A size in pixels and its percentage twin are one style key, so a later write of either replaces both.
277
+ const setField = (field, write) => {
278
+ fields.delete(field.endsWith('_pct') ? field.slice(0, -'_pct'.length) : `${field}_pct`);
279
+ fields.set(field, write);
280
+ };
281
+ // The C handle of an animated value used directly as a style value, or null.
282
+ const animRef = (node) => node?.type === 'Identifier' && env.animations?.has(node.name)
283
+ ? env.animations.get(node.name).cVar
284
+ : null;
285
+ // `<animValue>.interpolate({ inputRange, outputRange, extrapolate })` → { cVar, interp } for a mapped bind.
286
+ const animInterpRef = (node) => {
287
+ if (node?.type === 'CallExpression' &&
288
+ node.callee.type === 'MemberExpression' &&
289
+ !node.callee.computed &&
290
+ node.callee.property.name === 'interpolate' &&
291
+ node.callee.object.type === 'Identifier' &&
292
+ env.animations?.has(node.callee.object.name)) {
293
+ return {
294
+ cVar: env.animations.get(node.callee.object.name).cVar,
295
+ interp: parseInterp(node.arguments[0], env),
296
+ };
297
+ }
298
+ return null;
299
+ };
300
+ // A transform array's binds, or null when no entry is animated. Flow B has no static transform, so once one
301
+ // entry binds an animated value, every other entry must too; one left behind would be dropped.
302
+ const animatedTransform = (array) => {
303
+ const transformBinds = [];
304
+ const leftOver = [];
305
+ for (const transformEntry of array.elements) {
306
+ if (transformEntry?.type !== 'ObjectExpression') {
307
+ leftOver.push(transformEntry ?? array);
308
+ continue;
309
+ }
310
+ for (const transformProp of transformEntry.properties) {
311
+ if (transformProp.type !== 'ObjectProperty') {
312
+ leftOver.push(transformProp);
313
+ continue;
314
+ }
315
+ const transformKey = transformProp.key.name ??
316
+ transformProp.key.value;
317
+ const direct = animRef(transformProp.value);
318
+ const mapped = direct ? null : animInterpRef(transformProp.value);
319
+ if (!direct && !mapped) {
320
+ leftOver.push(transformProp);
321
+ continue;
322
+ }
323
+ // An animated entry the engine has no property for is refused, not skipped.
324
+ if (!Object.hasOwn(ANIM_TRANSFORM_PROPS, transformKey)) {
325
+ throw at(aotError(`AOT: transform "${transformKey}" cannot be animated in Flow B`, `animated transforms: ${Object.keys(ANIM_TRANSFORM_PROPS).join(', ')}.`), transformProp);
326
+ }
327
+ for (const animProp of ANIM_TRANSFORM_PROPS[transformKey]) {
328
+ transformBinds.push(mapped
329
+ ? { cVar: mapped.cVar, prop: animProp, interp: mapped.interp }
330
+ : { cVar: direct, prop: animProp });
331
+ }
332
+ }
333
+ }
334
+ if (!transformBinds.length)
335
+ return null;
336
+ if (leftOver.length) {
337
+ throw at(aotError('AOT: a transform entry that is not an animated value cannot sit beside an animated one', 'Flow B lowers a transform only as animated values bound on the native driver, so this entry ' +
338
+ 'would be dropped. Drive it from an animated value too (useAnimatedValue(45) holds a fixed one).'), leftOver[0]);
339
+ }
340
+ return transformBinds;
341
+ };
342
+ // Lowers one style source (an array, an inline object, or a static reference) into `fields` and `binds`.
343
+ const applyStyle = (expr) => {
344
+ // RN ignores an undefined style or style-array entry; so does Flow A's flattenStyle.
345
+ if (expr.type === 'Identifier' && expr.name === 'undefined')
346
+ return;
347
+ // A style array applies its entries in order, so later entries win.
348
+ if (expr.type === 'ArrayExpression') {
349
+ for (const styleEntry of expr.elements) {
350
+ if (styleEntry) {
351
+ applyStyle(styleEntry);
352
+ }
353
+ }
354
+ return;
355
+ }
356
+ // Inline object: bind animated values natively; fold other keys statically or re-apply them in app_update.
357
+ if (expr.type === 'ObjectExpression') {
358
+ for (const prop of expr.properties) {
359
+ if (prop.type !== 'ObjectProperty') {
360
+ throw new Error('AOT: spread/method in an inline style object not supported');
361
+ }
362
+ const key = (prop.computed
363
+ ? evalStatic(prop.key, scope)
364
+ : (prop.key.name ??
365
+ prop.key.value));
366
+ // `{transform: undefined}` is a no-op in RN and Flow A.
367
+ if (prop.value.type === 'Identifier' &&
368
+ prop.value.name === 'undefined') {
369
+ continue;
370
+ }
371
+ // Bind an animated value to its prop (opacity / backgroundColor / color), directly or via .interpolate().
372
+ const animVar = animRef(prop.value);
373
+ if (animVar && ANIM_STYLE_PROPS[key]) {
374
+ checkAnimatedStyleKey(spec, key, prop);
375
+ for (const animProp of ANIM_STYLE_PROPS[key]) {
376
+ binds.push({ cVar: animVar, prop: animProp });
377
+ }
378
+ continue;
379
+ }
380
+ const animInterp = animInterpRef(prop.value);
381
+ if (animInterp && ANIM_STYLE_PROPS[key]) {
382
+ checkAnimatedStyleKey(spec, key, prop);
383
+ for (const animProp of ANIM_STYLE_PROPS[key]) {
384
+ binds.push({
385
+ cVar: animInterp.cVar,
386
+ prop: animProp,
387
+ interp: animInterp.interp,
388
+ });
389
+ }
390
+ continue;
391
+ }
392
+ // transform: [{ scale: <anim> }, { translateX: <anim>.interpolate(...) }, ...] — bind each entry.
393
+ if (key === 'transform' && prop.value.type === 'ArrayExpression') {
394
+ const transformBinds = animatedTransform(prop.value);
395
+ if (transformBinds) {
396
+ checkAnimatedStyleKey(spec, key, prop);
397
+ binds.push(...transformBinds);
398
+ continue;
399
+ }
400
+ }
401
+ // Only a failed fold falls back to the dynamic path, so an unknown key is not misreported as state-driven.
402
+ let staticValue;
403
+ try {
404
+ staticValue = { v: evalStatic(prop.value, withUndefined(scope)) };
405
+ }
406
+ catch {
407
+ staticValue = null; // references state — lower it as a dynamic value
408
+ }
409
+ if (staticValue) {
410
+ if (staticValue.v != null) {
411
+ checkStyleKey(spec, key, prop);
412
+ }
413
+ for (const assign of lowerStyleChecked(key, staticValue.v)) {
414
+ setField(assign.field, { code: assign.expr });
415
+ }
416
+ }
417
+ else {
418
+ checkStyleKey(spec, key, prop);
419
+ for (const assign of lowerDynamicStyleValue(key, prop.value, env)) {
420
+ setField(assign.field, { value: assign.value });
421
+ }
422
+ }
423
+ }
424
+ return;
425
+ }
426
+ // A static style reference; null, undefined or false (`cond && s`) means no style, as in RN.
427
+ const resolved = evalStatic(expr, withUndefined(scope));
428
+ if (resolved === null || resolved === undefined || resolved === false) {
429
+ return;
430
+ }
431
+ for (const [styleKey, styleValue] of Object.entries(resolved)) {
432
+ if (styleValue === undefined || styleValue === null)
433
+ continue;
434
+ checkStyleKey(spec, styleKey, expr);
435
+ for (const assign of lowerStyleChecked(styleKey, styleValue)) {
436
+ setField(assign.field, { code: assign.expr });
437
+ }
438
+ }
439
+ };
440
+ // Apply every style attribute in source order.
441
+ for (const attr of openingElement.attributes) {
442
+ if (attr.type !== 'JSXAttribute' ||
443
+ attr.name.name !== 'style') {
444
+ continue;
445
+ }
446
+ applyStyle(attrExpr(attr));
447
+ }
448
+ // Split the merged fields into constant writes and state-driven writes.
449
+ const staticAssigns = [];
450
+ const dynAssigns = [];
451
+ for (const [field, fieldWrite] of fields) {
452
+ if ('value' in fieldWrite) {
453
+ dynAssigns.push({ field, value: fieldWrite.value });
454
+ }
455
+ else {
456
+ staticAssigns.push({ field, expr: fieldWrite.code });
457
+ }
458
+ }
459
+ return { staticAssigns, dynAssigns, binds };
460
+ }
461
+ /**
462
+ * Lowers a Text node's body. Static interpolations fold into literal text; any that reference state are values
463
+ * set again on every update.
464
+ *
465
+ * @param children The <Text>'s children.
466
+ * @param scope Compile-time constants in reach.
467
+ * @param env The expression environment.
468
+ *
469
+ * @returns The body.
470
+ */
471
+ export function lowerNodeText(children, scope, env) {
472
+ const parts = [];
473
+ for (const child of inlineFragments(children)) {
474
+ if (child.type === 'JSXText') {
475
+ const text = /\n/.test(child.value)
476
+ ? child.value.replace(/\s+/g, ' ').trim()
477
+ : child.value;
478
+ parts.push({ kind: 'literal', text });
479
+ }
480
+ else if (child.type === 'JSXExpressionContainer') {
481
+ if (child.expression.type === 'JSXEmptyExpression')
482
+ continue;
483
+ // Constants fold into literal text; anything referencing state is a runtime value.
484
+ parts.push(...lowerText(child.expression, env, scope).parts);
485
+ }
486
+ else if (child.type === 'JSXElement') {
487
+ throw new Error('AOT: nested <Text> / element children inside <Text> not yet supported (spans)');
488
+ }
489
+ else {
490
+ throw unsupportedTextChild(child);
491
+ }
492
+ }
493
+ return { parts };
494
+ }
495
+ /**
496
+ * The error for a <Text> child that is neither text, a `{…}` value nor a nested <Text>.
497
+ *
498
+ * @param child The child.
499
+ *
500
+ * @returns The error, for the caller to throw.
501
+ */
502
+ const unsupportedTextChild = (child) => at(aotError(`AOT: a ${child.type} cannot be part of a <Text>`, 'a <Text> holds text, {values} and nested <Text> spans.'), child);
503
+ /**
504
+ * Normalizes JSX text the way Babel does: trim per-line, drop blank lines, join with single spaces; a
505
+ * same-line leading/trailing space is preserved (so `Hello <b>x</b>` keeps the space before the span).
506
+ *
507
+ * @param value The JSXText's raw value.
508
+ *
509
+ * @returns The text as React would render it.
510
+ */
511
+ function cleanJsxText(value) {
512
+ // Find the last line with content: it is the only one not followed by a joining space.
513
+ const lines = value.split(/\r\n|\n|\r/);
514
+ let lastContentLine = 0;
515
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
516
+ if (/[^ \t]/.test(lines[lineIndex])) {
517
+ lastContentLine = lineIndex;
518
+ }
519
+ }
520
+ // Trim each line where it meets a line break, drop blank lines, and join the rest with single spaces.
521
+ let cleaned = '';
522
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
523
+ let line = lines[lineIndex].replace(/\t/g, ' ');
524
+ if (lineIndex !== 0) {
525
+ line = line.replace(/^ +/, '');
526
+ }
527
+ if (lineIndex !== lines.length - 1) {
528
+ line = line.replace(/ +$/, '');
529
+ }
530
+ if (line) {
531
+ cleaned += lineIndex !== lastContentLine ? line + ' ' : line;
532
+ }
533
+ }
534
+ return cleaned;
535
+ }
536
+ /**
537
+ * Concatenates a (span) <Text>'s static text content (literal + folded {expr}); a nested element throws.
538
+ *
539
+ * @param children The span's children.
540
+ * @param scope Compile-time constants in reach.
541
+ *
542
+ * @returns The span's text.
543
+ */
544
+ function staticTextContent(children, scope) {
545
+ let text = '';
546
+ for (const child of inlineFragments(children)) {
547
+ if (child.type === 'JSXText') {
548
+ text += cleanJsxText(child.value);
549
+ }
550
+ else if (child.type === 'JSXExpressionContainer' &&
551
+ child.expression.type !== 'JSXEmptyExpression') {
552
+ const value = evalStatic(child.expression, scope); // throws if it references state
553
+ text += jsxChildText(value);
554
+ }
555
+ else if (child.type === 'JSXElement') {
556
+ throw aotError('AOT: a nested <Text> span may not itself contain another <Text> (one level of spans only)');
557
+ }
558
+ else if (child.type === 'JSXSpreadChild') {
559
+ throw unsupportedTextChild(child);
560
+ }
561
+ }
562
+ return text;
563
+ }
564
+ /**
565
+ * If a <Text>'s children include a nested <Text>, returns inline SPANS [{text, color, font_size,
566
+ * font_weight, font_style, text_decoration, letter_spacing}] (C-expr fields; inherit sentinels for unset).
567
+ * Returns null when there's no nested <Text> (caller uses the single-string buildText path). Static only —
568
+ * a dynamic {…} segment or a state-driven span style throws.
569
+ *
570
+ * @param children The <Text>'s children.
571
+ * @param scope Compile-time constants in reach.
572
+ * @param env The expression environment.
573
+ *
574
+ * @returns The spans, or null when the <Text> has no nested <Text>.
575
+ */
576
+ export function collectTextSpans(children, scope, env) {
577
+ // Without a nested <Text>, the caller uses the single-string buildText path.
578
+ children = inlineFragments(children);
579
+ if (!children.some(child => child.type === 'JSXElement' &&
580
+ child.openingElement.name.name === 'Text')) {
581
+ return null;
582
+ }
583
+ // Inherit sentinels (see ERTextSpan doc): color 0, font_size 0, weight/style/decoration 0xFF, spacing AUTO.
584
+ const inheritSpan = (text) => ({
585
+ text,
586
+ color: '0u',
587
+ font_size: '0',
588
+ font_weight: '0xFF',
589
+ font_style: '0xFF',
590
+ text_decoration: '0xFF',
591
+ letter_spacing: 'ER_LAYOUT_AUTO',
592
+ });
593
+ // One span per child: text and static {…} values inherit the parent's style; a nested <Text> carries its own.
594
+ const spans = [];
595
+ for (const child of children) {
596
+ if (child.type === 'JSXText') {
597
+ const text = cleanJsxText(child.value);
598
+ if (text) {
599
+ spans.push(inheritSpan(cstr(text)));
600
+ }
601
+ }
602
+ else if (child.type === 'JSXExpressionContainer') {
603
+ if (child.expression.type === 'JSXEmptyExpression')
604
+ continue;
605
+ let value;
606
+ try {
607
+ value = evalStatic(child.expression, scope);
608
+ }
609
+ catch {
610
+ throw aotError('AOT: a dynamic {…} segment inside a multi-span <Text> is not supported', 'spans must be static; keep dynamic text in its own single <Text> (no nested <Text> siblings).');
611
+ }
612
+ // React draws nothing for null, undefined, or a boolean child.
613
+ if (value !== undefined && value !== null && typeof value !== 'boolean') {
614
+ spans.push(inheritSpan(cstr(String(value))));
615
+ }
616
+ }
617
+ else if (child.type === 'JSXElement' &&
618
+ child.openingElement.name.name === 'Text') {
619
+ checkAttributes(TEXT_SPAN, child.openingElement);
620
+ const { staticAssigns, dynAssigns } = collectStyleAssigns(child.openingElement, scope, env, TEXT_SPAN);
621
+ if (dynAssigns.length) {
622
+ throw aotError('AOT: a state-driven style on a nested <Text> span is not supported', 'give the span <Text> a static style.');
623
+ }
624
+ // Each span field is the nested <Text>'s own static style value, or the inherit sentinel.
625
+ const spanStyle = (fieldName, fallback) => staticAssigns.find(assign => assign.field === fieldName)?.expr ??
626
+ fallback;
627
+ spans.push({
628
+ text: cstr(staticTextContent(child.children, scope)),
629
+ color: spanStyle('color', '0u'),
630
+ font_size: spanStyle('font_size', '0'),
631
+ font_weight: spanStyle('font_weight', '0xFF'),
632
+ font_style: spanStyle('font_style', '0xFF'),
633
+ text_decoration: spanStyle('text_decoration', '0xFF'),
634
+ letter_spacing: spanStyle('letter_spacing', 'ER_LAYOUT_AUTO'),
635
+ });
636
+ }
637
+ else {
638
+ throw aotError('AOT: unsupported child inside a multi-span <Text>', 'a <Text> with a nested <Text> may contain text, {static expressions}, and nested <Text> only.');
639
+ }
640
+ }
641
+ // The engine renders at most ER_TEXT_MAX_SPANS segments; the check pass refuses to silently drop the rest.
642
+ check({
643
+ kind: 'textSpans',
644
+ count: spans.length,
645
+ max: env.caps.maxTextSpans,
646
+ });
647
+ return spans;
648
+ }