skia-motion-runtime 3.0.0 → 3.1.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.
@@ -0,0 +1,107 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
3
+ import type { AssetImages } from './asset-draw';
4
+
5
+ export type MotionAssetSource = string | { uri: string } | {
6
+ /** Stable identity for a custom loader. Change it when the source changes. */
7
+ key: string;
8
+ read: (signal: AbortSignal) => Promise<string>;
9
+ };
10
+ export type MotionAssetOptions = MotionPrepareOptions & { uploadImages?: boolean };
11
+ type Failure = { status: 'error'; asset: null; error: Error };
12
+ export type MotionAssetResult =
13
+ | { status: 'idle' | 'loading'; asset: null; error: null }
14
+ | { status: 'ready'; asset: LoadedMotionAsset; error: null }
15
+ | Failure;
16
+
17
+ type CacheEntry = {
18
+ promise: Promise<LoadedMotionAsset>;
19
+ controller: AbortController;
20
+ users: number;
21
+ };
22
+
23
+ // Cache prepared resources while subscribers own them. Each player creates its own machine snapshot.
24
+ const cache = new Map<string, CacheEntry>();
25
+ const imageIds = new WeakMap<object, number>();
26
+ let nextImageId = 0;
27
+ const idle = { status: 'idle', asset: null, error: null } as const;
28
+ const loading = { status: 'loading', asset: null, error: null } as const;
29
+
30
+ function slotKey(images: AssetImages | undefined) {
31
+ return Object.keys(images ?? {}).sort().map((name) => {
32
+ const image = images![name]!;
33
+ let id = imageIds.get(image);
34
+ if (id === undefined) {
35
+ id = nextImageId++;
36
+ imageIds.set(image, id);
37
+ }
38
+ return [name, id];
39
+ });
40
+ }
41
+
42
+ async function readSource(source: MotionAssetSource, signal: AbortSignal) {
43
+ if (typeof source === 'string') return source;
44
+ if ('read' in source) return source.read(signal);
45
+ const response = await fetch(source.uri, { signal });
46
+ if (!response.ok) throw new Error(`Unable to load motion asset (HTTP ${response.status})`);
47
+ return response.text();
48
+ }
49
+
50
+ function retain(key: string, source: MotionAssetSource, options: MotionAssetOptions) {
51
+ let entry = cache.get(key);
52
+ if (!entry) {
53
+ const controller = new AbortController();
54
+ const signal = controller.signal;
55
+ const promise = Promise.resolve().then(async () => {
56
+ if (signal.aborted) throw new Error('Motion asset load cancelled');
57
+ const text = await readSource(source, signal);
58
+ if (signal.aborted) throw new Error('Motion asset load cancelled');
59
+ return preloadMotionAsset(text, options);
60
+ });
61
+ entry = { promise, controller, users: 0 };
62
+ const created = entry;
63
+ cache.set(key, created);
64
+ promise.catch(() => {
65
+ if (cache.get(key) === created) cache.delete(key);
66
+ });
67
+ }
68
+ entry.users++;
69
+ return entry;
70
+ }
71
+
72
+ /** Asynchronously load and share an asset. For Expo module IDs use the /expo entry point. */
73
+ export function useMotionAsset(source?: MotionAssetSource | null, options: MotionAssetOptions = {}): MotionAssetResult {
74
+ const { uploadImages = false, artboard, imageSlots, palette } = options;
75
+ const kind = source == null ? undefined : typeof source === 'string' ? 'text' : 'uri' in source ? 'uri' : 'custom';
76
+ const id = typeof source === 'string' ? source : source == null ? undefined : 'uri' in source ? source.uri : source.key;
77
+ const key = useMemo(() => kind === undefined ? undefined : JSON.stringify([
78
+ kind, id, uploadImages, artboard, slotKey(imageSlots),
79
+ Object.keys(palette ?? {}).sort().map((name) => [name, palette![name]]),
80
+ ]), [kind, id, uploadImages, artboard, imageSlots, palette]);
81
+ const [state, setState] = useState<{ key: string; result: MotionAssetResult }>();
82
+ useEffect(() => {
83
+ setState((previous) => previous?.key === key ? previous : undefined);
84
+ if (key === undefined || source == null) return;
85
+ const entry = retain(key, source, options);
86
+ let active = true;
87
+ entry.promise.then(
88
+ (asset) => { if (active) setState({ key, result: { status: 'ready', asset, error: null } }); },
89
+ (error: unknown) => {
90
+ if (active) setState({ key, result: {
91
+ status: 'error', asset: null, error: error instanceof Error ? error : new Error(String(error)),
92
+ } });
93
+ },
94
+ );
95
+ return () => {
96
+ active = false;
97
+ if (--entry.users === 0) {
98
+ if (cache.get(key) === entry) cache.delete(key);
99
+ entry.controller.abort();
100
+ }
101
+ };
102
+ // The key includes the source identity and options. Custom loaders are retained for that identity.
103
+ // eslint-disable-next-line react-hooks/exhaustive-deps
104
+ }, [key]);
105
+ if (key === undefined) return idle;
106
+ return state?.key === key ? state.result : loading;
107
+ }
@@ -101,12 +101,13 @@ export function compile(m: Machine, clips: Clips): Compiled {
101
101
  for (const name of Object.keys(m.values ?? {})) {
102
102
  const v = m.values![name]!;
103
103
  index[name] = values.length;
104
- const def: Literal = v.default !== undefined ? v.default : v.type === 'number' ? 0 : v.type === 'enum' ? v.options![0]! : false;
104
+ const def: Literal = v.default !== undefined ? v.default
105
+ : v.type === 'number' ? 0 : v.type === 'enum' ? v.options![0]! : v.type === 'string' ? '' : false;
105
106
  values.push({ name, type: v.type, def, bind: v.bind ?? 'in', options: v.options ?? [] });
106
107
  }
107
108
  // A string operand names a value unless it is an option of the enum it is compared with or written to.
108
109
  const ref = (x: Literal, owner: string): number =>
109
- (typeof x === 'string' && index[x] !== undefined && !(m.values?.[owner]?.options ?? []).includes(x) ? index[x]! : -1);
110
+ (typeof x === 'string' && Object.hasOwn(index, x) && !(m.values?.[owner]?.options ?? []).includes(x) ? index[x]! : -1);
110
111
  const conds = (when: readonly Condition[] | undefined): CCond[] =>
111
112
  (when ?? []).map(([name, op, rhs]): CCond => {
112
113
  const owner = name as string;
@@ -273,13 +274,14 @@ function step(c: Compiled, s: Snapshot, li: number, t: number, clock: ClockRead,
273
274
  */
274
275
  export function writeProblem(c: Compiled, name: string, to: Literal): string {
275
276
  'worklet';
276
- const i = c.index[name];
277
- if (i === undefined) return `the machine has no value "${name}"`;
277
+ if (!Object.hasOwn(c.index, name)) return `the machine has no value "${name}"`;
278
+ const i = c.index[name]!;
278
279
  const v = c.values[i]!;
279
280
  if (v.bind === 'out') return `"${name}" is an out-value: the machine writes it, the app reads it`;
280
281
  const fits = v.type === 'trigger' ? to === true
281
282
  : v.type === 'boolean' ? typeof to === 'boolean'
282
283
  : v.type === 'number' ? typeof to === 'number' && Number.isFinite(to)
284
+ : v.type === 'string' ? typeof to === 'string' && to.length <= 4096
283
285
  : typeof to === 'string' && v.options.includes(to);
284
286
  if (fits) return '';
285
287
  const wanted = v.type === 'trigger' ? 'a fire (true)' : v.type === 'enum' ? `one of ${v.options.join(', ')}` : `a ${v.type}`;
@@ -386,14 +388,19 @@ function clipTime(loop: number, ms: number, local: number, reduced: boolean, red
386
388
  return p <= ms ? p : 2 * ms - p;
387
389
  }
388
390
 
389
- function lerpPose(a: Pose, b: Pose, w: number): Pose {
391
+ function lerpPose(a: Pose, b: Pose, w: number, underneath: Readonly<Record<string, number>>): Pose {
390
392
  'worklet';
391
393
  const channels: Record<string, number> = { ...a.channels };
392
394
  for (const k of Object.keys(b.channels)) {
393
395
  const bv = b.channels[k]!;
394
- const av = a.channels[k];
396
+ const av = a.channels[k] ?? underneath[k];
395
397
  channels[k] = av === undefined ? bv : av + (bv - av) * w;
396
398
  }
399
+ for (const k of Object.keys(a.channels)) {
400
+ if (Object.hasOwn(b.channels, k) || !Object.hasOwn(underneath, k)) continue;
401
+ const av = a.channels[k]!;
402
+ channels[k] = av + (underneath[k]! - av) * w;
403
+ }
397
404
  let parts: Record<string, PartBox> | undefined;
398
405
  if (a.parts || b.parts) {
399
406
  parts = { ...(a.parts ?? {}) };
@@ -411,7 +418,7 @@ function lerpPose(a: Pose, b: Pose, w: number): Pose {
411
418
  }
412
419
 
413
420
  /** State `si`'s pose `local` ms in: its clip, or its 1D blend at the current value. */
414
- function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips: Clips, reduced: boolean): Pose {
421
+ function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips: Clips, reduced: boolean, underneath: Readonly<Record<string, number>> = {}): Pose {
415
422
  'worklet';
416
423
  const st = L.states[si]!;
417
424
  if (!st.keys) {
@@ -430,7 +437,7 @@ function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips:
430
437
  if (v <= keys[i]![0]) {
431
438
  const a = keys[i - 1]!;
432
439
  const b = keys[i]!;
433
- return lerpPose(at(a), at(b), (v - a[0]) / (b[0] - a[0]));
440
+ return lerpPose(at(a), at(b), (v - a[0]) / (b[0] - a[0]), underneath);
434
441
  }
435
442
  }
436
443
  return at(keys[keys.length - 1]!);
@@ -449,9 +456,9 @@ function ease(kind: number, p: number): number {
449
456
  * What the machine draws at `t` (at or after `s.t`, before the next instant): every layer's pose, mixes applied, a later
450
457
  * layer's channel or part over an earlier one's.
451
458
  */
452
- export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: ClockRead, reduced = false): Pose {
459
+ export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: ClockRead, reduced = false, defaults?: Readonly<Record<string, number>>): Pose {
453
460
  'worklet';
454
- const channels: Record<string, number> = {};
461
+ const channels: Record<string, number> = { ...defaults };
455
462
  let parts: Record<string, PartBox> | undefined;
456
463
  for (let li = 0; li < c.layers.length; li++) {
457
464
  const L = c.layers[li]!;
@@ -463,16 +470,16 @@ export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: C
463
470
  const by = L.states[l.heldS]!.by;
464
471
  let vals = s.vals;
465
472
  if (by >= 0) { vals = s.vals.slice(); vals[by] = l.heldBy; }
466
- p = statePose(L, l.heldS, l.held, vals, clips, reduced);
473
+ p = statePose(L, l.heldS, l.held, vals, clips, reduced, channels);
467
474
  } else if (l.s < 0) {
468
475
  continue;
469
476
  } else {
470
- p = statePose(L, l.s, localMs(L, l, t, clock), s.vals, clips, reduced);
477
+ p = statePose(L, l.s, localMs(L, l, t, clock), s.vals, clips, reduced, channels);
471
478
  if (l.mixTr >= 0 && t < l.mixEnd && !reduced) {
472
479
  const from = L.states[l.mixFrom]!;
473
- const fromPose = statePose(L, l.mixFrom, sinceEntry(L, l.mixAt, l.mixCAt, t, clock) * from.speed, s.vals, clips, reduced);
480
+ const fromPose = statePose(L, l.mixFrom, sinceEntry(L, l.mixAt, l.mixCAt, t, clock) * from.speed, s.vals, clips, reduced, channels);
474
481
  const tr = L.trans[l.mixTr]!;
475
- p = lerpPose(fromPose, p, ease(tr.ease, (t - l.mixStart) / (l.mixEnd - l.mixStart)));
482
+ p = lerpPose(fromPose, p, ease(tr.ease, (t - l.mixStart) / (l.mixEnd - l.mixStart)), channels);
476
483
  }
477
484
  }
478
485
  for (const k of Object.keys(p.channels)) channels[k] = p.channels[k]!;