skia-motion-runtime 3.4.0 → 3.4.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/README.md CHANGED
@@ -64,6 +64,10 @@ export function LessonReward() {
64
64
  - A `row` group places an icon and its count by their ink on a plate that never resizes. It measures the ink with `SkParagraph.extendedVisit` (react-native-skia 3.10.2 or later); older react-native-skia and React Native Web fall back to advances and cap height, which is approximate.
65
65
  - For a rolling count, give the text node `roll: { progress, from }`: set the old and new strings with `setValues`, then `fire` the trigger whose clip runs `progress` from 0 to 1. Each digit place turns in its own column.
66
66
  - Use `live={false}` to pause a mounted player. The player uses system reduced motion by default and accepts a `reduced` override.
67
+ - The player pauses by itself only when the app is in the background. iOS 'inactive' (permission prompts, StoreKit and sign-in sheets, the app switcher, Notification Center) keeps it playing, as on Android.
68
+ - A stalled frame (an image decode, a sheet opening) delays motion instead of skipping a clip's start; a steadily slow device keeps real time.
69
+ - Images drawn smaller than their size are filtered through mip levels. `preloadMotionAsset(text, { uploadImages: true })` uploads textures with their mip levels.
70
+ - Bound text, rows and rolling numbers are laid out once per distinct string, so updating a counter is cheap; a string that changes every frame is laid out every frame.
67
71
  - Select a board by name with the `artboard` option when loading a multi-artboard file.
68
72
  - Prepare a shared file with `loadMotionAsset(text)` or `await preloadMotionAsset(text)`. Each player keeps its own state while sharing prepared artwork and image handles.
69
73
  - Use `MotionPicture` for a named clip in an existing Skia Canvas at a shared `timeMs`. Provide `width` and `height` to draw without a separate player layout pass. Use `MotionPlayer` when the asset owns transitions and markers.
package/package.json CHANGED
@@ -58,7 +58,7 @@
58
58
  "templates/motion/machine.ts",
59
59
  "templates/motion/motion.ts"
60
60
  ],
61
- "version": "3.4.0",
61
+ "version": "3.4.1",
62
62
  "license": "MIT",
63
63
  "repository": {
64
64
  "type": "git",
@@ -35,6 +35,8 @@ type TextValues = Readonly<Record<string, string>>;
35
35
  export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
36
36
  artboard: Omit<MotionAsset['artboard'], 'nodes'> & { nodes: readonly DrawableNode[] };
37
37
  meshShaders?: AssetMeshShaders;
38
+ /** Each image's shader for image nodes, sampled through its mip levels (drawImageRect's strict constraint would turn them off). */
39
+ imageShaders?: AssetImageShaders;
38
40
  fontProvider?: SkTypefaceFontProvider;
39
41
  textBindings?: readonly string[];
40
42
  palette?: Palette;
@@ -42,6 +44,9 @@ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
42
44
  export type AssetImages = Readonly<Record<string, SkImage>>;
43
45
  export type AssetFontSlots = Readonly<Record<string, SkTypeface>>;
44
46
  export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
47
+ /** An image node's shader with the image it samples, so a different image passed at draw time is not drawn with it. */
48
+ export type AssetImageShaders = Readonly<Record<string, { image: SkImage; shader: SkShader }>>;
49
+ type DrawShaders = { mesh: AssetMeshShaders; image: AssetImageShaders };
45
50
 
46
51
  function skiaData(resource: AssetResource): SkData {
47
52
  if (typeof resource === 'string') return Skia.Data.fromBase64(resource.slice(resource.indexOf(',') + 1));
@@ -144,14 +149,67 @@ function meshTextureCoords(node: MeshNode | DrawableMesh, image: SkImage): Point
144
149
 
145
150
  function meshShader(image: SkImage): SkShader {
146
151
  'worklet';
147
- return image.makeShaderOptions(TileMode.Decal, TileMode.Decal, FilterMode.Linear, MipmapMode.None);
152
+ // Mip levels keep art drawn below its size from aliasing.
153
+ return image.makeShaderOptions(TileMode.Decal, TileMode.Decal, FilterMode.Linear, MipmapMode.Linear);
148
154
  }
149
155
 
150
156
  /**
151
- * Lay out a text node's paragraph. `text` is the whole string, or runs of it each shown or laid out unseen (a rolling number keeps its
152
- * digits' place in the line while it draws them itself).
157
+ * An image node's shader. react-native-skia's drawImageRectOptions draws with SkCanvas::kStrict_SrcRectConstraint, under which Skia
158
+ * samples no mip levels, so art drawn small aliased whatever mipmap mode it asked for. A shader samples them; Clamp keeps the edges as
159
+ * drawImageRect drew them.
153
160
  */
154
- function makeParagraph(
161
+ function imageShader(image: SkImage): SkShader {
162
+ 'worklet';
163
+ return image.makeShaderOptions(TileMode.Clamp, TileMode.Clamp, FilterMode.Linear, MipmapMode.Linear);
164
+ }
165
+
166
+ function imageShaders(images: AssetImages): AssetImageShaders {
167
+ const byImage = new Map<SkImage, SkShader>();
168
+ return Object.fromEntries(Object.entries(images).map(([name, image]) => {
169
+ const shader = byImage.get(image) ?? imageShader(image);
170
+ byImage.set(image, shader);
171
+ return [name, { image, shader }];
172
+ }));
173
+ }
174
+
175
+ /** The most laid-out paragraphs, row inks and image paints the drawing thread keeps; the oldest unused one goes first. */
176
+ const CACHE_LIMIT = 256;
177
+ type CacheStore = Map<string, unknown>;
178
+
179
+ /**
180
+ * The value under `key` on this thread, made once. Each thread (the UI thread, or Node for asset frame) has its own store on its global
181
+ * object: drawing worklets get a copy of every captured object, so a cache held by the drawing would start empty each frame.
182
+ */
183
+ function cached<T>(key: string | undefined, make: () => T): T {
184
+ 'worklet';
185
+ if (key === undefined) return make();
186
+ const holder = globalThis as unknown as { __skiaMotionCache?: CacheStore };
187
+ const store = holder.__skiaMotionCache ?? (holder.__skiaMotionCache = new Map());
188
+ if (store.has(key)) {
189
+ const hit = store.get(key) as T;
190
+ store.delete(key);
191
+ store.set(key, hit);
192
+ return hit;
193
+ }
194
+ const value = make();
195
+ if (store.size >= CACHE_LIMIT) store.delete(store.keys().next().value as string);
196
+ store.set(key, value);
197
+ return value;
198
+ }
199
+
200
+ let nextNodeKey = 0;
201
+
202
+ /** A text's layout key: the node (unique per prepared drawing, so per font provider), the style variant and the text runs. */
203
+ function paragraphKey(node: AssetTextNode & { cacheKey?: string }, text: string | readonly (readonly [string, boolean])[]): string | undefined {
204
+ 'worklet';
205
+ if (node.cacheKey === undefined) return undefined;
206
+ let runs = '';
207
+ if (typeof text === 'string') runs = text;
208
+ else for (const [content, shown] of text) runs += (shown ? '\x01' : '\x02') + content;
209
+ return `${node.cacheKey}|${node.align ?? ''}|${node.direction ?? ''}|${node.maxLines ?? 1}|${node.fontFeatures?.length ?? 0}|${runs}`;
210
+ }
211
+
212
+ function layOut(
155
213
  node: AssetTextNode, text: string | readonly (readonly [string, boolean])[], provider?: SkTypefaceFontProvider,
156
214
  ): SkParagraph {
157
215
  'worklet';
@@ -177,6 +235,18 @@ function makeParagraph(
177
235
  return paragraph;
178
236
  }
179
237
 
238
+ /**
239
+ * Lay out a text node's paragraph. `text` is the whole string, or runs of it each shown or laid out unseen (a rolling number keeps its
240
+ * digits' place in the line while it draws them itself).
241
+ */
242
+ function makeParagraph(
243
+ node: AssetTextNode, text: string | readonly (readonly [string, boolean])[], provider?: SkTypefaceFontProvider,
244
+ ): SkParagraph {
245
+ 'worklet';
246
+ return cached(paragraphKey(node, text), () => layOut(node, text, provider));
247
+ }
248
+
249
+
180
250
  /** The baseline of a paragraph's first line, from its top. */
181
251
  function baselineOf(paragraph: SkParagraph): number {
182
252
  'worklet';
@@ -293,6 +363,7 @@ function prepareNode(
293
363
  ): DrawableNode {
294
364
  if (node.kind === 'text') {
295
365
  if (typeof node.text === 'string') return { ...node, paragraph: makeParagraph(node, node.text, provider) };
366
+ node = { ...node, cacheKey: `n${nextNodeKey++}` } as AssetTextNode;
296
367
  textBindings.add(node.text.value);
297
368
  if (node.roll) textBindings.add(node.roll.from);
298
369
  return node;
@@ -324,6 +395,7 @@ function prepareNode(
324
395
  textureCoords: image ? meshTextureCoords(node, image) : undefined,
325
396
  };
326
397
  }
398
+ if (node.kind === 'image') return { ...node, cacheKey: `n${nextNodeKey++}` } as DrawableNode;
327
399
  return { ...node, preparedPath: prepared, preparedPaint: preparePaint(node, palette) };
328
400
  }
329
401
 
@@ -405,7 +477,7 @@ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetIma
405
477
  };
406
478
  const nodes = asset.artboard.nodes.map((node) => withParts(prepareNode(node, images, shaders, shadersByImage, fontProvider, textBindings, palette)));
407
479
  return {
408
- channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders,
480
+ channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders, imageShaders: imageShaders(images),
409
481
  ...(fontProvider && { fontProvider }),
410
482
  ...(textBindings.size && { textBindings: [...textBindings] }),
411
483
  ...(asset.palette && { palette }),
@@ -414,6 +486,8 @@ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetIma
414
486
 
415
487
  /** Warmed images may be different native objects. Prepare their shaders with the same geometry. */
416
488
  export function rebindAssetMeshShaders(drawing: DrawableAsset, images: AssetImages): DrawableAsset {
489
+ const shown = Object.keys(drawing.imageShaders ?? {});
490
+ if (shown.length) drawing = { ...drawing, imageShaders: imageShaders(Object.fromEntries(shown.map((name) => [name, images[name]!]))) };
417
491
  const names = Object.keys(drawing.meshShaders ?? {});
418
492
  if (!names.length) return drawing;
419
493
  const byImage = new Map<SkImage, SkShader>();
@@ -526,6 +600,13 @@ function paragraphInk(paragraph: SkParagraph, text: string, node: AssetTextNode,
526
600
  return textInk(glyphs, first, last, text, heights);
527
601
  }
528
602
 
603
+ /** A text's ink as a row places it, measured once per text. */
604
+ function inkFor(node: AssetTextNode, text: string, fonts: SkTypefaceFontProvider | undefined): TextInk | undefined {
605
+ 'worklet';
606
+ const key = paragraphKey(node, text);
607
+ return cached(key === undefined ? undefined : `ink|${key}`, () => paragraphInk(makeParagraph(node, text, fonts), text, node, fonts));
608
+ }
609
+
529
610
  type RowGroup = Extract<DrawableNode, { kind: 'group' }> & { row: NonNullable<Extract<AssetNode, { kind: 'group' }>['row']> };
530
611
 
531
612
  /**
@@ -548,13 +629,14 @@ function layoutRow(
548
629
  // A rolling count is placed between its old value's ink and its new one's, so at rest it is placed by the value it shows.
549
630
  const styled = rollTextStyle(drawn);
550
631
  const from = values[drawn.roll.from] ?? '';
551
- const inkOf = (value: string) => (value ? paragraphInk(makeParagraph(styled, value, fonts), value, styled, fonts) : undefined);
632
+ const inkOf = (value: string) => (value ? inkFor(styled, value, fonts) : undefined);
552
633
  return blendInk(inkOf(from), inkOf(text), rollWidthShare(from, text, read(drawn.roll.progress, channels), drawn.roll));
553
634
  }
554
635
  if (!text) return undefined;
555
636
  const paragraph = !wide && drawn.paragraph ? drawn.paragraph : makeParagraph(rollTextStyle(drawn), text, fonts);
556
637
  if (!wide) paragraphs[index] = paragraph;
557
- return paragraphInk(paragraph, text, drawn, fonts);
638
+ const key = paragraphKey(rollTextStyle(drawn), text);
639
+ return cached(key === undefined ? undefined : `ink|${key}`, () => paragraphInk(paragraph, text, drawn, fonts));
558
640
  }, (index) => node.rowParts?.[index], Boolean(row.plate?.widest));
559
641
  const { moves } = rowLayout(items, row.gap, align, rtl);
560
642
  if (row.plate) {
@@ -578,7 +660,7 @@ function layoutRow(
578
660
  }
579
661
 
580
662
  function drawNodes(
581
- canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders: AssetMeshShaders,
663
+ canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders: DrawShaders,
582
664
  values: TextValues, fonts: SkTypefaceFontProvider | undefined, palette: Palette, layout?: ReturnType<typeof fitAsset>,
583
665
  ): void {
584
666
  'worklet';
@@ -619,7 +701,7 @@ function drawNodes(
619
701
  const alpha = Math.min(1, Math.max(0, read(node.opacity, channels, 1)));
620
702
  if (node.kind === 'mesh') {
621
703
  const image = images[node.image];
622
- if (image && alpha) drawMesh(canvas, node, channels, image, alpha, shaders[node.image]);
704
+ if (image && alpha) drawMesh(canvas, node, channels, image, alpha, shaders.mesh[node.image]);
623
705
  if (node.pins) {
624
706
  for (const pin of node.pins) {
625
707
  const { x, y } = meshPinPosition(node, pin, channels);
@@ -638,20 +720,33 @@ function drawNodes(
638
720
  if (node.stroke) drawStroke(canvas, path, node.stroke, alpha, Math.min(MAX_FEATHER, read(node.feather, channels)), channels, palette);
639
721
  continue;
640
722
  }
641
- const paint = node.preparedPaint ?? makePaint(node, alpha, channels, palette);
642
723
  if (node.kind === 'image') {
643
724
  const image = images[node.image];
644
725
  const width = read(node.width, channels);
645
726
  const height = read(node.height, channels);
646
727
  if (!image || width <= 0 || height <= 0) continue;
647
- canvas.drawImageRectOptions(
648
- image,
649
- Skia.XYWHRect(0, 0, image.width(), image.height()),
650
- Skia.XYWHRect(read(node.x, channels), read(node.y, channels), width, height),
651
- FilterMode.Linear, MipmapMode.None, paint,
652
- );
728
+ const imageWidth = image.width();
729
+ const imageHeight = image.height();
730
+ // The prepared shader only for the image it was made from: a host can pass other images to drawAsset.
731
+ const prepared = shaders.image[node.image];
732
+ const shader = prepared && prepared.image === image ? prepared.shader : imageShader(image);
733
+ const key = (node as { cacheKey?: string }).cacheKey;
734
+ // One paint per image node, reset each frame: a picture records a copy of the paint it draws with.
735
+ const filled = cached(key === undefined ? undefined : `paint|${key}`, () => {
736
+ const paint = Skia.Paint();
737
+ paint.setAntiAlias(true);
738
+ return paint;
739
+ });
740
+ filled.setAlphaf(alpha);
741
+ filled.setShader(shader);
742
+ canvas.save();
743
+ canvas.translate(read(node.x, channels), read(node.y, channels));
744
+ canvas.scale(width / imageWidth, height / imageHeight);
745
+ canvas.drawRect(Skia.XYWHRect(0, 0, imageWidth, imageHeight), filled);
746
+ canvas.restore();
653
747
  continue;
654
748
  }
749
+ const paint = node.preparedPaint ?? makePaint(node, alpha, channels, palette);
655
750
  const w = read(node.width, channels);
656
751
  const h = read(node.height, channels);
657
752
  if (w <= 0 || h <= 0) continue;
@@ -683,6 +778,7 @@ export function drawAsset(
683
778
  ? Skia.XYWHRect(-offsetX, -offsetY, board.width + spaceX, board.height + spaceY)
684
779
  : Skia.XYWHRect(0, 0, board.width, board.height);
685
780
  canvas.clipRect(bounds, ClipOp.Intersect, true);
686
- drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, asset.meshShaders ?? {}, values, asset.fontProvider, asset.palette ?? {}, layout);
781
+ drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, { mesh: asset.meshShaders ?? {}, image: asset.imageShaders ?? {} },
782
+ values, asset.fontProvider, asset.palette ?? {}, layout);
687
783
  canvas.restore();
688
784
  }
@@ -64,9 +64,11 @@ export async function preloadMotionAsset(
64
64
  const preloadable = image as SkImage & { makeRasterImage?: () => Promise<SkImage> };
65
65
  ready = await preloadable.makeRasterImage?.() ?? image;
66
66
  if (uploadImages) {
67
- const uploadable = ready as SkImage & { makeTextureImage?: () => SkImage };
67
+ // Uploaded with mip levels: the draw samples them, and a texture made without them (react-native-skia's default) is
68
+ // sampled at full size, so art drawn small aliases. Older versions take no options and ignore it.
69
+ const uploadable = ready as SkImage & { makeTextureImage?: (options?: { mipmapped?: boolean }) => SkImage };
68
70
  try {
69
- ready = uploadable.makeTextureImage?.() ?? ready;
71
+ ready = uploadable.makeTextureImage?.({ mipmapped: true }) ?? ready;
70
72
  } catch {
71
73
  // A reduced or unsupported backend can still upload the raster image when drawn.
72
74
  }
@@ -120,9 +120,11 @@ function LoadedPlayer({
120
120
  setViewport((current) => current.width === width && current.height === height ? current : { width, height });
121
121
  }, []);
122
122
  const measured = viewport.width > 0 && viewport.height > 0;
123
- const [foreground, setForeground] = useState(() => !AppState.currentState || AppState.currentState === 'active');
123
+ // Away is 'background' only: iOS reports system sheets (permission prompts, password managers, StoreKit) as 'inactive' and
124
+ // launch can read 'unknown', states Android never reports, so pausing on them made one file play differently on each platform.
125
+ const [foreground, setForeground] = useState(() => AppState.currentState !== 'background');
124
126
  useEffect(() => {
125
- const subscription = AppState.addEventListener('change', (state) => setForeground(state === 'active'));
127
+ const subscription = AppState.addEventListener('change', (state) => setForeground(state !== 'background'));
126
128
  return () => subscription.remove();
127
129
  }, []);
128
130
  const markerCallback = useRef(onMarker);
@@ -16,6 +16,12 @@ import { assertRuntimeVersion } from './version';
16
16
 
17
17
  declare const __DEV__: boolean;
18
18
  const noClocks: Record<string, SharedValue<number>> = {};
19
+ /** The longest frame the clock always takes whole, in ms; a longer one counts whole only if recent frames were as long. */
20
+ const MAX_STEP_MS = 50;
21
+ /** A frame longer than this many typical frames (and than MAX_STEP_MS) is a stall, and moves the clock only that far. */
22
+ const STALL_FACTOR = 3;
23
+ /** How fast the typical frame length follows the frames: a tenth of the way each frame. */
24
+ const TYPICAL_WEIGHT = 0.1;
19
25
 
20
26
  /** 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. */
21
27
  export type MachineProbe = { onWrite?: (frameMs: number) => void; onChanged?: (frameMs: number) => void };
@@ -125,6 +131,9 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
125
131
  const rate = options.frameRate;
126
132
  if (rate !== undefined && (!Number.isFinite(rate) || rate <= 0)) throw new Error('useMachine: frameRate must be positive');
127
133
  const frameInterval = rate === undefined ? 0 : 1000 / rate;
134
+ // The least a frame may move the clock before it counts as a stall: two intervals under a frame rate cap, so a frame a
135
+ // little late still counts whole. A stall (an image decode, a sheet opening) delays motion instead of eating it.
136
+ const minCap = Math.max(2 * frameInterval, MAX_STEP_MS);
128
137
  const compiled = useMemo(() => compile(machine, clips), [machine, clips]);
129
138
  // The clocks its layers run on: the pose reads only these, and each must be passed, since a missing one would read
130
139
  // machine time, which stops while the machine rests.
@@ -142,6 +151,8 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
142
151
  const first = useMemo(() => advance(compiled, start(compiled), 0, valueWrites(compiled, options.initialValues), read), [compiled]); // eslint-disable-line react-hooks/exhaustive-deps
143
152
  const ms = useSharedValue(0);
144
153
  const elapsed = useSharedValue(0);
154
+ // A running average of frame lengths, in ms, starting at one 60 Hz frame.
155
+ const typical = useSharedValue(1000 / 60);
145
156
  const snapshot = useSharedValue<Snapshot>(first);
146
157
  const pending = useSharedValue<Write[]>([]);
147
158
  const lastChannels = useSharedValue('');
@@ -188,7 +199,11 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
188
199
  const writes = pending.value;
189
200
  // The first frame after a wake has no previous frame (dt 0); advance takes writes after the snapshot's time only,
190
201
  // so writes waiting then are stamped a hair later, or they would be lost.
191
- const dt = elapsed.value + (frame.timeSincePreviousFrame ?? 0);
202
+ // A stall is a frame far longer than the recent ones: a device that is steadily slow keeps real time.
203
+ const raw = frame.timeSincePreviousFrame ?? 0;
204
+ const step = Math.min(raw, Math.max(minCap, STALL_FACTOR * typical.value));
205
+ if (raw > 0) typical.value += (step - typical.value) * TYPICAL_WEIGHT;
206
+ const dt = elapsed.value + step;
192
207
  if (!writes.length && frameInterval > 0 && dt + 0.1 < frameInterval) {
193
208
  elapsed.value = dt;
194
209
  return;
@@ -212,11 +227,11 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
212
227
  }
213
228
  }
214
229
  if (pending.value.length === 0 && settled(compiled, next, read, reduced).frame) scheduleOnRN(sleep);
215
- }, [compiled, clips, reduced, probe, onStateEntries, frameInterval, read, channelDefaults]);
230
+ }, [compiled, clips, reduced, probe, onStateEntries, frameInterval, minCap, typical, read, channelDefaults]);
216
231
 
217
232
  const frames = useFrameCallback(tick, false);
218
233
  // The callback is switched from JavaScript only: switching it from a worklet makes a synchronous remote call that
219
- // release builds refuse (found in Word Quran, 18 Oct 2026).
234
+ // release builds refuse (found in a host app, 18 Oct 2026).
220
235
  function sleep() {
221
236
  frames.setActive(false);
222
237
  }