skia-motion-runtime 3.2.0 → 3.3.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 ADDED
@@ -0,0 +1,80 @@
1
+ # Skia Motion Runtime
2
+
3
+ Play interactive `.skmotion` assets in React Native and Expo. A file can contain artwork, animation timelines, state machines, and inputs for game HUDs, characters, rewards, and other app interactions.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install skia-motion-runtime
9
+ ```
10
+
11
+ The app supplies React 19+, React Native 0.79+, `react-native-skia` 3+, Reanimated 4+, and `react-native-worklets` 0.7+. In Expo, use a development build that includes Skia v3.
12
+
13
+ ## React Native
14
+
15
+ Read a JSON `.skmotion` as UTF-8 text or pass a binary `.skmotion` as a `Uint8Array`. By default the player uses the available width and derives its height from the artboard. Supply `style`, `width`, or `height` to fit a specific layout.
16
+
17
+ ```tsx
18
+ import { MotionPlayer, type MotionAssetData } from 'skia-motion-runtime';
19
+
20
+ export function LessonReward({ source }: { source: MotionAssetData }) {
21
+ return <MotionPlayer source={source} />;
22
+ }
23
+ ```
24
+
25
+ ## Expo
26
+
27
+ Install the Expo asset loader dependencies in your app.
28
+
29
+ ```sh
30
+ npx expo install expo-asset expo-file-system
31
+ ```
32
+
33
+ Add `skmotion` to Metro's asset extensions in `metro.config.js`.
34
+
35
+ ```js
36
+ const { getDefaultConfig } = require('expo/metro-config');
37
+
38
+ const config = getDefaultConfig(__dirname);
39
+ config.resolver.assetExts.push('skmotion');
40
+ module.exports = config;
41
+ ```
42
+
43
+ Load the bundled file with `useExpoMotionAsset` and render the player when it is ready.
44
+
45
+ ```tsx
46
+ import { Text } from 'react-native';
47
+ import { MotionPlayer } from 'skia-motion-runtime';
48
+ import { useExpoMotionAsset } from 'skia-motion-runtime/expo';
49
+
50
+ export function LessonReward() {
51
+ const result = useExpoMotionAsset(require('./lesson-reward.skmotion'));
52
+ if (result.status === 'error') {
53
+ return <Text accessibilityRole="alert">{result.error.message}</Text>;
54
+ }
55
+ if (result.status !== 'ready') return null;
56
+ return <MotionPlayer source={result.asset} />;
57
+ }
58
+ ```
59
+
60
+ ## Control playback
61
+
62
+ - Attach a `MotionPlayerHandle` ref to call `set(name, value)`, `setValues(values)`, or `fire(name)` using the asset's named inputs. Handle asset cues with `onMarker` and `onAudio`.
63
+ - Call the mounted handle's `setOnUI(name, value)` from a Reanimated worklet. A host-formatted string can update the digits in a bound text node during a count-up.
64
+ - Use `live={false}` to pause a mounted player. The player uses system reduced motion by default and accepts a `reduced` override.
65
+ - Select a board by name with the `artboard` option when loading a multi-artboard file.
66
+ - Prepare a shared file with `loadMotionAsset(text)` or `await preloadMotionAsset(text)`. Each player keeps its own state while sharing prepared artwork and image handles.
67
+ - 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.
68
+
69
+ The text schema supports 1–16 lines and optional OpenType features such as `tnum` for fonts
70
+ with tabular digits. Skia can ellipsize overflow. Check representative labels with the CLI's
71
+ `asset check --text-layout` before shipping. The entire packed file has a 1 MiB budget
72
+ for motion data and embedded resources, including fonts.
73
+
74
+ For an asset that declares host font slots, supply the app’s loaded Skia typefaces during
75
+ preparation, for example `loadMotionAsset(bytes, { fontSlots: { Counter: counterTypeface } })`.
76
+ The same options work with `useMotionAsset` and `useExpoMotionAsset`. Keep borrowed faces
77
+ available while the prepared file is in use. An embedded fallback is optional and a missing
78
+ required slot produces a load error. Run `skac asset guide font-slots` for the authoring recipe.
79
+
80
+ [Project and examples](https://github.com/asifnawaz/skia-motion-agentic-cli) · [Release notes](https://github.com/asifnawaz/skia-motion-agentic-cli/releases)
package/package.json CHANGED
@@ -55,7 +55,7 @@
55
55
  "templates/motion/machine.ts",
56
56
  "templates/motion/motion.ts"
57
57
  ],
58
- "version": "3.2.0",
58
+ "version": "3.3.1",
59
59
  "license": "MIT",
60
60
  "repository": {
61
61
  "type": "git",
@@ -13,6 +13,9 @@ const MAGIC = 0x534b4d4f; // SKMO
13
13
  const VERSION = 1;
14
14
  const MAX_RESOURCES = 4096;
15
15
  const RESOURCE_KEYS = ['images', 'fonts', 'audio'] as const;
16
+ type ResourceKind = typeof RESOURCE_KEYS[number];
17
+ type SizeBreakdown = Record<ResourceKind | 'scene', number>;
18
+ type MapResource = (value: unknown, kind: ResourceKind) => unknown;
16
19
  const RESOURCE_MIMES = new Set([
17
20
  'image/png', 'image/webp', 'font/ttf', 'font/otf', 'audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac',
18
21
  ]);
@@ -43,19 +46,19 @@ export function decodeAssetText(bytes: Uint8Array): string {
43
46
  return decodeURIComponent(chunks.join('')).replace(/^\uFEFF/, '');
44
47
  }
45
48
 
46
- function mapResources(value: unknown, map: (value: unknown) => unknown): unknown {
49
+ function mapResources(value: unknown, map: MapResource): unknown {
47
50
  if (!isRecord(value)) return value;
48
51
  const result = { ...value };
49
52
  for (const key of RESOURCE_KEYS) {
50
53
  const resources = value[key];
51
54
  if (isRecord(resources)) {
52
- result[key] = Object.fromEntries(Object.entries(resources).map(([name, resource]) => [name, map(resource)]));
55
+ result[key] = Object.fromEntries(Object.entries(resources).map(([name, resource]) => [name, map(resource, key)]));
53
56
  }
54
57
  }
55
58
  return result;
56
59
  }
57
60
 
58
- export function mapFileResources(value: unknown, map: (value: unknown) => unknown): unknown {
61
+ export function mapFileResources(value: unknown, map: MapResource): unknown {
59
62
  const file = mapResources(value, map);
60
63
  if (isRecord(file) && file.schema === 'skac.bundle/1' && isRecord(file.artboards)) {
61
64
  file.artboards = Object.fromEntries(Object.entries(file.artboards).map(([name, board]) => [name, mapResources(board, map)]));
@@ -103,11 +106,12 @@ export function decodeBinaryAsset(bytes: Uint8Array, parseJSON: (text: string) =
103
106
  }
104
107
 
105
108
  /** The authoring CLI writes a validated legacy scene into an SKMO container. */
106
- export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => Uint8Array, limit: number): Uint8Array {
109
+ export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => Uint8Array, limit: number) {
107
110
  const uriIndices = new Map<string, number>();
108
111
  const payloadIndices = new Map<string, number[]>();
109
112
  const payload: ResourceBytes[] = [];
110
- const asset = mapFileResources(file, (resource) => {
113
+ const sizeBreakdown: SizeBreakdown = { scene: HEADER_SIZE, images: 0, fonts: 0, audio: 0 };
114
+ const asset = mapFileResources(file, (resource, kind) => {
111
115
  if (typeof resource !== 'string') invalid('expected a data URI to pack');
112
116
  const known = uriIndices.get(resource);
113
117
  if (known !== undefined) return known;
@@ -125,6 +129,7 @@ export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => U
125
129
  index = payload.length;
126
130
  if (index >= MAX_RESOURCES) invalid('too many resources');
127
131
  payload.push({ mime, bytes });
132
+ sizeBreakdown[kind] += bytes.length;
128
133
  candidates.push(index);
129
134
  payloadIndices.set(key, candidates);
130
135
  }
@@ -132,8 +137,9 @@ export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => U
132
137
  return index;
133
138
  });
134
139
  const manifest = encodeText(JSON.stringify({ asset, resources: payload.map(({ mime, bytes }) => [mime, bytes.length]) }));
135
- const size = payload.reduce((total, { bytes }) => total + bytes.length, HEADER_SIZE + manifest.length);
136
- if (size > limit) throw new Error('packed asset exceeds 1 MiB');
140
+ sizeBreakdown.scene += manifest.length;
141
+ const size = Object.values(sizeBreakdown).reduce((total, value) => total + value, 0);
142
+ if (size > limit) throw Object.assign(new Error('packed asset exceeds 1 MiB'), { bytes: size, sizeBreakdown });
137
143
  const result = new Uint8Array(size);
138
144
  const view = new DataView(result.buffer);
139
145
  view.setUint32(0, MAGIC);
@@ -145,5 +151,5 @@ export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => U
145
151
  result.set(resource.bytes, offset);
146
152
  offset += resource.bytes.length;
147
153
  }
148
- return result;
154
+ return { data: result, sizeBreakdown };
149
155
  }
@@ -2,7 +2,7 @@ import {
2
2
  BlendMode, BlurStyle, ClipOp, FilterMode, MipmapMode, PaintStyle, Skia, StrokeCap, StrokeJoin, TextAlign, TextDirection, TileMode, VertexMode,
3
3
  type SkCanvas, type SkData, type SkImage, type SkPaint, type SkParagraph, type SkPath, type SkShader, type SkTypeface, type SkTypefaceFontProvider,
4
4
  } from 'react-native-skia';
5
- import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type DrawableMotionAsset, type MotionAsset, type PathCommand } from './asset';
5
+ import { MAX_FEATHER, resolveAssetColor, resolveAssetFonts, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type DrawableMotionAsset, type MotionAsset, type PathCommand } from './asset';
6
6
  import type { AssetResource } from './asset-binary';
7
7
  import { fitAsset, fittedAnchorOffset, type AssetLayoutOptions } from './asset-layout';
8
8
  import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
@@ -36,6 +36,7 @@ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
36
36
  palette?: Palette;
37
37
  };
38
38
  export type AssetImages = Readonly<Record<string, SkImage>>;
39
+ export type AssetFontSlots = Readonly<Record<string, SkTypeface>>;
39
40
  export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
40
41
 
41
42
  function skiaData(resource: AssetResource): SkData {
@@ -201,13 +202,19 @@ function prepareNode(
201
202
  }
202
203
 
203
204
  /** Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose. */
204
- export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetImages = {}): DrawableAsset {
205
+ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetImages = {}, fontSlots?: AssetFontSlots): DrawableAsset {
206
+ const { fonts, missing } = resolveAssetFonts(asset, fontSlots);
207
+ if (missing.length) throw new Error(`Missing motion font slots: ${missing.join(', ')}`);
205
208
  const shaders: Record<string, SkShader> = {};
206
209
  const shadersByImage = new Map<SkImage, SkShader>();
207
210
  let fontProvider: SkTypefaceFontProvider | undefined;
208
211
  const typefaces = new Map<AssetResource, SkTypeface>();
209
- for (const [name, resource] of Object.entries(asset.fonts ?? {})) {
212
+ for (const [name, resource] of Object.entries(fonts)) {
210
213
  fontProvider ??= Skia.TypefaceFontProvider.Make();
214
+ if (typeof resource !== 'string' && !('bytes' in resource)) {
215
+ fontProvider.registerFont(resource, name);
216
+ continue;
217
+ }
211
218
  let typeface = typefaces.get(resource);
212
219
  if (!typeface) {
213
220
  const data = skiaData(resource);
@@ -1,7 +1,7 @@
1
1
  import type { SkImage } from 'react-native-skia';
2
2
  import { assetClips, bindAssetPalette, parseDrawableAsset, type MotionAsset } from './asset';
3
3
  import { resourceDataUri, type MotionAssetData, type ResourceBytes } from './asset-binary';
4
- import { decodeAssetImages, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
4
+ import { decodeAssetImages, prepareAssetDrawing, rebindAssetMeshShaders, type AssetFontSlots, type AssetImages, type DrawableAsset } from './asset-draw';
5
5
 
6
6
  let nextAssetKey = 0;
7
7
 
@@ -17,9 +17,15 @@ export type LoadedMotionAsset = Readonly<{
17
17
  }>;
18
18
 
19
19
  /** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
20
- export type MotionPrepareOptions = { artboard?: string; imageSlots?: AssetImages; palette?: Readonly<Record<string, string>> };
20
+ export type MotionPrepareOptions = {
21
+ artboard?: string;
22
+ imageSlots?: AssetImages;
23
+ /** Already-loaded Skia typefaces, borrowed for the life of the prepared drawing. */
24
+ fontSlots?: AssetFontSlots;
25
+ palette?: Readonly<Record<string, string>>;
26
+ };
21
27
 
22
- export function loadMotionAsset(source: MotionAssetData, { artboard, imageSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
28
+ export function loadMotionAsset(source: MotionAssetData, { artboard, imageSlots, fontSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
23
29
  const asset = bindAssetPalette(parseDrawableAsset(source, artboard), palette);
24
30
  const images = decodeAssetImages(asset, imageSlots);
25
31
  let audio: LoadedMotionAsset['audio'];
@@ -31,7 +37,7 @@ export function loadMotionAsset(source: MotionAssetData, { artboard, imageSlots,
31
37
  key: nextAssetKey++,
32
38
  machine: asset.machine,
33
39
  markers: asset.markers,
34
- drawing: prepareAssetDrawing(asset, images),
40
+ drawing: prepareAssetDrawing(asset, images, fontSlots),
35
41
  images,
36
42
  clips: assetClips(asset),
37
43
  semantics: asset.semantics,
package/runtime/asset.ts CHANGED
@@ -75,6 +75,7 @@ export type MotionAsset<M extends Machine = Machine, R extends AssetResource = s
75
75
  imageSlots?: Readonly<Record<string, string>>;
76
76
  palette?: Readonly<Record<string, string>>;
77
77
  fonts?: Readonly<Record<string, R>>;
78
+ fontSlots?: Readonly<Record<string, { readonly fallback?: string }>>;
78
79
  fontLicenses?: Readonly<Record<string, string>>;
79
80
  audio?: Readonly<Record<string, R>>;
80
81
  semantics?: readonly AssetSemantic[];
@@ -90,6 +91,7 @@ export type MotionAssetFile<R extends AssetResource = string> = MotionAsset<Mach
90
91
  defaultArtboard: string;
91
92
  artboards: Readonly<Record<string, MotionAsset<Machine, R>>>;
92
93
  fonts?: MotionAsset<Machine, R>['fonts'];
94
+ fontSlots?: MotionAsset['fontSlots'];
93
95
  fontLicenses?: MotionAsset['fontLicenses'];
94
96
  audio?: MotionAsset<Machine, R>['audio'];
95
97
  };
@@ -159,6 +161,7 @@ type NodeValidation = {
159
161
  imageSlots: Record<string, unknown>;
160
162
  points: Set<string>;
161
163
  fonts: Record<string, unknown>;
164
+ fontSlots: NonNullable<MotionAsset['fontSlots']>;
162
165
  values: Record<string, unknown>;
163
166
  palette: Record<string, unknown>;
164
167
  };
@@ -242,6 +245,24 @@ function checkFontLicenses(value: unknown, fonts: Record<string, unknown>, at: s
242
245
  }
243
246
  }
244
247
 
248
+ function checkFontSlots(value: unknown, fonts: Record<string, unknown>, at: string): NonNullable<MotionAsset['fontSlots']> {
249
+ if (value === undefined) return {};
250
+ const slots = Object.entries(record(value, at));
251
+ if (slots.length > 32) invalid(at, 'expected at most 32 font slots');
252
+ const names = new Set(Object.keys(fonts).map((name) => name.toLowerCase()));
253
+ for (const [name, entry] of slots) {
254
+ const key = `${at}.${name}`;
255
+ identifier(name, key);
256
+ if (names.has(name.toLowerCase())) invalid(key, 'font names and slot aliases must be distinct');
257
+ names.add(name.toLowerCase());
258
+ const { fallback } = record(entry, key, ['fallback']);
259
+ if (fallback !== undefined && (typeof fallback !== 'string' || !Object.hasOwn(fonts, fallback))) {
260
+ invalid(`${key}.fallback`, 'expected an embedded font name');
261
+ }
262
+ }
263
+ return value as NonNullable<MotionAsset['fontSlots']>;
264
+ }
265
+
245
266
  function registerPoint(name: string, at: string, points: Set<string>): void {
246
267
  identifier(name, at);
247
268
  if (points.has(name)) invalid(at, 'duplicate point name');
@@ -307,7 +328,9 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
307
328
  number(node.fontSize, `${at}.fontSize`, 1, 512);
308
329
  color(node.fill, `${at}.fill`);
309
330
  if (node.fonts !== undefined) list(node.fonts, `${at}.fonts`, 8).forEach((name, i) => {
310
- if (typeof name !== 'string' || !Object.hasOwn(context.fonts, name)) invalid(`${at}.fonts[${i}]`, 'unknown embedded font');
331
+ if (typeof name !== 'string' || (!Object.hasOwn(context.fonts, name) && !Object.hasOwn(context.fontSlots, name))) {
332
+ invalid(`${at}.fonts[${i}]`, 'unknown embedded font or font slot');
333
+ }
311
334
  });
312
335
  if (node.fontFeatures !== undefined) {
313
336
  const names = new Set<string>();
@@ -410,13 +433,14 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
410
433
 
411
434
  function validateAsset(value: unknown): DrawableMotionAsset {
412
435
  const data = record(value, 'asset', [
413
- 'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontLicenses', 'audio', 'semantics',
436
+ 'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontSlots', 'fontLicenses', 'audio', 'semantics',
414
437
  ]);
415
438
  if (data.schema !== ASSET_SCHEMA) invalid('asset.schema', `this player reads ${ASSET_SCHEMA}`);
416
439
  identifier(data.name, 'asset.name');
417
440
  const machine = record(data.machine, 'machine');
418
441
  const values = machine.values === undefined ? {} : record(machine.values, 'machine.values');
419
442
  const fonts = resourceMap(data.fonts, 'fonts', FONT_URI);
443
+ const fontSlots = checkFontSlots(data.fontSlots, fonts, 'fontSlots');
420
444
  checkFontLicenses(data.fontLicenses, fonts, 'fontLicenses');
421
445
  const audio = resourceMap(data.audio, 'audio', AUDIO_URI);
422
446
  const palette = data.palette === undefined ? {} : record(data.palette, 'palette');
@@ -453,7 +477,7 @@ function validateAsset(value: unknown): DrawableMotionAsset {
453
477
  number(artboard.height, 'artboard.height', 1, 4096);
454
478
  const nodes = list(artboard.nodes, 'artboard.nodes', 256);
455
479
  if (!nodes.length) invalid('artboard.nodes', 'add at least one shape');
456
- const context = { channels, images, imageSlots, fonts, values, palette, points: new Set<string>() };
480
+ const context = { channels, images, imageSlots, fonts, fontSlots, values, palette, points: new Set<string>() };
457
481
  nodes.forEach((node, i) => checkNode(node, `artboard.nodes[${i}]`, context, 0));
458
482
  if (data.semantics !== undefined) {
459
483
  const names = new Set<string>();
@@ -586,11 +610,12 @@ function parseJSON(text: string): unknown {
586
610
  function validateAssetFile(decoded: unknown): MotionAssetFile<AssetResource> {
587
611
  const file = record(decoded, 'asset');
588
612
  if (file.schema !== ASSET_BUNDLE_SCHEMA) return validateAsset(file);
589
- record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontLicenses', 'audio']);
613
+ record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontSlots', 'fontLicenses', 'audio']);
590
614
  const name = identifier(file.name, 'bundle.name');
591
615
  const defaultArtboard = identifier(file.defaultArtboard, 'bundle.defaultArtboard');
592
616
  const artboards = record(file.artboards, 'bundle.artboards');
593
617
  const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<DrawableMotionAsset['fonts']>;
618
+ const fontSlots = checkFontSlots(file.fontSlots, fonts, 'bundle.fontSlots');
594
619
  checkFontLicenses(file.fontLicenses, fonts, 'bundle.fontLicenses');
595
620
  const fontLicenses = file.fontLicenses as MotionAsset['fontLicenses'];
596
621
  const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<DrawableMotionAsset['audio']>;
@@ -600,6 +625,7 @@ function validateAssetFile(decoded: unknown): MotionAssetFile<AssetResource> {
600
625
  return {
601
626
  schema: ASSET_BUNDLE_SCHEMA, name, defaultArtboard,
602
627
  ...(Object.keys(fonts).length && { fonts }),
628
+ ...(Object.keys(fontSlots).length && { fontSlots }),
603
629
  ...(fontLicenses && { fontLicenses }),
604
630
  ...(Object.keys(audio).length && { audio }),
605
631
  artboards: Object.fromEntries(entries.map(([key, value]) => {
@@ -607,10 +633,11 @@ function validateAssetFile(decoded: unknown): MotionAssetFile<AssetResource> {
607
633
  try {
608
634
  const board = record(value, `bundle.artboards.${key}`);
609
635
  const localFonts = board.fonts === undefined ? {} : record(board.fonts, 'fonts');
636
+ const localSlots = board.fontSlots === undefined ? {} : record(board.fontSlots, 'fontSlots');
610
637
  const localAudio = board.audio === undefined ? {} : record(board.audio, 'audio');
611
638
  const localLicenses = board.fontLicenses === undefined ? {} : record(board.fontLicenses, 'fontLicenses');
612
639
  validateAsset({
613
- ...board, fonts: { ...fonts, ...localFonts },
640
+ ...board, fonts: { ...fonts, ...localFonts }, fontSlots: { ...fontSlots, ...localSlots },
614
641
  fontLicenses: { ...fontLicenses, ...localLicenses }, audio: { ...audio, ...localAudio },
615
642
  });
616
643
  return [key, board as DrawableMotionAsset];
@@ -634,6 +661,7 @@ export function selectArtboard<R extends AssetResource>(file: MotionAssetFile<R>
634
661
  return {
635
662
  ...selected,
636
663
  ...(file.fonts && { fonts: { ...file.fonts, ...selected.fonts } }),
664
+ ...(file.fontSlots && { fontSlots: { ...file.fontSlots, ...selected.fontSlots } }),
637
665
  ...(file.fontLicenses && { fontLicenses: { ...file.fontLicenses, ...selected.fontLicenses } }),
638
666
  ...(file.audio && { audio: { ...file.audio, ...selected.audio } }),
639
667
  };
@@ -648,6 +676,57 @@ export function parseDrawableAsset(source: MotionAssetData, artboard?: string):
648
676
  return selectArtboard(parseDrawableFile(source), artboard);
649
677
  }
650
678
 
679
+ export function assetTextNodes(
680
+ nodes: readonly AssetNode[], parent = 'artboard.nodes', text: { node: AssetTextNode; where: string }[] = [],
681
+ ) {
682
+ nodes.forEach((node, index) => {
683
+ const where = `${parent}[${index}]`;
684
+ if (node.kind === 'text') text.push({ node, where });
685
+ if (node.kind === 'group') assetTextNodes(node.children, `${where}.children`, text);
686
+ if (node.kind === 'mesh') {
687
+ for (const [name, pin] of Object.entries(node.pins ?? {})) {
688
+ if (pin.children) assetTextNodes(pin.children, `${where}.pins.${name}.children`, text);
689
+ }
690
+ }
691
+ });
692
+ return text;
693
+ }
694
+
695
+ /** Bind fonts for the selected board and report referenced slots that still need a face. */
696
+ export function resolveAssetFonts<R extends AssetResource, Host>(
697
+ asset: MotionAsset<Machine, R>, overrides: Readonly<Record<string, Host>> = {},
698
+ ) {
699
+ const slots = asset.fontSlots ?? {};
700
+ for (const name of Object.keys(overrides)) {
701
+ if (!Object.hasOwn(slots, name)) invalid(`fontSlots.${name}`, 'unknown font slot');
702
+ }
703
+ const fonts: Record<string, R | Host> = { ...asset.fonts };
704
+ const missing: string[] = [];
705
+ if (Object.keys(slots).length) {
706
+ const used = new Set<string>();
707
+ for (const { node } of assetTextNodes(asset.artboard.nodes)) {
708
+ for (const name of node.fonts ?? []) used.add(name);
709
+ }
710
+ const replacedFallbacks = new Set<string>();
711
+ const activeFallbacks = new Set<string>();
712
+ for (const [name, { fallback }] of Object.entries(slots)) {
713
+ if (!used.has(name)) continue;
714
+ const host = Object.hasOwn(overrides, name) ? overrides[name] : undefined;
715
+ const face = host ?? (fallback === undefined ? undefined : asset.fonts?.[fallback]);
716
+ if (face === undefined) missing.push(name);
717
+ else fonts[name] = face;
718
+ if (fallback !== undefined) {
719
+ if (host == null) activeFallbacks.add(fallback);
720
+ else replacedFallbacks.add(fallback);
721
+ }
722
+ }
723
+ replacedFallbacks.forEach((fallback) => {
724
+ if (!used.has(fallback) && !activeFallbacks.has(fallback)) delete fonts[fallback];
725
+ });
726
+ }
727
+ return { fonts, missing };
728
+ }
729
+
651
730
  export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<string, string>>): string {
652
731
  'worklet';
653
732
  return typeof value === 'string' ? value : palette[value.palette]!;
@@ -1,6 +1,5 @@
1
1
  import { useEffect, useMemo, useState } from 'react';
2
2
  import { preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
3
- import type { AssetImages } from './asset-draw';
4
3
  import type { MotionAssetData } from './asset-binary';
5
4
 
6
5
  export type MotionAssetSource = MotionAssetData | { uri: string } | {
@@ -23,20 +22,20 @@ type CacheEntry = {
23
22
 
24
23
  // Cache prepared resources while subscribers own them. Each player creates its own machine snapshot.
25
24
  const cache = new Map<string, CacheEntry>();
26
- const imageIds = new WeakMap<object, number>();
25
+ const slotIds = new WeakMap<object, number>();
27
26
  const byteIds = new WeakMap<Uint8Array, number>();
28
- let nextImageId = 0;
27
+ let nextSlotId = 0;
29
28
  let nextByteId = 0;
30
29
  const idle = { status: 'idle', asset: null, error: null } as const;
31
30
  const loading = { status: 'loading', asset: null, error: null } as const;
32
31
 
33
- function slotKey(images: AssetImages | undefined) {
34
- return Object.keys(images ?? {}).sort().map((name) => {
35
- const image = images![name]!;
36
- let id = imageIds.get(image);
32
+ function slotKey(slots: Readonly<Record<string, object>> | undefined) {
33
+ return Object.keys(slots ?? {}).sort().map((name) => {
34
+ const resource = slots![name]!;
35
+ let id = slotIds.get(resource);
37
36
  if (id === undefined) {
38
- id = nextImageId++;
39
- imageIds.set(image, id);
37
+ id = nextSlotId++;
38
+ slotIds.set(resource, id);
40
39
  }
41
40
  return [name, id];
42
41
  });
@@ -83,15 +82,15 @@ function retain(key: string, source: MotionAssetSource, options: MotionAssetOpti
83
82
 
84
83
  /** Asynchronously load and share an asset. For Expo module IDs use the /expo entry point. */
85
84
  export function useMotionAsset(source?: MotionAssetSource | null, options: MotionAssetOptions = {}): MotionAssetResult {
86
- const { uploadImages = false, artboard, imageSlots, palette } = options;
85
+ const { uploadImages = false, artboard, imageSlots, fontSlots, palette } = options;
87
86
  const kind = source == null ? undefined : typeof source === 'string' ? 'text'
88
87
  : source instanceof Uint8Array ? 'bytes' : 'uri' in source ? 'uri' : 'custom';
89
88
  const id = source == null || typeof source === 'string' ? source
90
89
  : source instanceof Uint8Array ? byteId(source) : 'uri' in source ? source.uri : source.key;
91
90
  const key = useMemo(() => kind === undefined ? undefined : JSON.stringify([
92
- kind, id, uploadImages, artboard, slotKey(imageSlots),
91
+ kind, id, uploadImages, artboard, slotKey(imageSlots), slotKey(fontSlots),
93
92
  Object.keys(palette ?? {}).sort().map((name) => [name, palette![name]]),
94
- ]), [kind, id, uploadImages, artboard, imageSlots, palette]);
93
+ ]), [kind, id, uploadImages, artboard, imageSlots, fontSlots, palette]);
95
94
  const [state, setState] = useState<{ key: string; result: MotionAssetResult }>();
96
95
  useEffect(() => {
97
96
  setState((previous) => previous?.key === key ? previous : undefined);