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,1167 @@
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, checkNumber } from './check.mjs';
20
+ import { lowerStyle, NODE_TYPES } from '../style-map.mjs';
21
+ import { flattenSvg, parseColor, parsePath, KAPPA, PAINT_STRIDE, scaleVectorArtifact, } from '../../src/embedded-react/svg-ops.js';
22
+ import { aotError } from './diagnostics.mjs';
23
+ import { evalStatic, withUndefined } from './static-eval.mjs';
24
+ import { lowerExpr } from './expressions.mjs';
25
+ import { lowerColorValue, collectStyleAssigns, styleWrites, } from './style-text.mjs';
26
+ import { checkInterpolations, lowerRefBinds } from './nodes.mjs';
27
+ import { at, checkAttributes, checkNoChildren, elementSpec, svgShapeSpec, } from './elements/props.mjs';
28
+ import { MAX_GRADIENT_STOPS, printTapeValue } from './c/vectors.mjs';
29
+ /*----------------------------------------------------------------------------------------------------------------------
30
+ - Constants
31
+ ---------------------------------------------------------------------------------------------------------------------*/
32
+ /** strokeLinecap → ERVectorPaint cap. */
33
+ export const CAP_MAP = { butt: 0, round: 1, square: 2 };
34
+ /** strokeLinejoin → ERVectorPaint join. */
35
+ export const JOIN_MAP = { miter: 0, round: 1, bevel: 2 };
36
+ /** A C number (sign, decimals, exponent) as a regex source for reading folded literals back. */
37
+ const C_NUMBER = '-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?';
38
+ /*----------------------------------------------------------------------------------------------------------------------
39
+ - Implementation
40
+ ---------------------------------------------------------------------------------------------------------------------*/
41
+ /**
42
+ * Refuses a child an <Svg> cannot draw, an attribute its shape does not declare, and children on a shape
43
+ * other than a <G>.
44
+ *
45
+ * @param child The child element.
46
+ */
47
+ function checkShape(child) {
48
+ const nameNode = child.openingElement.name;
49
+ const tag = nameNode.type === 'JSXIdentifier' ? nameNode.name : null;
50
+ const spec = tag == null ? undefined : svgShapeSpec(tag);
51
+ if (!spec) {
52
+ throw at(aotError(`AOT: <${tag ?? 'this element'}> is not a shape an <Svg> draws`, 'an <Svg> draws Path, Circle, Ellipse, Rect, Line and Arc, grouped by G. A component is not ' +
53
+ 'rendered inside one: inline its shapes.'), child);
54
+ }
55
+ checkAttributes(spec, child.openingElement);
56
+ if (spec.children === 'none') {
57
+ checkNoChildren(spec, child.children);
58
+ }
59
+ }
60
+ /**
61
+ * Refuses a constant `fillGrad` / `strokeGrad` the engine cannot draw as written: the same type and stop rules
62
+ * a state-driven one meets (see lowerGradient). `null` is no gradient.
63
+ *
64
+ * @param name The attribute.
65
+ * @param value Its folded value.
66
+ */
67
+ function checkStaticGradient(name, value) {
68
+ if (value == null)
69
+ return;
70
+ const gradient = value;
71
+ if (typeof value !== 'object' ||
72
+ ![1, 2, 3].includes(gradient.type)) {
73
+ throw aotError(`AOT: "${name}.type" must be 1 (linear), 2 (radial) or 3 (conic)`);
74
+ }
75
+ if (!Array.isArray(gradient.stops)) {
76
+ throw aotError(`AOT: "${name}.stops" must be an array`);
77
+ }
78
+ check({ kind: 'gradientStops', attribute: name, count: gradient.stops.length });
79
+ for (const stop of gradient.stops) {
80
+ if (stop == null || typeof stop !== 'object') {
81
+ throw aotError(`AOT: each "${name}.stops" entry must be an object`);
82
+ }
83
+ }
84
+ }
85
+ /**
86
+ * Yields an <Svg> subtree's shape children in source order, inlining any `<>…</>` in place: a fragment
87
+ * carries no paint and no transform, so it is transparent to the tape (the Flow A walk in flattenSvg
88
+ * treats it the same way). Whitespace between elements and JSX comments are skipped; anything else
89
+ * that has no shape to contribute throws, rather than vanishing from the generated C.
90
+ *
91
+ * @param children An <Svg>'s (or fragment's) children.
92
+ *
93
+ * @returns The shape elements, in order.
94
+ */
95
+ function* svgShapeChildren(children) {
96
+ for (const child of children) {
97
+ if (child.type === 'JSXElement') {
98
+ checkShape(child);
99
+ yield child;
100
+ }
101
+ else if (child.type === 'JSXFragment') {
102
+ yield* svgShapeChildren(child.children);
103
+ }
104
+ else if (child.type === 'JSXText') {
105
+ if (child.value.trim()) {
106
+ throw new Error(`AOT: <Svg> cannot draw text — remove ${JSON.stringify(child.value.trim())} from the subtree`);
107
+ }
108
+ }
109
+ else if (child.type === 'JSXExpressionContainer') {
110
+ if (child.expression.type !== 'JSXEmptyExpression') {
111
+ throw new Error('AOT: dynamic <Svg> children ({…}) not yet supported — use literal shape elements');
112
+ }
113
+ }
114
+ else {
115
+ throw new Error(`AOT: unsupported <Svg> child (${child.type})`);
116
+ }
117
+ }
118
+ }
119
+ /**
120
+ * Converts an SVG JSX element (Svg/Circle/Path/Rect/Line/Arc/G/…) to flattenSvg's `{type, props}` shape,
121
+ * statically evaluating every attribute; it serves the static path, so an unfoldable attribute throws.
122
+ *
123
+ * @param element The element.
124
+ * @param scope Compile-time constants in reach.
125
+ *
126
+ * @returns The element, its subtree included.
127
+ */
128
+ function jsxToSvgElement(element, scope) {
129
+ if (element.type !== 'JSXElement')
130
+ return null;
131
+ // Fold every attribute; a bare attribute is `true`.
132
+ const type = element.openingElement.name.name;
133
+ const props = {};
134
+ for (const attr of element.openingElement.attributes) {
135
+ if (attr.type !== 'JSXAttribute') {
136
+ throw new Error('AOT: spread attributes on an <Svg> element not supported');
137
+ }
138
+ const name = attr.name.name;
139
+ if (name === 'ref' || name === 'key' || name === 'style')
140
+ continue; // the box's, not the drawing's
141
+ if (attr.value == null) {
142
+ props[name] = true;
143
+ }
144
+ else if (attr.value.type === 'StringLiteral') {
145
+ props[name] = attr.value.value;
146
+ }
147
+ else if (attr.value.type === 'JSXExpressionContainer') {
148
+ props[name] = evalStatic(attr.value.expression, scope);
149
+ }
150
+ else {
151
+ throw new Error(`AOT: unsupported <${type}> attribute value for "${name}"`);
152
+ }
153
+ }
154
+ // A baked gradient takes the same checks as a state-driven one.
155
+ for (const name of ['fillGrad', 'strokeGrad']) {
156
+ checkStaticGradient(name, props[name]);
157
+ }
158
+ // Convert the shape children the same way, with fragments inlined.
159
+ const children = [];
160
+ for (const child of svgShapeChildren(element.children)) {
161
+ children.push(jsxToSvgElement(child, scope));
162
+ }
163
+ if (children.length) {
164
+ props.children = children;
165
+ }
166
+ return { type, props };
167
+ }
168
+ /**
169
+ * A flattenSvg paint record [fill, stroke, w, miter, cap, join, rule, fill_grad, stroke_grad] as a paint.
170
+ * fill_grad/stroke_grad (1-based gradient-table indices, 0 = solid) are absent on inline-<Svg> records (7-wide)
171
+ * and set on a baked <Svg source>.
172
+ *
173
+ * @param record The paint record.
174
+ *
175
+ * @returns The paint.
176
+ */
177
+ export const vectorPaintOf = (record) => ({
178
+ fill: record[0] >>> 0,
179
+ stroke: record[1] >>> 0,
180
+ strokeWidth: record[2],
181
+ miter: record[3],
182
+ cap: record[4] | 0,
183
+ join: record[5] | 0,
184
+ fillRule: record[6] | 0,
185
+ fillGradient: (record[7] || 0) | 0,
186
+ strokeGradient: (record[8] || 0) | 0,
187
+ });
188
+ /**
189
+ * Refuses a paint whose widths C cannot write, where the paint is lowered rather than when its table is.
190
+ *
191
+ * @param paints The paints, in table order.
192
+ */
193
+ export function checkVectorPaints(paints) {
194
+ for (const paint of paints) {
195
+ checkNumber(paint.strokeWidth);
196
+ checkNumber(paint.miter);
197
+ }
198
+ }
199
+ /**
200
+ * Refuses baked tables holding a number C cannot write, in the order the tables are written: the ops, the
201
+ * paints, then each gradient's kept stops, and geometry. An empty tape has no tables to check.
202
+ *
203
+ * @param tables The drawing.
204
+ */
205
+ function checkVectorTables(tables) {
206
+ if (!tables.ops.length)
207
+ return;
208
+ for (const op of tables.ops) {
209
+ checkNumber(op);
210
+ }
211
+ checkVectorPaints(tables.paints);
212
+ for (const gradient of tables.gradients) {
213
+ for (const stop of (gradient.stops || []).slice(0, MAX_GRADIENT_STOPS)) {
214
+ checkNumber(stop.offset);
215
+ }
216
+ const { ax, ay, bx, by, r } = gradient;
217
+ for (const field of [ax, ay, bx, by, r]) {
218
+ checkNumber(field || 0);
219
+ }
220
+ }
221
+ }
222
+ /**
223
+ * A drawing's flat paint records as paints, one per shape.
224
+ *
225
+ * @param records The records, PAINT_STRIDE numbers each.
226
+ *
227
+ * @returns The paints.
228
+ */
229
+ function paintsOf(records) {
230
+ const values = Array.from(records);
231
+ return Array.from({ length: values.length / PAINT_STRIDE }, (_, paintIndex) => {
232
+ const start = paintIndex * PAINT_STRIDE;
233
+ return vectorPaintOf(values.slice(start, start + PAINT_STRIDE));
234
+ });
235
+ }
236
+ /**
237
+ * Static numeric coercion for an SVG attribute value (mirrors svg-ops `num`).
238
+ *
239
+ * @param value The attribute's value.
240
+ * @param fallback The value to use when it is not a number.
241
+ *
242
+ * @returns The number.
243
+ */
244
+ export const svgNum = (value, fallback = 0) => {
245
+ const parsed = typeof value === 'number' ? value : parseFloat(value);
246
+ return Number.isNaN(parsed) ? fallback : parsed;
247
+ };
248
+ /**
249
+ * True if an attribute value is a state-driven C expression (vs. a static number/string).
250
+ *
251
+ * @param value An attribute value from svgAttrs.
252
+ *
253
+ * @returns Whether it is a DynamicAttr.
254
+ */
255
+ const isDynamicAttr = (value) => value != null && typeof value === 'object' && 'node' in value;
256
+ /**
257
+ * Reads an SVG element's attributes → { name: number|string|true | DynamicAttr } (state attrs → DynamicAttr).
258
+ *
259
+ * @param openingElement The element's opening tag.
260
+ * @param scope Compile-time constants in reach.
261
+ * @param env The expression environment.
262
+ *
263
+ * @returns The attributes, by name.
264
+ */
265
+ function svgAttrs(openingElement, scope, env) {
266
+ const attrs = {};
267
+ for (const attr of openingElement.attributes) {
268
+ if (attr.type !== 'JSXAttribute') {
269
+ throw new Error('AOT: spread attributes on an <Svg> element not supported');
270
+ }
271
+ // Not geometry or paint: the box's style and ref are lowerSvgBox's.
272
+ const name = attr.name.name;
273
+ if (name === 'ref' || name === 'key' || name === 'style')
274
+ continue;
275
+ // Keep a gradient as its expression; gradAttr lowers it, conditions included.
276
+ const valueNode = attr.value;
277
+ if (name === 'fillGrad' || name === 'strokeGrad') {
278
+ if (valueNode == null || valueNode.type !== 'JSXExpressionContainer') {
279
+ throw new Error(`AOT: "${name}" must be an object expression`);
280
+ }
281
+ attrs[name] = { gradNode: valueNode.expression };
282
+ continue;
283
+ }
284
+ // Fold everything else; an expression that does not fold is state-driven.
285
+ if (valueNode == null) {
286
+ attrs[name] = true;
287
+ }
288
+ else if (valueNode.type === 'StringLiteral') {
289
+ attrs[name] = valueNode.value;
290
+ }
291
+ else if (valueNode.type === 'JSXExpressionContainer') {
292
+ try {
293
+ attrs[name] = evalStatic(valueNode.expression, withUndefined(scope));
294
+ }
295
+ catch {
296
+ // Defer a state-driven `d` so pathEntries raises the error naming the fix, not the expression's own error.
297
+ if (name === 'd') {
298
+ attrs[name] = { value: null, node: valueNode.expression };
299
+ continue;
300
+ }
301
+ // Keep the node too: fill/stroke lower to an ARGB color from it, not from the numeric value.
302
+ attrs[name] = {
303
+ value: lowerExpr(valueNode.expression, env),
304
+ node: valueNode.expression,
305
+ };
306
+ }
307
+ }
308
+ else {
309
+ throw new Error(`AOT: unsupported SVG attribute value for "${name}"`);
310
+ }
311
+ }
312
+ return attrs;
313
+ }
314
+ /**
315
+ * Lowers a `{ type, ax, ay, bx, by, r, stops: [{ color, offset }] }` gradient descriptor — the SAME shape
316
+ * Flow A's svg-ops.js takes. Every geometry field and every stop may be static or state-driven; `type` and the
317
+ * stop COUNT must be static, since they decide the emitted table's shape.
318
+ *
319
+ * Conic gradients carry the sweep's start angle in `r` (radians, clockwise from the top), so a dial whose
320
+ * ramp must follow a setpoint drives `r` from state — which is exactly why the table can't be const.
321
+ *
322
+ * @param node The descriptor's object literal.
323
+ * @param scope Compile-time constants in reach.
324
+ * @param env The expression environment.
325
+ * @param attrName The attribute, for errors.
326
+ *
327
+ * @returns The gradient.
328
+ */
329
+ function lowerGradient(node, scope, env, attrName) {
330
+ if (!node || node.type !== 'ObjectExpression') {
331
+ throw new Error(`AOT: "${attrName}" must be an object literal`);
332
+ }
333
+ // Index the descriptor's properties by key.
334
+ const props = {};
335
+ for (const property of node.properties) {
336
+ if (property.type !== 'ObjectProperty' || property.computed) {
337
+ throw new Error(`AOT: "${attrName}" takes plain key: value pairs only`);
338
+ }
339
+ props[property.key.name ??
340
+ property.key.value] = property.value;
341
+ }
342
+ // A numeric field: a number when it folds to one (which the check pass checks), otherwise the state-driven value.
343
+ const floatField = (valueNode, fallback) => {
344
+ if (valueNode == null)
345
+ return tapeNumber(fallback);
346
+ let value;
347
+ try {
348
+ value = evalStatic(valueNode, scope);
349
+ }
350
+ catch {
351
+ return { kind: 'float', value: lowerExpr(valueNode, env) };
352
+ }
353
+ checkNumber(value);
354
+ return tapeNumber(Number(value));
355
+ };
356
+ // The type and the stop count decide the table's shape, so both must be static.
357
+ let type;
358
+ try {
359
+ type = evalStatic(props.type, scope) | 0;
360
+ }
361
+ catch {
362
+ throw new Error(`AOT: "${attrName}.type" must be a compile-time constant (1 linear, 2 radial, 3 conic)`);
363
+ }
364
+ if (type < 1 || type > 3) {
365
+ throw new Error(`AOT: "${attrName}.type" must be 1 (linear), 2 (radial) or 3 (conic)`);
366
+ }
367
+ const stopsNode = props.stops;
368
+ if (!stopsNode || stopsNode.type !== 'ArrayExpression') {
369
+ throw new Error(`AOT: "${attrName}.stops" must be an array literal`);
370
+ }
371
+ check({
372
+ kind: 'gradientStops',
373
+ attribute: attrName,
374
+ count: stopsNode.elements.length,
375
+ });
376
+ // Lower each stop: a static color folds to its ARGB, a state-driven one to the color state chooses.
377
+ const stops = stopsNode.elements.map(stopNode => {
378
+ if (!stopNode || stopNode.type !== 'ObjectExpression') {
379
+ throw new Error(`AOT: each "${attrName}.stops" entry must be an object literal`);
380
+ }
381
+ const stopProps = {};
382
+ for (const property of stopNode.properties) {
383
+ stopProps[property.key.name ??
384
+ property.key.value] = property.value;
385
+ }
386
+ let color;
387
+ try {
388
+ color = {
389
+ kind: 'static',
390
+ argb: parseColor(evalStatic(stopProps.color, scope)) >>> 0,
391
+ };
392
+ }
393
+ catch {
394
+ color = { kind: 'state', value: lowerColorValue(stopProps.color, env) };
395
+ }
396
+ return { color, offset: floatField(stopProps.offset, 0) };
397
+ });
398
+ return {
399
+ type,
400
+ stops,
401
+ ax: floatField(props.ax, 0),
402
+ ay: floatField(props.ay, 0),
403
+ bx: floatField(props.bx, 0),
404
+ by: floatField(props.by, 0),
405
+ r: floatField(props.r, 0),
406
+ };
407
+ }
408
+ /**
409
+ * Unwraps a gradient attribute, which may be a bare object literal or a CONDITIONAL one:
410
+ * `cond ? {…} : null` (either way round) or `cond && {…}`. The gradient table entry is emitted either
411
+ * way; what the condition drives is the PAINT'S INDEX, which is the entry only while the condition holds.
412
+ *
413
+ * Without this a gradient applied to a shape that is only sometimes gradient-filled leaks into every
414
+ * other state — the index is a compile-time constant, so "no gradient here" is not expressible by
415
+ * omission: a thermostat dial's Auto ramp would paint over its Cool and Heat modes as well.
416
+ *
417
+ * @param gradientAttr The attribute, if the shape has it.
418
+ * @param scope Compile-time constants in reach.
419
+ * @param env The expression environment.
420
+ * @param attrName The attribute, for errors.
421
+ *
422
+ * @returns The gradient and its condition, or null when the shape has none.
423
+ */
424
+ function lowerGradientAttr(gradientAttr, scope, env, attrName) {
425
+ if (!gradientAttr)
426
+ return null;
427
+ // Peel a conditional down to its object literal, keeping the condition.
428
+ let node = gradientAttr.gradNode;
429
+ let when = null;
430
+ const nullish = (branch) => branch.type === 'NullLiteral' ||
431
+ (branch.type === 'Identifier' && branch.name === 'undefined');
432
+ if (node.type === 'ConditionalExpression') {
433
+ if (node.consequent.type === 'ObjectExpression' &&
434
+ nullish(node.alternate)) {
435
+ when = { test: lowerExpr(node.test, env), negate: false };
436
+ node = node.consequent;
437
+ }
438
+ else if (node.alternate.type === 'ObjectExpression' &&
439
+ nullish(node.consequent)) {
440
+ when = { test: lowerExpr(node.test, env), negate: true };
441
+ node = node.alternate;
442
+ }
443
+ else {
444
+ throw new Error(`AOT: a conditional "${attrName}" must be \`cond ? { … } : null\` (one branch an ` +
445
+ `object literal, the other null)`);
446
+ }
447
+ }
448
+ else if (node.type === 'LogicalExpression' &&
449
+ node.operator === '&&' &&
450
+ node.right.type === 'ObjectExpression') {
451
+ when = { test: lowerExpr(node.left, env), negate: false };
452
+ node = node.right;
453
+ }
454
+ return { gradient: lowerGradient(node, scope, env, attrName), when };
455
+ }
456
+ /**
457
+ * Lowers a shape's paint and the gradients it uses:
458
+ * - fill / stroke may be state-driven (a color string, a ternary of them, or a folded theme token);
459
+ * - strokeWidth may be state-driven;
460
+ * - cap / join / miterlimit / fillRule must be static (a state-driven one throws a clear error);
461
+ * - fillGrad / strokeGrad are lowered here; the caller gives them places in the drawing's table.
462
+ *
463
+ * @param attrs The shape's attributes.
464
+ * @param env The expression environment.
465
+ * @param scope Compile-time constants in reach.
466
+ *
467
+ * @returns The paint, and the shape's gradients.
468
+ */
469
+ function lowerShapePaint(attrs, env, scope) {
470
+ // Colors and the stroke width are the only paint attributes that may be state-driven.
471
+ const color = (attrValue, fallback) => isDynamicAttr(attrValue)
472
+ ? { kind: 'state', value: lowerColorValue(attrValue.node, env) }
473
+ : { kind: 'static', argb: parseColor(attrValue ?? fallback) >>> 0 };
474
+ const strokeWidth = isDynamicAttr(attrs.strokeWidth)
475
+ ? { kind: 'float', value: attrs.strokeWidth.value }
476
+ : checkedTapeNumber(svgNum(attrs.strokeWidth, 1));
477
+ // The rest of the paint must be static.
478
+ for (const attrName of [
479
+ 'strokeLinecap',
480
+ 'strokeLinejoin',
481
+ 'strokeMiterlimit',
482
+ 'fillRule',
483
+ ]) {
484
+ if (isDynamicAttr(attrs[attrName])) {
485
+ throw new Error(`AOT: a state-driven <Svg> "${attrName}" is not supported (only fill / stroke / ` +
486
+ `strokeWidth can be state-driven)`);
487
+ }
488
+ }
489
+ const fill = color(attrs.fill, 'black');
490
+ const stroke = color(attrs.stroke, 'none');
491
+ const miter = svgNum(attrs.strokeMiterlimit, 4);
492
+ checkNumber(miter);
493
+ const paint = {
494
+ fill,
495
+ stroke,
496
+ strokeWidth,
497
+ miter,
498
+ cap: CAP_MAP[attrs.strokeLinecap] ?? 0,
499
+ join: JOIN_MAP[attrs.strokeLinejoin] ?? 0,
500
+ fillRule: attrs.fillRule === 'evenodd' ? 1 : 0,
501
+ };
502
+ const fillGradient = lowerGradientAttr(attrs.fillGrad, scope, env, 'fillGrad');
503
+ const strokeGradient = lowerGradientAttr(attrs.strokeGrad, scope, env, 'strokeGrad');
504
+ return { paint, fillGradient, strokeGradient };
505
+ }
506
+ // Per-shape op-tape geometry, shared by the JSX path and the imperative updateVector path, as in svg-ops.
507
+ /** A number as a tape slot. */
508
+ const tapeNumber = (value) => ({ kind: 'number', value });
509
+ /** The zero slot. */
510
+ const TAPE_ZERO = tapeNumber(0);
511
+ /**
512
+ * A number from the app as a tape slot, checked now that C can write it, where the shape is lowered.
513
+ *
514
+ * @param value The number.
515
+ *
516
+ * @returns The slot.
517
+ */
518
+ export const checkedTapeNumber = (value) => {
519
+ checkNumber(value);
520
+ return tapeNumber(value);
521
+ };
522
+ /**
523
+ * An opcode as a tape slot.
524
+ *
525
+ * @param op The ER_VOP_* name.
526
+ *
527
+ * @returns The slot.
528
+ */
529
+ const tapeOp = (op) => ({ kind: 'op', op });
530
+ /**
531
+ * `first`, then each operator and operand in turn.
532
+ *
533
+ * @param first The first operand.
534
+ * @param rest Each operator and the operand after it.
535
+ *
536
+ * @returns The slot.
537
+ */
538
+ const tapeChain = (first, ...rest) => ({
539
+ kind: 'chain',
540
+ first,
541
+ rest: rest.map(([op, value]) => ({ op, value })),
542
+ });
543
+ /**
544
+ * The value of a slot that reads as a C float literal, or null when state drives it. This reads the slot's C
545
+ * text, the way the geometry folded before it was IR, so the generated C stays the same.
546
+ *
547
+ * @param value The slot, if there is one.
548
+ *
549
+ * @returns Its value, or null.
550
+ */
551
+ const tapeLiteral = (value) => value == null ? null : cLiteralValue(printTapeValue(value));
552
+ /**
553
+ * An arc's tape slots. The engine measures angles in radians clockwise from 3 o'clock, so each angle is
554
+ * converted from degrees clockwise from the top.
555
+ *
556
+ * @param cx The center's x.
557
+ * @param cy The center's y.
558
+ * @param radius The radius.
559
+ * @param startDeg The start angle, in degrees clockwise from the top.
560
+ * @param endDeg The end angle, likewise.
561
+ *
562
+ * @returns The slots.
563
+ */
564
+ export const arcTape = (cx, cy, radius, startDeg, endDeg) => [
565
+ tapeOp('ER_VOP_ARC'),
566
+ cx,
567
+ cy,
568
+ radius,
569
+ { kind: 'radians', degrees: startDeg },
570
+ { kind: 'radians', degrees: endDeg },
571
+ TAPE_ZERO,
572
+ ];
573
+ /**
574
+ * A circle's tape slots.
575
+ *
576
+ * @param cx The center's x.
577
+ * @param cy The center's y.
578
+ * @param radius The radius.
579
+ *
580
+ * @returns The slots.
581
+ */
582
+ export const circleTape = (cx, cy, radius) => [
583
+ tapeOp('ER_VOP_MOVE'),
584
+ tapeChain(cx, ['+', radius]),
585
+ cy,
586
+ tapeOp('ER_VOP_ARC'),
587
+ cx,
588
+ cy,
589
+ radius,
590
+ TAPE_ZERO,
591
+ { kind: 'fullTurn' },
592
+ TAPE_ZERO,
593
+ tapeOp('ER_VOP_CLOSE'),
594
+ ];
595
+ /**
596
+ * The numeric value of a C float literal (as produced by floatLit, or the `(float)(N)` cast the imperative
597
+ * updateVector path emits), or null for a state-driven expr.
598
+ *
599
+ * @param floatExpr C for a float.
600
+ *
601
+ * @returns Its value, or null when it is not a literal.
602
+ */
603
+ const cLiteralValue = (floatExpr) => {
604
+ const trimmed = String(floatExpr).trim();
605
+ const cast = new RegExp(`^\\(float\\)\\((${C_NUMBER})\\)$`).exec(trimmed);
606
+ if (cast)
607
+ return parseFloat(cast[1]);
608
+ return new RegExp(`^${C_NUMBER}f$`).test(trimmed)
609
+ ? parseFloat(trimmed)
610
+ : null;
611
+ };
612
+ /**
613
+ * A corner radius clamped to half its side, mirroring svg-ops rectRadii. Folded to a number when both the
614
+ * radius and the side are known — the usual case, since only x/y/width tend to be state-driven.
615
+ *
616
+ * @param radius The radius.
617
+ * @param side The side it is clamped against.
618
+ *
619
+ * @returns The clamped radius.
620
+ */
621
+ const clampRadius = (radius, side) => {
622
+ const radiusValue = tapeLiteral(radius);
623
+ if (radiusValue != null && radiusValue <= 0)
624
+ return TAPE_ZERO;
625
+ const sideValue = tapeLiteral(side);
626
+ if (radiusValue != null && sideValue != null) {
627
+ return tapeNumber(Math.max(0, Math.min(radiusValue, sideValue / 2)));
628
+ }
629
+ return { kind: 'clampRadius', radius, side };
630
+ };
631
+ /**
632
+ * A square-cornered rectangle's tape slots.
633
+ *
634
+ * @param x The left edge.
635
+ * @param y The top edge.
636
+ * @param width The width.
637
+ * @param height The height.
638
+ *
639
+ * @returns The slots.
640
+ */
641
+ const sharpRectTape = (x, y, width, height) => [
642
+ tapeOp('ER_VOP_MOVE'),
643
+ x,
644
+ y,
645
+ tapeOp('ER_VOP_LINE'),
646
+ tapeChain(x, ['+', width]),
647
+ y,
648
+ tapeOp('ER_VOP_LINE'),
649
+ tapeChain(x, ['+', width]),
650
+ tapeChain(y, ['+', height]),
651
+ tapeOp('ER_VOP_LINE'),
652
+ x,
653
+ tapeChain(y, ['+', height]),
654
+ tapeOp('ER_VOP_CLOSE'),
655
+ ];
656
+ /**
657
+ * A rectangle's tape slots. rx/ry are null when the rect has no corner radius at all. Corners are cubics, not
658
+ * ER_VOP_ARC, for the same reason svg-ops uses them: a corner must start at EXACTLY the preceding line's
659
+ * endpoint. `tag` names the locals and must be unique within the caller's C block.
660
+ *
661
+ * @param x The left edge.
662
+ * @param y The top edge.
663
+ * @param width The width.
664
+ * @param height The height.
665
+ * @param rx The horizontal corner radius, or null.
666
+ * @param ry The vertical corner radius, or null.
667
+ * @param tag Names the locals a state-driven radius needs.
668
+ *
669
+ * @returns The slots, and the locals to declare ahead of them.
670
+ */
671
+ export const rectTape = (x, y, width, height, rx, ry, tag) => {
672
+ // A negative literal radius means `auto` (use the other one, as browsers do); a state-driven radius only clamps.
673
+ const isNegativeLiteral = (radius) => {
674
+ const value = tapeLiteral(radius);
675
+ return value != null && value < 0;
676
+ };
677
+ if (isNegativeLiteral(rx)) {
678
+ rx = null;
679
+ }
680
+ if (isNegativeLiteral(ry)) {
681
+ ry = null;
682
+ }
683
+ if (rx == null && ry == null) {
684
+ return { entries: sharpRectTape(x, y, width, height), locals: [] };
685
+ }
686
+ // A missing radius takes the other's value, each clamps to half its side, and a zero radius squares the corners.
687
+ let radiusX = clampRadius((rx ?? ry), width);
688
+ let radiusY = clampRadius((ry ?? rx), height);
689
+ if (tapeLiteral(radiusX) === 0 || tapeLiteral(radiusY) === 0) {
690
+ return { entries: sharpRectTape(x, y, width, height), locals: [] };
691
+ }
692
+ // Bind an unfolded clamp to a local rather than repeat it ten times in the tape; a folded radius stays inline.
693
+ const locals = [];
694
+ if (tapeLiteral(radiusX) == null) {
695
+ locals.push({ name: `rx_${tag}`, value: radiusX });
696
+ radiusX = { kind: 'local', name: `rx_${tag}` };
697
+ }
698
+ if (tapeLiteral(radiusY) == null) {
699
+ locals.push({ name: `ry_${tag}`, value: radiusY });
700
+ radiusY = { kind: 'local', name: `ry_${tag}` };
701
+ }
702
+ // Trace clockwise from the top edge's start: each side a line, each corner a cubic with KAPPA-length handles.
703
+ const kappa = tapeNumber(KAPPA);
704
+ const handleX = tapeChain(radiusX, ['*', kappa]);
705
+ const handleY = tapeChain(radiusY, ['*', kappa]);
706
+ const innerLeft = tapeChain(x, ['+', radiusX]);
707
+ const innerRight = tapeChain(x, ['+', width], ['-', radiusX]);
708
+ const innerTop = tapeChain(y, ['+', radiusY]);
709
+ const innerBottom = tapeChain(y, ['+', height], ['-', radiusY]);
710
+ const right = tapeChain(x, ['+', width]);
711
+ const bottom = tapeChain(y, ['+', height]);
712
+ const entries = [
713
+ tapeOp('ER_VOP_MOVE'),
714
+ innerLeft,
715
+ y,
716
+ tapeOp('ER_VOP_LINE'),
717
+ innerRight,
718
+ y,
719
+ tapeOp('ER_VOP_CUBIC'),
720
+ tapeChain(innerRight, ['+', handleX]),
721
+ y,
722
+ right,
723
+ tapeChain(innerTop, ['-', handleY]),
724
+ right,
725
+ innerTop,
726
+ tapeOp('ER_VOP_LINE'),
727
+ right,
728
+ innerBottom,
729
+ tapeOp('ER_VOP_CUBIC'),
730
+ right,
731
+ tapeChain(innerBottom, ['+', handleY]),
732
+ tapeChain(innerRight, ['+', handleX]),
733
+ bottom,
734
+ innerRight,
735
+ bottom,
736
+ tapeOp('ER_VOP_LINE'),
737
+ innerLeft,
738
+ bottom,
739
+ tapeOp('ER_VOP_CUBIC'),
740
+ tapeChain(innerLeft, ['-', handleX]),
741
+ bottom,
742
+ x,
743
+ tapeChain(innerBottom, ['+', handleY]),
744
+ x,
745
+ innerBottom,
746
+ tapeOp('ER_VOP_LINE'),
747
+ x,
748
+ innerTop,
749
+ tapeOp('ER_VOP_CUBIC'),
750
+ x,
751
+ tapeChain(innerTop, ['-', handleY]),
752
+ tapeChain(innerLeft, ['-', handleX]),
753
+ y,
754
+ innerLeft,
755
+ y,
756
+ tapeOp('ER_VOP_CLOSE'),
757
+ ];
758
+ return { entries, locals };
759
+ };
760
+ /**
761
+ * A line's tape slots.
762
+ *
763
+ * @param x1 The start's x.
764
+ * @param y1 The start's y.
765
+ * @param x2 The end's x.
766
+ * @param y2 The end's y.
767
+ *
768
+ * @returns The slots.
769
+ */
770
+ export const lineTape = (x1, y1, x2, y2) => [
771
+ tapeOp('ER_VOP_MOVE'),
772
+ x1,
773
+ y1,
774
+ tapeOp('ER_VOP_LINE'),
775
+ x2,
776
+ y2,
777
+ ];
778
+ /**
779
+ * An SVG coordinate attribute as a tape slot: a number when static, the state-driven value read as a float.
780
+ *
781
+ * @param attrValue The attribute's value.
782
+ * @param fallback The value to use when it is absent or not a number.
783
+ *
784
+ * @returns The slot.
785
+ */
786
+ const attrTape = (attrValue, fallback = 0) => isDynamicAttr(attrValue)
787
+ ? { kind: 'float', value: attrValue.value }
788
+ : checkedTapeNumber(svgNum(attrValue, fallback));
789
+ // The JSX path: each shape's attributes resolve to tape slots via attrTape.
790
+ const arcShape = (attrs) => ({
791
+ entries: arcTape(attrTape(attrs.cx), attrTape(attrs.cy), attrTape(attrs.r), attrTape(attrs.startAngle), attrTape(attrs.endAngle)),
792
+ locals: [],
793
+ });
794
+ const circleShape = (attrs) => ({
795
+ entries: circleTape(attrTape(attrs.cx), attrTape(attrs.cy), attrTape(attrs.r)),
796
+ locals: [],
797
+ });
798
+ const rectShape = (attrs, tag) => rectTape(attrTape(attrs.x), attrTape(attrs.y), attrTape(attrs.width), attrTape(attrs.height), attrs.rx == null ? null : attrTape(attrs.rx), attrs.ry == null ? null : attrTape(attrs.ry), tag);
799
+ const lineShape = (attrs) => ({
800
+ entries: lineTape(attrTape(attrs.x1), attrTape(attrs.y1), attrTape(attrs.x2), attrTape(attrs.y2)),
801
+ locals: [],
802
+ });
803
+ const pathShape = (attrs) => {
804
+ if (attrs.d == null)
805
+ return { entries: [], locals: [] };
806
+ if (isDynamicAttr(attrs.d)) {
807
+ throw new Error('AOT: a state-driven <Path d=…> is not yet supported (use Arc/Circle/Rect/Line for dynamic shapes)');
808
+ }
809
+ // Opcodes are encoded as float values 0..6, like coords.
810
+ return {
811
+ entries: parsePath(String(attrs.d)).map((value) => checkedTapeNumber(value)),
812
+ locals: [],
813
+ };
814
+ };
815
+ /** The shapes a state-driven <Svg> can hold, by tag. */
816
+ const SHAPE_TAPES = {
817
+ Arc: arcShape,
818
+ Circle: circleShape,
819
+ Rect: rectShape,
820
+ Line: lineShape,
821
+ Path: pathShape,
822
+ };
823
+ /**
824
+ * True if any attribute anywhere in the <Svg> subtree references state (→ the state-driven path).
825
+ *
826
+ * @param element The <Svg>.
827
+ * @param scope Compile-time constants in reach.
828
+ *
829
+ * @returns Whether an attribute does not fold.
830
+ */
831
+ function svgHasDynamic(element, scope) {
832
+ let hasDynamic = false;
833
+ const walk = (node) => {
834
+ // A fragment holds no attributes of its own, but its shapes' attributes still count.
835
+ if (node.type === 'JSXFragment') {
836
+ for (const child of node.children) {
837
+ walk(child);
838
+ }
839
+ return;
840
+ }
841
+ if (node.type !== 'JSXElement')
842
+ return;
843
+ for (const attr of node.openingElement.attributes) {
844
+ if (attr.type === 'JSXAttribute' &&
845
+ attr.name.name !== 'ref' &&
846
+ attr.name.name !== 'key' &&
847
+ attr.name.name !== 'style' &&
848
+ attr.value?.type === 'JSXExpressionContainer') {
849
+ try {
850
+ evalStatic(attr.value.expression, scope);
851
+ }
852
+ catch {
853
+ hasDynamic = true;
854
+ }
855
+ }
856
+ }
857
+ for (const child of node.children) {
858
+ walk(child);
859
+ }
860
+ };
861
+ walk(element);
862
+ return hasDynamic;
863
+ }
864
+ /**
865
+ * An <Svg> width or height as pixels.
866
+ *
867
+ * @param field Which one.
868
+ * @param value Its folded value.
869
+ * @param scaled Whether the drawing is scaled to it, which takes pixels.
870
+ *
871
+ * @returns The pixels.
872
+ */
873
+ function svgPixels(field, value, scaled) {
874
+ const pixels = typeof value === 'number' ? value : NaN;
875
+ if (!Number.isFinite(pixels)) {
876
+ throw aotError(`AOT: <Svg ${field}> must be a number of pixels${scaled ? '' : ' or a percentage'} ` +
877
+ `(got ${JSON.stringify(value) ?? String(value)})`, scaled
878
+ ? 'a viewBox or a baked source is scaled to the box, so the box takes pixels; size a wrapping ' +
879
+ "<View> with style={{width: '50%'}} for a share of the parent."
880
+ : `write the pixels as a number (${field}={100}): Flow A ignores a numeric string here.`);
881
+ }
882
+ return pixels;
883
+ }
884
+ /**
885
+ * The ERProps writes for an <Svg> width or height: pixels as an int16, or a percentage of the parent when the
886
+ * drawing is not scaled to the box. Absent, it writes nothing.
887
+ *
888
+ * @param field Which one.
889
+ * @param value Its folded value, or the state-driven one.
890
+ * @param scaled Whether the drawing is scaled to the box (a viewBox or a baked source).
891
+ *
892
+ * @returns The writes.
893
+ */
894
+ function svgBoxSize(field, value, scaled) {
895
+ if (value == null)
896
+ return [];
897
+ if (isDynamicAttr(value)) {
898
+ throw aotError(`AOT: a state-driven <Svg ${field}> is not supported`, `give the <Svg> a constant ${field} and drive the size of a wrapping <View> from state instead.`);
899
+ }
900
+ if (!scaled && typeof value === 'string' && value.trim().endsWith('%')) {
901
+ return lowerStyle({ [field]: value });
902
+ }
903
+ return [
904
+ {
905
+ field,
906
+ expr: `(int16_t)${Math.round(svgPixels(field, value, scaled))}`,
907
+ },
908
+ ];
909
+ }
910
+ /**
911
+ * Lowers the box an <Svg> draws in: a node of `type` with its size, then its static style, its animated
912
+ * transform and its refs. No state drives the box: it is not a node app_update() rewrites.
913
+ *
914
+ * @param nodeId The node's variable.
915
+ * @param type The engine node type: a vector node, or an image for a rasterized .svg.
916
+ * @param width Its width writes (see svgBoxSize).
917
+ * @param height Its height writes.
918
+ * @param openingElement The <Svg>'s opening tag, for its style and ref.
919
+ * @param scope Compile-time constants in reach.
920
+ * @param env The expression environment.
921
+ *
922
+ * @returns The node, with its refs wired.
923
+ */
924
+ function lowerSvgBox(nodeId, type, width, height, openingElement, scope, env) {
925
+ const { staticAssigns, dynAssigns, binds } = collectStyleAssigns(openingElement, scope, env, elementSpec('Svg'));
926
+ if (dynAssigns.length) {
927
+ throw aotError('AOT: a state-driven style on an <Svg> is not supported', 'put the changing style on a wrapping <View>: <View style={…}><Svg …/></View>.');
928
+ }
929
+ // A style width or height wins over the attribute, in pixels or as a percentage of the parent.
930
+ const size = [...width, ...height].filter(assign => !styleWrites(staticAssigns, [], assign.field.replace(/_pct$/, '')));
931
+ const node = {
932
+ id: nodeId,
933
+ type,
934
+ constantProps: [...size, ...staticAssigns],
935
+ stateProps: [],
936
+ placeholder: null,
937
+ text: null,
938
+ image: null,
939
+ spans: null,
940
+ wiring: [
941
+ ...binds.map((bind, index) => ({ kind: 'bind', bind, index })),
942
+ ...lowerRefBinds(openingElement, env).map(slot => ({
943
+ kind: 'ref',
944
+ slot,
945
+ })),
946
+ ],
947
+ children: [],
948
+ };
949
+ checkInterpolations(node);
950
+ return node;
951
+ }
952
+ /**
953
+ * <Svg> → ER_NODE_VECTOR. Static subtree → is a baked const op-tape, converted by flattenSvg (the same
954
+ * converter Flow A uses); any state-driven attr → a symbolic op-tape rebuilt by a generated build_svgN() at
955
+ * build time and on every app_update. <Svg source> draws a .svg baked ahead of time (bakeSvgArtifacts).
956
+ *
957
+ * @param element The <Svg>.
958
+ * @param scope Compile-time constants in reach.
959
+ * @param out Everything emitted so far.
960
+ * @param env The expression environment.
961
+ * @param state The component's state table.
962
+ * @param opts How the element is placed.
963
+ *
964
+ * @returns The node.
965
+ */
966
+ export function emitSvg(element, scope, out, env, state, opts) {
967
+ if (opts.show) {
968
+ throw new Error('AOT: an <Svg> inside a dynamic conditional is not yet supported');
969
+ }
970
+ // Pick the path: a baked .svg file, a state-driven tape, or a static one.
971
+ const sourceAttr = element.openingElement.attributes.find((candidate) => candidate.type === 'JSXAttribute' &&
972
+ candidate.name &&
973
+ candidate.name.name === 'source');
974
+ if (sourceAttr)
975
+ return emitSvgSource(element, sourceAttr, scope, out, env);
976
+ return svgHasDynamic(element, scope)
977
+ ? emitSvgDynamic(element, scope, out, env, state)
978
+ : emitSvgStatic(element, scope, out, env);
979
+ }
980
+ /**
981
+ * Static <Svg>: reuse flattenSvg (full feature set: viewBox, <G>, Path) and bake const arrays.
982
+ *
983
+ * @param element The <Svg>.
984
+ * @param scope Compile-time constants in reach.
985
+ * @param out Everything emitted so far.
986
+ * @param env The expression environment.
987
+ *
988
+ * @returns The node.
989
+ */
990
+ function emitSvgStatic(element, scope, out, env) {
991
+ // Flatten the subtree and bake its ops and paints into const tables.
992
+ const svgElement = jsxToSvgElement(element, scope);
993
+ const { ops, paints, gradients } = flattenSvg(svgElement.props);
994
+ const nodeId = `n${out.allocateNodeId()}`;
995
+ const tables = {
996
+ id: out.svgN++,
997
+ ops: Array.from(ops),
998
+ paints: paintsOf(paints),
999
+ gradients,
1000
+ };
1001
+ checkVectorTables(tables);
1002
+ out.vectors.push({ kind: 'tables', tables });
1003
+ // Create the vector node and point it at the tables.
1004
+ const node = lowerSvgBox(nodeId, 'ER_NODE_VECTOR', svgBoxSize('width', svgElement.props.width, svgElement.props.viewBox != null), svgBoxSize('height', svgElement.props.height, svgElement.props.viewBox != null), element.openingElement, scope, env);
1005
+ node.wiring.push({ kind: 'vectorTables', tables });
1006
+ return node;
1007
+ }
1008
+ /**
1009
+ * Baked <Svg source={importedSvg}>: the CLI pre-bakes the .svg to a vector artifact (ops/paints/GRADIENTS) *
1010
+ * (bakeSvgArtifacts → opts.svgArtifacts) since compileSource is I/O-free. Scaled to the static
1011
+ * width/height at compile time, then emitted as const tables. This is the path that carries gradients into
1012
+ * Flow B.
1013
+ *
1014
+ * @param element The <Svg>.
1015
+ * @param sourceAttr Its `source` attribute.
1016
+ * @param scope Compile-time constants in reach.
1017
+ * @param out Everything emitted so far.
1018
+ * @param env The expression environment.
1019
+ *
1020
+ * @returns The node.
1021
+ */
1022
+ function emitSvgSource(element, sourceAttr, scope, out, env) {
1023
+ // Resolve the source to its imported .svg's baked artifact.
1024
+ const expr = sourceAttr.value && sourceAttr.value.type === 'JSXExpressionContainer'
1025
+ ? sourceAttr.value.expression
1026
+ : null;
1027
+ if (!expr || expr.type !== 'Identifier') {
1028
+ throw new Error('AOT: <Svg source> must reference an imported .svg (source={importedSvg})');
1029
+ }
1030
+ const svgImport = env.svgImports.get(expr.name);
1031
+ if (!svgImport) {
1032
+ throw new Error(`AOT: <Svg source={${expr.name}}> — no matching \`import ${expr.name} from '...svg'\``);
1033
+ }
1034
+ const artifact = env.svgArtifacts[svgImport.name];
1035
+ if (!artifact) {
1036
+ throw new Error(`AOT: vector artifact for "${svgImport.name}" was not baked (internal: opts.svgArtifacts missing it)`);
1037
+ }
1038
+ // Scale the artifact at compile time to a static width/height, defaulting to its intrinsic size.
1039
+ const numericAttr = (attrName, fallback) => {
1040
+ const attr = element.openingElement.attributes.find((candidate) => candidate.type === 'JSXAttribute' &&
1041
+ candidate.name &&
1042
+ candidate.name.name === attrName);
1043
+ if (!attr)
1044
+ return fallback;
1045
+ let value = true; // a bare attribute
1046
+ if (attr.value?.type === 'StringLiteral') {
1047
+ value = attr.value.value;
1048
+ }
1049
+ else if (attr.value?.type === 'JSXExpressionContainer') {
1050
+ try {
1051
+ value = evalStatic(attr.value.expression, scope);
1052
+ }
1053
+ catch {
1054
+ throw at(aotError('AOT: <Svg source> width/height must be a static number'), attr);
1055
+ }
1056
+ }
1057
+ try {
1058
+ return svgPixels(attrName, value, true);
1059
+ }
1060
+ catch (error) {
1061
+ throw at(error, attr);
1062
+ }
1063
+ };
1064
+ // The drawing is scaled to the box, so a style size wins over the attribute, as in Flow A.
1065
+ const { staticAssigns: style } = collectStyleAssigns(element.openingElement, scope, env, elementSpec('Svg'));
1066
+ const boxSize = (field, fallback) => {
1067
+ if (style.some(assign => assign.field === `${field}_pct`)) {
1068
+ throw aotError(`AOT: a percentage style ${field} on an <Svg source> is not supported`, 'the drawing is scaled to the box at build time, when the parent size is unknown; give the ' +
1069
+ `<Svg> its ${field} in pixels.`);
1070
+ }
1071
+ const styled = style.find(assign => assign.field === field);
1072
+ return styled ? Number(styled.expr) : numericAttr(field, fallback);
1073
+ };
1074
+ // Raster fallback: a .svg with unsupported features was baked to a PNG; register it and emit an Image node.
1075
+ const width = boxSize('width', artifact.width);
1076
+ const height = boxSize('height', artifact.height);
1077
+ if (artifact.kind === 'raster') {
1078
+ if (artifact.png) {
1079
+ out.images.set(artifact.name, artifact.png);
1080
+ }
1081
+ const node = lowerSvgBox(`n${out.allocateNodeId()}`, NODE_TYPES.Image, svgBoxSize('width', width, true), svgBoxSize('height', height, true), element.openingElement, scope, env);
1082
+ node.image = { kind: 'static', name: artifact.name, resetOnUpdate: false };
1083
+ return node;
1084
+ }
1085
+ // Scale the vector artifact to the box and bake its ops, paints and gradients into const tables.
1086
+ const scaled = scaleVectorArtifact(artifact, width, height);
1087
+ const nodeId = `n${out.allocateNodeId()}`;
1088
+ const tables = {
1089
+ id: out.svgN++,
1090
+ ops: Array.from(scaled.ops),
1091
+ paints: paintsOf(scaled.paints),
1092
+ gradients: scaled.gradients || [],
1093
+ };
1094
+ checkVectorTables(tables);
1095
+ out.vectors.push({ kind: 'tables', tables });
1096
+ // Create the vector node and point it at the tables.
1097
+ const node = lowerSvgBox(nodeId, 'ER_NODE_VECTOR', svgBoxSize('width', width, true), svgBoxSize('height', height, true), element.openingElement, scope, env);
1098
+ node.wiring.push({ kind: 'vectorTables', tables });
1099
+ return node;
1100
+ }
1101
+ /**
1102
+ * State-driven <Svg> (flat Arc/Circle/Rect/Line/static-Path; no viewBox/<G>): emit a mutable op-tape
1103
+ * + build_svgN() that recomputes it from state, called at build and re-called on each app_update.
1104
+ *
1105
+ * @param element The <Svg>.
1106
+ * @param scope Compile-time constants in reach.
1107
+ * @param out Everything emitted so far.
1108
+ * @param env The expression environment.
1109
+ * @param state The component's state table.
1110
+ *
1111
+ * @returns The node.
1112
+ */
1113
+ function emitSvgDynamic(element, scope, out, env, state) {
1114
+ // The root's attributes give the box; this path has no viewBox transform.
1115
+ const rootAttrs = svgAttrs(element.openingElement, scope, env);
1116
+ if (rootAttrs.viewBox != null) {
1117
+ throw new Error('AOT: a viewBox on a state-driven <Svg> is not yet supported — size shapes in the width/height space');
1118
+ }
1119
+ // Lower each shape to tape slots (after an ER_VOP_SHAPE marker naming its paint) and its paint.
1120
+ const tape = [];
1121
+ const locals = []; // declared ahead of the tape (rounded-rect radii)
1122
+ const shapePaints = [];
1123
+ for (const child of svgShapeChildren(element.children)) {
1124
+ const type = child.openingElement.name.name;
1125
+ const lowerShape = SHAPE_TAPES[type];
1126
+ if (!lowerShape) {
1127
+ throw new Error(`AOT: <${type}> is not a supported shape in a state-driven <Svg> (no <G>/viewBox yet)`);
1128
+ }
1129
+ const attrs = svgAttrs(child.openingElement, scope, env);
1130
+ // build_svgN() is this <Svg>'s own function, so the shape index alone keeps a local's name unique.
1131
+ const shape = lowerShape(attrs, `s${shapePaints.length}`);
1132
+ if (!shape.entries.length)
1133
+ continue;
1134
+ locals.push(...shape.locals);
1135
+ tape.push(tapeOp('ER_VOP_SHAPE'), tapeNumber(shapePaints.length), ...shape.entries);
1136
+ shapePaints.push(lowerShapePaint(attrs, env, scope));
1137
+ }
1138
+ // Allocate the node and this <Svg>'s table names.
1139
+ const nodeId = `n${out.allocateNodeId()}`;
1140
+ const svgId = out.svgN++;
1141
+ out.needsMath = true; // build_svg uses cosf/sinf/M_PI for arcs
1142
+ // Gather the gradients into one 1-based table per <Svg>, fill then stroke, shape by shape.
1143
+ const gradients = [];
1144
+ const place = (shapeGradient) => shapeGradient
1145
+ ? {
1146
+ index: gradients.push(shapeGradient.gradient),
1147
+ when: shapeGradient.when,
1148
+ }
1149
+ : { index: 0, when: null };
1150
+ const vector = {
1151
+ id: svgId,
1152
+ locals,
1153
+ tape,
1154
+ paints: shapePaints.map(shapePaint => ({
1155
+ ...shapePaint.paint,
1156
+ fillGradient: place(shapePaint.fillGradient),
1157
+ strokeGradient: place(shapePaint.strokeGradient),
1158
+ })),
1159
+ gradients,
1160
+ };
1161
+ // Declare the tables and build_svgN(), which rewrites the tape (and anything in the paints state drives).
1162
+ out.vectors.push({ kind: 'drawing', vector });
1163
+ // Create the vector node, build its tape once, and register it for app_update() to rebuild.
1164
+ const node = lowerSvgBox(nodeId, 'ER_NODE_VECTOR', svgBoxSize('width', rootAttrs.width, false), svgBoxSize('height', rootAttrs.height, false), element.openingElement, scope, env);
1165
+ node.wiring.push({ kind: 'stateDrivenVector', vector });
1166
+ return node;
1167
+ }