embedded-react 0.14.0 → 0.14.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
@@ -2702,11 +2702,8 @@ function emitAnimEntry(entry, env, idx, onCompleteCb) {
2702
2702
  * `duration` is this node's own run length in ms, used to offset later siblings in a sequence/stagger;
2703
2703
  * null = unknown (spring/decay/loop), which is illegal to sequence anything after. */
2704
2704
  function flattenAnim(node, env, baseDelay, loop) {
2705
- if (
2706
- node?.type !== 'CallExpression' ||
2707
- node.callee.type !== 'MemberExpression' ||
2708
- node.callee.object?.name !== 'Animated'
2709
- )
2705
+ node = resolveAnim(node, env);
2706
+ if (!isAnimatedCall(node))
2710
2707
  throw aotError(
2711
2708
  'AOT: an animation must be Animated.timing/spring/decay/sequence/parallel/stagger/delay/loop(...)',
2712
2709
  );
@@ -2786,31 +2783,89 @@ function flattenAnim(node, env, baseDelay, loop) {
2786
2783
  const r = flattenAnim(args[0], env, baseDelay, true);
2787
2784
  if (r.entries.length !== 1)
2788
2785
  throw aotError(
2789
- 'AOT: Animated.loop currently wraps a single Animated.timing/spring/decay (looping a sequence/parallel is not yet supported)',
2786
+ 'AOT: an Animated.loop inside another composition can only wrap a single Animated.timing/spring/decay',
2787
+ 'a loop around a sequence works when the loop is the animation you start: Animated.loop(Animated.sequence([...])).start().',
2790
2788
  );
2791
2789
  return {entries: r.entries, duration: null};
2792
2790
  }
2793
2791
  throw aotError(`AOT: Animated.${kind}(...) is not a supported animation`);
2794
2792
  }
2795
2793
 
2796
- /** Lowers `Animated.sequence([...]).start()` to an on_complete CHAIN: step 0 starts inline (in the handler),
2797
- * and each step's completion callback starts the next. Unlike the flat delay_ms path this is correct when
2798
- * steps share a value (out-and-back) — er_anim_value_animate cancels the running anim on a value, so
2799
- * synchronous same-value animates would cancel each other — and needs no fixed duration (spring/decay OK).
2800
- * delay() entries fold into the next step's delay_ms. Nested parallel/stagger/loop in a sequence throws. */
2801
- function compileSequenceChain(seqNode, env, ctx, doneCb = null) {
2794
+ const ANIM_KINDS = new Set([
2795
+ 'timing',
2796
+ 'spring',
2797
+ 'decay',
2798
+ 'sequence',
2799
+ 'parallel',
2800
+ 'stagger',
2801
+ 'delay',
2802
+ 'loop',
2803
+ ]);
2804
+
2805
+ /** True for an `Animated.timing/spring/…/loop(…)` call: an animation, not a value. */
2806
+ const isAnimatedCall = n =>
2807
+ n?.type === 'CallExpression' &&
2808
+ n.callee.type === 'MemberExpression' &&
2809
+ n.callee.object?.name === 'Animated' &&
2810
+ ANIM_KINDS.has(n.callee.property?.name);
2811
+
2812
+ /** An animation handle (`anim` after `const anim = Animated.loop(…)`) resolved to the call it names. */
2813
+ const resolveAnim = (node, env) =>
2814
+ node?.type === 'Identifier' && env.animLocals?.has(node.name)
2815
+ ? env.animLocals.get(node.name)
2816
+ : node;
2817
+
2818
+ /** One Animated.timing/spring/decay call as a chain step, started `extraDelay` ms later than its own delay. */
2819
+ function animStep(node, env, extraDelay) {
2820
+ const kind = node.callee.property.name;
2821
+ const valRef = node.arguments[0];
2822
+ if (valRef?.type !== 'Identifier' || !env.anims?.has(valRef.name))
2823
+ throw aotError(
2824
+ `AOT: Animated.${kind}() first argument must be a useAnimatedValue`,
2825
+ );
2826
+ const get = animConfigGetter(node.arguments[1]);
2827
+ const ownDelay = Math.round(Number(evalStaticOr(get('delay'), env, 0)));
2828
+ return {
2829
+ cVar: env.anims.get(valRef.name).cVar,
2830
+ kind,
2831
+ get,
2832
+ delayMs: extraDelay + ownDelay,
2833
+ loop: false,
2834
+ };
2835
+ }
2836
+
2837
+ /** The C handle of every value an animation drives. */
2838
+ function animValues(node, env, acc = new Set()) {
2839
+ node = resolveAnim(node, env);
2840
+ if (!isAnimatedCall(node))
2841
+ throw aotError(
2842
+ 'AOT: an animation must be Animated.timing/spring/decay/sequence/parallel/stagger/delay/loop(...)',
2843
+ );
2844
+ const kind = node.callee.property.name;
2845
+ const args = node.arguments;
2846
+ if (kind === 'timing' || kind === 'spring' || kind === 'decay')
2847
+ acc.add(animStep(node, env, 0).cVar);
2848
+ else if (kind === 'loop') animValues(args[0], env, acc);
2849
+ else if (kind !== 'delay') {
2850
+ const list = kind === 'stagger' ? args[1] : args[0];
2851
+ for (const child of list?.elements ?? [])
2852
+ if (child) animValues(child, env, acc);
2853
+ }
2854
+ return acc;
2855
+ }
2856
+
2857
+ /** The steps of an `Animated.sequence([...])` for an on_complete chain. A delay() folds into the next step's
2858
+ * delay_ms; `trailingDelay` is what follows the last step. A nested parallel/stagger/loop throws. */
2859
+ function sequenceSteps(seqNode, env) {
2802
2860
  const list = seqNode.arguments[0];
2803
2861
  if (list?.type !== 'ArrayExpression')
2804
2862
  throw aotError('AOT: Animated.sequence(...) needs an array of animations');
2805
2863
  const steps = [];
2806
2864
  let pendingDelay = 0;
2807
- for (const child of list.elements) {
2808
- if (!child) continue;
2809
- if (
2810
- child.type !== 'CallExpression' ||
2811
- child.callee.type !== 'MemberExpression' ||
2812
- child.callee.object?.name !== 'Animated'
2813
- )
2865
+ for (const el of list.elements) {
2866
+ if (!el) continue;
2867
+ const child = resolveAnim(el, env);
2868
+ if (!isAnimatedCall(child))
2814
2869
  throw aotError(
2815
2870
  'AOT: Animated.sequence entries must be Animated.timing/spring/decay/delay(...)',
2816
2871
  );
@@ -2825,41 +2880,136 @@ function compileSequenceChain(seqNode, env, ctx, doneCb = null) {
2825
2880
  throw aotError(
2826
2881
  'AOT: Animated.sequence entries must be Animated.timing/spring/decay/delay (a nested parallel/stagger/loop inside a sequence is not yet supported — keep the sequence flat)',
2827
2882
  );
2828
- const valRef = child.arguments[0];
2829
- if (valRef?.type !== 'Identifier' || !env.anims?.has(valRef.name))
2830
- throw aotError(
2831
- `AOT: Animated.${kind}() first argument must be a useAnimatedValue`,
2832
- );
2833
- const get = animConfigGetter(child.arguments[1]);
2834
- const ownDelay = Math.round(Number(evalStaticOr(get('delay'), env, 0)));
2835
- steps.push({
2836
- cVar: env.anims.get(valRef.name).cVar,
2837
- kind,
2838
- get,
2839
- delayMs: pendingDelay + ownDelay,
2840
- loop: false,
2841
- });
2883
+ steps.push(animStep(child, env, pendingDelay));
2842
2884
  pendingDelay = 0;
2843
2885
  }
2844
- if (!steps.length) return [];
2886
+ return {steps, trailingDelay: pendingDelay};
2887
+ }
2888
+
2889
+ /**
2890
+ * Emits steps as an on_complete CHAIN: step 0 starts inline and each step's completion callback starts the
2891
+ * next. Unlike the flat delay_ms path this is correct when steps share a value — er_anim_value_animate
2892
+ * cancels the running anim on a value, so starting them together would cancel all but the last — and needs
2893
+ * no fixed duration. A step that is interrupted (finished == false) ends the chain, as it does in JS.
2894
+ *
2895
+ * `loop` makes the last step start the first again: {iterations (negative = forever), resetTo (the value to
2896
+ * put back where it started before each repeat, or null), trailingDelay (ms before each repeat)}.
2897
+ */
2898
+ function emitAnimChain(steps, env, ctx, doneCb, loop = null) {
2845
2899
  const seqId = ctx.out.seqN++; // GLOBAL: callback names are file-scope, so must be unique across handlers
2846
- let firstLines = [];
2847
- // Build from the tail so each step knows its successor's callback name. Step 0 runs inline; the rest
2848
- // become on_complete callbacks pushed to out.animCbs (emitted at file scope).
2849
- for (let i = steps.length - 1; i >= 0; i--) {
2850
- // The last step's on_complete is the .start(onComplete) callback (if any) — the sequence is "done".
2851
- const nextCb = i < steps.length - 1 ? `er_seqcb_${seqId}_${i + 1}` : doneCb;
2852
- const lines = emitAnimEntry(steps[i], env, `${seqId}_${i}`, nextCb);
2853
- if (i === 0) firstLines = lines;
2854
- else ctx.out.animCbs.push({name: `er_seqcb_${seqId}_${i}`, body: lines});
2900
+ const cb = i => `er_seqcb_${seqId}_${i}`;
2901
+ const done = finished =>
2902
+ doneCb ? [` ${doneCb}(${finished}, NULL);`] : [];
2903
+ const interrupted = [
2904
+ ' if (!finished)',
2905
+ ' {',
2906
+ ...done('false'),
2907
+ ' return;',
2908
+ ' }',
2909
+ ];
2910
+ const last = loop ? cb(0) : doneCb;
2911
+ // Built from the tail so each step knows its successor's callback name.
2912
+ for (let i = steps.length - 1; i >= 1; i--) {
2913
+ const next = i < steps.length - 1 ? cb(i + 1) : last;
2914
+ ctx.out.animCbs.push({
2915
+ name: cb(i),
2916
+ body: [
2917
+ ...interrupted,
2918
+ ...emitAnimEntry(steps[i], env, `${seqId}_${i}`, next),
2919
+ ],
2920
+ });
2855
2921
  }
2856
- return firstLines;
2922
+ const next0 = steps.length > 1 ? cb(1) : last;
2923
+ const first = emitAnimEntry(steps[0], env, `${seqId}_0`, next0);
2924
+ if (!loop) return first;
2925
+
2926
+ // The repeat: cb(0) runs when the last step finishes, and starts step 0 again.
2927
+ const lines = [];
2928
+ const repeat = [...interrupted];
2929
+ if (loop.iterations >= 0) {
2930
+ const n = `s_loop${seqId}_n`;
2931
+ ctx.out.effectDecls.push(`static int ${n};`);
2932
+ lines.push(` ${n} = 1;`);
2933
+ repeat.push(
2934
+ ` if (${n} >= ${loop.iterations})`,
2935
+ ' {',
2936
+ ...done('true'),
2937
+ ' return;',
2938
+ ' }',
2939
+ ` ${n}++;`,
2940
+ );
2941
+ }
2942
+ if (loop.resetTo) {
2943
+ const from = `s_loop${seqId}_from`;
2944
+ ctx.out.effectDecls.push(`static float ${from};`);
2945
+ lines.push(` ${from} = er_anim_value_get(${loop.resetTo});`);
2946
+ repeat.push(` er_anim_value_set(${loop.resetTo}, ${from});`);
2947
+ }
2948
+ const again = {...steps[0], delayMs: steps[0].delayMs + loop.trailingDelay};
2949
+ repeat.push(...emitAnimEntry(again, env, `${seqId}_0`, next0));
2950
+ ctx.out.animCbs.push({name: cb(0), body: repeat});
2951
+ return [...lines, ...first];
2952
+ }
2953
+
2954
+ /**
2955
+ * Compiles `Animated.loop(animation, config?).start()`, or returns null for the flat path. An endless loop of
2956
+ * one timing is the engine's own cfg.loop; anything else (a sequence, a spring or decay, a counted loop) is a
2957
+ * chain whose last step starts the first again. As in JS, a looped single animation goes back to where it
2958
+ * started before each repeat (resetBeforeIteration), and a looped sequence carries on from where it ended.
2959
+ */
2960
+ function compileLoopStart(loopNode, env, ctx, doneCb) {
2961
+ const inner = resolveAnim(loopNode.arguments[0], env);
2962
+ const kind = isAnimatedCall(inner) ? inner.callee.property.name : null;
2963
+ const get = animConfigGetter(loopNode.arguments[1]);
2964
+ let iterations = -1;
2965
+ if (get('iterations')) {
2966
+ let v;
2967
+ try {
2968
+ v = evalStatic(get('iterations'), foldScope(env, env.consts ?? {}));
2969
+ } catch {
2970
+ throw aotError(
2971
+ 'AOT: Animated.loop iterations must be known at build time',
2972
+ 'use a number or a module-level constant.',
2973
+ );
2974
+ }
2975
+ // JS loops forever on anything but a whole number.
2976
+ iterations = Number.isInteger(v) ? Math.min(v, INT_MAX) : -1;
2977
+ }
2978
+ const reset = evalStaticOr(get('resetBeforeIteration'), env, true) !== false;
2979
+ let steps;
2980
+ let trailingDelay = 0;
2981
+ let resetTo = null;
2982
+ if (kind === 'sequence') {
2983
+ ({steps, trailingDelay} = sequenceSteps(inner, env));
2984
+ } else if (kind === 'timing' || kind === 'spring' || kind === 'decay') {
2985
+ if (kind === 'timing' && iterations < 0 && reset) return null;
2986
+ steps = [animStep(inner, env, 0)];
2987
+ if (reset) resetTo = steps[0].cVar;
2988
+ } else {
2989
+ throw aotError(
2990
+ 'AOT: Animated.loop can repeat a timing, spring, decay or sequence (looping a parallel/stagger is not yet supported)',
2991
+ );
2992
+ }
2993
+ if (!steps.length) return [];
2994
+ if (iterations === 0) return doneCb ? [` ${doneCb}(true, NULL);`] : [];
2995
+ // A timing with no duration and no delay completes inside er_anim_value_animate, so a loop made only of
2996
+ // those would restart itself forever without returning.
2997
+ const instant = s =>
2998
+ s.kind === 'timing' &&
2999
+ s.delayMs === 0 &&
3000
+ Math.round(Number(evalStaticOr(s.get('duration'), env, 250))) === 0;
3001
+ if (trailingDelay === 0 && steps.every(instant))
3002
+ throw aotError(
3003
+ 'AOT: every step of this Animated.loop finishes instantly, so it would never stop repeating',
3004
+ 'give a step a duration or a delay.',
3005
+ );
3006
+ return emitAnimChain(steps, env, ctx, doneCb, {
3007
+ iterations,
3008
+ resetTo,
3009
+ trailingDelay,
3010
+ });
2857
3011
  }
2858
3012
 
2859
- /** Compiles `<animation>.start()` — a single Animated.timing/spring/decay or a composition
2860
- * (sequence/parallel/stagger/delay/loop). A top-level sequence chains via on_complete (compileSequenceChain);
2861
- * everything else flattens to one ERAnimConfig + er_anim_value_animate per atomic entry, composition
2862
- * expressed through per-entry delay_ms. Native-driven; sets no React state. */
2863
3013
  /** Compiles a `.start(onComplete)` completion callback to a file-scope C fn (ERAnimCompleteFn) set as the
2864
3014
  * animation's on_complete; its body runs setters/refs/etc. and re-applies state via app_update if needed. */
2865
3015
  function emitCompletionCb(fnNode, env, state, ctx) {
@@ -2888,19 +3038,24 @@ function emitCompletionCb(fnNode, env, state, ctx) {
2888
3038
  return name;
2889
3039
  }
2890
3040
 
3041
+ /** Compiles `<animation>.start()` — a single Animated.timing/spring/decay or a composition
3042
+ * (sequence/parallel/stagger/delay/loop). A sequence, and a loop the engine cannot repeat on its own, become
3043
+ * an on_complete chain (emitAnimChain); everything else flattens to one ERAnimConfig + er_anim_value_animate
3044
+ * per atomic entry, composition expressed through per-entry delay_ms. Native-driven; sets no React state. */
2891
3045
  function compileAnimateStart(expr, env, state, ctx) {
2892
3046
  // .start(onComplete?) — an optional completion callback fired when the animation finishes.
2893
3047
  const doneCb = isFn(expr.arguments[0])
2894
3048
  ? emitCompletionCb(expr.arguments[0], env, state, ctx)
2895
3049
  : null;
2896
- const receiver = expr.callee.object;
2897
- if (
2898
- receiver?.type === 'CallExpression' &&
2899
- receiver.callee.type === 'MemberExpression' &&
2900
- receiver.callee.object?.name === 'Animated' &&
2901
- receiver.callee.property.name === 'sequence'
2902
- ) {
2903
- return compileSequenceChain(receiver, env, ctx, doneCb);
3050
+ const receiver = resolveAnim(expr.callee.object, env);
3051
+ const kind = isAnimatedCall(receiver) ? receiver.callee.property.name : null;
3052
+ if (kind === 'sequence') {
3053
+ const {steps} = sequenceSteps(receiver, env);
3054
+ return steps.length ? emitAnimChain(steps, env, ctx, doneCb) : [];
3055
+ }
3056
+ if (kind === 'loop') {
3057
+ const lines = compileLoopStart(receiver, env, ctx, doneCb);
3058
+ if (lines) return lines;
2904
3059
  }
2905
3060
  const {entries} = flattenAnim(receiver, env, 0, false);
2906
3061
  if (doneCb && entries.length > 1)
@@ -3335,6 +3490,18 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
3335
3490
  ];
3336
3491
  return [`${indent}${r.cVar}${expr.operator};`];
3337
3492
  }
3493
+ // `anim.stop()` stops every value the animation drives where it is. The cancellation reports finished ==
3494
+ // false, which also ends a sequence or loop chain.
3495
+ if (
3496
+ expr.type === 'CallExpression' &&
3497
+ expr.callee.type === 'MemberExpression' &&
3498
+ expr.callee.property.name === 'stop' &&
3499
+ isAnimatedCall(resolveAnim(expr.callee.object, env))
3500
+ ) {
3501
+ return [...animValues(expr.callee.object, env)].map(
3502
+ v => `${indent}er_anim_value_set(${v}, er_anim_value_get(${v}));`,
3503
+ );
3504
+ }
3338
3505
  // Animated.*(…).start() — single timing/spring/decay OR a sequence/parallel/stagger/delay/loop
3339
3506
  // composition; native-driven, sets no React state, needs no app_update.
3340
3507
  if (
@@ -3409,6 +3576,18 @@ function compileStmts(list, env, state, ctx, indent) {
3409
3576
  );
3410
3577
  if (!decl.init)
3411
3578
  throw new Error('AOT: a handler local must have an initializer');
3579
+ // `const anim = Animated.loop(…)` holds no C value: `anim.start()` and `anim.stop()` compile the
3580
+ // animation it names.
3581
+ if (isAnimatedCall(decl.init)) {
3582
+ const locals = new Map(env.locals);
3583
+ locals.delete(decl.id.name);
3584
+ env = {
3585
+ ...env,
3586
+ locals,
3587
+ animLocals: new Map(env.animLocals).set(decl.id.name, decl.init),
3588
+ };
3589
+ continue;
3590
+ }
3412
3591
  // A cleanup closure outlives the call that created it, so when one is emitted (a dep-driven
3413
3592
  // effect) the body's own locals become file-scope slots instead of C locals.
3414
3593
  const hoist = ctx.hoist && list === ctx.bodyList;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.14.0",
3
+ "version": "0.14.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",
@@ -809,7 +809,7 @@ export interface AnimationConfig {
809
809
 
810
810
  export interface Animation {
811
811
  start(callback?: (result: {finished: boolean}) => void): void;
812
- stop?(): void;
812
+ stop(): void;
813
813
  }
814
814
 
815
815
  export const Animated: {
@@ -826,7 +826,10 @@ export const Animated: {
826
826
  config?: {stopTogether?: boolean},
827
827
  ): Animation;
828
828
  stagger(delay: number, animations: Animation[]): Animation;
829
- loop(animation: Animation, config?: {iterations?: number}): Animation;
829
+ loop(
830
+ animation: Animation,
831
+ config?: {iterations?: number; resetBeforeIteration?: boolean},
832
+ ): Animation;
830
833
  delay(ms: number): Animation;
831
834
  };
832
835