skia-motion-runtime 3.0.0 → 3.1.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.
@@ -1,106 +1,105 @@
1
1
  import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
- import type { ForwardedRef } from 'react';
3
- import { AppState, StyleSheet, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from 'react-native';
4
- import { Canvas, Picture, Skia, createPicture, type SkImage } from 'react-native-skia';
2
+ import type { ForwardedRef, ReactElement, RefAttributes } from 'react';
3
+ import { AppState, Pressable, StyleSheet, View, type LayoutChangeEvent, type ViewProps } from 'react-native';
4
+ import { Canvas, Picture, Skia, createPicture, type SkCanvas } from 'react-native-skia';
5
5
  import { useDerivedValue, type SharedValue } from 'react-native-reanimated';
6
- import { assetClips, assetMarkerEvents, parseAsset, type MotionAsset, type AssetMarkerEvent } from './asset';
7
- import { decodeAssetImages, drawAsset, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
8
- import { useMachine, type MachineHandle } from './useMachine';
9
- import type { Pose, StateEntry } from '../templates/motion/machine';
6
+ import { assetMarkerEvents, type AssetMarkerEvent, type AssetSemantic } from './asset';
7
+ import { drawAsset, type AssetImages, type DrawableAsset } from './asset-draw';
8
+ import { loadMotionAsset, type LoadedMotionAsset } from './asset-load';
9
+ import { fitAsset, type AssetLayoutOptions } from './asset-layout';
10
+ import { useMachine, type MachineHandle, type MachineInputs, type MachineValues } from './useMachine';
11
+ import type { Machine, Pose, StateEntry } from '../templates/motion/machine';
10
12
 
11
- export { parseAsset, type MotionAsset, type AssetMarkerEvent } from './asset';
13
+ export { parseAsset, parseAssetFile, selectArtboard, type MotionAsset, type MotionAssetFile, type AssetMarkerEvent } from './asset';
12
14
 
13
- let nextAssetKey = 0;
15
+ export { loadMotionAsset, preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
16
+ export { useMotionAsset, type MotionAssetOptions, type MotionAssetSource, type MotionAssetResult } from './useMotionAsset';
17
+ export type { AssetFit, AssetAnchor } from './asset-layout';
14
18
 
15
- export type LoadedMotionAsset = Readonly<{
16
- key: number;
17
- machine: MotionAsset['machine'];
18
- markers: MotionAsset['markers'];
19
- drawing: DrawableAsset;
20
- images: AssetImages;
21
- clips: ReturnType<typeof assetClips>;
22
- }>;
23
-
24
- /** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
25
- export function loadMotionAsset(source: string): LoadedMotionAsset {
26
- const asset = parseAsset(source);
27
- const images = decodeAssetImages(asset);
28
- return {
29
- key: nextAssetKey++,
30
- machine: asset.machine,
31
- markers: asset.markers,
32
- drawing: prepareAssetDrawing(asset, images),
33
- images,
34
- clips: assetClips(asset),
35
- };
36
- }
37
-
38
- /**
39
- * Prepare a file before mounting it. Skia versions with asynchronous raster decoding perform
40
- * that work off the JS thread. Upload is opt-in and can retain textures until the file is released.
41
- */
42
- export async function preloadMotionAsset(
43
- source: string | LoadedMotionAsset,
44
- { uploadImages = false }: { uploadImages?: boolean } = {},
45
- ): Promise<LoadedMotionAsset> {
46
- const loaded = typeof source === 'string' ? loadMotionAsset(source) : source;
47
- const warmed = new Map<SkImage, SkImage>();
48
- const images: [string, SkImage][] = [];
49
- let changed = false;
50
- for (const [name, image] of Object.entries(loaded.images)) {
51
- let ready = warmed.get(image);
52
- if (!ready) {
53
- // Neither method is available at the 3.0 peer dependency floor.
54
- const preloadable = image as SkImage & { makeRasterImage?: () => Promise<SkImage> };
55
- ready = await preloadable.makeRasterImage?.() ?? image;
56
- if (uploadImages) {
57
- const uploadable = ready as SkImage & { makeTextureImage?: () => SkImage };
58
- try {
59
- ready = uploadable.makeTextureImage?.() ?? ready;
60
- } catch {
61
- // A reduced or unsupported backend can still upload the raster image when drawn.
62
- }
63
- }
64
- warmed.set(image, ready);
65
- }
66
- images.push([name, ready]);
67
- changed ||= ready !== image;
68
- }
69
- if (!warmed.size) return loaded;
70
- const ready = Object.fromEntries(images);
71
- return { ...loaded, images: ready, drawing: changed ? rebindAssetMeshShaders(loaded.drawing, ready) : loaded.drawing };
72
- }
19
+ export type MotionBindings = { values: NonNullable<Machine['values']>; markers: string };
20
+ export type MotionAudioCue = { name: string; source: string; marker: AssetMarkerEvent };
21
+ export type MotionSharedNumbers = Readonly<Record<string, SharedValue<number>>>;
22
+ type BoundMachine<B extends MotionBindings> = Omit<Machine, 'values'> & { values: B['values'] };
23
+ type BoundValues<B extends MotionBindings> = MachineValues<BoundMachine<B>>;
73
24
 
74
- export type MotionPlayerHandle = Pick<MachineHandle, 'set' | 'fire' | 'setOnUI' | 'readOnUI'>;
25
+ export type MotionPlayerHandle<B extends MotionBindings = MotionBindings> = Pick<
26
+ MachineHandle<BoundMachine<B>>, 'set' | 'setValues' | 'fire' | 'setOnUI' | 'readOnUI'
27
+ >;
75
28
 
76
- export type MotionPlayerProps = {
29
+ export type MotionPlayerProps<B extends MotionBindings = MotionBindings> = Pick<ViewProps,
30
+ 'style' | 'testID' | 'accessible' | 'accessibilityRole' | 'accessibilityLabel' |
31
+ 'accessibilityHint' | 'accessibilityValue' | 'accessibilityState' |
32
+ 'accessibilityActions' | 'onAccessibilityAction'
33
+ > & AssetLayoutOptions & {
77
34
  source: string | LoadedMotionAsset;
35
+ artboard?: string;
78
36
  width?: number;
79
37
  height?: number;
80
38
  live?: boolean;
81
39
  reduced?: boolean;
82
- style?: StyleProp<ViewStyle>;
83
- onMarker?: (marker: AssetMarkerEvent) => void;
40
+ /** Cap passive animation updates. Host writes still take effect on the next display frame. */
41
+ frameRate?: number;
42
+ /** Author-declared clocks in milliseconds. Layers use time since state entry. */
43
+ clocks?: MotionSharedNumbers;
44
+ /** Channel overrides sampled on the UI thread when drawing. */
45
+ channels?: MotionSharedNumbers;
46
+ initialValues?: MachineInputs<BoundMachine<B>>;
47
+ observeValues?: readonly Extract<keyof BoundValues<B>, string>[];
48
+ onValuesChange?: (values: BoundValues<B>) => void;
49
+ onMarker?: (marker: AssetMarkerEvent & { name: B['markers'] }) => void;
50
+ onAudio?: (cue: MotionAudioCue) => void;
51
+ semantics?: boolean;
84
52
  };
85
53
 
86
54
  type LoadedProps = Omit<MotionPlayerProps, 'source'> & { loaded: LoadedMotionAsset; playerRef: ForwardedRef<MotionPlayerHandle> };
87
55
 
88
- function AssetPicture({ drawing, images, pose, width, height }: {
56
+ function readChannels(pose: Pose, channels?: MotionSharedNumbers) {
57
+ 'worklet';
58
+ if (!channels) return pose.channels;
59
+ const values = { ...pose.channels };
60
+ for (const [name, shared] of Object.entries(channels)) {
61
+ const value = shared.value;
62
+ if (Number.isFinite(value)) values[name] = value;
63
+ }
64
+ return values;
65
+ }
66
+
67
+ function AssetPicture({ drawing, images, pose, snapshot, readOnUI, width, height, layout, channels }: {
89
68
  drawing: DrawableAsset;
90
69
  images: AssetImages;
91
70
  pose: SharedValue<Pose>;
71
+ snapshot?: MachineHandle['snapshot'];
72
+ readOnUI: MachineHandle['readOnUI'];
92
73
  width: number;
93
74
  height: number;
75
+ layout: AssetLayoutOptions;
76
+ channels?: MotionSharedNumbers;
94
77
  }) {
95
- const picture = useDerivedValue(() => createPicture(
96
- (canvas) => drawAsset(canvas, drawing, pose.value.channels, width, height, images),
97
- Skia.XYWHRect(0, 0, width, height),
98
- ), [drawing, images, pose, width, height]);
78
+ const picture = useDerivedValue(() => {
79
+ // The mapper subscribes to captured shared values, and readOnUI hides its snapshot.
80
+ void snapshot?.value;
81
+ const values: Record<string, string> = {};
82
+ for (const name of drawing.textBindings ?? []) {
83
+ const value = readOnUI(name);
84
+ if (typeof value === 'string') values[name] = value;
85
+ }
86
+ return createPicture(
87
+ (canvas) => drawAsset(canvas, drawing, readChannels(pose.value, channels), width, height, images, values, layout),
88
+ Skia.XYWHRect(0, 0, width, height),
89
+ );
90
+ });
99
91
  return <Picture picture={picture} />;
100
92
  }
101
93
 
102
- function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style, onMarker }: LoadedProps) {
94
+ function LoadedPlayer({
95
+ loaded, playerRef, width, height, live, reduced, frameRate, clocks, channels, fit, alignment, style, onMarker, onAudio,
96
+ initialValues, observeValues, onValuesChange, semantics = true, ...viewProps
97
+ }: LoadedProps) {
103
98
  const { markers, drawing, images, clips } = loaded;
99
+ for (const name of Object.keys(channels ?? {})) {
100
+ if (!Object.hasOwn(drawing.channels, name)) throw new Error(`Unknown motion channel "${name}"`);
101
+ }
102
+ const layout = useMemo(() => ({ fit, alignment }), [fit, alignment]);
104
103
  const [viewport, setViewport] = useState({ width: 0, height: 0 });
105
104
  const onLayout = useCallback(({ nativeEvent }: LayoutChangeEvent) => {
106
105
  const { width, height } = nativeEvent.layout;
@@ -113,25 +112,62 @@ function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style,
113
112
  return () => subscription.remove();
114
113
  }, []);
115
114
  const markerCallback = useRef(onMarker);
115
+ const audioCallback = useRef(onAudio);
116
116
  useEffect(() => {
117
117
  markerCallback.current = onMarker;
118
- return () => { markerCallback.current = undefined; };
119
- }, [onMarker]);
118
+ audioCallback.current = onAudio;
119
+ return () => { markerCallback.current = audioCallback.current = undefined; };
120
+ }, [onMarker, onAudio]);
120
121
  const onStateEntries = useCallback((entries: StateEntry[]) => {
121
- for (const marker of assetMarkerEvents(loaded, entries)) markerCallback.current?.(marker);
122
+ for (const marker of assetMarkerEvents(loaded, entries)) {
123
+ if (marker.audio) {
124
+ const source = loaded.audio?.[marker.audio];
125
+ if (source) audioCallback.current?.({ name: marker.audio, source, marker });
126
+ }
127
+ markerCallback.current?.(marker);
128
+ }
122
129
  }, [loaded]);
130
+ const semanticNames = useMemo(() => {
131
+ const names = new Set<string>();
132
+ if (semantics) for (const entry of loaded.semantics ?? []) {
133
+ if (typeof entry.label !== 'string') names.add(entry.label.value);
134
+ }
135
+ return names;
136
+ }, [loaded, semantics]);
137
+ const watched = useMemo(() => [...new Set([...(observeValues ?? []), ...semanticNames])], [observeValues, semanticNames]);
138
+ const [labels, setLabels] = useState<Record<string, string>>({});
139
+ const valuesCallback = useRef(onValuesChange);
140
+ useEffect(() => {
141
+ valuesCallback.current = onValuesChange;
142
+ return () => { valuesCallback.current = undefined; };
143
+ }, [onValuesChange]);
144
+ const reportValues = useCallback((values: BoundValues<MotionBindings>) => {
145
+ const labelChanges: Record<string, string> = {};
146
+ const appChanges: BoundValues<MotionBindings> = {};
147
+ for (const [name, value] of Object.entries(values)) {
148
+ if (observeValues?.includes(name)) appChanges[name] = value;
149
+ if (semanticNames.has(name) && typeof value === 'string') labelChanges[name] = value;
150
+ }
151
+ if (Object.keys(labelChanges).length) setLabels((previous) => ({ ...previous, ...labelChanges }));
152
+ if (Object.keys(appChanges).length) valuesCallback.current?.(appChanges);
153
+ }, [observeValues, semanticNames]);
123
154
  const machine = useMachine(loaded.machine, clips, {
124
155
  live: measured && foreground && (live ?? true),
125
156
  reduced,
126
- onStateEntries: markers?.length && onMarker ? onStateEntries : undefined,
157
+ frameRate,
158
+ clocks,
159
+ onStateEntries: markers?.length && (onMarker || onAudio) ? onStateEntries : undefined,
160
+ initialValues,
161
+ observeValues: watched,
162
+ onValuesChange: onValuesChange || semanticNames.size ? reportValues : undefined,
127
163
  });
128
164
  useImperativeHandle(playerRef, () => ({
129
- set: machine.set, fire: machine.fire, setOnUI: machine.setOnUI, readOnUI: machine.readOnUI,
130
- }), [machine.set, machine.fire, machine.setOnUI, machine.readOnUI]);
165
+ set: machine.set, setValues: machine.setValues, fire: machine.fire, setOnUI: machine.setOnUI, readOnUI: machine.readOnUI,
166
+ }), [machine.set, machine.setValues, machine.fire, machine.setOnUI, machine.readOnUI]);
131
167
  const hostStyle = StyleSheet.flatten(style);
132
168
  const grows = (hostStyle?.flex ?? 0) > 0 || (hostStyle?.flexGrow ?? 0) > 0;
133
169
  const hasSize = (width ?? hostStyle?.width) != null || (height ?? hostStyle?.height) != null;
134
- const defaults: ViewStyle | undefined = grows ? undefined : {
170
+ const defaults: ViewProps['style'] = grows ? undefined : {
135
171
  aspectRatio: drawing.artboard.width / drawing.artboard.height,
136
172
  ...(hasSize ? {} : { width: '100%' }),
137
173
  };
@@ -139,20 +175,89 @@ function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style,
139
175
  ...(width !== undefined && { width }),
140
176
  ...(height !== undefined && { height }),
141
177
  };
142
- // Measure a regular View. Early Skia v3 releases don't report Canvas onLayout on native.
178
+ const entries = measured && semantics ? loaded.semantics ?? [] : [];
179
+ const regions = entries.map((entry) => {
180
+ const input = typeof entry.label === 'string' ? undefined : entry.label.value;
181
+ const value = input === undefined ? entry.label : labels[input] ?? initialValues?.[input] ?? loaded.machine.values?.[input]?.default;
182
+ return <SemanticRegion key={entry.name} entry={entry} label={typeof value === 'string' ? value : ''}
183
+ artboard={drawing.artboard} viewport={viewport} layout={layout} fire={machine.fire} />;
184
+ });
185
+ // Mount the native canvas while the regular View measures its first viewport.
143
186
  return (
144
- <View style={[defaults, style, explicitSize]} onLayout={onLayout}>
145
- {measured && (
146
- <Canvas style={StyleSheet.absoluteFill}>
147
- <AssetPicture drawing={drawing} images={images} pose={machine.pose} width={viewport.width} height={viewport.height} />
148
- </Canvas>
149
- )}
187
+ <View {...viewProps} style={[defaults, style, explicitSize]} onLayout={onLayout}>
188
+ <Canvas style={StyleSheet.absoluteFill}>
189
+ {measured && <AssetPicture drawing={drawing} images={images} pose={machine.pose} readOnUI={machine.readOnUI}
190
+ snapshot={drawing.textBindings?.length ? machine.snapshot : undefined}
191
+ width={viewport.width} height={viewport.height} layout={layout} channels={channels} />}
192
+ </Canvas>
193
+ {regions}
150
194
  </View>
151
195
  );
152
196
  }
153
197
 
154
- export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, ...props }, ref) {
198
+ function SemanticRegion({ entry, label, artboard, viewport, layout, fire }: {
199
+ entry: AssetSemantic; label: string; artboard: { width: number; height: number };
200
+ viewport: { width: number; height: number }; layout: AssetLayoutOptions; fire: (name: string) => void;
201
+ }) {
202
+ const { scale, offsetX, offsetY } = fitAsset(artboard, viewport.width, viewport.height, layout);
203
+ const [x, y, width, height] = entry.bounds;
204
+ const left = Math.max(0, (x + offsetX) * scale);
205
+ const top = Math.max(0, (y + offsetY) * scale);
206
+ const right = Math.min(viewport.width, (x + offsetX + width) * scale);
207
+ const bottom = Math.min(viewport.height, (y + offsetY + height) * scale);
208
+ if (right <= left || bottom <= top || !label) return null;
209
+ const props = {
210
+ accessible: true,
211
+ accessibilityRole: entry.role,
212
+ accessibilityLabel: label,
213
+ style: { position: 'absolute' as const, left, top, width: right - left, height: bottom - top },
214
+ };
215
+ const trigger = entry.trigger;
216
+ return trigger ? <Pressable {...props} onPress={() => fire(trigger)} /> : <View {...props} pointerEvents="none" />;
217
+ }
218
+
219
+ export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, artboard, ...props }, ref) {
155
220
  // The inner hook owns one machine snapshot per loaded file. An updated file starts at t=0.
156
- const loaded = useMemo(() => typeof source === 'string' ? loadMotionAsset(source) : source, [source]);
221
+ const loaded = useMemo(() => typeof source === 'string' ? loadMotionAsset(source, { artboard }) : source, [source, artboard]);
157
222
  return <LoadedPlayer key={loaded.key} loaded={loaded} playerRef={ref} {...props} />;
158
- });
223
+ }) as <B extends MotionBindings = MotionBindings>(props: MotionPlayerProps<B> & RefAttributes<MotionPlayerHandle<B>>) => ReactElement;
224
+
225
+ export type MotionClipOptions = AssetLayoutOptions & {
226
+ width: number;
227
+ height: number;
228
+ reduced?: boolean;
229
+ channels?: MotionSharedNumbers;
230
+ text?: Readonly<Record<string, string>>;
231
+ };
232
+
233
+ /** Sample one named clip at absolute local time and paint into the supplied Skia canvas. */
234
+ export function drawMotionClip(
235
+ canvas: SkCanvas, asset: LoadedMotionAsset, name: string, timeMs: number, options: MotionClipOptions,
236
+ ): void {
237
+ 'worklet';
238
+ if (!Object.hasOwn(asset.clips, name)) throw new Error(`Unknown motion clip "${name}"`);
239
+ const clip = asset.clips[name]!;
240
+ const time = options.reduced ? clip.reducedAt ?? clip.ms
241
+ : Math.max(0, Math.min(clip.ms, Number.isFinite(timeMs) ? timeMs : 0));
242
+ const text: Record<string, string> = {};
243
+ for (const key of asset.drawing.textBindings ?? []) {
244
+ const value = options.text?.[key] ?? asset.machine.values?.[key]?.default;
245
+ if (typeof value === 'string') text[key] = value;
246
+ }
247
+ drawAsset(canvas, asset.drawing, readChannels(clip.play(time), options.channels),
248
+ options.width, options.height, asset.images, text, options);
249
+ }
250
+
251
+ /** Compose a host-controlled clip inside an existing Skia Canvas. */
252
+ export function MotionPicture({ asset, clip, timeMs, ...options }: MotionClipOptions & {
253
+ asset: LoadedMotionAsset;
254
+ clip: string;
255
+ timeMs: SharedValue<number>;
256
+ }) {
257
+ if (!Object.hasOwn(asset.clips, clip)) throw new Error(`Unknown motion clip "${clip}"`);
258
+ const picture = useDerivedValue(() => createPicture(
259
+ (canvas) => drawMotionClip(canvas, asset, clip, timeMs.value, options),
260
+ Skia.XYWHRect(0, 0, options.width, options.height),
261
+ ));
262
+ return <Picture picture={picture} />;
263
+ }
@@ -15,6 +15,7 @@ import {
15
15
  import { assertRuntimeVersion } from './version';
16
16
 
17
17
  declare const __DEV__: boolean;
18
+ const noClocks: Record<string, SharedValue<number>> = {};
18
19
 
19
20
  /** Dev-only timing probe (skac docs app): frame timestamps, in ms, of the frame that applied a write and of the first frame that drew something different after it. */
20
21
  export type MachineProbe = { onWrite?: (frameMs: number) => void; onChanged?: (frameMs: number) => void };
@@ -24,11 +25,18 @@ export type MachineOptions = {
24
25
  live?: boolean;
25
26
  /** Overrides the system's reduced-motion setting: once-clips show their end, loops their start. */
26
27
  reduced?: boolean;
27
- /** Named clocks the machine's layers read, as shared values in ms (Word Quran passes its ambient phase × 64000). */
28
+ /** Target maximum cadence for passive frame-clock sampling. */
29
+ frameRate?: number;
30
+ /** Host clocks in milliseconds, keyed by the machine's declared clock names. */
28
31
  clocks?: Record<string, SharedValue<number>>;
29
32
  probe?: MachineProbe;
30
33
  /** Entries after initialization, in machine order. Delivered on the React Native thread. */
31
34
  onStateEntries?: (entries: StateEntry[]) => void;
35
+ /** Host values applied together before the first state is selected. */
36
+ initialValues?: Readonly<Partial<Record<string, Literal>>>;
37
+ /** Reports initial and changed values for the named properties on the React Native thread. */
38
+ observeValues?: readonly string[];
39
+ onValuesChange?: (values: Record<string, Literal>) => void;
32
40
  /** The skac version that wrote the exported machine module. */
33
41
  exportedBy?: string;
34
42
  };
@@ -41,14 +49,27 @@ type TriggerName<V> = string extends keyof V ? string : ValueName<{
41
49
  }>;
42
50
  type WriteValue<V> = V extends { type: 'boolean' } ? boolean
43
51
  : V extends { type: 'number' } ? number
52
+ : V extends { type: 'string' } ? string
44
53
  : V extends { type: 'enum'; options: readonly (infer O extends string)[] } ? O
45
54
  : V extends { type: 'trigger' } ? true : Literal;
46
55
 
56
+ type StoredName<V> = ValueName<{ [K in keyof V as V[K] extends { type: 'trigger' } ? never : K]: V[K] }>;
57
+ export type MachineInputs<M extends Machine> = Partial<{
58
+ [K in Extract<StoredName<Values<M>>, WritableName<Values<M>>>]: WriteValue<Values<M>[K]>;
59
+ }>;
60
+ export type MachineValues<M extends Machine> = Partial<{
61
+ [K in StoredName<Values<M>>]: WriteValue<Values<M>[K]>;
62
+ }>;
63
+
47
64
  export type MachineHandle<M extends Machine = Machine> = {
48
65
  /** What to draw: channels and part boxes. Read it in a derived value or a Skia picture; it changes only when the drawing does. */
49
66
  pose: SharedValue<Pose>;
67
+ /** Shared state dependency for consumers that draw stored values. */
68
+ snapshot: Readonly<Pick<SharedValue<Snapshot>, 'value'>>;
50
69
  /** Write a value from JavaScript; it applies at the next frame. */
51
70
  set: <K extends WritableName<Values<M>>>(name: K, to: WriteValue<Values<M>[NoInfer<K>]>) => void;
71
+ /** Apply these values together at the next frame. */
72
+ setValues: (values: MachineInputs<M>) => void;
52
73
  /** Fire a trigger from JavaScript. */
53
74
  fire: (name: TriggerName<Values<M>>) => void;
54
75
  /** Write a value from the UI thread (a gesture worklet); it applies at the next frame. */
@@ -96,9 +117,12 @@ function samePose(left: Pose, right: Pose): boolean {
96
117
  /** Play `machine` with its `clips`. The machine and clips must be stable (module constants), as an exported scene's are. */
97
118
  export function useMachine<const M extends Machine>(machine: M, clips: Clips, options: MachineOptions = {}): MachineHandle<M> {
98
119
  if (__DEV__ && options.exportedBy !== undefined) assertRuntimeVersion(options.exportedBy);
99
- const { live = true, clocks = {}, probe, onStateEntries } = options;
120
+ const { live = true, clocks = noClocks, probe, onStateEntries, onValuesChange, observeValues } = options;
100
121
  const systemReduced = useReducedMotion();
101
122
  const reduced = options.reduced ?? systemReduced;
123
+ const rate = options.frameRate;
124
+ if (rate !== undefined && (!Number.isFinite(rate) || rate <= 0)) throw new Error('useMachine: frameRate must be positive');
125
+ const frameInterval = rate === undefined ? 0 : 1000 / rate;
102
126
  const compiled = useMemo(() => compile(machine, clips), [machine, clips]);
103
127
  // The clocks its layers run on: the pose reads only these, and each must be passed, since a missing one would read
104
128
  // machine time, which stops while the machine rests.
@@ -107,14 +131,15 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
107
131
  if (missing.length) throw new Error(`useMachine: layers run on clock${missing.length > 1 ? 's' : ''} ${missing.join(', ')}; pass clocks={{ ${missing.join(', ')} }} as shared values in ms`);
108
132
 
109
133
  // The snapshot at machine time `ms`; writes wait in `pending` until the next frame stamps and applies them.
110
- const read: ClockRead = (name: string, t: number) => {
134
+ const read = useCallback<ClockRead>((name, t) => {
111
135
  'worklet';
112
136
  const clock = clocks[name];
113
137
  return clock ? clock.value : t;
114
- };
138
+ }, [clocks]);
115
139
  // Entered at mount, at machine time 0, with each named clock's reading now.
116
- const first = useMemo(() => advance(compiled, start(compiled), 0, [], read), [compiled]); // eslint-disable-line react-hooks/exhaustive-deps
140
+ const first = useMemo(() => advance(compiled, start(compiled), 0, valueWrites(compiled, options.initialValues), read), [compiled]); // eslint-disable-line react-hooks/exhaustive-deps
117
141
  const ms = useSharedValue(0);
142
+ const elapsed = useSharedValue(0);
118
143
  const snapshot = useSharedValue<Snapshot>(first);
119
144
  const pending = useSharedValue<Write[]>([]);
120
145
  const lastChannels = useSharedValue('');
@@ -123,6 +148,26 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
123
148
  const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced), [first]); // eslint-disable-line react-hooks/exhaustive-deps
124
149
  const pose = useSharedValue<Pose>(firstPose);
125
150
 
151
+ const observed = useMemo(() => Array.from(new Set(observeValues), (name) => {
152
+ if (!Object.hasOwn(compiled.index, name) || compiled.values[compiled.index[name]!]!.type === 'trigger') {
153
+ throw new Error(`useMachine: "${name}" is not a stored value`);
154
+ }
155
+ return { name, index: compiled.index[name]! };
156
+ }), [compiled, observeValues]);
157
+
158
+ useAnimatedReaction(
159
+ () => {
160
+ if (!onValuesChange || !observed.length) return null;
161
+ const values = snapshot.value.vals;
162
+ return Object.fromEntries(observed.map(({ name, index }) => [name, values[index]!]));
163
+ },
164
+ (next, previous) => {
165
+ if (!next || !onValuesChange) return;
166
+ const changes = Object.entries(next).filter(([name, value]) => previous?.[name] !== value);
167
+ if (changes.length) scheduleOnRN(onValuesChange, Object.fromEntries(changes));
168
+ },
169
+ );
170
+
126
171
  useAnimatedReaction(
127
172
  () => {
128
173
  if (!liveNow.value) return undefined;
@@ -141,7 +186,12 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
141
186
  const writes = pending.value;
142
187
  // The first frame after a wake has no previous frame (dt 0); advance takes writes after the snapshot's time only,
143
188
  // so writes waiting then are stamped a hair later, or they would be lost.
144
- const dt = frame.timeSincePreviousFrame ?? 0;
189
+ const dt = elapsed.value + (frame.timeSincePreviousFrame ?? 0);
190
+ if (!writes.length && frameInterval > 0 && dt + 0.1 < frameInterval) {
191
+ elapsed.value = dt;
192
+ return;
193
+ }
194
+ if (frameInterval > 0) elapsed.value = 0;
145
195
  const t = ms.value + (writes.length ? Math.max(dt, 0.001) : dt);
146
196
  ms.value = t;
147
197
  if (writes.length) {
@@ -160,7 +210,7 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
160
210
  }
161
211
  }
162
212
  if (pending.value.length === 0 && settled(compiled, next, read, reduced).frame) scheduleOnRN(sleep);
163
- }, [compiled, clips, reduced, probe, onStateEntries]);
213
+ }, [compiled, clips, reduced, probe, onStateEntries, frameInterval, read]);
164
214
 
165
215
  const frames = useFrameCallback(tick, false);
166
216
  // The callback is switched from JavaScript only: switching it from a worklet makes a synchronous remote call that
@@ -174,18 +224,27 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
174
224
  liveNow.value = live;
175
225
  frames.setActive(live);
176
226
  }, [frames, live, liveNow, reduced]);
227
+ useEffect(() => { elapsed.value = 0; }, [elapsed, frameInterval]);
177
228
 
178
- const setOnUI = useCallback((name: string, to: Literal) => {
229
+ const enqueue = useCallback((writes: Write[]) => {
179
230
  'worklet';
180
- pending.value = [...pending.value, { at: 0, value: name, to }];
231
+ pending.value = [...pending.value, ...writes];
181
232
  scheduleOnRN(wake);
182
233
  }, [pending, wake]);
234
+ const setOnUI = useCallback((name: string, to: Literal) => {
235
+ 'worklet';
236
+ enqueue([{ at: 0, value: name, to }]);
237
+ }, [enqueue]);
183
238
  const set = useCallback((name: string, to: Literal) => {
184
239
  const problem = writeProblem(compiled, name, to);
185
240
  if (problem) throw new Error(`useMachine set: ${problem}`);
186
241
  // The UI worklet queues the wake after any sleep the tick has already queued on JavaScript.
187
242
  scheduleOnUI(setOnUI, name, to);
188
243
  }, [compiled, setOnUI]);
244
+ const setValues = useCallback((values: MachineInputs<M>) => {
245
+ const writes = valueWrites(compiled, values);
246
+ if (writes.length) scheduleOnUI(enqueue, writes);
247
+ }, [compiled, enqueue]);
189
248
  const fire = useCallback((name: string) => set(name, true), [set]);
190
249
  const tapOnUI = useCallback((x: number, y: number) => {
191
250
  'worklet';
@@ -198,9 +257,20 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
198
257
  }, [compiled, pose, snapshot, pending, wake]);
199
258
  const readOnUI = useCallback((name: string) => {
200
259
  'worklet';
201
- const i = compiled.index[name];
202
- return i === undefined ? undefined : snapshot.value.vals[i];
260
+ return Object.hasOwn(compiled.index, name) ? snapshot.value.vals[compiled.index[name]!] : undefined;
203
261
  }, [compiled, snapshot]);
204
262
 
205
- return { pose, set, fire, setOnUI, tapOnUI, readOnUI };
263
+ return { pose, snapshot, set, setValues, fire, setOnUI, tapOnUI, readOnUI };
264
+ }
265
+
266
+ function valueWrites(compiled: ReturnType<typeof compile>, values?: Readonly<Partial<Record<string, Literal>>>): Write[] {
267
+ return Object.entries(values ?? {}).flatMap(([name, to]) => {
268
+ if (to === undefined) return [];
269
+ const problem = writeProblem(compiled, name, to);
270
+ if (problem) throw new Error(`useMachine values: ${problem}`);
271
+ if (compiled.values[compiled.index[name]!]!.type === 'trigger') {
272
+ throw new Error(`useMachine values: use fire for "${name}"`);
273
+ }
274
+ return [{ at: 0, value: name, to }];
275
+ });
206
276
  }
@@ -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
+ }