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.
- package/package.json +34 -13
- package/runtime/asset-draw.ts +136 -32
- package/runtime/asset-image.ts +3 -20
- package/runtime/asset-layout.ts +27 -0
- package/runtime/asset-load.ts +70 -0
- package/runtime/asset.ts +285 -20
- package/runtime/base64.ts +19 -0
- package/runtime/expo-audio.ts +72 -0
- package/runtime/expo.ts +16 -0
- package/runtime/machine-schema.js +3 -3
- package/runtime/mobile.tsx +215 -96
- package/runtime/useMachine.ts +87 -15
- package/runtime/useMotionAsset.ts +107 -0
- package/templates/motion/machine.ts +21 -14
package/runtime/mobile.tsx
CHANGED
|
@@ -1,106 +1,117 @@
|
|
|
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
|
|
4
|
-
import { Canvas, Picture, Skia, createPicture, type
|
|
5
|
-
import { useDerivedValue, type SharedValue } from 'react-native-reanimated';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import
|
|
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
|
+
import { useAnimatedReaction, useDerivedValue, useSharedValue, type SharedValue } from 'react-native-reanimated';
|
|
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
|
-
|
|
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
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
images: AssetImages;
|
|
21
|
-
clips: ReturnType<typeof assetClips>;
|
|
22
|
-
}>;
|
|
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>>;
|
|
23
24
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
}
|
|
25
|
+
export type MotionPlayerHandle<B extends MotionBindings = MotionBindings> = Pick<
|
|
26
|
+
MachineHandle<BoundMachine<B>>, 'set' | 'setValues' | 'fire' | 'setOnUI' | 'readOnUI'
|
|
27
|
+
>;
|
|
37
28
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
}
|
|
73
|
-
|
|
74
|
-
export type MotionPlayerHandle = Pick<MachineHandle, 'set' | 'fire' | 'setOnUI' | 'readOnUI'>;
|
|
75
|
-
|
|
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
|
-
|
|
83
|
-
|
|
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
|
|
56
|
+
function readChannels(base: Pose['channels'], channels?: MotionSharedNumbers) {
|
|
57
|
+
'worklet';
|
|
58
|
+
if (!channels) return base;
|
|
59
|
+
const values = { ...base };
|
|
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, active }: {
|
|
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;
|
|
77
|
+
active: boolean;
|
|
94
78
|
}) {
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
79
|
+
const overrides = useSharedValue<Record<string, number> | undefined>(undefined);
|
|
80
|
+
useAnimatedReaction(
|
|
81
|
+
() => active ? readChannels({}, channels) : null,
|
|
82
|
+
(next, previous) => {
|
|
83
|
+
if (next === null) return;
|
|
84
|
+
const keys = Object.keys(next);
|
|
85
|
+
if (!previous || keys.length !== Object.keys(previous).length || keys.some((name) => next[name] !== previous[name])) {
|
|
86
|
+
overrides.value = next;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
);
|
|
90
|
+
const picture = useDerivedValue(() => {
|
|
91
|
+
// The mapper subscribes to captured shared values, and readOnUI hides its snapshot.
|
|
92
|
+
void snapshot?.value;
|
|
93
|
+
const values: Record<string, string> = {};
|
|
94
|
+
for (const name of drawing.textBindings ?? []) {
|
|
95
|
+
const value = readOnUI(name);
|
|
96
|
+
if (typeof value === 'string') values[name] = value;
|
|
97
|
+
}
|
|
98
|
+
return createPicture(
|
|
99
|
+
(canvas) => drawAsset(canvas, drawing, { ...pose.value.channels, ...overrides.value }, width, height, images, values, layout),
|
|
100
|
+
Skia.XYWHRect(0, 0, width, height),
|
|
101
|
+
);
|
|
102
|
+
});
|
|
99
103
|
return <Picture picture={picture} />;
|
|
100
104
|
}
|
|
101
105
|
|
|
102
|
-
function LoadedPlayer({
|
|
106
|
+
function LoadedPlayer({
|
|
107
|
+
loaded, playerRef, width, height, live, reduced, frameRate, clocks, channels, fit, alignment, style, onMarker, onAudio,
|
|
108
|
+
initialValues, observeValues, onValuesChange, semantics = true, ...viewProps
|
|
109
|
+
}: LoadedProps) {
|
|
103
110
|
const { markers, drawing, images, clips } = loaded;
|
|
111
|
+
for (const name of Object.keys(channels ?? {})) {
|
|
112
|
+
if (!Object.hasOwn(drawing.channels, name)) throw new Error(`Unknown motion channel "${name}"`);
|
|
113
|
+
}
|
|
114
|
+
const layout = useMemo(() => ({ fit, alignment }), [fit, alignment]);
|
|
104
115
|
const [viewport, setViewport] = useState({ width: 0, height: 0 });
|
|
105
116
|
const onLayout = useCallback(({ nativeEvent }: LayoutChangeEvent) => {
|
|
106
117
|
const { width, height } = nativeEvent.layout;
|
|
@@ -113,25 +124,64 @@ function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style,
|
|
|
113
124
|
return () => subscription.remove();
|
|
114
125
|
}, []);
|
|
115
126
|
const markerCallback = useRef(onMarker);
|
|
127
|
+
const audioCallback = useRef(onAudio);
|
|
116
128
|
useEffect(() => {
|
|
117
129
|
markerCallback.current = onMarker;
|
|
118
|
-
|
|
119
|
-
|
|
130
|
+
audioCallback.current = onAudio;
|
|
131
|
+
return () => { markerCallback.current = audioCallback.current = undefined; };
|
|
132
|
+
}, [onMarker, onAudio]);
|
|
120
133
|
const onStateEntries = useCallback((entries: StateEntry[]) => {
|
|
121
|
-
for (const marker of assetMarkerEvents(loaded, entries))
|
|
134
|
+
for (const marker of assetMarkerEvents(loaded, entries)) {
|
|
135
|
+
if (marker.audio) {
|
|
136
|
+
const source = loaded.audio?.[marker.audio];
|
|
137
|
+
if (source) audioCallback.current?.({ name: marker.audio, source, marker });
|
|
138
|
+
}
|
|
139
|
+
markerCallback.current?.(marker);
|
|
140
|
+
}
|
|
122
141
|
}, [loaded]);
|
|
142
|
+
const semanticNames = useMemo(() => {
|
|
143
|
+
const names = new Set<string>();
|
|
144
|
+
if (semantics) for (const entry of loaded.semantics ?? []) {
|
|
145
|
+
if (typeof entry.label !== 'string') names.add(entry.label.value);
|
|
146
|
+
}
|
|
147
|
+
return names;
|
|
148
|
+
}, [loaded, semantics]);
|
|
149
|
+
const watched = useMemo(() => [...new Set([...(observeValues ?? []), ...semanticNames])], [observeValues, semanticNames]);
|
|
150
|
+
const [labels, setLabels] = useState<Record<string, string>>({});
|
|
151
|
+
const valuesCallback = useRef(onValuesChange);
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
valuesCallback.current = onValuesChange;
|
|
154
|
+
return () => { valuesCallback.current = undefined; };
|
|
155
|
+
}, [onValuesChange]);
|
|
156
|
+
const reportValues = useCallback((values: BoundValues<MotionBindings>) => {
|
|
157
|
+
const labelChanges: Record<string, string> = {};
|
|
158
|
+
const appChanges: BoundValues<MotionBindings> = {};
|
|
159
|
+
for (const [name, value] of Object.entries(values)) {
|
|
160
|
+
if (observeValues?.includes(name)) appChanges[name] = value;
|
|
161
|
+
if (semanticNames.has(name) && typeof value === 'string') labelChanges[name] = value;
|
|
162
|
+
}
|
|
163
|
+
if (Object.keys(labelChanges).length) setLabels((previous) => ({ ...previous, ...labelChanges }));
|
|
164
|
+
if (Object.keys(appChanges).length) valuesCallback.current?.(appChanges);
|
|
165
|
+
}, [observeValues, semanticNames]);
|
|
166
|
+
const active = measured && foreground && (live ?? true);
|
|
123
167
|
const machine = useMachine(loaded.machine, clips, {
|
|
124
|
-
live:
|
|
168
|
+
live: active,
|
|
125
169
|
reduced,
|
|
126
|
-
|
|
170
|
+
frameRate,
|
|
171
|
+
clocks,
|
|
172
|
+
channelDefaults: drawing.channels,
|
|
173
|
+
onStateEntries: markers?.length && (onMarker || onAudio) ? onStateEntries : undefined,
|
|
174
|
+
initialValues,
|
|
175
|
+
observeValues: watched,
|
|
176
|
+
onValuesChange: onValuesChange || semanticNames.size ? reportValues : undefined,
|
|
127
177
|
});
|
|
128
178
|
useImperativeHandle(playerRef, () => ({
|
|
129
|
-
set: machine.set, fire: machine.fire, setOnUI: machine.setOnUI, readOnUI: machine.readOnUI,
|
|
130
|
-
}), [machine.set, machine.fire, machine.setOnUI, machine.readOnUI]);
|
|
179
|
+
set: machine.set, setValues: machine.setValues, fire: machine.fire, setOnUI: machine.setOnUI, readOnUI: machine.readOnUI,
|
|
180
|
+
}), [machine.set, machine.setValues, machine.fire, machine.setOnUI, machine.readOnUI]);
|
|
131
181
|
const hostStyle = StyleSheet.flatten(style);
|
|
132
182
|
const grows = (hostStyle?.flex ?? 0) > 0 || (hostStyle?.flexGrow ?? 0) > 0;
|
|
133
183
|
const hasSize = (width ?? hostStyle?.width) != null || (height ?? hostStyle?.height) != null;
|
|
134
|
-
const defaults:
|
|
184
|
+
const defaults: ViewProps['style'] = grows ? undefined : {
|
|
135
185
|
aspectRatio: drawing.artboard.width / drawing.artboard.height,
|
|
136
186
|
...(hasSize ? {} : { width: '100%' }),
|
|
137
187
|
};
|
|
@@ -139,20 +189,89 @@ function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style,
|
|
|
139
189
|
...(width !== undefined && { width }),
|
|
140
190
|
...(height !== undefined && { height }),
|
|
141
191
|
};
|
|
142
|
-
|
|
192
|
+
const entries = measured && semantics ? loaded.semantics ?? [] : [];
|
|
193
|
+
const regions = entries.map((entry) => {
|
|
194
|
+
const input = typeof entry.label === 'string' ? undefined : entry.label.value;
|
|
195
|
+
const value = input === undefined ? entry.label : labels[input] ?? initialValues?.[input] ?? loaded.machine.values?.[input]?.default;
|
|
196
|
+
return <SemanticRegion key={entry.name} entry={entry} label={typeof value === 'string' ? value : ''}
|
|
197
|
+
artboard={drawing.artboard} viewport={viewport} layout={layout} fire={machine.fire} />;
|
|
198
|
+
});
|
|
199
|
+
// Mount the native canvas while the regular View measures its first viewport.
|
|
143
200
|
return (
|
|
144
|
-
<View style={[defaults, style, explicitSize]} onLayout={onLayout}>
|
|
145
|
-
{
|
|
146
|
-
<
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
201
|
+
<View {...viewProps} style={[defaults, style, explicitSize]} onLayout={onLayout}>
|
|
202
|
+
<Canvas style={StyleSheet.absoluteFill}>
|
|
203
|
+
{measured && <AssetPicture drawing={drawing} images={images} pose={machine.pose} readOnUI={machine.readOnUI}
|
|
204
|
+
snapshot={drawing.textBindings?.length ? machine.snapshot : undefined}
|
|
205
|
+
width={viewport.width} height={viewport.height} layout={layout} channels={channels} active={active} />}
|
|
206
|
+
</Canvas>
|
|
207
|
+
{regions}
|
|
150
208
|
</View>
|
|
151
209
|
);
|
|
152
210
|
}
|
|
153
211
|
|
|
154
|
-
|
|
212
|
+
function SemanticRegion({ entry, label, artboard, viewport, layout, fire }: {
|
|
213
|
+
entry: AssetSemantic; label: string; artboard: { width: number; height: number };
|
|
214
|
+
viewport: { width: number; height: number }; layout: AssetLayoutOptions; fire: (name: string) => void;
|
|
215
|
+
}) {
|
|
216
|
+
const { scale, offsetX, offsetY } = fitAsset(artboard, viewport.width, viewport.height, layout);
|
|
217
|
+
const [x, y, width, height] = entry.bounds;
|
|
218
|
+
const left = Math.max(0, (x + offsetX) * scale);
|
|
219
|
+
const top = Math.max(0, (y + offsetY) * scale);
|
|
220
|
+
const right = Math.min(viewport.width, (x + offsetX + width) * scale);
|
|
221
|
+
const bottom = Math.min(viewport.height, (y + offsetY + height) * scale);
|
|
222
|
+
if (right <= left || bottom <= top || !label) return null;
|
|
223
|
+
const props = {
|
|
224
|
+
accessible: true,
|
|
225
|
+
accessibilityRole: entry.role,
|
|
226
|
+
accessibilityLabel: label,
|
|
227
|
+
style: { position: 'absolute' as const, left, top, width: right - left, height: bottom - top },
|
|
228
|
+
};
|
|
229
|
+
const trigger = entry.trigger;
|
|
230
|
+
return trigger ? <Pressable {...props} onPress={() => fire(trigger)} /> : <View {...props} pointerEvents="none" />;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, artboard, ...props }, ref) {
|
|
155
234
|
// 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]);
|
|
235
|
+
const loaded = useMemo(() => typeof source === 'string' ? loadMotionAsset(source, { artboard }) : source, [source, artboard]);
|
|
157
236
|
return <LoadedPlayer key={loaded.key} loaded={loaded} playerRef={ref} {...props} />;
|
|
158
|
-
});
|
|
237
|
+
}) as <B extends MotionBindings = MotionBindings>(props: MotionPlayerProps<B> & RefAttributes<MotionPlayerHandle<B>>) => ReactElement;
|
|
238
|
+
|
|
239
|
+
export type MotionClipOptions = AssetLayoutOptions & {
|
|
240
|
+
width: number;
|
|
241
|
+
height: number;
|
|
242
|
+
reduced?: boolean;
|
|
243
|
+
channels?: MotionSharedNumbers;
|
|
244
|
+
text?: Readonly<Record<string, string>>;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
/** Sample one named clip at absolute local time and paint into the supplied Skia canvas. */
|
|
248
|
+
export function drawMotionClip(
|
|
249
|
+
canvas: SkCanvas, asset: LoadedMotionAsset, name: string, timeMs: number, options: MotionClipOptions,
|
|
250
|
+
): void {
|
|
251
|
+
'worklet';
|
|
252
|
+
if (!Object.hasOwn(asset.clips, name)) throw new Error(`Unknown motion clip "${name}"`);
|
|
253
|
+
const clip = asset.clips[name]!;
|
|
254
|
+
const time = options.reduced ? clip.reducedAt ?? clip.ms
|
|
255
|
+
: Math.max(0, Math.min(clip.ms, Number.isFinite(timeMs) ? timeMs : 0));
|
|
256
|
+
const text: Record<string, string> = {};
|
|
257
|
+
for (const key of asset.drawing.textBindings ?? []) {
|
|
258
|
+
const value = options.text?.[key] ?? asset.machine.values?.[key]?.default;
|
|
259
|
+
if (typeof value === 'string') text[key] = value;
|
|
260
|
+
}
|
|
261
|
+
drawAsset(canvas, asset.drawing, readChannels(clip.play(time).channels, options.channels),
|
|
262
|
+
options.width, options.height, asset.images, text, options);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Compose a host-controlled clip inside an existing Skia Canvas. */
|
|
266
|
+
export function MotionPicture({ asset, clip, timeMs, ...options }: MotionClipOptions & {
|
|
267
|
+
asset: LoadedMotionAsset;
|
|
268
|
+
clip: string;
|
|
269
|
+
timeMs: SharedValue<number>;
|
|
270
|
+
}) {
|
|
271
|
+
if (!Object.hasOwn(asset.clips, clip)) throw new Error(`Unknown motion clip "${clip}"`);
|
|
272
|
+
const picture = useDerivedValue(() => createPicture(
|
|
273
|
+
(canvas) => drawMotionClip(canvas, asset, clip, timeMs.value, options),
|
|
274
|
+
Skia.XYWHRect(0, 0, options.width, options.height),
|
|
275
|
+
));
|
|
276
|
+
return <Picture picture={picture} />;
|
|
277
|
+
}
|
package/runtime/useMachine.ts
CHANGED
|
@@ -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,20 @@ 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
|
-
/**
|
|
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>>;
|
|
32
|
+
/** Resting values for channels that an animation does not key. */
|
|
33
|
+
channelDefaults?: Readonly<Record<string, number>>;
|
|
29
34
|
probe?: MachineProbe;
|
|
30
35
|
/** Entries after initialization, in machine order. Delivered on the React Native thread. */
|
|
31
36
|
onStateEntries?: (entries: StateEntry[]) => void;
|
|
37
|
+
/** Host values applied together before the first state is selected. */
|
|
38
|
+
initialValues?: Readonly<Partial<Record<string, Literal>>>;
|
|
39
|
+
/** Reports initial and changed values for the named properties on the React Native thread. */
|
|
40
|
+
observeValues?: readonly string[];
|
|
41
|
+
onValuesChange?: (values: Record<string, Literal>) => void;
|
|
32
42
|
/** The skac version that wrote the exported machine module. */
|
|
33
43
|
exportedBy?: string;
|
|
34
44
|
};
|
|
@@ -41,14 +51,27 @@ type TriggerName<V> = string extends keyof V ? string : ValueName<{
|
|
|
41
51
|
}>;
|
|
42
52
|
type WriteValue<V> = V extends { type: 'boolean' } ? boolean
|
|
43
53
|
: V extends { type: 'number' } ? number
|
|
54
|
+
: V extends { type: 'string' } ? string
|
|
44
55
|
: V extends { type: 'enum'; options: readonly (infer O extends string)[] } ? O
|
|
45
56
|
: V extends { type: 'trigger' } ? true : Literal;
|
|
46
57
|
|
|
58
|
+
type StoredName<V> = ValueName<{ [K in keyof V as V[K] extends { type: 'trigger' } ? never : K]: V[K] }>;
|
|
59
|
+
export type MachineInputs<M extends Machine> = Partial<{
|
|
60
|
+
[K in Extract<StoredName<Values<M>>, WritableName<Values<M>>>]: WriteValue<Values<M>[K]>;
|
|
61
|
+
}>;
|
|
62
|
+
export type MachineValues<M extends Machine> = Partial<{
|
|
63
|
+
[K in StoredName<Values<M>>]: WriteValue<Values<M>[K]>;
|
|
64
|
+
}>;
|
|
65
|
+
|
|
47
66
|
export type MachineHandle<M extends Machine = Machine> = {
|
|
48
67
|
/** 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
68
|
pose: SharedValue<Pose>;
|
|
69
|
+
/** Shared state dependency for consumers that draw stored values. */
|
|
70
|
+
snapshot: Readonly<Pick<SharedValue<Snapshot>, 'value'>>;
|
|
50
71
|
/** Write a value from JavaScript; it applies at the next frame. */
|
|
51
72
|
set: <K extends WritableName<Values<M>>>(name: K, to: WriteValue<Values<M>[NoInfer<K>]>) => void;
|
|
73
|
+
/** Apply these values together at the next frame. */
|
|
74
|
+
setValues: (values: MachineInputs<M>) => void;
|
|
52
75
|
/** Fire a trigger from JavaScript. */
|
|
53
76
|
fire: (name: TriggerName<Values<M>>) => void;
|
|
54
77
|
/** Write a value from the UI thread (a gesture worklet); it applies at the next frame. */
|
|
@@ -96,9 +119,12 @@ function samePose(left: Pose, right: Pose): boolean {
|
|
|
96
119
|
/** Play `machine` with its `clips`. The machine and clips must be stable (module constants), as an exported scene's are. */
|
|
97
120
|
export function useMachine<const M extends Machine>(machine: M, clips: Clips, options: MachineOptions = {}): MachineHandle<M> {
|
|
98
121
|
if (__DEV__ && options.exportedBy !== undefined) assertRuntimeVersion(options.exportedBy);
|
|
99
|
-
const { live = true, clocks =
|
|
122
|
+
const { live = true, clocks = noClocks, channelDefaults, probe, onStateEntries, onValuesChange, observeValues } = options;
|
|
100
123
|
const systemReduced = useReducedMotion();
|
|
101
124
|
const reduced = options.reduced ?? systemReduced;
|
|
125
|
+
const rate = options.frameRate;
|
|
126
|
+
if (rate !== undefined && (!Number.isFinite(rate) || rate <= 0)) throw new Error('useMachine: frameRate must be positive');
|
|
127
|
+
const frameInterval = rate === undefined ? 0 : 1000 / rate;
|
|
102
128
|
const compiled = useMemo(() => compile(machine, clips), [machine, clips]);
|
|
103
129
|
// The clocks its layers run on: the pose reads only these, and each must be passed, since a missing one would read
|
|
104
130
|
// machine time, which stops while the machine rests.
|
|
@@ -107,28 +133,49 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
|
|
|
107
133
|
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
134
|
|
|
109
135
|
// The snapshot at machine time `ms`; writes wait in `pending` until the next frame stamps and applies them.
|
|
110
|
-
const read
|
|
136
|
+
const read = useCallback<ClockRead>((name, t) => {
|
|
111
137
|
'worklet';
|
|
112
138
|
const clock = clocks[name];
|
|
113
139
|
return clock ? clock.value : t;
|
|
114
|
-
};
|
|
140
|
+
}, [clocks]);
|
|
115
141
|
// Entered at mount, at machine time 0, with each named clock's reading now.
|
|
116
|
-
const first = useMemo(() => advance(compiled, start(compiled), 0,
|
|
142
|
+
const first = useMemo(() => advance(compiled, start(compiled), 0, valueWrites(compiled, options.initialValues), read), [compiled]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
117
143
|
const ms = useSharedValue(0);
|
|
144
|
+
const elapsed = useSharedValue(0);
|
|
118
145
|
const snapshot = useSharedValue<Snapshot>(first);
|
|
119
146
|
const pending = useSharedValue<Write[]>([]);
|
|
120
147
|
const lastChannels = useSharedValue('');
|
|
121
148
|
const awaitingChange = useSharedValue(false);
|
|
122
149
|
const liveNow = useSharedValue(live);
|
|
123
|
-
const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced), [first]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
150
|
+
const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced, channelDefaults), [first]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
124
151
|
const pose = useSharedValue<Pose>(firstPose);
|
|
125
152
|
|
|
153
|
+
const observed = useMemo(() => Array.from(new Set(observeValues), (name) => {
|
|
154
|
+
if (!Object.hasOwn(compiled.index, name) || compiled.values[compiled.index[name]!]!.type === 'trigger') {
|
|
155
|
+
throw new Error(`useMachine: "${name}" is not a stored value`);
|
|
156
|
+
}
|
|
157
|
+
return { name, index: compiled.index[name]! };
|
|
158
|
+
}), [compiled, observeValues]);
|
|
159
|
+
|
|
160
|
+
useAnimatedReaction(
|
|
161
|
+
() => {
|
|
162
|
+
if (!onValuesChange || !observed.length) return null;
|
|
163
|
+
const values = snapshot.value.vals;
|
|
164
|
+
return Object.fromEntries(observed.map(({ name, index }) => [name, values[index]!]));
|
|
165
|
+
},
|
|
166
|
+
(next, previous) => {
|
|
167
|
+
if (!next || !onValuesChange) return;
|
|
168
|
+
const changes = Object.entries(next).filter(([name, value]) => previous?.[name] !== value);
|
|
169
|
+
if (changes.length) scheduleOnRN(onValuesChange, Object.fromEntries(changes));
|
|
170
|
+
},
|
|
171
|
+
);
|
|
172
|
+
|
|
126
173
|
useAnimatedReaction(
|
|
127
174
|
() => {
|
|
128
175
|
if (!liveNow.value) return undefined;
|
|
129
176
|
// Subscribe to the named clocks, including when the frame callback sleeps.
|
|
130
177
|
for (const n of clockNames) void clocks[n]!.value;
|
|
131
|
-
return poseAt(compiled, clips, snapshot.value, ms.value, read, reduced);
|
|
178
|
+
return poseAt(compiled, clips, snapshot.value, ms.value, read, reduced, channelDefaults);
|
|
132
179
|
},
|
|
133
180
|
(next) => {
|
|
134
181
|
// The reaction subscribes only to the prepare inputs. Updating its output cannot wake it again.
|
|
@@ -141,7 +188,12 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
|
|
|
141
188
|
const writes = pending.value;
|
|
142
189
|
// The first frame after a wake has no previous frame (dt 0); advance takes writes after the snapshot's time only,
|
|
143
190
|
// so writes waiting then are stamped a hair later, or they would be lost.
|
|
144
|
-
const dt = frame.timeSincePreviousFrame ?? 0;
|
|
191
|
+
const dt = elapsed.value + (frame.timeSincePreviousFrame ?? 0);
|
|
192
|
+
if (!writes.length && frameInterval > 0 && dt + 0.1 < frameInterval) {
|
|
193
|
+
elapsed.value = dt;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (frameInterval > 0) elapsed.value = 0;
|
|
145
197
|
const t = ms.value + (writes.length ? Math.max(dt, 0.001) : dt);
|
|
146
198
|
ms.value = t;
|
|
147
199
|
if (writes.length) {
|
|
@@ -153,14 +205,14 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
|
|
|
153
205
|
snapshot.value = next;
|
|
154
206
|
if (entries?.length && onStateEntries) scheduleOnRN(onStateEntries, entries);
|
|
155
207
|
if (probe?.onChanged) {
|
|
156
|
-
const key = JSON.stringify(poseAt(compiled, clips, next, t, read, reduced).channels);
|
|
208
|
+
const key = JSON.stringify(poseAt(compiled, clips, next, t, read, reduced, channelDefaults).channels);
|
|
157
209
|
if (key !== lastChannels.value) {
|
|
158
210
|
lastChannels.value = key;
|
|
159
211
|
if (awaitingChange.value) { awaitingChange.value = false; scheduleOnRN(probe.onChanged, frame.timestamp); }
|
|
160
212
|
}
|
|
161
213
|
}
|
|
162
214
|
if (pending.value.length === 0 && settled(compiled, next, read, reduced).frame) scheduleOnRN(sleep);
|
|
163
|
-
}, [compiled, clips, reduced, probe, onStateEntries]);
|
|
215
|
+
}, [compiled, clips, reduced, probe, onStateEntries, frameInterval, read, channelDefaults]);
|
|
164
216
|
|
|
165
217
|
const frames = useFrameCallback(tick, false);
|
|
166
218
|
// The callback is switched from JavaScript only: switching it from a worklet makes a synchronous remote call that
|
|
@@ -174,18 +226,27 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
|
|
|
174
226
|
liveNow.value = live;
|
|
175
227
|
frames.setActive(live);
|
|
176
228
|
}, [frames, live, liveNow, reduced]);
|
|
229
|
+
useEffect(() => { elapsed.value = 0; }, [elapsed, frameInterval]);
|
|
177
230
|
|
|
178
|
-
const
|
|
231
|
+
const enqueue = useCallback((writes: Write[]) => {
|
|
179
232
|
'worklet';
|
|
180
|
-
pending.value = [...pending.value,
|
|
233
|
+
pending.value = [...pending.value, ...writes];
|
|
181
234
|
scheduleOnRN(wake);
|
|
182
235
|
}, [pending, wake]);
|
|
236
|
+
const setOnUI = useCallback((name: string, to: Literal) => {
|
|
237
|
+
'worklet';
|
|
238
|
+
enqueue([{ at: 0, value: name, to }]);
|
|
239
|
+
}, [enqueue]);
|
|
183
240
|
const set = useCallback((name: string, to: Literal) => {
|
|
184
241
|
const problem = writeProblem(compiled, name, to);
|
|
185
242
|
if (problem) throw new Error(`useMachine set: ${problem}`);
|
|
186
243
|
// The UI worklet queues the wake after any sleep the tick has already queued on JavaScript.
|
|
187
244
|
scheduleOnUI(setOnUI, name, to);
|
|
188
245
|
}, [compiled, setOnUI]);
|
|
246
|
+
const setValues = useCallback((values: MachineInputs<M>) => {
|
|
247
|
+
const writes = valueWrites(compiled, values);
|
|
248
|
+
if (writes.length) scheduleOnUI(enqueue, writes);
|
|
249
|
+
}, [compiled, enqueue]);
|
|
189
250
|
const fire = useCallback((name: string) => set(name, true), [set]);
|
|
190
251
|
const tapOnUI = useCallback((x: number, y: number) => {
|
|
191
252
|
'worklet';
|
|
@@ -198,9 +259,20 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
|
|
|
198
259
|
}, [compiled, pose, snapshot, pending, wake]);
|
|
199
260
|
const readOnUI = useCallback((name: string) => {
|
|
200
261
|
'worklet';
|
|
201
|
-
|
|
202
|
-
return i === undefined ? undefined : snapshot.value.vals[i];
|
|
262
|
+
return Object.hasOwn(compiled.index, name) ? snapshot.value.vals[compiled.index[name]!] : undefined;
|
|
203
263
|
}, [compiled, snapshot]);
|
|
204
264
|
|
|
205
|
-
return { pose, set, fire, setOnUI, tapOnUI, readOnUI };
|
|
265
|
+
return { pose, snapshot, set, setValues, fire, setOnUI, tapOnUI, readOnUI };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function valueWrites(compiled: ReturnType<typeof compile>, values?: Readonly<Partial<Record<string, Literal>>>): Write[] {
|
|
269
|
+
return Object.entries(values ?? {}).flatMap(([name, to]) => {
|
|
270
|
+
if (to === undefined) return [];
|
|
271
|
+
const problem = writeProblem(compiled, name, to);
|
|
272
|
+
if (problem) throw new Error(`useMachine values: ${problem}`);
|
|
273
|
+
if (compiled.values[compiled.index[name]!]!.type === 'trigger') {
|
|
274
|
+
throw new Error(`useMachine values: use fire for "${name}"`);
|
|
275
|
+
}
|
|
276
|
+
return [{ at: 0, value: name, to }];
|
|
277
|
+
});
|
|
206
278
|
}
|