embedded-react 0.12.0 → 0.13.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.
package/aot/compile.mjs CHANGED
@@ -21,7 +21,7 @@
21
21
  // internal RAM.
22
22
  //
23
23
  // Supported subset (grows demo by demo; unsupported syntax throws "AOT: ..."):
24
- // - View / Text / Pressable / Image / ScrollView elements
24
+ // - View / Text / Pressable / TouchableOpacity / Image / ScrollView elements
25
25
  // - StyleSheet + inline styles → ERProps (static values)
26
26
  // - text with literal + {interpolation} segments (interpolations may reference state)
27
27
  // - useState(initial) → C state; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → C functions
@@ -54,11 +54,14 @@ import {
54
54
  flattenSvg,
55
55
  parseColor,
56
56
  parsePath,
57
+ KAPPA,
57
58
  PAINT_STRIDE,
58
59
  GRAD_MAX_STOPS,
59
60
  scaleVectorArtifact,
60
61
  } from '../src/embedded-react/svg-ops.js';
61
62
  import {bakeAssets} from '../assets/index.mjs';
63
+ import {warnMissingGlyphs} from '../assets/glyph-coverage.mjs';
64
+ import {analyzeFontSizes, warnFontSizes} from '../assets/font-sizes.mjs';
62
65
 
63
66
  const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js/aot
64
67
  const repoRoot = resolve(here, '../../../..');
@@ -128,7 +131,8 @@ function withLoc(fn) {
128
131
  };
129
132
  }
130
133
 
131
- /** Re-throws an AOT error with `file:line:col`, a code-frame, and any hint folded into the message. */
134
+ /** Re-throws an AOT error with `file:line:col`, a code-frame, any hint, and the screen size this build
135
+ * folded its layout at — all folded into the message. */
132
136
  function formatAotError(e, src, filename) {
133
137
  if (!e || !e.aotLoc) return e; // nothing to locate — leave the bare message
134
138
  const {line, column} = e.aotLoc;
@@ -140,8 +144,16 @@ function formatAotError(e, src, filename) {
140
144
  /* code-frame is best-effort */
141
145
  }
142
146
  const hint = e.aotHint ? `\n\nhint: ${e.aotHint}` : '';
147
+ // A responsive app folds its layout from `screen`, so the size baked into THIS build decides which
148
+ // branch the compiler walks. Compile at the wrong one and the error points at whatever unsupported
149
+ // thing the unintended branch happens to hold, with nothing on screen tying it back to the size.
150
+ const screen = SCREEN_FROM_ENV
151
+ ? `\n\nscreen: ${SCREEN_W}×${SCREEN_H} (from ER_AOT_SCREEN_W/H).`
152
+ : `\n\nscreen: ${SCREEN_W}×${SCREEN_H} — ER_AOT_SCREEN_W/H did not supply both dimensions, so the ` +
153
+ `default filled in. A responsive app picks its layout from \`screen\`, so this may be compiling a ` +
154
+ `branch meant for another board.`;
143
155
  const out = new Error(
144
- `${e.message}\n at ${filename}:${line}:${column + 1}\n\n${frame}${hint}`,
156
+ `${e.message}\n at ${filename}:${line}:${column + 1}\n\n${frame}${hint}${screen}`,
145
157
  );
146
158
  out.aotLoc = e.aotLoc;
147
159
  if (e.aotHint) out.aotHint = e.aotHint;
@@ -426,6 +438,7 @@ function emitExprImpl(node, env) {
426
438
  prop === 'current'
427
439
  ) {
428
440
  const r = env.refs.get(obj.name);
441
+ r.used = true;
429
442
  return {code: r.cVar, cType: r.cType};
430
443
  }
431
444
  // `<event>.x / .y / .dx / .dy` — touch fields of the handler's EREventData.
@@ -436,6 +449,19 @@ function emitExprImpl(node, env) {
436
449
  ) {
437
450
  return {code: `data->${prop}`, cType: 'int'};
438
451
  }
452
+ // `<event>.vx / .vy` — how fast the finger was going (px/ms) at the last measured move. The engine
453
+ // measures it; a Flow B handler could not, having neither a clock nor the previous point.
454
+ if (
455
+ obj.type === 'Identifier' &&
456
+ env.event === obj.name &&
457
+ (prop === 'vx' || prop === 'vy')
458
+ ) {
459
+ return {code: `data->${prop}`, cType: 'float'};
460
+ }
461
+ // `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
462
+ if (obj.type === 'Identifier' && env.gesture === obj.name && prop) {
463
+ return panGestureField(prop, env.pan);
464
+ }
439
465
  // `<event>.layout.x / .y / .width / .height` — the onLayout rect (EREventData.layout_rect; ERRect uses w/h).
440
466
  if (
441
467
  obj.type === 'MemberExpression' &&
@@ -456,7 +482,7 @@ function emitExprImpl(node, env) {
456
482
  return {code: '(float)M_PI', cType: 'float'};
457
483
  throw aotError(
458
484
  'AOT: unsupported member expression in a dynamic context',
459
- 'in a handler or dynamic expression you can read state, `ref.current`, a `.map` item field, event fields (e.x / e.y / e.dx / e.dy / e.layout.*), and Math.PI — other member access must be a compile-time constant.',
485
+ 'in a handler or dynamic expression you can read state, `ref.current`, a `.map` item field, event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and Math.PI — other member access must be a compile-time constant.',
460
486
  );
461
487
  }
462
488
  case 'CallExpression': {
@@ -545,6 +571,11 @@ function findComponent(program) {
545
571
  // e.g. ER_AOT_SCREEN_W=240 ER_AOT_SCREEN_H=320 for the CYD; defaults to a wide 800×480.
546
572
  const SCREEN_W = Number(process.env.ER_AOT_SCREEN_W) || 800;
547
573
  const SCREEN_H = Number(process.env.ER_AOT_SCREEN_H) || 480;
574
+ // Whether BOTH dimensions above came from the environment. A blank or unparsable override falls back to
575
+ // the default for that axis alone, so this asks what was actually used, not whether the vars are set.
576
+ const SCREEN_FROM_ENV =
577
+ Number(process.env.ER_AOT_SCREEN_W) > 0 &&
578
+ Number(process.env.ER_AOT_SCREEN_H) > 0;
548
579
 
549
580
  function moduleScope(program, screen, seed = {}) {
550
581
  // `seed` pre-populates the scope (e.g. image imports as their asset-name strings) BEFORE module consts are
@@ -906,9 +937,8 @@ export async function bakeSvgArtifacts(src, baseDir) {
906
937
  }).program;
907
938
  const imports = collectSvgImports(program);
908
939
  if (imports.size === 0) return {};
909
- const {svgToVector, svgToRaster, writeRasterPng} = await import(
910
- '../assets/bake-svg.mjs'
911
- );
940
+ const {svgToVector, svgToRaster, writeRasterPng} =
941
+ await import('../assets/bake-svg.mjs');
912
942
  const artifacts = {};
913
943
  for (const [, imp] of imports) {
914
944
  const p = resolve(baseDir, imp.importPath);
@@ -1084,14 +1114,16 @@ function collectRefs(fnBody, scope, prefix = '') {
1084
1114
  init.callee.name === 'useRef' &&
1085
1115
  decl.id.type === 'Identifier'
1086
1116
  ) {
1087
- const cVar = `s_ref_${prefix}${decl.id.name}`;
1088
1117
  const arg = init.arguments[0];
1118
+ if (isPanCreate(arg)) continue; // a PanResponder ref — collectPanResponders owns it
1119
+ const cVar = `s_ref_${prefix}${decl.id.name}`;
1089
1120
  if (!arg || arg.type === 'NullLiteral') {
1090
1121
  refs.set(decl.id.name, {
1091
1122
  cVar,
1092
1123
  cType: 'ERNode*',
1093
1124
  initCode: 'NULL',
1094
1125
  kind: 'node',
1126
+ used: false,
1095
1127
  });
1096
1128
  continue;
1097
1129
  }
@@ -1106,6 +1138,7 @@ function collectRefs(fnBody, scope, prefix = '') {
1106
1138
  cType,
1107
1139
  initCode: cType === 'float' ? `${v}f` : String(v),
1108
1140
  kind: 'value',
1141
+ used: false,
1109
1142
  });
1110
1143
  }
1111
1144
  }
@@ -1344,10 +1377,30 @@ function lowerDynamicStyleValue(key, valueNode, env) {
1344
1377
  {field: meta.field, code: emitEnumExpr(valueNode, meta.table, env)},
1345
1378
  ];
1346
1379
  return [
1347
- {field: meta.field, code: `(int16_t)(${emitExpr(valueNode, env).code})`},
1380
+ {
1381
+ field: meta.field,
1382
+ code: `app_round_dim(${emitExpr(valueNode, env).code})`,
1383
+ },
1348
1384
  ]; /* num */
1349
1385
  }
1350
1386
 
1387
+ /**
1388
+ * Whether a style already writes `field`, counting its percentage twin: `width: '50%'` lowers to
1389
+ * `width_pct`, and the author has still set the width. Used by the components that fall back to a
1390
+ * built-in size or inset when the style leaves one out — without the twin they inject a pixel default
1391
+ * ALONGSIDE the percentage, and the engine prefers the pixel value for a size.
1392
+ *
1393
+ * @param {{field: string}[]} staticAssigns Static field writes from collectStyleAssigns().
1394
+ * @param {{field: string}[]} dynAssigns State-driven field writes from collectStyleAssigns().
1395
+ * @param {string} field ERProps field to look for.
1396
+ */
1397
+ const styleWrites = (staticAssigns, dynAssigns, field) =>
1398
+ [field, `${field}_pct`].some(
1399
+ f =>
1400
+ staticAssigns.some(a => a.field === f) ||
1401
+ dynAssigns.some(a => a.field === f),
1402
+ );
1403
+
1351
1404
  /**
1352
1405
  * Collects an element's merged style into static field assigns and dynamic (state-driven) field assigns.
1353
1406
  * Inline object values are tried statically first; a value that references state becomes a dynAssign.
@@ -2002,15 +2055,19 @@ function refTarget(node, env) {
2002
2055
  node.property.name === 'current' &&
2003
2056
  env.refs?.has(node.object.name)
2004
2057
  ) {
2005
- return env.refs.get(node.object.name);
2058
+ const r = env.refs.get(node.object.name);
2059
+ r.used = true;
2060
+ return r;
2006
2061
  }
2007
2062
  return null;
2008
2063
  }
2009
2064
 
2010
- /** An imperative updateVector shape `{ arc:[…]|circle:[…]|rect:[…]|line:[…]|path:'…', fill, stroke, … }`
2011
- * → { entries (op-tape C exprs), paint (static 7-num record) }. Geometry coords may reference state/refs/
2012
- * event fields (emitExpr); paint must be static. Shares the ...EntriesC geometry with the JSX path. */
2013
- function imperativeShape(shapeNode, env) {
2065
+ /** An imperative updateVector shape `{ arc:[…]|circle:[…]|rect:[x,y,w,h,rx?,ry?]|line:[…]|path:'…', fill, … }`
2066
+ * → { entries (op-tape C exprs), locals (C declarations to emit ahead of them), paint (static 7-num
2067
+ * record) }. Geometry coords may reference state/refs/event fields (emitExpr); paint must be static.
2068
+ * Shares the ...EntriesC geometry with the JSX path. `tag` names any locals and must be unique in the
2069
+ * handler block the caller writes them into. */
2070
+ function imperativeShape(shapeNode, env, tag) {
2014
2071
  if (shapeNode?.type !== 'ObjectExpression')
2015
2072
  throw new Error('AOT: each updateVector shape must be an object literal');
2016
2073
  const props = {};
@@ -2028,14 +2085,18 @@ function imperativeShape(shapeNode, env) {
2028
2085
  .slice(0, n)
2029
2086
  .map(el => `(float)(${emitExpr(el, env).code})`);
2030
2087
  };
2031
- let entries;
2032
- if (props.arc) entries = arcEntriesC(...arr('arc', 5));
2033
- else if (props.circle) entries = circleEntriesC(...arr('circle', 3));
2034
- else if (props.rect) entries = rectEntriesC(...arr('rect', 4));
2035
- else if (props.line) entries = lineEntriesC(...arr('line', 4));
2088
+ let geo;
2089
+ if (props.arc) geo = geometryOf(arcEntriesC(...arr('arc', 5)));
2090
+ else if (props.circle) geo = geometryOf(circleEntriesC(...arr('circle', 3)));
2091
+ else if (props.rect) {
2092
+ // Destructured rather than spread: the radii are optional, so a 4-element literal must not slide
2093
+ // `tag` into rx's slot.
2094
+ const [x, y, w, h, rx = null, ry = null] = arr('rect', 6);
2095
+ geo = geometryOf(rectEntriesC(x, y, w, h, rx, ry, tag));
2096
+ } else if (props.line) geo = geometryOf(lineEntriesC(...arr('line', 4)));
2036
2097
  else if (props.path)
2037
- entries = parsePath(String(evalStatic(props.path, env.consts ?? {}))).map(
2038
- floatLit,
2098
+ geo = geometryOf(
2099
+ parsePath(String(evalStatic(props.path, env.consts ?? {}))).map(floatLit),
2039
2100
  );
2040
2101
  else
2041
2102
  throw new Error(
@@ -2058,7 +2119,7 @@ function imperativeShape(shapeNode, env) {
2058
2119
  JOIN_MAP[stat('join', 'miter')] ?? 0,
2059
2120
  stat('fillRule', 'nonzero') === 'evenodd' ? 1 : 0,
2060
2121
  ];
2061
- return {entries, paint};
2122
+ return {...geo, paint};
2062
2123
  }
2063
2124
 
2064
2125
  /** Lowers `updateVector(nodeRef, shapes, [x,y,w,h]?)` to: fill a mutable op-tape, push it to the node, and
@@ -2071,25 +2132,37 @@ function compileUpdateVector(expr, env, ctx, indent) {
2071
2132
  throw new Error(
2072
2133
  'AOT: updateVector(ref, …) first arg must be a node ref (const r = useRef())',
2073
2134
  );
2135
+ ref.used = true;
2074
2136
  if (shapesArg?.type !== 'ArrayExpression')
2075
2137
  throw new Error(
2076
2138
  'AOT: updateVector(ref, shapes, …) shapes must be an array literal',
2077
2139
  );
2140
+ // Claimed before the shape loop so a shape's locals can carry it: two updateVector calls can land in
2141
+ // the same handler block, where a name keyed only on the shape index would collide.
2142
+ const id = out.svgN++;
2078
2143
  const entries = [];
2144
+ const decls = [];
2079
2145
  const paints = [];
2080
2146
  for (const s of shapesArg.elements) {
2081
- const {entries: e, paint} = imperativeShape(s, env);
2147
+ const {
2148
+ entries: e,
2149
+ locals,
2150
+ paint,
2151
+ } = imperativeShape(s, env, `uv${id}_${paints.length}`);
2152
+ decls.push(...locals);
2082
2153
  entries.push('ER_VOP_SHAPE', floatLit(paints.length), ...e);
2083
2154
  paints.push(paint);
2084
2155
  }
2085
- const id = out.svgN++;
2086
2156
  const len = entries.length;
2087
2157
  out.needsMath = true;
2088
2158
  out.vectorData.push(`static float s_uv${id}_ops[${len}];`);
2089
2159
  out.vectorData.push(
2090
2160
  `static const ERVectorPaint s_uv${id}_paints[] = {\n${paints.map(p => ' ' + emitVectorPaint(p)).join(',\n')}\n};`,
2091
2161
  );
2092
- const lines = entries.map((e, i) => `${indent}s_uv${id}_ops[${i}] = ${e};`);
2162
+ const lines = [
2163
+ ...decls.map(d => `${indent}${d}`),
2164
+ ...entries.map((e, i) => `${indent}s_uv${id}_ops[${i}] = ${e};`),
2165
+ ];
2093
2166
  lines.push(
2094
2167
  `${indent}er_node_set_vector_ops(${ref.cVar}, s_uv${id}_ops, ${len}, s_uv${id}_paints, ${paints.length}, NULL, 0);`,
2095
2168
  );
@@ -2434,22 +2507,371 @@ function compileEffect(eff, env, state, out) {
2434
2507
  out.depEffects.push(check.join('\n'));
2435
2508
  }
2436
2509
 
2437
- function compileHandler(fnNode, env, state, out) {
2510
+ function compileHandler(fnNode, env, state, out, pan = null) {
2438
2511
  const body = fnNode.body;
2439
2512
  const list =
2440
2513
  body.type === 'BlockStatement'
2441
2514
  ? body.body
2442
2515
  : [{type: 'ExpressionStatement', expression: body}];
2443
- // The handler's first parameter is the event; `<event>.x/.y/.dx/.dy` map to EREventData fields.
2516
+ // The handler's first parameter is the event; `<event>.x/.y/.dx/.dy/.vx/.vy` map to EREventData fields.
2517
+ // A PanResponder callback takes a second one, RN's gestureState — see panGestureField.
2444
2518
  const eventParam =
2445
2519
  fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
2446
- const henv = eventParam ? {...env, event: eventParam} : env;
2520
+ const gestureParam =
2521
+ pan && fnNode.params[1]?.type === 'Identifier'
2522
+ ? fnNode.params[1].name
2523
+ : null;
2524
+ let henv = env;
2525
+ if (eventParam) henv = {...henv, event: eventParam};
2526
+ if (gestureParam) henv = {...henv, gesture: gestureParam, pan};
2447
2527
  const ctx = {stateChanged: false, animIdx: 0, out};
2448
2528
  const stmts = compileStmts(list, henv, state, ctx, ' ');
2449
2529
  if (ctx.stateChanged) stmts.push(' app_update();'); // re-apply state-dependent props once
2450
2530
  return stmts;
2451
2531
  }
2452
2532
 
2533
+ // ---------------------------------------------------------------------------------------------------
2534
+ // PanResponder (Flow B) — LOWERED onto the engine's responder system, not transpiled.
2535
+ //
2536
+ // RN's PanResponder is a JS state machine over raw touches. The engine already has that machine, in C:
2537
+ // capture/bubble negotiation (er_responder_query_set) picks an owner, and GRANT / MOVE / RELEASE /
2538
+ // TERMINATE then fire on the owner alone, carrying cumulative travel and velocity. So the should-set
2539
+ // predicates become QUERIES and the callbacks become responder EVENT handlers — no gesture math is
2540
+ // duplicated into the generated C, and the app gets real arbitration for free (a granted pan owns the
2541
+ // gesture, so a ScrollView ancestor cannot auto-scroll out from under it).
2542
+ //
2543
+ // The one thing with no engine counterpart is RN's anchor: `g.dx` is measured from the GRANT, while the
2544
+ // engine's `data->dx` runs from touch-down — a claim that needed 10 px of slop would otherwise open with
2545
+ // a 10 px jump. That anchor, plus `x0`/`y0`, is a handful of file-scope ints per responder.
2546
+ // ---------------------------------------------------------------------------------------------------
2547
+
2548
+ /** RN PanResponder config key → the engine responder QUERY it lowers to. */
2549
+ const PAN_QUERIES = {
2550
+ onStartShouldSetPanResponder: 'ER_QUERY_START_SHOULD_SET',
2551
+ onStartShouldSetPanResponderCapture: 'ER_QUERY_START_SHOULD_SET_CAPTURE',
2552
+ onMoveShouldSetPanResponder: 'ER_QUERY_MOVE_SHOULD_SET',
2553
+ onMoveShouldSetPanResponderCapture: 'ER_QUERY_MOVE_SHOULD_SET_CAPTURE',
2554
+ onPanResponderTerminationRequest: 'ER_QUERY_TERMINATION_REQUEST',
2555
+ };
2556
+
2557
+ /** Query constant → the suffix of the C function emitted for it. */
2558
+ const PAN_QUERY_SUFFIX = {
2559
+ ER_QUERY_START_SHOULD_SET: 'start_should_set',
2560
+ ER_QUERY_START_SHOULD_SET_CAPTURE: 'start_should_set_capture',
2561
+ ER_QUERY_MOVE_SHOULD_SET: 'move_should_set',
2562
+ ER_QUERY_MOVE_SHOULD_SET_CAPTURE: 'move_should_set_capture',
2563
+ ER_QUERY_TERMINATION_REQUEST: 'termination_request',
2564
+ };
2565
+
2566
+ /** RN PanResponder config key → the engine responder EVENT it lowers to. */
2567
+ const PAN_EVENTS = {
2568
+ onPanResponderGrant: 'ER_EVENT_RESPONDER_GRANT',
2569
+ onPanResponderMove: 'ER_EVENT_RESPONDER_MOVE',
2570
+ onPanResponderRelease: 'ER_EVENT_RESPONDER_RELEASE',
2571
+ onPanResponderTerminate: 'ER_EVENT_RESPONDER_TERMINATE',
2572
+ onPanResponderReject: 'ER_EVENT_RESPONDER_REJECT',
2573
+ };
2574
+
2575
+ /** Config keys the Flow A module acts on that have no Flow B lowering — rejected by name, not ignored. */
2576
+ const PAN_FLOW_A_ONLY = {
2577
+ onPanResponderStart:
2578
+ 'it reports EXTRA fingers joining a gesture already in flight; Flow B lowers one gesture per responder.',
2579
+ onPanResponderEnd:
2580
+ 'it reports a finger lifting while others stay down; Flow B lowers one gesture per responder.',
2581
+ };
2582
+
2583
+ /** True for a `PanResponder.create({…})` call. */
2584
+ const isPanCreate = n =>
2585
+ n?.type === 'CallExpression' &&
2586
+ n.callee.type === 'MemberExpression' &&
2587
+ !n.callee.computed &&
2588
+ n.callee.object.type === 'Identifier' &&
2589
+ n.callee.object.name === 'PanResponder' &&
2590
+ n.callee.property.name === 'create';
2591
+
2592
+ /**
2593
+ * One `gestureState` field → the C expression that reads it. Travel is rebased onto the grant (RN's
2594
+ * anchor); the point and the velocity come straight off the engine payload; the finger count is the
2595
+ * engine's own, which is why er_touch_active_count() exists.
2596
+ */
2597
+ function panGestureField(prop, pan) {
2598
+ switch (prop) {
2599
+ case 'dx':
2600
+ return {code: `(data->dx - ${pan.cPrefix}_base_dx)`, cType: 'int'};
2601
+ case 'dy':
2602
+ return {code: `(data->dy - ${pan.cPrefix}_base_dy)`, cType: 'int'};
2603
+ case 'moveX':
2604
+ return {code: 'data->x', cType: 'int'};
2605
+ case 'moveY':
2606
+ return {code: 'data->y', cType: 'int'};
2607
+ case 'x0':
2608
+ return {code: `${pan.cPrefix}_x0`, cType: 'int'};
2609
+ case 'y0':
2610
+ return {code: `${pan.cPrefix}_y0`, cType: 'int'};
2611
+ case 'vx':
2612
+ case 'vy':
2613
+ return {code: `data->${prop}`, cType: 'float'};
2614
+ case 'numberActiveTouches':
2615
+ return {code: 'er_touch_active_count()', cType: 'int'};
2616
+ case 'stateID':
2617
+ return {code: String(pan.stateID), cType: 'int'};
2618
+ }
2619
+ throw aotError(
2620
+ `AOT: unknown gestureState field "${prop}" in a PanResponder callback`,
2621
+ 'a gestureState carries dx / dy / moveX / moveY / x0 / y0 / vx / vy / numberActiveTouches / stateID.',
2622
+ );
2623
+ }
2624
+
2625
+ /** Validates one `PanResponder.create({…})` config and builds the descriptor the emitter works from. */
2626
+ function buildPanDescriptor(name, createCall, prefix) {
2627
+ const cfg = createCall.arguments[0];
2628
+ if (!cfg || cfg.type !== 'ObjectExpression')
2629
+ throw aotError(
2630
+ 'AOT: PanResponder.create(...) needs an object literal of callbacks',
2631
+ 'write the config inline — `PanResponder.create({ onStartShouldSetPanResponder: () => true, … })` — so the AOT can see which callbacks exist at compile time.',
2632
+ );
2633
+ const queries = new Map();
2634
+ const events = new Map();
2635
+ for (const prop of cfg.properties) {
2636
+ if (prop.type !== 'ObjectProperty' && prop.type !== 'ObjectMethod')
2637
+ throw aotError(
2638
+ 'AOT: a spread inside PanResponder.create({…}) is not supported',
2639
+ 'list the callbacks explicitly.',
2640
+ );
2641
+ if (prop.computed)
2642
+ throw aotError(
2643
+ 'AOT: a computed key in PanResponder.create({…}) is not supported',
2644
+ 'name each callback literally — the AOT decides at compile time which engine query or event a key becomes.',
2645
+ );
2646
+ const key = prop.key.name ?? prop.key.value;
2647
+ // A shorthand method (`onPanResponderMove(e, g) { … }`) IS the function node; a property holds it.
2648
+ const fn = prop.type === 'ObjectMethod' ? prop : prop.value;
2649
+ if (PAN_FLOW_A_ONLY[key])
2650
+ throw aotError(
2651
+ `AOT: PanResponder "${key}" is not supported in Flow B`,
2652
+ `${PAN_FLOW_A_ONLY[key]} Use onPanResponderGrant / Release / Terminate instead, or build this screen for Flow A.`,
2653
+ );
2654
+ const query = PAN_QUERIES[key];
2655
+ const event = PAN_EVENTS[key];
2656
+ if (!query && !event)
2657
+ throw aotError(
2658
+ `AOT: unknown PanResponder config key "${key}"`,
2659
+ `supported: ${[...Object.keys(PAN_QUERIES), ...Object.keys(PAN_EVENTS)].join(', ')}.`,
2660
+ );
2661
+ if (prop.type !== 'ObjectMethod' && !isFn(fn))
2662
+ throw aotError(
2663
+ `AOT: PanResponder "${key}" must be a function`,
2664
+ 'pass an inline arrow — `(e, g) => …` — so it can be compiled into the generated C.',
2665
+ );
2666
+ if (query) queries.set(query, fn);
2667
+ else events.set(event, fn);
2668
+ }
2669
+ return {
2670
+ name,
2671
+ cPrefix: `s_pan_${prefix}${name}`,
2672
+ fnPrefix: `er_pan_${prefix}${name}`,
2673
+ stateID: 0, // assigned when the responder is first wired to a node
2674
+ queries,
2675
+ events,
2676
+ emitted: null,
2677
+ };
2678
+ }
2679
+
2680
+ /**
2681
+ * Collects `const pan = useRef(PanResponder.create({…})).current` → Map(name → descriptor). The
2682
+ * `useRef(…)` form (read back as `pan.current.panHandlers`) is accepted too; a bare `create(…)` is not,
2683
+ * because it would re-create the recogniser every render in Flow A and the two flows must agree.
2684
+ */
2685
+ function collectPanResponders(fnBody, prefix = '') {
2686
+ const pans = new Map();
2687
+ if (fnBody.type !== 'BlockStatement') return pans;
2688
+ for (const stmt of fnBody.body) {
2689
+ if (stmt.type !== 'VariableDeclaration') continue;
2690
+ for (const decl of stmt.declarations) {
2691
+ const init = decl.init;
2692
+ if (decl.id.type !== 'Identifier' || !init) continue;
2693
+ const viaCurrent =
2694
+ init.type === 'MemberExpression' &&
2695
+ !init.computed &&
2696
+ init.property.name === 'current' &&
2697
+ init.object.type === 'CallExpression' &&
2698
+ init.object.callee.name === 'useRef'
2699
+ ? init.object
2700
+ : null;
2701
+ const viaRef =
2702
+ init.type === 'CallExpression' && init.callee.name === 'useRef'
2703
+ ? init
2704
+ : null;
2705
+ const useRefCall = viaCurrent || viaRef;
2706
+ if (!useRefCall || !isPanCreate(useRefCall.arguments[0])) {
2707
+ if (isPanCreate(init))
2708
+ throw aotError(
2709
+ 'AOT: PanResponder.create(...) must be kept in a useRef',
2710
+ `write \`const ${decl.id.name} = useRef(PanResponder.create({…})).current;\` — the recogniser owns the live gesture, so a fresh one per render would throw the drag away (the same rule Flow A enforces).`,
2711
+ );
2712
+ continue;
2713
+ }
2714
+ const pan = buildPanDescriptor(
2715
+ decl.id.name,
2716
+ useRefCall.arguments[0],
2717
+ prefix,
2718
+ );
2719
+ pan.viaRefCurrent = !viaCurrent; // how the app spells the spread: pan.current.panHandlers
2720
+ pans.set(decl.id.name, pan);
2721
+ }
2722
+ }
2723
+ return pans;
2724
+ }
2725
+
2726
+ /**
2727
+ * Lowers a should-set predicate to a single C boolean expression: the engine calls these synchronously
2728
+ * inside hit-testing, before anyone owns the gesture, so they may only READ.
2729
+ */
2730
+ function compilePanQuery(fnNode, env, pan) {
2731
+ const eventParam =
2732
+ fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
2733
+ const gestureParam =
2734
+ fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
2735
+ const qenv = {...env, pan};
2736
+ if (eventParam) qenv.event = eventParam;
2737
+ if (gestureParam) qenv.gesture = gestureParam;
2738
+ const body = fnNode.body;
2739
+ const expr =
2740
+ body.type === 'BlockStatement'
2741
+ ? body.body.length === 1 && body.body[0].type === 'ReturnStatement'
2742
+ ? body.body[0].argument
2743
+ : null
2744
+ : body;
2745
+ if (!expr)
2746
+ throw aotError(
2747
+ 'AOT: a PanResponder should-set predicate must be a single boolean expression',
2748
+ 'write it as `() => true` or `(e, g) => Math.abs(g.dx) > 8`. The engine asks these mid-hit-test, so they may only read (state, event/gesture fields, constants) — never set state.',
2749
+ );
2750
+ return `(${emitExpr(expr, qenv).code}) != 0`;
2751
+ }
2752
+
2753
+ /**
2754
+ * Emits one PanResponder's gesture state + C callbacks (once, however many nodes spread it), then wires
2755
+ * them onto a node. Grant/release/terminate are ALWAYS emitted even with no user callback: they own the
2756
+ * anchor bookkeeping that makes `g.dx` grant-relative.
2757
+ */
2758
+ function emitPanResponder(pan, v, out, env, state) {
2759
+ if (!pan.emitted) {
2760
+ pan.stateID = ++out.panN;
2761
+ const p = pan.cPrefix;
2762
+ const penv = {...env, pan};
2763
+ const userBody = evt =>
2764
+ pan.events.has(evt)
2765
+ ? compileHandler(pan.events.get(evt), penv, state, out, pan)
2766
+ : [];
2767
+ const guard = [
2768
+ ' if (!' + p + '_granted)',
2769
+ ' {',
2770
+ ' return;',
2771
+ ' }',
2772
+ ];
2773
+
2774
+ out.panDecls.push(
2775
+ `/* PanResponder "${pan.name}" (gesture ${pan.stateID}) — RN's gestureState. The grant anchors the`,
2776
+ ` travel so g.dx opens at 0 however much slop the claim cost; data->dx runs from touch-down. */`,
2777
+ `static int ${p}_granted = 0;`,
2778
+ `static int ${p}_base_dx = 0;`,
2779
+ `static int ${p}_base_dy = 0;`,
2780
+ `static int ${p}_x0 = 0;`,
2781
+ `static int ${p}_y0 = 0;`,
2782
+ );
2783
+
2784
+ pan.emitted = {events: [], queries: []};
2785
+ const push = (evt, suffix, body) => {
2786
+ const name = `${pan.fnPrefix}_${suffix}`;
2787
+ out.handlers.push({name, body});
2788
+ pan.emitted.events.push([evt, name]);
2789
+ };
2790
+ push('ER_EVENT_RESPONDER_GRANT', 'grant', [
2791
+ ` if (${p}_granted)`,
2792
+ ' {',
2793
+ ' return; /* a second finger re-granted this node: one gesture, not two */',
2794
+ ' }',
2795
+ ` ${p}_granted = 1;`,
2796
+ ` ${p}_base_dx = data->dx;`,
2797
+ ` ${p}_base_dy = data->dy;`,
2798
+ ` ${p}_x0 = data->x;`,
2799
+ ` ${p}_y0 = data->y;`,
2800
+ ...userBody('ER_EVENT_RESPONDER_GRANT'),
2801
+ ]);
2802
+ // Release and terminate both END the gesture: run the app's callback while the anchor is still
2803
+ // valid (it is what g.dx reads through), then clear it for the next one.
2804
+ for (const [evt, suffix] of [
2805
+ ['ER_EVENT_RESPONDER_RELEASE', 'release'],
2806
+ ['ER_EVENT_RESPONDER_TERMINATE', 'terminate'],
2807
+ ])
2808
+ push(evt, suffix, [
2809
+ ...guard,
2810
+ ...userBody(evt),
2811
+ ` ${p}_granted = 0;`,
2812
+ ` ${p}_base_dx = 0;`,
2813
+ ` ${p}_base_dy = 0;`,
2814
+ ]);
2815
+ if (pan.events.has('ER_EVENT_RESPONDER_MOVE'))
2816
+ push('ER_EVENT_RESPONDER_MOVE', 'move', [
2817
+ ...guard,
2818
+ ...userBody('ER_EVENT_RESPONDER_MOVE'),
2819
+ ]);
2820
+ // Reject fires on a node that ASKED for the gesture and was refused — it never owned it, so no guard.
2821
+ if (pan.events.has('ER_EVENT_RESPONDER_REJECT'))
2822
+ push(
2823
+ 'ER_EVENT_RESPONDER_REJECT',
2824
+ 'reject',
2825
+ userBody('ER_EVENT_RESPONDER_REJECT'),
2826
+ );
2827
+
2828
+ for (const [query, fn] of pan.queries) {
2829
+ const name = `${pan.fnPrefix}_${PAN_QUERY_SUFFIX[query]}`;
2830
+ out.queries.push({name, expr: compilePanQuery(fn, penv, pan)});
2831
+ pan.emitted.queries.push([query, name]);
2832
+ }
2833
+ }
2834
+
2835
+ for (const [evt, name] of pan.emitted.events)
2836
+ out.build.push(` er_event_set(${v}, ${evt}, ${name}, NULL);`);
2837
+ for (const [query, name] of pan.emitted.queries)
2838
+ out.build.push(
2839
+ ` er_responder_query_set(${v}, ${query}, ${name}, NULL);`,
2840
+ );
2841
+ }
2842
+
2843
+ /**
2844
+ * Resolves a JSX spread to the PanResponder it spreads, or null when it is some other spread. A name
2845
+ * that IS a responder but is spelled the other way round (`.current` where the app already unwrapped it,
2846
+ * or vice versa) is an error rather than a silent miss — Flow A would throw at runtime on the same code.
2847
+ */
2848
+ function panSpreadTarget(argument, env) {
2849
+ if (
2850
+ argument?.type !== 'MemberExpression' ||
2851
+ argument.computed ||
2852
+ argument.property.name !== 'panHandlers'
2853
+ )
2854
+ return null;
2855
+ const obj = argument.object;
2856
+ const viaCurrent =
2857
+ obj.type === 'MemberExpression' &&
2858
+ !obj.computed &&
2859
+ obj.property.name === 'current' &&
2860
+ obj.object.type === 'Identifier';
2861
+ const rootName = viaCurrent ? obj.object.name : obj.name;
2862
+ const pan =
2863
+ obj.type === 'Identifier' || viaCurrent ? env.pans?.get(rootName) : null;
2864
+ if (!pan) return null;
2865
+ if (pan.viaRefCurrent !== viaCurrent)
2866
+ throw aotError(
2867
+ `AOT: "${rootName}" is a PanResponder, but this spread does not match how it was declared`,
2868
+ pan.viaRefCurrent
2869
+ ? `it was declared as \`useRef(PanResponder.create({…}))\`, so spread \`{...${rootName}.current.panHandlers}\`.`
2870
+ : `it was declared as \`useRef(PanResponder.create({…})).current\`, so spread \`{...${rootName}.panHandlers}\`.`,
2871
+ );
2872
+ return pan;
2873
+ }
2874
+
2453
2875
  // ---------------------------------------------------------------------------------------------------
2454
2876
  // Emit — control flow (components / conditionals / lists) all unroll at COMPILE TIME into fixed nodes.
2455
2877
  // Runtime-dynamic conditionals/lists (where the node COUNT changes with state) are not yet supported
@@ -2464,6 +2886,11 @@ function extractProps(openingElement, scope, env) {
2464
2886
  for (const attr of openingElement.attributes) {
2465
2887
  if (attr.type === 'JSXSpreadAttribute') {
2466
2888
  // Static spread: {...obj} where obj folds to a compile-time object → merge its keys as props.
2889
+ if (panSpreadTarget(attr.argument, env))
2890
+ throw aotError(
2891
+ 'AOT: a PanResponder can only be spread onto a host element',
2892
+ 'spread `{...pan.panHandlers}` onto the <View> (or <Pressable>/<ScrollView>) that should own the gesture, not onto a component instance — the AOT wires the responder to a real scene node.',
2893
+ );
2467
2894
  let obj;
2468
2895
  try {
2469
2896
  obj = evalStatic(attr.argument, scope);
@@ -2614,6 +3041,7 @@ function emitComponent(el, scope, out, env, state, opts) {
2614
3041
  const prefix = `c${out.instN++}_`;
2615
3042
  const childAnims = collectAnims(fn.body, childScope, prefix);
2616
3043
  const childRefs = collectRefs(fn.body, childScope, prefix);
3044
+ const childPans = collectPanResponders(fn.body, prefix);
2617
3045
  const childCallbacks = collectCallbacks(fn.body);
2618
3046
  const childMemos = collectMemos(fn.body);
2619
3047
  let childState = state;
@@ -2633,6 +3061,7 @@ function emitComponent(el, scope, out, env, state, opts) {
2633
3061
  state: childState.byName,
2634
3062
  anims: childAnims,
2635
3063
  refs: childRefs,
3064
+ pans: childPans,
2636
3065
  callbacks: childCallbacks,
2637
3066
  helpers: collectHelpers(fn.body, out.program),
2638
3067
  cbPrefix: prefix,
@@ -2847,6 +3276,32 @@ function emitChildren(children, parentVar, scope, out, env, state) {
2847
3276
  // Flow A uses), giving a flat {ops, paints}. We bake those into C const arrays + er_node_set_vector_ops.
2848
3277
  // ---------------------------------------------------------------------------------------------------
2849
3278
 
3279
+ /**
3280
+ * Yields an <Svg> subtree's shape children in source order, inlining any `<>…</>` in place: a fragment
3281
+ * carries no paint and no transform, so it is transparent to the tape (the Flow A walk in flattenSvg
3282
+ * treats it the same way). Whitespace between elements and JSX comments are skipped; anything else
3283
+ * that has no shape to contribute throws, rather than vanishing from the generated C.
3284
+ */
3285
+ function* svgShapeChildren(children) {
3286
+ for (const c of children) {
3287
+ if (c.type === 'JSXElement') yield c;
3288
+ else if (c.type === 'JSXFragment') yield* svgShapeChildren(c.children);
3289
+ else if (c.type === 'JSXText') {
3290
+ if (c.value.trim())
3291
+ throw new Error(
3292
+ `AOT: <Svg> cannot draw text — remove ${JSON.stringify(c.value.trim())} from the subtree`,
3293
+ );
3294
+ } else if (c.type === 'JSXExpressionContainer') {
3295
+ if (c.expression.type !== 'JSXEmptyExpression')
3296
+ throw new Error(
3297
+ 'AOT: dynamic <Svg> children ({…}) not yet supported — use literal shape elements',
3298
+ );
3299
+ } else {
3300
+ throw new Error(`AOT: unsupported <Svg> child (${c.type})`);
3301
+ }
3302
+ }
3303
+ }
3304
+
2850
3305
  /** Converts an SVG JSX element (Svg/Circle/Path/Rect/Line/Arc/G/…) to flattenSvg's `{type, props}` shape,
2851
3306
  * statically evaluating every attribute. Dynamic attrs/children throw (a state-driven Svg is not supported). */
2852
3307
  function jsxToSvgElement(node, scope) {
@@ -2871,16 +3326,8 @@ function jsxToSvgElement(node, scope) {
2871
3326
  );
2872
3327
  }
2873
3328
  const children = [];
2874
- for (const c of node.children) {
2875
- if (c.type === 'JSXElement') children.push(jsxToSvgElement(c, scope));
2876
- else if (
2877
- c.type === 'JSXExpressionContainer' &&
2878
- c.expression.type !== 'JSXEmptyExpression'
2879
- )
2880
- throw new Error(
2881
- 'AOT: dynamic <Svg> children ({…}) not yet supported — use literal shape elements',
2882
- );
2883
- }
3329
+ for (const c of svgShapeChildren(node.children))
3330
+ children.push(jsxToSvgElement(c, scope));
2884
3331
  if (children.length) props.children = children;
2885
3332
  return {type, props};
2886
3333
  }
@@ -3202,7 +3649,32 @@ const circleEntriesC = (cx, cy, r) => [
3202
3649
  '0.0f',
3203
3650
  'ER_VOP_CLOSE',
3204
3651
  ];
3205
- const rectEntriesC = (x, y, w, h) => [
3652
+ /** The numeric value of a C float literal (as produced by floatLit/cf, or the `(float)(N)` cast the
3653
+ * imperative updateVector path emits), or null for a state-driven expr. */
3654
+ const C_NUM = '-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?';
3655
+ const cLit = e => {
3656
+ const t = String(e).trim();
3657
+ const cast = new RegExp(`^\\(float\\)\\((${C_NUM})\\)$`).exec(t);
3658
+ if (cast) return parseFloat(cast[1]);
3659
+ return new RegExp(`^${C_NUM}f$`).test(t) ? parseFloat(t) : null;
3660
+ };
3661
+
3662
+ /** Normalizes a shape's geometry result. Most shapes are just an op-tape; a rounded <Rect> also returns
3663
+ * the `const float` locals the caller must declare ahead of that tape, in the same C block. */
3664
+ const geometryOf = g => (Array.isArray(g) ? {entries: g, locals: []} : g);
3665
+
3666
+ /** A corner radius clamped to half its side, mirroring svg-ops rectRadii. Folded to a literal when both
3667
+ * the radius and the side are static — the usual case, since only x/y/width tend to be state-driven. */
3668
+ const clampRadiusC = (r, side) => {
3669
+ const lr = cLit(r);
3670
+ if (lr != null && lr <= 0) return '0.0f';
3671
+ const ls = cLit(side);
3672
+ if (lr != null && ls != null)
3673
+ return floatLit(Math.max(0, Math.min(lr, ls / 2)));
3674
+ return `fminf(fmaxf(${r}, 0.0f), (${side}) * 0.5f)`;
3675
+ };
3676
+
3677
+ const sharpRectEntriesC = (x, y, w, h) => [
3206
3678
  'ER_VOP_MOVE',
3207
3679
  x,
3208
3680
  y,
@@ -3217,6 +3689,95 @@ const rectEntriesC = (x, y, w, h) => [
3217
3689
  `(${y} + ${h})`,
3218
3690
  'ER_VOP_CLOSE',
3219
3691
  ];
3692
+
3693
+ // rx/ry are null when the rect has no corner radius at all. Corners are cubics, not ER_VOP_ARC, for the
3694
+ // same reason svg-ops uses them: a corner must start at EXACTLY the preceding line's endpoint. Returns
3695
+ // { entries, locals }; `tag` names the locals and must be unique within the caller's C block.
3696
+ const rectEntriesC = (x, y, w, h, rx = null, ry = null, tag = '') => {
3697
+ // A negative radius is invalid, and invalid means `auto` — so it falls back to the other radius
3698
+ // rather than squaring the corners (svg-ops rectRadii, and what browsers render). Only a literal can
3699
+ // be resolved here; a state-driven radius is assumed non-negative and merely clamped at runtime.
3700
+ const isNeg = e => {
3701
+ const l = cLit(e);
3702
+ return l != null && l < 0;
3703
+ };
3704
+ if (isNeg(rx)) rx = null;
3705
+ if (isNeg(ry)) ry = null;
3706
+ if (rx == null && ry == null)
3707
+ return {entries: sharpRectEntriesC(x, y, w, h), locals: []};
3708
+ let cx = clampRadiusC(rx ?? ry, w);
3709
+ let cy = clampRadiusC(ry ?? rx, h);
3710
+ if (cLit(cx) === 0 || cLit(cy) === 0)
3711
+ return {entries: sharpRectEntriesC(x, y, w, h), locals: []};
3712
+ // A clamp that did not fold is a runtime fminf/fmaxf pair the tape below would otherwise repeat ten
3713
+ // times over — and with a state-driven side, each copy drags the whole side expression with it. Bind
3714
+ // it once instead; a folded radius stays inline, so an all-static rect emits exactly what it used to.
3715
+ const locals = [];
3716
+ if (cLit(cx) == null) {
3717
+ locals.push(`const float rx_${tag} = ${cx};`);
3718
+ cx = `rx_${tag}`;
3719
+ }
3720
+ if (cLit(cy) == null) {
3721
+ locals.push(`const float ry_${tag} = ${cy};`);
3722
+ cy = `ry_${tag}`;
3723
+ }
3724
+ const k = floatLit(KAPPA);
3725
+ const kx = `(${cx} * ${k})`;
3726
+ const ky = `(${cy} * ${k})`;
3727
+ const x1 = `(${x} + ${cx})`;
3728
+ const x2 = `(${x} + ${w} - ${cx})`;
3729
+ const y1 = `(${y} + ${cy})`;
3730
+ const y2 = `(${y} + ${h} - ${cy})`;
3731
+ const r = `(${x} + ${w})`;
3732
+ const b = `(${y} + ${h})`;
3733
+ const entries = [
3734
+ 'ER_VOP_MOVE',
3735
+ x1,
3736
+ y,
3737
+ 'ER_VOP_LINE',
3738
+ x2,
3739
+ y,
3740
+ 'ER_VOP_CUBIC',
3741
+ `(${x2} + ${kx})`,
3742
+ y,
3743
+ r,
3744
+ `(${y1} - ${ky})`,
3745
+ r,
3746
+ y1,
3747
+ 'ER_VOP_LINE',
3748
+ r,
3749
+ y2,
3750
+ 'ER_VOP_CUBIC',
3751
+ r,
3752
+ `(${y2} + ${ky})`,
3753
+ `(${x2} + ${kx})`,
3754
+ b,
3755
+ x2,
3756
+ b,
3757
+ 'ER_VOP_LINE',
3758
+ x1,
3759
+ b,
3760
+ 'ER_VOP_CUBIC',
3761
+ `(${x1} - ${kx})`,
3762
+ b,
3763
+ x,
3764
+ `(${y2} + ${ky})`,
3765
+ x,
3766
+ y2,
3767
+ 'ER_VOP_LINE',
3768
+ x,
3769
+ y1,
3770
+ 'ER_VOP_CUBIC',
3771
+ x,
3772
+ `(${y1} - ${ky})`,
3773
+ `(${x1} - ${kx})`,
3774
+ y,
3775
+ x1,
3776
+ y,
3777
+ 'ER_VOP_CLOSE',
3778
+ ];
3779
+ return {entries, locals};
3780
+ };
3220
3781
  const lineEntriesC = (x1, y1, x2, y2) => [
3221
3782
  'ER_VOP_MOVE',
3222
3783
  x1,
@@ -3230,8 +3791,16 @@ const lineEntriesC = (x1, y1, x2, y2) => [
3230
3791
  const arcEntries = a =>
3231
3792
  arcEntriesC(cf(a.cx), cf(a.cy), cf(a.r), cf(a.startAngle), cf(a.endAngle));
3232
3793
  const circleEntries = a => circleEntriesC(cf(a.cx), cf(a.cy), cf(a.r));
3233
- const rectEntries = a =>
3234
- rectEntriesC(cf(a.x), cf(a.y), cf(a.width), cf(a.height));
3794
+ const rectEntries = (a, tag) =>
3795
+ rectEntriesC(
3796
+ cf(a.x),
3797
+ cf(a.y),
3798
+ cf(a.width),
3799
+ cf(a.height),
3800
+ a.rx == null ? null : cf(a.rx),
3801
+ a.ry == null ? null : cf(a.ry),
3802
+ tag,
3803
+ );
3235
3804
  const lineEntries = a => lineEntriesC(cf(a.x1), cf(a.y1), cf(a.x2), cf(a.y2));
3236
3805
  const pathEntries = a => {
3237
3806
  if (a.d == null) return [];
@@ -3253,6 +3822,11 @@ const SHAPE_ENTRIES = {
3253
3822
  function svgHasDynamic(el, scope) {
3254
3823
  let dyn = false;
3255
3824
  const walk = node => {
3825
+ // A fragment holds no attributes of its own but its shapes' attributes still count.
3826
+ if (node.type === 'JSXFragment') {
3827
+ for (const c of node.children) walk(c);
3828
+ return;
3829
+ }
3256
3830
  if (node.type !== 'JSXElement') return;
3257
3831
  for (const attr of node.openingElement.attributes) {
3258
3832
  if (
@@ -3458,9 +4032,9 @@ function emitSvgDynamic(el, scope, out, env, state) {
3458
4032
  'AOT: a viewBox on a state-driven <Svg> is not yet supported — size shapes in the width/height space',
3459
4033
  );
3460
4034
  const entries = [];
4035
+ const decls = []; // C locals the shapes need declared ahead of the tape (rounded-rect radii)
3461
4036
  const specs = [];
3462
- for (const c of el.children) {
3463
- if (c.type !== 'JSXElement') continue;
4037
+ for (const c of svgShapeChildren(el.children)) {
3464
4038
  const type = c.openingElement.name.name;
3465
4039
  const fn = SHAPE_ENTRIES[type];
3466
4040
  if (!fn)
@@ -3468,9 +4042,11 @@ function emitSvgDynamic(el, scope, out, env, state) {
3468
4042
  `AOT: <${type}> is not a supported shape in a state-driven <Svg> (no <G>/viewBox yet)`,
3469
4043
  );
3470
4044
  const a = svgAttrs(c.openingElement, scope, env);
3471
- const shape = fn(a);
3472
- if (!shape.length) continue;
3473
- entries.push('ER_VOP_SHAPE', floatLit(specs.length), ...shape);
4045
+ // build_svgN() is this <Svg>'s own function, so the shape index alone keeps a local's name unique.
4046
+ const shape = geometryOf(fn(a, `s${specs.length}`));
4047
+ if (!shape.entries.length) continue;
4048
+ decls.push(...shape.locals);
4049
+ entries.push('ER_VOP_SHAPE', floatLit(specs.length), ...shape.entries);
3474
4050
  specs.push(paintSpec(a, env, scope));
3475
4051
  }
3476
4052
  const v = `n${out.n++}`;
@@ -3515,9 +4091,10 @@ function emitSvgDynamic(el, scope, out, env, state) {
3515
4091
  out.vectorData.push(
3516
4092
  `static const ERVectorPaint s_svg${id}_paints[] = {\n${specs.map(p => ' ' + paintInitFromSpec(p)).join(',\n')}\n};`,
3517
4093
  );
3518
- const builderLines = entries.map(
3519
- (e, i) => ` s_svg${id}_ops[${i}] = ${e};`,
3520
- );
4094
+ const builderLines = [
4095
+ ...decls.map(d => ` ${d}`),
4096
+ ...entries.map((e, i) => ` s_svg${id}_ops[${i}] = ${e};`),
4097
+ ];
3521
4098
  if (dynPaint)
3522
4099
  specs.forEach((ps, pi) =>
3523
4100
  ps.fields.forEach((f, fi) =>
@@ -3566,9 +4143,11 @@ function emitRefBind(v, openingElement, out, env) {
3566
4143
  attr.value?.type === 'JSXExpressionContainer'
3567
4144
  ? attr.value.expression
3568
4145
  : null;
3569
- if (e?.type === 'Identifier' && env.refs?.get(e.name)?.kind === 'node')
3570
- out.build.push(` ${env.refs.get(e.name).cVar} = ${v};`);
3571
- else
4146
+ if (e?.type === 'Identifier' && env.refs?.get(e.name)?.kind === 'node') {
4147
+ const r = env.refs.get(e.name);
4148
+ r.used = true;
4149
+ out.build.push(` ${r.cVar} = ${v};`);
4150
+ } else
3572
4151
  throw new Error(
3573
4152
  'AOT: ref={…} must reference a node ref declared with useRef()',
3574
4153
  );
@@ -3583,11 +4162,17 @@ function compileValueHandler(
3583
4162
  state,
3584
4163
  out,
3585
4164
  cType = 'int',
4165
+ valueCode2 = null,
3586
4166
  ) {
3587
4167
  const param =
3588
4168
  fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
3589
4169
  const locals = new Map(env.locals);
3590
4170
  if (param) locals.set(param, {code: valueCode, cType});
4171
+ // A second parameter (a RANGE <Dial>'s low end) binds the same way, so `onChange={(hi, lo) => …}`
4172
+ // lowers to data->value / data->value_start with no object allocated on device.
4173
+ const param2 =
4174
+ fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
4175
+ if (param2 && valueCode2) locals.set(param2, {code: valueCode2, cType});
3591
4176
  const ctx = {stateChanged: false, animIdx: 0, out};
3592
4177
  const body = fnNode.body;
3593
4178
  const list =
@@ -3599,6 +4184,295 @@ function compileValueHandler(
3599
4184
  return stmts;
3600
4185
  }
3601
4186
 
4187
+ /** <Dial> prop → ERProps field tables (see emitDial). */
4188
+ const DIAL_FLOAT_PROPS = {
4189
+ value: 'arc_value',
4190
+ valueStart: 'arc_value_start',
4191
+ minSpan: 'arc_min_span',
4192
+ min: 'arc_min',
4193
+ max: 'arc_max',
4194
+ startAngle: 'arc_start_angle',
4195
+ sweepAngle: 'arc_sweep_angle',
4196
+ step: 'arc_step',
4197
+ gapAngle: 'arc_gap_angle',
4198
+ };
4199
+ const DIAL_INT_PROPS = {
4200
+ thickness: 'arc_width',
4201
+ bandThickness: 'arc_band_width',
4202
+ knobSize: 'arc_knob_size',
4203
+ knobBorderWidth: 'arc_knob_border_width',
4204
+ segments: 'arc_segments',
4205
+ };
4206
+ const DIAL_COLOR_PROPS = {
4207
+ trackColor: 'arc_track_color',
4208
+ indicatorColor: 'arc_indicator_color',
4209
+ bandColor: 'arc_band_color',
4210
+ knobColor: 'arc_knob_color',
4211
+ knobBorderColor: 'arc_knob_border_color',
4212
+ };
4213
+ const DIAL_ENUM_PROPS = {
4214
+ cap: {
4215
+ field: 'arc_cap',
4216
+ table: {butt: 'ER_ARC_CAP_BUTT', round: 'ER_ARC_CAP_ROUND'},
4217
+ },
4218
+ knob: {
4219
+ field: 'arc_knob',
4220
+ table: {
4221
+ none: 'ER_ARC_KNOB_NONE',
4222
+ circle: 'ER_ARC_KNOB_CIRCLE',
4223
+ image: 'ER_ARC_KNOB_IMAGE',
4224
+ child: 'ER_ARC_KNOB_CHILD',
4225
+ },
4226
+ },
4227
+ };
4228
+
4229
+ /**
4230
+ * <Dial value={v} min max startAngle sweepAngle step thickness bandThickness trackColor indicatorColor
4231
+ * indicatorGradient bandColor cap segments gapAngle knob knobSize knobColor knobBorderColor
4232
+ * knobBorderWidth knobImage adjustable onChange={(v) => setV(v)} style=… />
4233
+ * → ER_NODE_ARC, the engine's native arc widget. Numbers and colours are static literals or state-driven
4234
+ * (recomputed in app_update); `value` may also be a useAnimatedValue handle, which binds ER_PROP_ARC_VALUE
4235
+ * natively so a ramp costs no app_update at all. onChange lowers to ER_EVENT_VALUE_CHANGE with its param
4236
+ * bound to data->value (the quantized value the built-in drag produced). Default 120x120 box.
4237
+ */
4238
+ function emitDial(el, scope, out, env, state) {
4239
+ const v = `n${out.n++}`;
4240
+ const {staticAssigns, dynAssigns, binds} = collectStyleAssigns(
4241
+ el.openingElement,
4242
+ scope,
4243
+ env,
4244
+ );
4245
+ const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
4246
+ if (!hasField('width')) staticAssigns.push({field: 'width', expr: '120'});
4247
+ if (!hasField('height')) staticAssigns.push({field: 'height', expr: '120'});
4248
+
4249
+ const SUPPORTED =
4250
+ 'supported props: value, min, max, startAngle, sweepAngle, step, thickness, bandThickness, ' +
4251
+ 'trackColor, indicatorColor, indicatorGradient, bandColor, cap, segments, gapAngle, knob, knobSize, ' +
4252
+ 'minSpan, ' +
4253
+ 'knobColor, knobBorderColor, knobBorderWidth, knobImage, adjustable, range, valueStart, onChange, style.';
4254
+ const numeric = (field, node, isFloat) => {
4255
+ try {
4256
+ const n = evalStatic(node, scope);
4257
+ if (typeof n !== 'number') throw new Error('not a number');
4258
+ staticAssigns.push({
4259
+ field,
4260
+ expr: isFloat ? floatLit(n) : String(Math.round(n)),
4261
+ });
4262
+ } catch {
4263
+ const e = emitExpr(node, env);
4264
+ dynAssigns.push({
4265
+ field,
4266
+ code: isFloat ? `(float)(${e.code})` : `app_round_dim(${e.code})`,
4267
+ });
4268
+ }
4269
+ };
4270
+ const colour = (field, node) => {
4271
+ try {
4272
+ const c = evalStatic(node, scope);
4273
+ if (typeof c !== 'string') throw new Error('not a colour');
4274
+ staticAssigns.push({field, expr: colorLiteral(c)});
4275
+ } catch {
4276
+ dynAssigns.push({field, code: emitColorExpr(node, env)});
4277
+ }
4278
+ };
4279
+
4280
+ let onChangeFn = null;
4281
+ let knobImage = null; // static asset name
4282
+ for (const attr of el.openingElement.attributes) {
4283
+ if (attr.type !== 'JSXAttribute')
4284
+ throw aotError('AOT: spread props on <Dial> are not supported');
4285
+ const name = attr.name.name;
4286
+ if (name === 'style' || name === 'ref' || name === 'key') continue;
4287
+ const node = attrExpr(attr);
4288
+ if (
4289
+ (name === 'value' || name === 'valueStart') &&
4290
+ node?.type === 'Identifier' &&
4291
+ env.anims?.has(node.name)
4292
+ ) {
4293
+ binds.push({
4294
+ cVar: env.anims.get(node.name).cVar,
4295
+ prop:
4296
+ name === 'value' ? 'ER_PROP_ARC_VALUE' : 'ER_PROP_ARC_VALUE_START',
4297
+ });
4298
+ } else if (DIAL_FLOAT_PROPS[name])
4299
+ numeric(DIAL_FLOAT_PROPS[name], node, true);
4300
+ else if (DIAL_INT_PROPS[name]) numeric(DIAL_INT_PROPS[name], node, false);
4301
+ else if (DIAL_COLOR_PROPS[name]) colour(DIAL_COLOR_PROPS[name], node);
4302
+ else if (DIAL_ENUM_PROPS[name]) {
4303
+ const {field, table} = DIAL_ENUM_PROPS[name];
4304
+ let tok = null;
4305
+ try {
4306
+ tok = evalStatic(node, scope);
4307
+ } catch {
4308
+ /* state-driven — handled below */
4309
+ }
4310
+ if (typeof tok === 'string') {
4311
+ if (!table[tok])
4312
+ throw aotError(
4313
+ `AOT: unsupported <Dial ${name}> "${tok}"`,
4314
+ `${name} must be one of: ${Object.keys(table).join(' / ')}.`,
4315
+ );
4316
+ staticAssigns.push({field, expr: table[tok]});
4317
+ } else {
4318
+ dynAssigns.push({
4319
+ field,
4320
+ code: `(uint8_t)(${emitEnumExpr(node, table, env)})`,
4321
+ });
4322
+ }
4323
+ } else if (name === 'adjustable' || name === 'range') {
4324
+ const field = name === 'range' ? 'arc_range' : 'arc_adjustable';
4325
+ try {
4326
+ staticAssigns.push({field, expr: evalStatic(node, scope) ? '1' : '0'});
4327
+ } catch {
4328
+ dynAssigns.push({
4329
+ field,
4330
+ code: `(uint8_t)((${emitExpr(node, env).code}) ? 1 : 0)`,
4331
+ });
4332
+ }
4333
+ } else if (name === 'knobImage') {
4334
+ knobImage = imageNameFromSource(node, env);
4335
+ if (knobImage == null)
4336
+ throw aotError(
4337
+ 'AOT: <Dial knobImage> must resolve to a static asset name',
4338
+ "use an imported image (`import knob from './knob.png'` → knobImage={knob}) or a string asset name.",
4339
+ );
4340
+ const path = env.imageNames?.get(knobImage);
4341
+ if (path) out.images.set(knobImage, path);
4342
+ } else if (name === 'indicatorGradient') {
4343
+ // A gradient is usually applied only in SOME state (a thermostat ramps its band in AUTO and paints
4344
+ // it solid otherwise), so `cond ? {…} : null` is the common shape. The stops themselves are still
4345
+ // constant — only WHETHER they apply varies — so bake them and switch the stop COUNT at runtime:
4346
+ // the engine ignores a gradient with fewer than two stops and falls back to indicatorColor.
4347
+ let gradNode = node;
4348
+ let gradCond = null;
4349
+ if (node?.type === 'ConditionalExpression') {
4350
+ const nullish = n =>
4351
+ n?.type === 'NullLiteral' ||
4352
+ (n?.type === 'Identifier' && n.name === 'undefined');
4353
+ if (nullish(node.alternate)) {
4354
+ gradNode = node.consequent;
4355
+ gradCond = emitExpr(node.test, env).code;
4356
+ } else if (nullish(node.consequent)) {
4357
+ gradNode = node.alternate;
4358
+ gradCond = `!(${emitExpr(node.test, env).code})`;
4359
+ }
4360
+ }
4361
+ const g = evalStaticOrThrow(
4362
+ gradNode,
4363
+ scope,
4364
+ 'AOT: <Dial indicatorGradient> must be a static object (optionally behind a ternary against null)',
4365
+ "indicatorGradient={{ type: 'conic', stops: [{ color: '#00f' }, { color: '#f00' }] }}, or " +
4366
+ 'indicatorGradient={on ? {…} : null}',
4367
+ );
4368
+ const stops = Array.isArray(g?.stops) ? g.stops.slice(0, 4) : [];
4369
+ if (stops.length < 2)
4370
+ throw aotError(
4371
+ 'AOT: <Dial indicatorGradient> needs at least 2 stops (max 4)',
4372
+ );
4373
+ staticAssigns.push({
4374
+ field: 'gradient_type',
4375
+ expr: g.type === 'radial' ? 'ER_GRADIENT_RADIAL' : 'ER_GRADIENT_CONIC',
4376
+ });
4377
+ if (gradCond)
4378
+ dynAssigns.push({
4379
+ field: 'gradient_stop_count',
4380
+ code: `(uint8_t)((${gradCond}) ? ${stops.length} : 0)`,
4381
+ });
4382
+ else
4383
+ staticAssigns.push({
4384
+ field: 'gradient_stop_count',
4385
+ expr: String(stops.length),
4386
+ });
4387
+ stops.forEach((st, i) => {
4388
+ const off =
4389
+ typeof st.offset === 'number' ? st.offset : i / (stops.length - 1);
4390
+ staticAssigns.push({
4391
+ field: `gradient_stops[${i}].color`,
4392
+ expr: colorLiteral(String(st.color)),
4393
+ });
4394
+ staticAssigns.push({
4395
+ field: `gradient_stops[${i}].position`,
4396
+ expr: floatLit(off),
4397
+ });
4398
+ });
4399
+ } else if (name === 'onChange') onChangeFn = node;
4400
+ else
4401
+ throw aotError(`AOT: <Dial> prop "${name}" is not supported`, SUPPORTED);
4402
+ }
4403
+
4404
+ const isDynamic = dynAssigns.length > 0;
4405
+ out.build.push(` ${v} = er_node_create(ER_NODE_ARC);`);
4406
+ if (isDynamic) {
4407
+ out.build.push(` s_${v} = ${v};`);
4408
+ out.handles.push(v);
4409
+ out.updates.push({
4410
+ v,
4411
+ styleAssigns: staticAssigns,
4412
+ text: null,
4413
+ dynAssigns,
4414
+ imageName: knobImage != null ? cstr(knobImage) : null,
4415
+ });
4416
+ } else {
4417
+ out.build.push(` er_props_default(&p);`);
4418
+ for (const a of staticAssigns)
4419
+ out.build.push(` p.${a.field} = ${a.expr};`);
4420
+ if (knobImage != null)
4421
+ out.build.push(
4422
+ ` snprintf(p.image_name, sizeof(p.image_name), "%s", ${cstr(knobImage)});`,
4423
+ );
4424
+ out.build.push(` er_node_set_props(${v}, &p);`);
4425
+ }
4426
+
4427
+ // Animated bindings: style props plus an animated `value` (ER_PROP_ARC_VALUE).
4428
+ binds.forEach((b, i) => {
4429
+ if (b.interp) {
4430
+ const it = b.interp;
4431
+ out.build.push(
4432
+ ` {`,
4433
+ ` static const ERInterpolation interp_${v}_${i} = { { ${it.input.map(floatLit).join(', ')} }, { ${it.output.map(floatLit).join(', ')} }, ${it.input.length}, ${it.exLeft}, ${it.exRight} };`,
4434
+ ` er_anim_value_bind_interpolated(${b.cVar}, ${v}, ${b.prop}, &interp_${v}_${i});`,
4435
+ ` }`,
4436
+ );
4437
+ } else {
4438
+ out.build.push(` er_anim_value_bind(${b.cVar}, ${v}, ${b.prop});`);
4439
+ }
4440
+ });
4441
+
4442
+ if (onChangeFn) {
4443
+ // A useCallback identifier resolves to its arrow, the same way the generic host-node event path does —
4444
+ // a dial's change handler is exactly the kind of thing an app wraps in useCallback.
4445
+ if (onChangeFn.type === 'Identifier' && env.callbacks?.has(onChangeFn.name))
4446
+ onChangeFn = env.callbacks.get(onChangeFn.name);
4447
+ if (!isFn(onChangeFn))
4448
+ throw aotError(
4449
+ 'AOT: <Dial onChange> must be an inline function or a useCallback',
4450
+ 'onChange={(v) => setValue(v)}',
4451
+ );
4452
+ const handlerName = `er_handler_${out.handlers.length}`;
4453
+ out.handlers.push({
4454
+ name: handlerName,
4455
+ body: compileValueHandler(
4456
+ onChangeFn,
4457
+ 'data->value',
4458
+ env,
4459
+ state,
4460
+ out,
4461
+ 'float',
4462
+ 'data->value_start',
4463
+ ),
4464
+ });
4465
+ out.build.push(
4466
+ ` er_event_set(${v}, ER_EVENT_VALUE_CHANGE, ${handlerName}, NULL);`,
4467
+ );
4468
+ }
4469
+ emitRefBind(v, el.openingElement, out, env);
4470
+ // Children lay out inside the dial's box like any View's (a centre readout), and with knob="child" the
4471
+ // engine moves the first one onto the value point.
4472
+ emitChildren(el.children, v, scope, out, env, state);
4473
+ return v;
4474
+ }
4475
+
3602
4476
  /**
3603
4477
  * <Switch value={on} onValueChange={(v) => setOn(v)} trackColor={{false,true}} thumbColor=… style=… />
3604
4478
  * → ER_NODE_SWITCH. The engine flips its own value on press (+ animates the thumb) then fires ER_EVENT_PRESS,
@@ -3612,9 +4486,7 @@ function emitSwitch(el, scope, out, env, state) {
3612
4486
  scope,
3613
4487
  env,
3614
4488
  );
3615
- const hasField = f =>
3616
- staticAssigns.some(a => a.field === f) ||
3617
- dynAssigns.some(a => a.field === f);
4489
+ const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
3618
4490
  if (!hasField('width')) staticAssigns.push({field: 'width', expr: '51'});
3619
4491
  if (!hasField('height')) staticAssigns.push({field: 'height', expr: '31'});
3620
4492
 
@@ -3862,9 +4734,7 @@ function emitActivityIndicator(el, scope, out, env) {
3862
4734
  scope,
3863
4735
  env,
3864
4736
  );
3865
- const hasField = f =>
3866
- staticAssigns.some(a => a.field === f) ||
3867
- dynAssigns.some(a => a.field === f);
4737
+ const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
3868
4738
  let size = 36;
3869
4739
  for (const attr of el.openingElement.attributes) {
3870
4740
  if (attr.type !== 'JSXAttribute')
@@ -3941,9 +4811,7 @@ function emitModal(el, scope, out, env, state) {
3941
4811
  scope,
3942
4812
  env,
3943
4813
  );
3944
- const hasField = f =>
3945
- staticAssigns.some(a => a.field === f) ||
3946
- dynAssigns.some(a => a.field === f);
4814
+ const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
3947
4815
  // Overlay defaults: absolute, fill the parent via four 0 insets (the robust "stretch" for an absolute
3948
4816
  // node), centre the content. The user's style overrides any of these.
3949
4817
  const DEFAULTS = [
@@ -4214,14 +5082,149 @@ function resolveImageAttrs(el, env, out) {
4214
5082
  // ---------------------------------------------------------------------------------------------------
4215
5083
  // Node emitter — the element dispatcher + the generic host node. emitNodeImpl is the entry point for
4216
5084
  // every JSX element: it routes Svg / typed components / FlatList / components to their emitters above,
4217
- // and handles the generic host nodes (View / Text / Pressable / Image / ScrollView) itself — style,
5085
+ // and handles the generic host nodes (View / Text / Pressable / TouchableOpacity / Image / ScrollView)
5086
+ // itself — style,
4218
5087
  // text, events, refs, children. emitNode wraps it with withLoc so a thrown AOT error gets a location.
4219
5088
  // ---------------------------------------------------------------------------------------------------
4220
5089
 
5090
+ // The JS-only RN wrappers the package exports that this compiler cannot lower yet. Each is a fixed
5091
+ // rewrite over primitives the AOT DOES understand, so the fix is always to write that tree out — the
5092
+ // message says which one, because a stock "unknown element" here is actively misleading (the import
5093
+ // resolved, the simulator renders it, and the name is spelled right).
5094
+ const FLOW_A_ONLY_COMPONENTS = {
5095
+ Button:
5096
+ '<Pressable style={…} onPress={…}><Text style={…}>title</Text></Pressable>.',
5097
+ ImageBackground:
5098
+ "<View style={…}><Image source={…} style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0}} />…children…</View>.",
5099
+ SectionList:
5100
+ '<ScrollView> with the header element and a data.map(…) per section (a section is not one .map, which is why it has no lowering).',
5101
+ };
5102
+
5103
+ // <TouchableOpacity> is a Pressable node plus one synthetic animated value bound to its opacity:
5104
+ // press-in snaps it to activeOpacity, press-out fades it back to whatever the style asks for. Flow A
5105
+ // builds the same thing out of hooks (TouchableOpacity.js); lowering it here means the feedback runs on
5106
+ // the engine's native driver with no JS on the device at all.
5107
+ const TOUCHABLE_ACTIVE_OPACITY = 0.2; // RN's default
5108
+ const TOUCHABLE_RESTORE_MS = 250; // RN's fade-back; the dim itself lands with no ramp
5109
+
5110
+ /** The press events a <TouchableOpacity disabled> drops — RN presses none of them, and dims for none. */
5111
+ const PRESS_EVENTS = new Set([
5112
+ 'onPress',
5113
+ 'onLongPress',
5114
+ 'onPressIn',
5115
+ 'onPressOut',
5116
+ ]);
5117
+
5118
+ /** A JSX element's named attribute, or undefined. */
5119
+ function namedAttr(openingElement, name) {
5120
+ return openingElement.attributes.find(
5121
+ a => a.type === 'JSXAttribute' && a.name && a.name.name === name,
5122
+ );
5123
+ }
5124
+
5125
+ /** True for `<TouchableOpacity disabled>` / `disabled={SOME_CONST}`. Must fold: `disabled` decides what
5126
+ * the build EMITS — the press handlers and the dim binding — so there is nothing left to decide at runtime. */
5127
+ function touchableIsDisabled(el, scope) {
5128
+ const attr = namedAttr(el.openingElement, 'disabled');
5129
+ if (!attr) return false;
5130
+ return !!evalStaticOrThrow(
5131
+ attrExpr(attr),
5132
+ scope,
5133
+ 'AOT: <TouchableOpacity disabled> must be a compile-time constant',
5134
+ 'a disabled one still renders — it lowers to a plain <Pressable>, children, layout and style intact — but its press handlers and its dim are not emitted at all, so the AOT has to know at build time. To gate on state, leave it enabled and return early in the handler (`onPress={() => { if (!ready) return; … }}`).',
5135
+ );
5136
+ }
5137
+
5138
+ /** A folded `activeOpacity` as a number in 0..1. Everything else is an error HERE, where the source line
5139
+ * is still in reach: it would otherwise reach floatLit and land in the generated C as a literal that
5140
+ * either does not compile (`NaNf`) or quietly means something the app never asked for — a bare
5141
+ * `activeOpacity` is `true`, so `1.0f`, which is no dim at all; `{false}` is an invisible one. */
5142
+ function opacityLiteralOrThrow(value, attr) {
5143
+ if (
5144
+ typeof value !== 'number' ||
5145
+ !Number.isFinite(value) ||
5146
+ value < 0 ||
5147
+ value > 1
5148
+ ) {
5149
+ // JSON.stringify turns NaN into the STRING "null", which reads as a different mistake entirely.
5150
+ const shown =
5151
+ typeof value === 'number'
5152
+ ? String(value)
5153
+ : (JSON.stringify(value) ?? String(value));
5154
+ const e = aotError(
5155
+ `AOT: <TouchableOpacity activeOpacity> must be a number between 0 and 1 (got ${shown})`,
5156
+ 'it is the opacity the node dims to while held — 0 is invisible, 1 is no dim at all. RN defaults it to 0.2.',
5157
+ );
5158
+ if (attr.loc) e.aotLoc = attr.loc.start;
5159
+ throw e;
5160
+ }
5161
+ return value;
5162
+ }
5163
+
5164
+ /**
5165
+ * Creates a <TouchableOpacity>'s animated value and binds it to the node's opacity. Returns the two
5166
+ * fades as handler-body lines, for the event loop to fold into its press handlers.
5167
+ */
5168
+ function touchablePressFades(
5169
+ el,
5170
+ v,
5171
+ staticAssigns,
5172
+ dynAssigns,
5173
+ binds,
5174
+ out,
5175
+ scope,
5176
+ ) {
5177
+ const animatedOpacity = binds.some(b => b.prop === 'ER_PROP_OPACITY');
5178
+ if (animatedOpacity || dynAssigns.some(a => a.field === 'opacity'))
5179
+ throw aotError(
5180
+ `AOT: <TouchableOpacity> cannot take ${animatedOpacity ? 'an Animated' : 'a state-driven'} opacity`,
5181
+ "the press feedback owns this node's opacity — a second writer does not blend with it, it races it. To animate opacity yourself, use <Pressable>: the dim is just onPressIn/onPressOut driving an Animated.Value (see TouchableOpacity.js for the whole of it).",
5182
+ );
5183
+ // lowerStyle has already scaled a static opacity to 0–255, and that byte IS the resting value. It is
5184
+ // NaN for a style opacity that was not a number — which lowerStyle emits as a `p.opacity = NaN` the C
5185
+ // compiler rejects on its own, so leave that error to it rather than adding a second bad literal here.
5186
+ const restingByte = staticAssigns.find(a => a.field === 'opacity');
5187
+ const restingRaw = restingByte ? Number(restingByte.expr) / 255 : 1;
5188
+ const resting = Number.isFinite(restingRaw) ? restingRaw : 1;
5189
+
5190
+ const activeAttr = namedAttr(el.openingElement, 'activeOpacity');
5191
+ const active = activeAttr
5192
+ ? opacityLiteralOrThrow(
5193
+ evalStaticOrThrow(
5194
+ attrExpr(activeAttr),
5195
+ scope,
5196
+ 'AOT: <TouchableOpacity activeOpacity> must be a compile-time constant',
5197
+ 'the dim target is baked into the generated handler, so it cannot come from state.',
5198
+ ),
5199
+ activeAttr,
5200
+ )
5201
+ : TOUCHABLE_ACTIVE_OPACITY;
5202
+
5203
+ const cVar = `s_av_press_${v}`;
5204
+ out.childAnims.push({cVar, initCode: floatLit(resting)});
5205
+ out.build.push(` er_anim_value_bind(${cVar}, ${v}, ER_PROP_OPACITY);`);
5206
+
5207
+ const fade = (to, ms) => [
5208
+ ' {',
5209
+ ' ERAnimConfig cfg;',
5210
+ ' memset(&cfg, 0, sizeof(cfg));',
5211
+ ' cfg.type = ER_ANIM_TIMING;',
5212
+ ` cfg.duration_ms = ${ms};`,
5213
+ ' cfg.easing = ER_EASE_QUAD_IN_OUT;',
5214
+ ` er_anim_value_animate(${cVar}, ${floatLit(to)}, &cfg);`,
5215
+ ' }',
5216
+ ];
5217
+ return {
5218
+ onPressIn: fade(active, 0),
5219
+ onPressOut: fade(resting, TOUCHABLE_RESTORE_MS),
5220
+ };
5221
+ }
5222
+
4221
5223
  function emitNodeImpl(el, scope, out, env, state, opts = {}) {
4222
5224
  const tag = resolveTag(el.openingElement);
4223
5225
  if (tag === 'Svg') return emitSvg(el, scope, out, env, state, opts);
4224
5226
  if (tag === 'Switch') return emitSwitch(el, scope, out, env, state);
5227
+ if (tag === 'Dial') return emitDial(el, scope, out, env, state);
4225
5228
  if (tag === 'TextInput') return emitTextInput(el, scope, out, env, state);
4226
5229
  if (tag === 'ActivityIndicator')
4227
5230
  return emitActivityIndicator(el, scope, out, env);
@@ -4231,23 +5234,49 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
4231
5234
  if (!nodeType) {
4232
5235
  if (out.components.has(tag))
4233
5236
  return emitComponent(el, scope, out, env, state, opts);
5237
+ // Exported by the package and rendering fine in the simulator, but with no lowering here yet — so
5238
+ // say that, instead of "unknown element", which reads like a typo and sends people hunting for one.
5239
+ const flowAOnly = FLOW_A_ONLY_COMPONENTS[tag];
5240
+ if (flowAOnly)
5241
+ throw aotError(
5242
+ `AOT: <${tag}> is not supported in Flow B yet`,
5243
+ `it renders in Flow A (the simulator and the QuickJS runtime) but the AOT has no lowering for it. Write it out by hand for the device build: ${flowAOnly}`,
5244
+ );
4234
5245
  throw aotError(
4235
5246
  `AOT: unknown element <${tag}> (not a built-in or a component in this file)`,
4236
- `<${tag}> must be a built-in (View / Text / Pressable / Image / ScrollView / Svg + shapes / Animated.*) or a function component defined in THIS file. Check the import/spelling, or define the component here.`,
5247
+ `<${tag}> must be a built-in (View / Text / Pressable / TouchableOpacity / Image / ScrollView / Svg + shapes / Animated.*) or a function component defined in THIS file. Check the import/spelling, or define the component here.`,
4237
5248
  );
4238
5249
  }
4239
5250
 
5251
+ // A <TouchableOpacity disabled> lowers to a plain Pressable node — children, layout and style all
5252
+ // intact — with no press handlers and no animated value to dim it with. That is RN's `disabled`, and
5253
+ // it is the whole of it here: the engine has no such node flag, so a node left holding onPress would
5254
+ // still fire, and one left holding the binding would still dim.
5255
+ const touchableOff =
5256
+ tag === 'TouchableOpacity' && touchableIsDisabled(el, scope);
5257
+
4240
5258
  // Spread attributes on a host element (`<View {...props} />`) aren't lowered — the style/event loops
4241
- // below only read named JSXAttributes, so a spread would be SILENTLY dropped. Reject it explicitly
4242
- // (the typed components — Switch/TextInput/Modal/… — already throw on spreads). Pin the location to the
4243
- // spread itself, not the whole element, for a precise code-frame.
4244
- const spread = el.openingElement.attributes.find(
4245
- a => a.type === 'JSXSpreadAttribute',
4246
- );
4247
- if (spread) {
5259
+ // below only read named JSXAttributes, so a spread would be SILENTLY dropped. The one exception is
5260
+ // `{...pan.panHandlers}`, which the AOT understands as a whole (see emitPanResponder); everything else
5261
+ // is rejected explicitly (the typed components — Switch/TextInput/Modal/… — already throw on spreads).
5262
+ // Pin the location to the spread itself, not the whole element, for a precise code-frame.
5263
+ const panSpreads = [];
5264
+ for (const spread of el.openingElement.attributes) {
5265
+ if (spread.type !== 'JSXSpreadAttribute') continue;
5266
+ let pan;
5267
+ try {
5268
+ pan = panSpreadTarget(spread.argument, env);
5269
+ } catch (e) {
5270
+ if (spread.loc && !e.aotLoc) e.aotLoc = spread.loc.start;
5271
+ throw e;
5272
+ }
5273
+ if (pan) {
5274
+ panSpreads.push(pan);
5275
+ continue;
5276
+ }
4248
5277
  const e = aotError(
4249
5278
  `AOT: a spread {...} on <${tag}> is not supported`,
4250
- `list each prop explicitly (e.g. style={…} onPress={…}). Spread props are only supported on a function component instance whose spread object folds to a compile-time constant.`,
5279
+ `list each prop explicitly (e.g. style={…} onPress={…}). The only spread a host element understands is a PanResponder's ({...pan.panHandlers}); otherwise spread props are supported on a function component instance whose spread object folds to a compile-time constant.`,
4251
5280
  );
4252
5281
  if (spread.loc) e.aotLoc = spread.loc.start;
4253
5282
  throw e;
@@ -4305,6 +5334,29 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
4305
5334
  }
4306
5335
  }
4307
5336
 
5337
+ // `delayLongPress` is the hold time before onLongPress fires (RN's prop, same 500 ms default). It has
5338
+ // to fold: the value is baked into the node's props at build time. 0 is the engine's "no preference"
5339
+ // sentinel, so an app asking for 0 gets 1 ms — the next tick, which is what RN's setTimeout(0) means.
5340
+ const delayAttr = namedAttr(el.openingElement, 'delayLongPress');
5341
+ if (delayAttr) {
5342
+ const bad = aotError(
5343
+ `AOT: <${tag} delayLongPress> must fold to a number`,
5344
+ 'pass a literal or a module-level constant in milliseconds, e.g. delayLongPress={800}.',
5345
+ );
5346
+ if (delayAttr.value == null) throw bad;
5347
+ let ms;
5348
+ try {
5349
+ ms = Number(evalStatic(attrExpr(delayAttr), scope));
5350
+ } catch {
5351
+ throw bad;
5352
+ }
5353
+ if (!Number.isFinite(ms)) throw bad;
5354
+ staticAssigns.push({
5355
+ field: 'long_press_ms',
5356
+ expr: String(Math.min(65535, Math.max(1, Math.round(ms)))),
5357
+ });
5358
+ }
5359
+
4308
5360
  // `displayCode` toggles show/hide for a state-driven conditional: the node is always built, its
4309
5361
  // `display` flips between flex and none in app_update (joining any state-driven style assigns).
4310
5362
  // Pushed last so an enclosing conditional beats the element's own visible/display — app_update
@@ -4378,12 +5430,20 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
4378
5430
  }
4379
5431
  });
4380
5432
 
5433
+ // <TouchableOpacity>'s own opacity binding, on top of any the style asked for.
5434
+ const pressFades =
5435
+ tag === 'TouchableOpacity' && !touchableOff
5436
+ ? touchablePressFades(el, v, staticAssigns, dynAssigns, binds, out, scope)
5437
+ : null;
5438
+
4381
5439
  emitRefBind(v, el.openingElement, out, env);
4382
5440
 
5441
+ const fadesWired = new Set();
4383
5442
  for (const attr of el.openingElement.attributes) {
4384
5443
  if (attr.type !== 'JSXAttribute') continue;
4385
5444
  const evt = EVENT_TYPES[attr.name.name];
4386
5445
  if (!evt) continue;
5446
+ if (touchableOff && PRESS_EVENTS.has(attr.name.name)) continue;
4387
5447
  const fn = attrExpr(attr);
4388
5448
  let handlerName;
4389
5449
  if (fn.type === 'Identifier' && env.callbacks?.has(fn.name)) {
@@ -4421,9 +5481,35 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
4421
5481
  `pass an inline arrow (onPress={() => setX(…)}), a useCallback identifier, or a function prop received by this component.`,
4422
5482
  );
4423
5483
  }
5484
+ // The app's own press-in/out on a <TouchableOpacity>: wrap it rather than prepend the fade to its
5485
+ // body, which for a shared useCallback handler would dim every OTHER element using it too.
5486
+ const fade = pressFades?.[attr.name.name];
5487
+ if (fade) {
5488
+ const wrapped = `er_handler_${out.handlers.length}`;
5489
+ out.handlers.push({
5490
+ name: wrapped,
5491
+ body: [...fade, ` ${handlerName}(node, data, user_data);`],
5492
+ });
5493
+ handlerName = wrapped;
5494
+ fadesWired.add(attr.name.name);
5495
+ }
4424
5496
  out.build.push(` er_event_set(${v}, ${evt}, ${handlerName}, NULL);`);
4425
5497
  }
4426
5498
 
5499
+ // Whichever end of the press the app did not handle itself is the fade on its own.
5500
+ if (pressFades) {
5501
+ for (const key of ['onPressIn', 'onPressOut']) {
5502
+ if (fadesWired.has(key)) continue;
5503
+ const name = `er_handler_${out.handlers.length}`;
5504
+ out.handlers.push({name, body: pressFades[key]});
5505
+ out.build.push(
5506
+ ` er_event_set(${v}, ${EVENT_TYPES[key]}, ${name}, NULL);`,
5507
+ );
5508
+ }
5509
+ }
5510
+
5511
+ for (const pan of panSpreads) emitPanResponder(pan, v, out, env, state);
5512
+
4427
5513
  if (tag !== 'Text') emitChildren(el.children, v, scope, out, env, state);
4428
5514
  return v;
4429
5515
  }
@@ -4703,6 +5789,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4703
5789
 
4704
5790
  const anims = collectAnims(component.body, scope);
4705
5791
  const refs = collectRefs(component.body, scope);
5792
+ const pans = collectPanResponders(component.body);
4706
5793
  const callbacks = collectCallbacks(component.body);
4707
5794
  const memos = collectMemos(component.body);
4708
5795
  const helpers = collectHelpers(component.body, ast.program);
@@ -4715,6 +5802,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4715
5802
  consts: scope,
4716
5803
  anims,
4717
5804
  refs,
5805
+ pans,
4718
5806
  callbacks,
4719
5807
  helpers,
4720
5808
  imageNames,
@@ -4763,6 +5851,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4763
5851
  effectFns: [],
4764
5852
  effectDecls: [],
4765
5853
  depEffects: [],
5854
+ panN: 0,
5855
+ panDecls: [],
5856
+ queries: [],
4766
5857
  };
4767
5858
  compileKeyboardConfig(ast.program, out); // module-level setKeyboardConfig({...}) → static ERKeyboardConfig
4768
5859
  const appTop = emitNode(rootJSX, scope, out, env, state);
@@ -4813,7 +5904,10 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4813
5904
  const handleDecls = out.handles.map(v => `static ERNode* s_${v};`).join('\n');
4814
5905
 
4815
5906
  // Value refs — a plain mutable static each (escape-hatch state that does not trigger a re-render).
5907
+ // Refs the emitted C never touches (e.g. a `useRef(null)` that only holds a JS value) declare nothing,
5908
+ // so consumer builds don't warn about an unused static.
4816
5909
  const refDecls = [...refs.values(), ...out.childRefs]
5910
+ .filter(r => r.used)
4817
5911
  .map(r => `static ${r.cType} ${r.cVar} = ${r.initCode};`)
4818
5912
  .join('\n');
4819
5913
 
@@ -4877,6 +5971,16 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4877
5971
  return lines.join('\n');
4878
5972
  })();
4879
5973
 
5974
+ // PanResponder gesture state (one small block per responder) + the should-set predicates, which are
5975
+ // bool-returning callbacks the engine calls during negotiation rather than ordinary event handlers.
5976
+ const panDeclBlock = out.panDecls.join('\n');
5977
+ const queryDefs = out.queries
5978
+ .map(
5979
+ q =>
5980
+ `static bool ${q.name}(ERNode* node, const EREventData* data, void* user_data)\n{\n (void)node;\n (void)data;\n (void)user_data;\n return ${q.expr};\n}`,
5981
+ )
5982
+ .join('\n\n');
5983
+
4880
5984
  const handlerDefs = out.handlers
4881
5985
  .map(
4882
5986
  h =>
@@ -5002,6 +6106,47 @@ static void er_timer_clear(int id)
5002
6106
  '\n'
5003
6107
  : '';
5004
6108
 
6109
+ // app_round_dim() when a state-driven style value has to be snapped to a whole pixel at runtime.
6110
+ const usesDimRound = /\bapp_round_dim\(/.test(
6111
+ [
6112
+ updateBlock,
6113
+ handlerDefs,
6114
+ queryDefs,
6115
+ effectFnDefs,
6116
+ animCbDefs,
6117
+ timerFnDefs,
6118
+ out.mountEffects.join('\n'),
6119
+ out.build.join('\n'),
6120
+ ].join('\n'),
6121
+ );
6122
+ const dimRoundBlock = usesDimRound
6123
+ ? `
6124
+ /* Snaps a state-driven style value to a whole pixel the way JavaScript's Math.round does — floor(x + 0.5),
6125
+ halves UP rather than away from zero. ERProps dimensions are int16 and a plain cast would truncate toward
6126
+ zero, which is how the two flows once laid the same app out a pixel apart. Values known at compile time
6127
+ are folded with Math.round; this is that rule's runtime twin, and Flow A's bridge applies the same one. */
6128
+ static int16_t app_round_dim(double v)
6129
+ {
6130
+ /* NaN compares false against everything, so it would slip past both clamps into an undefined cast. */
6131
+ if (v != v)
6132
+ {
6133
+ return 0;
6134
+ }
6135
+ if (v < -32768.0)
6136
+ {
6137
+ return -32768;
6138
+ }
6139
+ if (v > 32767.0)
6140
+ {
6141
+ return 32767;
6142
+ }
6143
+ const double r = v + 0.5;
6144
+ const int32_t t = (int32_t)r; /* truncates toward zero */
6145
+ return (int16_t)(((double)t > r) ? t - 1 : t);
6146
+ }
6147
+ `
6148
+ : '';
6149
+
5005
6150
  // <math.h> when any libm symbol appears (Svg arc trig, or Math.* in expressions/handlers/timer callbacks).
5006
6151
  const usesMath =
5007
6152
  out.needsMath ||
@@ -5012,6 +6157,7 @@ static void er_timer_clear(int id)
5012
6157
  vectorBuilderBlock,
5013
6158
  updateBlock,
5014
6159
  handlerDefs,
6160
+ queryDefs,
5015
6161
  animCbDefs,
5016
6162
  timerFnDefs,
5017
6163
  out.mountEffects.join('\n'),
@@ -5052,7 +6198,7 @@ static void er_timer_clear(int id)
5052
6198
  A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
5053
6199
  _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
5054
6200
  "embedded-react version mismatch: app.gen.c was generated by ${PKG_VERSION} but the engine header (er_version.h) is a different major.minor. Regenerate the app with 'npm run aot', or align the engine and npm versions.");
5055
- ${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
6201
+ ${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${dimRoundBlock}${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${panDeclBlock ? '\n' + panDeclBlock + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${queryDefs ? '\n' + queryDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
5056
6202
  ${appTickFn}
5057
6203
  ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
5058
6204
  void er_app_build(int screen_w, int screen_h)
@@ -5170,6 +6316,10 @@ if (
5170
6316
  process.exit(1);
5171
6317
  }
5172
6318
  }
6319
+ // Flow B has no font imports — every string renders in the engine's built-in font, so check the
6320
+ // app's text and its font sizes against that coverage.
6321
+ warnMissingGlyphs({source: src, jsx: true});
6322
+ warnFontSizes({used: analyzeFontSizes(src)});
5173
6323
  const baked = bakeAssets({images: imageJobs, fonts: [], outDir: distDir});
5174
6324
  console.log(
5175
6325
  `AOT: compiled demo "${demo}" -> dist/app.gen.c (${result.nodes} nodes, ${result.state} state, ` +