embedded-react 0.9.0 → 0.10.1

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
@@ -32,7 +32,7 @@
32
32
  // nodes (er_node_set_props) — no diffing, no reconciler. See the root README (Flow B).
33
33
  //
34
34
  // npm run aot # default demo (thermostat) — but use a minimal demo for the slice
35
- // npm run aot -- music-player # a specific demo by folder name
35
+ // npm run aot -- watch-face # a specific demo by folder name
36
36
  import {parse} from '@babel/parser';
37
37
  import {codeFrameColumns} from '@babel/code-frame';
38
38
  import {
@@ -55,6 +55,7 @@ import {
55
55
  parseColor,
56
56
  parsePath,
57
57
  PAINT_STRIDE,
58
+ GRAD_MAX_STOPS,
58
59
  scaleVectorArtifact,
59
60
  } from '../src/embedded-react/svg-ops.js';
60
61
  import {bakeAssets} from '../assets/index.mjs';
@@ -327,6 +328,11 @@ function emitExprImpl(node, env) {
327
328
  const l = emitExpr(node.left, env);
328
329
  const r = emitExpr(node.right, env);
329
330
  if (ARITH.has(node.operator)) {
331
+ if (node.operator === '/')
332
+ return {
333
+ code: `((float)(${l.code}) / (float)(${r.code}))`,
334
+ cType: 'float',
335
+ };
330
336
  const cType =
331
337
  l.cType === 'float' || r.cType === 'float' ? 'float' : 'int';
332
338
  return {code: `(${l.code} ${node.operator} ${r.code})`, cType};
@@ -617,20 +623,25 @@ function collectState(fnBody, scope, prefix = '') {
617
623
  if (stmt.type !== 'VariableDeclaration') continue;
618
624
  for (const decl of stmt.declarations) {
619
625
  const init = decl.init;
626
+ if (init?.type !== 'CallExpression') continue;
627
+ // `useHostValue(initial)` — a scalar the HOST feeds at runtime (e.g. a step count from an IMU).
628
+ // It lowers to an ordinary s_state field (so reads/dep-tracking work exactly like useState), plus a
629
+ // generated public setter `er_app_set_<name>()` (see the host-setter emission). Written `const x =
630
+ // useHostValue(0)` — no JS setter, the C host is the only writer.
631
+ const isHost = init.callee.name === 'useHostValue';
632
+ if (init.callee.name !== 'useState' && !isHost) continue;
620
633
  if (
621
- init?.type !== 'CallExpression' ||
622
- init.callee.name !== 'useState' ||
623
- decl.id.type !== 'ArrayPattern'
634
+ isHost ? decl.id.type !== 'Identifier' : decl.id.type !== 'ArrayPattern'
624
635
  )
625
636
  continue;
626
- const name = decl.id.elements[0]?.name;
627
- const setter = decl.id.elements[1]?.name;
637
+ const name = isHost ? decl.id.name : decl.id.elements[0]?.name;
638
+ const setter = isHost ? undefined : decl.id.elements[1]?.name;
628
639
  if (!name) continue;
629
640
  const cField = prefix + name; // C storage name (== name for the App; instance-unique for a child)
630
641
  const initArg = init.arguments[0];
631
642
 
632
643
  let rec;
633
- if (initArg?.type === 'ArrayExpression') {
644
+ if (!isHost && initArg?.type === 'ArrayExpression') {
634
645
  // List state → a fixed-capacity C struct array + a count (s_<name>[CAP], s_<name>_count).
635
646
  const items = evalStaticOrThrow(
636
647
  initArg,
@@ -666,6 +677,14 @@ function collectState(fnBody, scope, prefix = '') {
666
677
  'useState(x) initial must be a literal or a constant expression (number, string, bool, or arithmetic over consts) — not a runtime value or function call.',
667
678
  )
668
679
  : 0;
680
+ // Host values (useHostValue) are numeric only — the public API is useHostValue(initial: number).
681
+ // cTypeOfValue funnels booleans/null/objects to 'int', so validate the evaluated value itself
682
+ // (Number.isFinite also rejects NaN/Infinity, and does not coerce booleans/strings).
683
+ if (isHost && !Number.isFinite(initVal))
684
+ throw aotError(
685
+ `AOT: useHostValue("${name}") must be a number — its initial value evaluated to ${JSON.stringify(initVal)}`,
686
+ 'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, strings, and objects are not supported.',
687
+ );
669
688
  let cType = cTypeOfValue(initVal);
670
689
  // A numeric literal written with a decimal point or exponent (e.g. useState(70.0)) forces a FLOAT
671
690
  // slot even though the value is integral — lets the state hold sub-integer values (a smooth drag)
@@ -693,6 +712,7 @@ function collectState(fnBody, scope, prefix = '') {
693
712
  cType,
694
713
  cMember: `s_state.${cField}`,
695
714
  initCode,
715
+ host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
696
716
  };
697
717
  }
698
718
  byName.set(name, rec);
@@ -886,8 +906,9 @@ export async function bakeSvgArtifacts(src, baseDir) {
886
906
  }).program;
887
907
  const imports = collectSvgImports(program);
888
908
  if (imports.size === 0) return {};
889
- const {svgToVector, svgToRaster, writeRasterPng} =
890
- await import('../assets/bake-svg.mjs');
909
+ const {svgToVector, svgToRaster, writeRasterPng} = await import(
910
+ '../assets/bake-svg.mjs'
911
+ );
891
912
  const artifacts = {};
892
913
  for (const [, imp] of imports) {
893
914
  const p = resolve(baseDir, imp.importPath);
@@ -2909,6 +2930,12 @@ function svgAttrs(openingElement, scope, env) {
2909
2930
  const name = attr.name.name;
2910
2931
  if (name === 'ref' || name === 'key') continue; // not geometry/paint
2911
2932
  const vn = attr.value;
2933
+ if (name === 'fillGrad' || name === 'strokeGrad') {
2934
+ if (vn == null || vn.type !== 'JSXExpressionContainer')
2935
+ throw new Error(`AOT: "${name}" must be an object expression`);
2936
+ out[name] = {gradNode: vn.expression};
2937
+ continue;
2938
+ }
2912
2939
  if (vn == null) out[name] = true;
2913
2940
  else if (vn.type === 'StringLiteral') out[name] = vn.value;
2914
2941
  else if (vn.type === 'JSXExpressionContainer') {
@@ -2928,6 +2955,154 @@ function svgAttrs(openingElement, scope, env) {
2928
2955
  return out;
2929
2956
  }
2930
2957
 
2958
+ /**
2959
+ * Lowers a `{ type, ax, ay, bx, by, r, stops: [{ color, offset }] }` gradient descriptor — the SAME shape
2960
+ * Flow A's svg-ops.js takes — to C-expression fields. Every geometry field and every stop may be static
2961
+ * or state-driven; `type` and the stop COUNT must be static, since they decide the emitted table's shape.
2962
+ *
2963
+ * Conic gradients carry the sweep's start angle in `r` (radians, clockwise from the top), so a dial whose
2964
+ * ramp must follow a setpoint drives `r` from state — which is exactly why the table can't be const.
2965
+ */
2966
+ function gradSpec(node, scope, env, what) {
2967
+ if (!node || node.type !== 'ObjectExpression')
2968
+ throw new Error(`AOT: "${what}" must be an object literal`);
2969
+ const props = {};
2970
+ for (const pr of node.properties) {
2971
+ if (pr.type !== 'ObjectProperty' || pr.computed)
2972
+ throw new Error(`AOT: "${what}" takes plain key: value pairs only`);
2973
+ props[pr.key.name ?? pr.key.value] = pr.value;
2974
+ }
2975
+ let anyDynamic = false;
2976
+ // A numeric field: fold when it can be, otherwise emit the state-driven expression.
2977
+ const numf = (v, dflt) => {
2978
+ if (v == null) return floatLit(dflt);
2979
+ try {
2980
+ return floatLit(evalStatic(v, scope));
2981
+ } catch {
2982
+ anyDynamic = true;
2983
+ return `(float)(${emitExpr(v, env).code})`;
2984
+ }
2985
+ };
2986
+ let type;
2987
+ try {
2988
+ type = evalStatic(props.type, scope) | 0;
2989
+ } catch {
2990
+ throw new Error(
2991
+ `AOT: "${what}.type" must be a compile-time constant (1 linear, 2 radial, 3 conic)`,
2992
+ );
2993
+ }
2994
+ if (type < 1 || type > 3)
2995
+ throw new Error(
2996
+ `AOT: "${what}.type" must be 1 (linear), 2 (radial) or 3 (conic)`,
2997
+ );
2998
+ const stopsNode = props.stops;
2999
+ if (!stopsNode || stopsNode.type !== 'ArrayExpression')
3000
+ throw new Error(`AOT: "${what}.stops" must be an array literal`);
3001
+ if (
3002
+ stopsNode.elements.length < 2 ||
3003
+ stopsNode.elements.length > GRAD_MAX_STOPS
3004
+ )
3005
+ throw new Error(
3006
+ `AOT: "${what}.stops" needs 2..${GRAD_MAX_STOPS} entries (got ${stopsNode.elements.length})`,
3007
+ );
3008
+ const stops = stopsNode.elements.map(e => {
3009
+ if (!e || e.type !== 'ObjectExpression')
3010
+ throw new Error(
3011
+ `AOT: each "${what}.stops" entry must be an object literal`,
3012
+ );
3013
+ const sp = {};
3014
+ for (const pr of e.properties) sp[pr.key.name ?? pr.key.value] = pr.value;
3015
+ let color;
3016
+ try {
3017
+ color = `${parseColor(evalStatic(sp.color, scope)) >>> 0}u`;
3018
+ } catch {
3019
+ anyDynamic = true;
3020
+ color = emitColorExpr(sp.color, env);
3021
+ }
3022
+ return {color, offset: numf(sp.offset, 0)};
3023
+ });
3024
+ return {
3025
+ type,
3026
+ stops,
3027
+ ax: numf(props.ax, 0),
3028
+ ay: numf(props.ay, 0),
3029
+ bx: numf(props.bx, 0),
3030
+ by: numf(props.by, 0),
3031
+ r: numf(props.r, 0),
3032
+ anyDynamic,
3033
+ };
3034
+ }
3035
+
3036
+ /**
3037
+ * Unwraps a gradient attribute, which may be a bare object literal or a CONDITIONAL one:
3038
+ * `cond ? {…} : null` (either way round) or `cond && {…}`. The gradient table entry is emitted either
3039
+ * way; what the condition drives is the PAINT'S INDEX, which becomes a runtime ternary of N or 0.
3040
+ *
3041
+ * Without this a gradient applied to a shape that is only sometimes gradient-filled leaks into every
3042
+ * other state — the index is a compile-time constant, so "no gradient here" is not expressible by
3043
+ * omission. The thermostat hit exactly that: its Auto ramp painted over Cool and Heat as well.
3044
+ */
3045
+ function gradAttr(v, scope, env, what) {
3046
+ if (!v) return null;
3047
+ let node = v.gradNode;
3048
+ let cond = null;
3049
+ const nullish = n =>
3050
+ n.type === 'NullLiteral' ||
3051
+ (n.type === 'Identifier' && n.name === 'undefined');
3052
+ if (node.type === 'ConditionalExpression') {
3053
+ if (
3054
+ node.consequent.type === 'ObjectExpression' &&
3055
+ nullish(node.alternate)
3056
+ ) {
3057
+ cond = emitExpr(node.test, env).code;
3058
+ node = node.consequent;
3059
+ } else if (
3060
+ node.alternate.type === 'ObjectExpression' &&
3061
+ nullish(node.consequent)
3062
+ ) {
3063
+ cond = `!(${emitExpr(node.test, env).code})`;
3064
+ node = node.alternate;
3065
+ } else
3066
+ throw new Error(
3067
+ `AOT: a conditional "${what}" must be \`cond ? { … } : null\` (one branch an object literal, the other null)`,
3068
+ );
3069
+ } else if (
3070
+ node.type === 'LogicalExpression' &&
3071
+ node.operator === '&&' &&
3072
+ node.right.type === 'ObjectExpression'
3073
+ ) {
3074
+ cond = emitExpr(node.left, env).code;
3075
+ node = node.right;
3076
+ }
3077
+ const spec = gradSpec(node, scope, env, what);
3078
+ spec.cond = cond;
3079
+ return spec;
3080
+ }
3081
+
3082
+ /** A `{ .type = …, .stops = { … }, … }` ERVectorGradient initializer from a gradSpec (const tables). */
3083
+ function gradInitFromSpec(g) {
3084
+ const stops = g.stops.map(st => `{ ${st.color}, ${st.offset} }`).join(', ');
3085
+ return (
3086
+ `{ .type = ${g.type}, .stop_count = ${g.stops.length}, .stops = { ${stops} }, ` +
3087
+ `.ax = ${g.ax}, .ay = ${g.ay}, .bx = ${g.bx}, .by = ${g.by}, .r = ${g.r} }`
3088
+ );
3089
+ }
3090
+
3091
+ /** Per-field assignments rebuilding one mutable gradient-table entry from state, for build_svgN(). */
3092
+ function gradAssigns(tab, i, g) {
3093
+ const out = [
3094
+ ` ${tab}[${i}].type = ${g.type};`,
3095
+ ` ${tab}[${i}].stop_count = ${g.stops.length};`,
3096
+ ];
3097
+ g.stops.forEach((st, si) => {
3098
+ out.push(` ${tab}[${i}].stops[${si}].color = ${st.color};`);
3099
+ out.push(` ${tab}[${i}].stops[${si}].position = ${st.offset};`);
3100
+ });
3101
+ for (const f of ['ax', 'ay', 'bx', 'by', 'r'])
3102
+ out.push(` ${tab}[${i}].${f} = ${g[f]};`);
3103
+ return out;
3104
+ }
3105
+
2931
3106
  const CAP_MAP = {butt: 0, round: 1, square: 2};
2932
3107
  const JOIN_MAP = {miter: 0, round: 1, bevel: 2};
2933
3108
 
@@ -2940,6 +3115,8 @@ const PAINT_FIELDS = [
2940
3115
  'cap',
2941
3116
  'join',
2942
3117
  'fill_rule',
3118
+ 'fill_grad',
3119
+ 'stroke_grad',
2943
3120
  ];
2944
3121
 
2945
3122
  /**
@@ -2949,7 +3126,7 @@ const PAINT_FIELDS = [
2949
3126
  * - strokeWidth may be DYNAMIC (numeric C expr); static → a float literal.
2950
3127
  * - cap / join / miterlimit / fillRule must be STATIC (a dynamic one throws clear).
2951
3128
  */
2952
- function paintSpec(a, env) {
3129
+ function paintSpec(a, env, scope) {
2953
3130
  let anyDynamic = false;
2954
3131
  const color = (v, dflt) => {
2955
3132
  if (isDyn(v)) {
@@ -2982,7 +3159,20 @@ function paintSpec(a, env) {
2982
3159
  String(JOIN_MAP[a.strokeLinejoin] ?? 0),
2983
3160
  String(a.fillRule === 'evenodd' ? 1 : 0),
2984
3161
  ];
2985
- return {fields, anyDynamic};
3162
+ // Gradient table indices are appended by the caller, which is the only place that knows the table
3163
+ // layout for the whole <Svg>. Placeholders keep `fields` aligned with PAINT_FIELDS until then.
3164
+ fields.push('0', '0');
3165
+ const fillGrad = gradAttr(a.fillGrad, scope, env, 'fillGrad');
3166
+ const strokeGrad = gradAttr(a.strokeGrad, scope, env, 'strokeGrad');
3167
+ // A conditional gradient makes the INDEX state-driven, so the paint table has to be mutable too.
3168
+ if (
3169
+ fillGrad?.anyDynamic ||
3170
+ strokeGrad?.anyDynamic ||
3171
+ fillGrad?.cond ||
3172
+ strokeGrad?.cond
3173
+ )
3174
+ anyDynamic = true;
3175
+ return {fields, anyDynamic, fillGrad, strokeGrad};
2986
3176
  }
2987
3177
 
2988
3178
  /** A `{ .fill = …, … }` ERVectorPaint initializer from a paintSpec's C-expr fields (used for static paints). */
@@ -2996,18 +3186,7 @@ function paintInitFromSpec(ps) {
2996
3186
  const arcEntriesC = (cx, cy, r, a0deg, a1deg) => {
2997
3187
  const a0 = `((${a0deg} - 90.0f) * (float)M_PI / 180.0f)`;
2998
3188
  const a1 = `((${a1deg} - 90.0f) * (float)M_PI / 180.0f)`;
2999
- return [
3000
- 'ER_VOP_MOVE',
3001
- `(${cx} + ${r} * cosf(${a0}))`,
3002
- `(${cy} + ${r} * sinf(${a0}))`,
3003
- 'ER_VOP_ARC',
3004
- cx,
3005
- cy,
3006
- r,
3007
- a0,
3008
- a1,
3009
- '0.0f',
3010
- ];
3189
+ return ['ER_VOP_ARC', cx, cy, r, a0, a1, '0.0f'];
3011
3190
  };
3012
3191
  const circleEntriesC = (cx, cy, r) => [
3013
3192
  'ER_VOP_MOVE',
@@ -3138,7 +3317,6 @@ function emitSvgStatic(el, scope, out, env) {
3138
3317
  out.vectorData.push(
3139
3318
  `static const float s_svg${id}_ops[] = {\n ${Array.from(ops, floatLit).join(', ')}\n};`,
3140
3319
  );
3141
- // flattenSvg paints are PAINT_STRIDE-wide; inline <Svg> has no gradients so fill_grad/stroke_grad are 0.
3142
3320
  out.vectorData.push(
3143
3321
  `static const ERVectorPaint s_svg${id}_paints[] = {\n${Array.from({length: nPaints}, (_, i) => ' ' + emitVectorPaint(paints.slice(i * PAINT_STRIDE, i * PAINT_STRIDE + PAINT_STRIDE))).join(',\n')}\n};`,
3144
3322
  );
@@ -3280,7 +3458,7 @@ function emitSvgDynamic(el, scope, out, env, state) {
3280
3458
  const shape = fn(a);
3281
3459
  if (!shape.length) continue;
3282
3460
  entries.push('ER_VOP_SHAPE', floatLit(specs.length), ...shape);
3283
- specs.push(paintSpec(a, env));
3461
+ specs.push(paintSpec(a, env, scope));
3284
3462
  }
3285
3463
  const v = `n${out.n++}`;
3286
3464
  const id = out.svgN++;
@@ -3288,7 +3466,35 @@ function emitSvgDynamic(el, scope, out, env, state) {
3288
3466
  const nPaints = specs.length;
3289
3467
  const dynPaint = specs.some(p => p.anyDynamic);
3290
3468
  out.needsMath = true; // build_svg uses cosf/sinf/M_PI for arcs
3469
+
3470
+ // Gradients referenced by these shapes, flattened into ONE table per <Svg> (the engine indexes it
3471
+ // 1-based off each paint). Done here rather than in paintSpec because the layout is per-<Svg>, not
3472
+ // per-shape, so a shape cannot know its own index.
3473
+ const grads = [];
3474
+ for (const ps of specs) {
3475
+ const idx = g => {
3476
+ if (!g) return '0';
3477
+ const n = grads.push(g); // push returns the new length = the 1-based index
3478
+ return g.cond ? `((${g.cond}) ? ${n} : 0)` : String(n);
3479
+ };
3480
+ ps.fields[7] = idx(ps.fillGrad);
3481
+ ps.fields[8] = idx(ps.strokeGrad);
3482
+ }
3483
+ const dynGrad = grads.some(g => g.anyDynamic);
3484
+
3291
3485
  out.vectorData.push(`static float s_svg${id}_ops[${len}];`);
3486
+ if (grads.length) {
3487
+ // Mutable when any field is state-driven — a conic ramp anchored to a setpoint rewrites its start
3488
+ // angle every update, exactly like the op-tape above it.
3489
+ if (dynGrad)
3490
+ out.vectorData.push(
3491
+ `static ERVectorGradient s_svg${id}_grads[${grads.length}];`,
3492
+ );
3493
+ else
3494
+ out.vectorData.push(
3495
+ `static const ERVectorGradient s_svg${id}_grads[] = {\n${grads.map(g => ' ' + gradInitFromSpec(g)).join(',\n')}\n};`,
3496
+ );
3497
+ }
3292
3498
  // Dynamic paint → a MUTABLE paint table (re)filled by build_svg from state each update; else a const table.
3293
3499
  if (dynPaint)
3294
3500
  out.vectorData.push(`static ERVectorPaint s_svg${id}_paints[${nPaints}];`);
@@ -3307,6 +3513,10 @@ function emitSvgDynamic(el, scope, out, env, state) {
3307
3513
  ),
3308
3514
  ),
3309
3515
  );
3516
+ if (dynGrad)
3517
+ grads.forEach((g, gi) =>
3518
+ builderLines.push(...gradAssigns(`s_svg${id}_grads`, gi, g)),
3519
+ );
3310
3520
  out.vectorBuilders.push(
3311
3521
  `static void build_svg${id}(void)\n{\n${builderLines.join('\n')}\n}`,
3312
3522
  );
@@ -3314,11 +3524,17 @@ function emitSvgDynamic(el, scope, out, env, state) {
3314
3524
  emitSvgBox(v, svgA.width, svgA.height, el.openingElement, scope, out, env);
3315
3525
  out.build.push(
3316
3526
  ` build_svg${id}();`,
3317
- ` er_node_set_vector_ops(${v}, s_svg${id}_ops, ${len}, s_svg${id}_paints, ${nPaints}, NULL, 0);`,
3527
+ ` er_node_set_vector_ops(${v}, s_svg${id}_ops, ${len}, s_svg${id}_paints, ${nPaints}, ${grads.length ? `s_svg${id}_grads` : 'NULL'}, ${grads.length});`,
3318
3528
  ` s_${v} = ${v};`,
3319
3529
  );
3320
3530
  out.handles.push(v);
3321
- out.svgUpdates.push({id, len, nPaints, nodeVar: `s_${v}`});
3531
+ out.svgUpdates.push({
3532
+ id,
3533
+ len,
3534
+ nPaints,
3535
+ nGrads: grads.length,
3536
+ nodeVar: `s_${v}`,
3537
+ });
3322
3538
  return v;
3323
3539
  }
3324
3540
 
@@ -4605,7 +4821,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
4605
4821
  for (const s of out.svgUpdates) {
4606
4822
  lines.push(` build_svg${s.id}();`);
4607
4823
  lines.push(
4608
- ` er_node_set_vector_ops(${s.nodeVar}, s_svg${s.id}_ops, ${s.len}, s_svg${s.id}_paints, ${s.nPaints}, NULL, 0);`,
4824
+ ` er_node_set_vector_ops(${s.nodeVar}, s_svg${s.id}_ops, ${s.len}, s_svg${s.id}_paints, ${s.nPaints}, ${s.nGrads ? `s_svg${s.id}_grads` : 'NULL'}, ${s.nGrads || 0});`,
4609
4825
  );
4610
4826
  }
4611
4827
  // Dep-driven useEffect: run each effect whose dependency value changed since the last app_update.
@@ -4681,6 +4897,12 @@ static void er_timer_clear(int id)
4681
4897
  .map(t => `static void ${t.name}(void)\n{\n${t.body.join('\n')}\n}`)
4682
4898
  .join('\n\n');
4683
4899
 
4900
+ // Timer callbacks are defined last, but a handler or a dep-driven effect fn can register one
4901
+ // (er_timer_add(…, er_timer_fn_N)) and those defs come earlier — so forward-declare every timer fn.
4902
+ const timerFnFwdDecls = out.timerFns
4903
+ .map(t => `static void ${t.name}(void);`)
4904
+ .join('\n');
4905
+
4684
4906
  // Animated.sequence on_complete callbacks: each starts the next step when the previous finishes. Forward-
4685
4907
  // declared (the handler that starts step 0 references the first callback, and each callback the next).
4686
4908
  const animCbDecls = out.animCbs
@@ -4749,6 +4971,23 @@ static void er_timer_clear(int id)
4749
4971
  out.build.join('\n'),
4750
4972
  ].join('\n'),
4751
4973
  );
4974
+ // Host-fed values (useHostValue) → a public setter each: write the s_state field, then re-apply
4975
+ // dependent nodes via app_update() (which the host also gets for free — it is the same refresh a JS
4976
+ // setter would trigger). The host calls e.g. er_app_set_steps(count) once per frame.
4977
+ const hostRecords = scalarRecords.filter(s => s.host);
4978
+ const hostSettersBlock = hostRecords
4979
+ .map(
4980
+ s =>
4981
+ `void er_app_set_${s.name}(${s.cType === 'float' ? 'float' : 'int'} v)\n{\n ${s.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`,
4982
+ )
4983
+ .join('\n\n');
4984
+ const hostSetterProtos = hostRecords
4985
+ .map(
4986
+ s =>
4987
+ `/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${s.cType === 'float' ? 'float' : 'int'} v);`,
4988
+ )
4989
+ .join('\n\n');
4990
+
4752
4991
  const body = `/*
4753
4992
  * Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
4754
4993
  * Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
@@ -4766,9 +5005,9 @@ static void er_timer_clear(int id)
4766
5005
  A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
4767
5006
  _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
4768
5007
  "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.");
4769
- ${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' : ''}${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' : ''}
5008
+ ${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' : ''}
4770
5009
  ${appTickFn}
4771
-
5010
+ ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
4772
5011
  void er_app_build(int screen_w, int screen_h)
4773
5012
  {
4774
5013
  ERProps p;
@@ -4797,7 +5036,7 @@ void er_app_build(int screen_w, int screen_h);
4797
5036
  /** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
4798
5037
  * for apps that use no timers, so it is always safe to call. */
4799
5038
  void er_app_tick(int dt_ms);
4800
-
5039
+ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
4801
5040
  #endif
4802
5041
  `;
4803
5042
 
@@ -44,9 +44,9 @@ const exe = resolve(
44
44
  const tmpDir = resolve(jsDir, 'dist', '.smoke');
45
45
 
46
46
  // Demos to smoke-test. `screen` (optional) sets ER_AOT_SCREEN_W/H so the responsive thermostat folds to its
47
- // compact (AOT-compilable) branch. `minColors` is the floor of distinct sampled colours for "rendered".
47
+ // `solo` (AOT-compilable) branch. `minColors` is the floor of distinct sampled colours for "rendered".
48
48
  const DEMOS = [
49
- {name: 'music-player', minColors: 40},
49
+ {name: 'watch-face', screen: {w: 240, h: 280}, minColors: 40},
50
50
  {name: 'thermostat', screen: {w: 240, h: 320}, minColors: 40},
51
51
  ];
52
52
 
package/cli.mjs CHANGED
@@ -63,6 +63,9 @@ Usage:
63
63
  upload to the device's config region)
64
64
  --aot → app.gen.c/.h + assets.generated.c (Flow B:
65
65
  no QuickJS, compiled into firmware)
66
+ --aot --screen <WxH> bake the target panel size so a
67
+ responsive app folds to that board's layout
68
+ (e.g. --screen 240x320)
66
69
 
67
70
  entry dev/export/build use ./index.jsx, ./src/index.jsx, or package.json "main";
68
71
  build --aot uses ./App.jsx or ./src/App.jsx. Pass one to override.
@@ -356,7 +359,13 @@ function resolveAppComponent(cwd, explicit) {
356
359
  }
357
360
 
358
361
  /** Flow B (--aot): compile the App component to C (app.gen.{c,h}) + bake assets, to compile into firmware. */
359
- async function buildAot(cwd, explicit, outDir) {
362
+ async function buildAot(cwd, explicit, outDir, screen) {
363
+ // Bake the target panel size (--screen <WxH>) BEFORE importing the compiler: it reads ER_AOT_SCREEN_W/H at
364
+ // module load to fold a responsive app's `screen.width` branch to the one that board renders.
365
+ if (screen) {
366
+ process.env.ER_AOT_SCREEN_W = screen.w;
367
+ process.env.ER_AOT_SCREEN_H = screen.h;
368
+ }
360
369
  const {compileSource, bakeSvgArtifacts} = await import('./aot/compile.mjs');
361
370
  const {bakeAssets} = await import('./assets/index.mjs');
362
371
  const appPath = resolveAppComponent(cwd, explicit);
@@ -442,17 +451,45 @@ async function buildContainer(cwd, explicit, outDir) {
442
451
  );
443
452
  }
444
453
 
445
- /** `embedded-react build [--aot] [entry] [--out dir]` — produce the device artifact. */
454
+ /** `embedded-react build [--aot] [entry] [--out dir] [--screen WxH]` — produce the device artifact. */
446
455
  async function build(args) {
447
456
  const cwd = process.cwd();
448
457
  const aot = args.includes('--aot');
449
458
  const outIdx = args.indexOf('--out');
450
459
  const outDir = resolve(cwd, outIdx >= 0 ? args[outIdx + 1] : 'dist');
451
- const explicit = args.find(
452
- (a, i) => !a.startsWith('--') && (outIdx < 0 || i !== outIdx + 1),
453
- );
460
+
461
+ // --screen <WxH> (AOT only): the target panel size, baked so a responsive app folds to the branch that
462
+ // board renders (e.g., 240x320 → the compact layout). Flow A reads the screen from the host at runtime.
463
+ const screenIdx = args.indexOf('--screen');
464
+ let screen = null;
465
+ if (screenIdx >= 0) {
466
+ if (!aot) {
467
+ console.error(
468
+ '--screen only applies to --aot (Flow A reads the panel size from the host at runtime).\n',
469
+ );
470
+ usage();
471
+ process.exit(1);
472
+ }
473
+ const raw = args[screenIdx + 1];
474
+ const m = raw && /^(\d+)x(\d+)$/i.exec(raw);
475
+ if (!m) {
476
+ console.error(
477
+ `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${raw ?? '(nothing)'}\n`,
478
+ );
479
+ usage();
480
+ process.exit(1);
481
+ }
482
+ screen = {w: m[1], h: m[2]};
483
+ }
484
+
485
+ // Consume the flag VALUES so they aren't mistaken for the entry (which is a bare, non-`--` token).
486
+ const consumed = new Set();
487
+ if (outIdx >= 0) consumed.add(outIdx + 1);
488
+ if (screenIdx >= 0) consumed.add(screenIdx + 1);
489
+ const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
490
+
454
491
  mkdirSync(outDir, {recursive: true});
455
- if (aot) await buildAot(cwd, explicit, outDir);
492
+ if (aot) await buildAot(cwd, explicit, outDir, screen);
456
493
  else await buildContainer(cwd, explicit, outDir);
457
494
  }
458
495
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "type": "module",
5
5
  "description": "React Native-style component package + reconciler that drives the embedded-react C engine through the QuickJS NativeUI bridge (Flow A).",
6
6
  "license": "Apache-2.0",
Binary file
package/sim-server.mjs CHANGED
@@ -45,6 +45,12 @@ const {transformPersist, shouldPersist} = await import(
45
45
  pathToFileURL(resolve(HERE, 'persist-transform.mjs')).href
46
46
  );
47
47
 
48
+ const REACT_PIN = Object.fromEntries(
49
+ ['react', 'react-reconciler', 'scheduler']
50
+ .map(p => [p, resolve(HERE, 'node_modules', p)])
51
+ .filter(([, p]) => existsSync(p)),
52
+ );
53
+
48
54
  const MIME = {
49
55
  '.html': 'text/html; charset=utf-8',
50
56
  '.js': 'text/javascript; charset=utf-8',
@@ -159,7 +165,7 @@ function createBundle({
159
165
  platform: 'neutral',
160
166
  target: 'es2020',
161
167
  jsx: 'automatic',
162
- alias: {'embedded-react': libSrc},
168
+ alias: {'embedded-react': libSrc, ...REACT_PIN},
163
169
  nodePaths,
164
170
  define: {'process.env.NODE_ENV': '"production"'},
165
171
  legalComments: 'none',
@@ -21,7 +21,11 @@
21
21
  // a ref and push updates directly here: it skips React entirely and, for vectors, skips the d-string
22
22
  // parser too. Commit back to React state when the gesture ends so the declarative tree re-syncs.
23
23
  import {NativeUI} from '../native-ui.js';
24
- import {shapesToVector, warnVectorCaps} from './svg-ops.js';
24
+ import {
25
+ shapesToVector,
26
+ warnVectorCaps,
27
+ encodeVectorGradients,
28
+ } from './svg-ops.js';
25
29
 
26
30
  /**
27
31
  * Imperatively sets an <Svg> node's geometry from primitive shape descriptors (see shapesToVector).
@@ -33,18 +37,20 @@ import {shapesToVector, warnVectorCaps} from './svg-ops.js';
33
37
  */
34
38
  export function updateVector(handle, shapes, dirtyRect) {
35
39
  if (handle == null) return;
36
- const {ops, paints} = shapesToVector(shapes);
40
+ const {ops, paints, gradients} = shapesToVector(shapes);
37
41
  warnVectorCaps(
38
42
  ops.length,
39
43
  paints.length,
40
44
  NativeUI.maxVectorOps,
41
45
  NativeUI.maxVectorPaints,
46
+ gradients.length,
47
+ NativeUI.maxVectorGrads,
42
48
  );
43
49
  NativeUI.setVectorOps(
44
50
  handle,
45
51
  ops,
46
52
  paints,
47
- undefined /* gradients: imperative shapes are solid */,
53
+ gradients.length ? encodeVectorGradients(gradients) : undefined,
48
54
  dirtyRect,
49
55
  );
50
56
  }
@@ -204,6 +204,7 @@ export function usePersistentState<S>(
204
204
  initialState: S | (() => S),
205
205
  ): [S, (value: S | ((prev: S) => S)) => void];
206
206
 
207
+ export function useHostValue(initial: number): number;
207
208
  export const Easing: Record<string, (t: number) => number>;
208
209
  export const LayoutAnimation: Record<string, unknown>;
209
210
  export function updateVector(...args: unknown[]): void;
@@ -48,5 +48,6 @@ export {Platform} from './Platform.js';
48
48
  export {AppRegistry} from './AppRegistry.js';
49
49
  export {Animated, useAnimatedValue} from './Animated.js';
50
50
  export {usePersistentState} from './usePersistentState.js';
51
+ export {useHostValue} from './useHostValue.js';
51
52
  export {Easing} from './Easing.js';
52
53
  export {LayoutAnimation} from './LayoutAnimation.js';
@@ -498,18 +498,7 @@ function arcOpsCW(cx, cy, r, a0deg, a1deg) {
498
498
  // The engine's arc angle runs from +X (cos/sin); top-clockwise => subtract 90°.
499
499
  const a0 = ((a0deg - 90) * Math.PI) / 180;
500
500
  const a1 = ((a1deg - 90) * Math.PI) / 180;
501
- return [
502
- VOP_MOVE,
503
- cx + r * Math.cos(a0),
504
- cy + r * Math.sin(a0),
505
- VOP_ARC,
506
- cx,
507
- cy,
508
- r,
509
- a0,
510
- a1,
511
- 0,
512
- ];
501
+ return [VOP_ARC, cx, cy, r, a0, a1, 0];
513
502
  }
514
503
 
515
504
  // --- Imperative shapes -> op-tape (the fast path; no JSX, no React) -------------------------------
@@ -530,12 +519,15 @@ function arcOpsCW(cx, cy, r, a0deg, a1deg) {
530
519
  // every move is pure GC. Push directly into these instead.
531
520
  const _vecOps = [];
532
521
  const _vecPaints = [];
522
+ const _vecGrads = [];
533
523
 
534
524
  export function shapesToVector(shapes) {
535
525
  const ops = _vecOps;
536
526
  const paints = _vecPaints;
527
+ const gradients = _vecGrads;
537
528
  ops.length = 0;
538
529
  paints.length = 0;
530
+ gradients.length = 0;
539
531
  for (let si = 0; si < shapes.length; si++) {
540
532
  const s = shapes[si];
541
533
  const opStart = ops.length;
@@ -547,18 +539,7 @@ export function shapesToVector(shapes) {
547
539
  const r = s.arc[2];
548
540
  const a0 = ((s.arc[3] - 90) * Math.PI) / 180;
549
541
  const a1 = ((s.arc[4] - 90) * Math.PI) / 180;
550
- ops.push(
551
- VOP_MOVE,
552
- cx + r * Math.cos(a0),
553
- cy + r * Math.sin(a0),
554
- VOP_ARC,
555
- cx,
556
- cy,
557
- r,
558
- a0,
559
- a1,
560
- 0,
561
- );
542
+ ops.push(VOP_ARC, cx, cy, r, a0, a1, 0);
562
543
  } else if (s.circle) {
563
544
  const cx = s.circle[0];
564
545
  const cy = s.circle[1];
@@ -606,6 +587,9 @@ export function shapesToVector(shapes) {
606
587
  ops.length = opStart; // nothing emitted — roll back the SHAPE header
607
588
  continue;
608
589
  }
590
+ // Optional gradients. `paint.fill_grad` / `stroke_grad` are 1-BASED indices into the gradient table
591
+ // (0 = solid), which is what lets one shape carry a smooth ramp instead of being chopped into many
592
+ // solid pieces. Stop colors may be strings here; the engine wants packed ARGB.
609
593
  paints.push(
610
594
  parseColor(s.fill),
611
595
  parseColor(s.stroke),
@@ -614,11 +598,28 @@ export function shapesToVector(shapes) {
614
598
  CAP[s.cap] ?? 0,
615
599
  JOIN[s.join] ?? 0,
616
600
  s.fillRule === 'evenodd' ? 1 : 0,
617
- 0, // fill_grad
618
- 0, // stroke_grad — the imperative path has no gradients
601
+ s.fillGrad ? pushGrad(gradients, s.fillGrad) : 0,
602
+ s.strokeGrad ? pushGrad(gradients, s.strokeGrad) : 0,
619
603
  );
620
604
  }
621
- return {ops, paints};
605
+ return {ops, paints, gradients};
606
+ }
607
+
608
+ /** Appends a gradient descriptor (normalizing string stop colours) and returns its 1-based index. */
609
+ function pushGrad(gradients, g) {
610
+ gradients.push({
611
+ type: g.type,
612
+ ax: g.ax,
613
+ ay: g.ay,
614
+ bx: g.bx,
615
+ by: g.by,
616
+ r: g.r,
617
+ stops: (g.stops || []).map(st => ({
618
+ color: typeof st.color === 'string' ? parseColor(st.color) : st.color,
619
+ offset: st.offset,
620
+ })),
621
+ });
622
+ return gradients.length;
622
623
  }
623
624
 
624
625
  // --- Flatten an <Svg> subtree --------------------------------------------------------------------
@@ -631,6 +632,8 @@ const PAINT_DEFAULT = {
631
632
  strokeLinejoin: 'miter',
632
633
  strokeMiterlimit: 4,
633
634
  fillRule: 'nonzero',
635
+ fillGrad: null,
636
+ strokeGrad: null,
634
637
  };
635
638
 
636
639
  function mergePaint(base, props) {
@@ -640,8 +643,10 @@ function mergePaint(base, props) {
640
643
  return out;
641
644
  }
642
645
 
643
- /** Maps the resolved paint to the PAINT_STRIDE-number record [fill,stroke,w,miter,cap,join,rule,fillGrad]. */
644
- function paintRecord(paint, scale) {
646
+ /** Maps the resolved paint to the PAINT_STRIDE-number record [fill,stroke, w,miter,cap,join,rule,
647
+ * fillGrad, strokeGrad]. Any gradient descriptor is appended to `gradients` and referenced by its
648
+ * 1-BASED index (0 = solid), the same encoding shapesToVector uses. */
649
+ function paintRecord(paint, scale, gradients) {
645
650
  return [
646
651
  parseColor(paint.fill),
647
652
  parseColor(paint.stroke),
@@ -650,8 +655,8 @@ function paintRecord(paint, scale) {
650
655
  CAP[paint.strokeLinecap] ?? 0,
651
656
  JOIN[paint.strokeLinejoin] ?? 0,
652
657
  paint.fillRule === 'evenodd' ? 1 : 0,
653
- 0, // fill_grad: inline <Svg> children don't reference gradients (baked <Svg source> does)
654
- 0, // stroke_grad
658
+ paint.fillGrad && gradients ? pushGrad(gradients, paint.fillGrad) : 0,
659
+ paint.strokeGrad && gradients ? pushGrad(gradients, paint.strokeGrad) : 0,
655
660
  ];
656
661
  }
657
662
 
@@ -703,13 +708,15 @@ function isElement(c) {
703
708
  }
704
709
 
705
710
  /**
706
- * Flattens an <Svg> element's props into {ops, paints} flat number arrays for NativeUI.setVectorOps.
711
+ * Flattens an <Svg> element's props into {ops, paints, gradients} flat arrays for NativeUI.setVectorOps.
707
712
  * Handles Path/Circle/Ellipse/Rect/Line shapes, <G> grouping (inherited paint + translate/scale), and
708
- * a root viewBox -> width/height scale. Returns empty arrays when there is nothing to draw.
713
+ * a root viewBox -> width/height scale. A shape's fillGrad/strokeGrad descriptor lands in `gradients`
714
+ * and is referenced 1-based from its paint record. Returns empty arrays when there is nothing to draw.
709
715
  */
710
716
  export function flattenSvg(props) {
711
717
  const ops = [];
712
718
  const paints = [];
719
+ const gradients = [];
713
720
 
714
721
  // Root transform from viewBox vs width/height.
715
722
  let root = {sx: 1, sy: 1, tx: 0, ty: 0};
@@ -762,13 +769,13 @@ export function flattenSvg(props) {
762
769
 
763
770
  const paintIndex = paints.length / PAINT_STRIDE;
764
771
  const scale = (T.sx + T.sy) / 2; // stroke-width scale (uniform assumed)
765
- paints.push(...paintRecord(merged, scale));
772
+ paints.push(...paintRecord(merged, scale, gradients));
766
773
  ops.push(VOP_SHAPE, paintIndex, ...transformOps(shapeOps, T));
767
774
  }
768
775
  };
769
776
 
770
777
  walk(props.children, PAINT_DEFAULT, root);
771
- return {ops, paints};
778
+ return {ops, paints, gradients};
772
779
  }
773
780
 
774
781
  // --- Imported SVG artifacts (<Svg source>) -------------------------------------------------------
@@ -0,0 +1,31 @@
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
+ // useHostValue — a numeric value fed by the C HOST at runtime, not by the app.
18
+ //
19
+ // Flow B (AOT): the compiler recognizes `const steps = useHostValue(0)` and lowers it to an ordinary
20
+ // `s_state` field PLUS a generated public setter `er_app_set_steps(int)`. The host (e.g. a pedometer
21
+ // reading an IMU in main.c) calls that setter each frame; the app renders the value like any state.
22
+ // There is no JS setter — the host is the only writer.
23
+ //
24
+ // Flow A / simulator: there is no host, so this simply returns the initial value (the simulator has no
25
+ // IMU to drive it anyway).
26
+ //
27
+ // @param {number} initial Initial value, used until the host writes one.
28
+ // @returns {number} the current value.
29
+ export function useHostValue(initial) {
30
+ return initial;
31
+ }
@@ -111,7 +111,7 @@ function applyVectorOps(type, handle, props) {
111
111
  svgBoxSize(props, 'height', src.height),
112
112
  ));
113
113
  } else {
114
- ({ops, paints} = flattenSvg(props));
114
+ ({ops, paints, gradients} = flattenSvg(props));
115
115
  }
116
116
  warnVectorCaps(
117
117
  ops.length,