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.
package/package.json CHANGED
@@ -1,29 +1,35 @@
1
1
  {
2
2
  "name": "skia-motion-runtime",
3
- "version": "3.0.0",
4
3
  "description": "React Native and Expo player for interactive .skmotion assets",
5
4
  "type": "module",
6
5
  "main": "./runtime/mobile.tsx",
7
6
  "types": "./runtime/mobile.tsx",
8
7
  "exports": {
9
8
  ".": "./runtime/mobile.tsx",
10
- "./machine": "./runtime/index.ts"
11
- },
12
- "license": "MIT",
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/asifnawaz/skia-motion-agentic-cli.git"
16
- },
17
- "homepage": "https://github.com/asifnawaz/skia-motion-agentic-cli",
18
- "bugs": {
19
- "url": "https://github.com/asifnawaz/skia-motion-agentic-cli/issues"
9
+ "./machine": "./runtime/index.ts",
10
+ "./expo": "./runtime/expo.ts",
11
+ "./expo-audio": "./runtime/expo-audio.ts"
20
12
  },
21
13
  "peerDependencies": {
22
14
  "react": ">=19",
23
15
  "react-native": ">=0.79",
24
16
  "react-native-reanimated": ">=4",
25
17
  "react-native-skia": ">=3.0.0",
26
- "react-native-worklets": ">=0.7"
18
+ "react-native-worklets": ">=0.7",
19
+ "expo-asset": ">=12",
20
+ "expo-audio": ">=1",
21
+ "expo-file-system": ">=19"
22
+ },
23
+ "peerDependenciesMeta": {
24
+ "expo-asset": {
25
+ "optional": true
26
+ },
27
+ "expo-audio": {
28
+ "optional": true
29
+ },
30
+ "expo-file-system": {
31
+ "optional": true
32
+ }
27
33
  },
28
34
  "files": [
29
35
  "LICENSE",
@@ -31,16 +37,31 @@
31
37
  "runtime/asset-draw.ts",
32
38
  "runtime/asset-image.ts",
33
39
  "runtime/asset-layout.ts",
40
+ "runtime/asset-load.ts",
34
41
  "runtime/asset-mesh.ts",
35
42
  "runtime/asset.ts",
43
+ "runtime/base64.ts",
44
+ "runtime/expo.ts",
45
+ "runtime/expo-audio.ts",
36
46
  "runtime/index.ts",
37
47
  "runtime/machine-schema.d.ts",
38
48
  "runtime/machine-schema.js",
39
49
  "runtime/mobile.tsx",
40
50
  "runtime/useMachine.ts",
51
+ "runtime/useMotionAsset.ts",
41
52
  "runtime/version.ts",
42
53
  "templates/motion/face.ts",
43
54
  "templates/motion/machine.ts",
44
55
  "templates/motion/motion.ts"
45
- ]
56
+ ],
57
+ "version": "3.1.0",
58
+ "license": "MIT",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git+https://github.com/asifnawaz/skia-motion-agentic-cli.git"
62
+ },
63
+ "homepage": "https://github.com/asifnawaz/skia-motion-agentic-cli",
64
+ "bugs": {
65
+ "url": "https://github.com/asifnawaz/skia-motion-agentic-cli/issues"
66
+ }
46
67
  }
@@ -1,9 +1,13 @@
1
- import { BlendMode, BlurStyle, ClipOp, FilterMode, MipmapMode, Skia, TileMode, VertexMode, type SkCanvas, type SkData, type SkImage, type SkPaint, type SkPath, type SkShader } from 'react-native-skia';
2
- import { MAX_FEATHER, usedAssetImages, type AssetNode, type MotionAsset, type PathCommand } from './asset';
3
- import { anchorOffset, layoutAsset } from './asset-layout';
1
+ import {
2
+ BlendMode, BlurStyle, ClipOp, FilterMode, MipmapMode, PaintStyle, Skia, StrokeCap, StrokeJoin, TextAlign, TextDirection, TileMode, VertexMode,
3
+ type SkCanvas, type SkData, type SkImage, type SkPaint, type SkParagraph, type SkPath, type SkShader, type SkTypeface, type SkTypefaceFontProvider,
4
+ } from 'react-native-skia';
5
+ import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type MotionAsset, type PathCommand } from './asset';
6
+ import { fitAsset, fittedAnchorOffset, type AssetLayoutOptions } from './asset-layout';
4
7
  import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
5
8
 
6
9
  type Channels = Readonly<Record<string, number>>;
10
+ type Palette = Readonly<Record<string, string>>;
7
11
  type Point = ReturnType<typeof meshPosition>;
8
12
  type DrawablePin = Omit<MeshPin, 'children'> & { children: readonly DrawableNode[] };
9
13
  type DrawableMesh = Omit<MeshNode, 'pins'> & {
@@ -17,19 +21,27 @@ type DrawableNode =
17
21
  preparedClip?: SkPath;
18
22
  })
19
23
  | DrawableMesh
24
+ | (AssetTextNode & { paragraph?: SkParagraph })
20
25
  | (DrawableShape & { preparedPath?: SkPath; preparedPaint?: SkPaint });
21
26
 
22
- type DrawableShape = Exclude<AssetNode, { kind: 'group' | 'mesh' }>;
27
+ type DrawableShape = Exclude<AssetNode, { kind: 'group' | 'mesh' | 'text' }>;
28
+ type TextValues = Readonly<Record<string, string>>;
23
29
 
24
30
  export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
25
31
  artboard: Omit<MotionAsset['artboard'], 'nodes'> & { nodes: readonly DrawableNode[] };
26
32
  meshShaders?: AssetMeshShaders;
33
+ fontProvider?: SkTypefaceFontProvider;
34
+ textBindings?: readonly string[];
35
+ palette?: Palette;
27
36
  };
28
37
  export type AssetImages = Readonly<Record<string, SkImage>>;
29
38
  export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
30
39
 
31
40
  /** Decode on the JS thread once per loaded file. Only the native images enter the UI worklet. */
32
- export function decodeAssetImages(asset: MotionAsset): AssetImages {
41
+ export function decodeAssetImages(asset: MotionAsset, slots: AssetImages = {}): AssetImages {
42
+ for (const name of Object.keys(slots)) {
43
+ if (!asset.imageSlots || !Object.hasOwn(asset.imageSlots, name)) throw new Error(`Unknown motion image slot "${name}"`);
44
+ }
33
45
  if (!asset.images) return {};
34
46
  // Skia v3 renamed this factory after 3.0. Keep both names usable at the peer dependency floor.
35
47
  const factory = Skia.Image as {
@@ -40,7 +52,8 @@ export function decodeAssetImages(asset: MotionAsset): AssetImages {
40
52
  const embedded = asset.images;
41
53
  const used = usedAssetImages(asset.artboard.nodes);
42
54
  return Object.fromEntries(Array.from(used, (name) => {
43
- const uri = embedded[name]!;
55
+ if (Object.hasOwn(slots, name)) return [name, slots[name]!];
56
+ const uri = embedded[asset.imageSlots?.[name] ?? name]!;
44
57
  const previous = byUri.get(uri);
45
58
  if (previous) return [name, previous];
46
59
  const data = Skia.Data.fromBase64(uri.slice(uri.indexOf(',') + 1));
@@ -71,7 +84,7 @@ function makePath(commands: readonly PathCommand[], channels: Channels) {
71
84
  return path.detach();
72
85
  }
73
86
 
74
- function makePaint(node: DrawableShape, alpha: number, channels: Channels): SkPaint {
87
+ function makePaint(node: DrawableShape, alpha: number, channels: Channels, palette: Palette): SkPaint {
75
88
  'worklet';
76
89
  const paint = Skia.Paint();
77
90
  paint.setAntiAlias(true);
@@ -81,8 +94,9 @@ function makePaint(node: DrawableShape, alpha: number, channels: Channels): SkPa
81
94
  }
82
95
  const feather = Math.min(MAX_FEATHER, read(node.feather, channels));
83
96
  if (feather > 0) paint.setMaskFilter(Skia.MaskFilter.MakeBlur(BlurStyle.Normal, feather, true));
84
- if (typeof node.fill === 'string') {
85
- const color = Skia.Color(node.fill);
97
+ if (!node.fill) return paint;
98
+ if (typeof node.fill === 'string' || 'palette' in node.fill) {
99
+ const color = Skia.Color(resolveAssetColor(node.fill, palette));
86
100
  paint.setColor(color);
87
101
  paint.setAlphaf(alpha * color[3]!);
88
102
  } else {
@@ -96,16 +110,16 @@ function makePaint(node: DrawableShape, alpha: number, channels: Channels): SkPa
96
110
  return paint;
97
111
  }
98
112
 
99
- function preparePaint(node: DrawableShape): SkPaint | undefined {
113
+ function preparePaint(node: DrawableShape, palette: Palette): SkPaint | undefined {
100
114
  if (typeof node.opacity === 'string' || node.opacity === 0) return undefined;
101
115
  if (node.kind !== 'image') {
102
116
  if (typeof node.feather === 'string') return undefined;
103
117
  const light = node.fill;
104
- if (typeof light !== 'string' && [light.x, light.y, light.radius].some((value) => typeof value === 'string')) {
118
+ if (!light || (typeof light !== 'string' && 'kind' in light && [light.x, light.y, light.radius].some((value) => typeof value === 'string'))) {
105
119
  return undefined;
106
120
  }
107
121
  }
108
- return makePaint(node, node.opacity ?? 1, {});
122
+ return makePaint(node, node.opacity ?? 1, {}, palette);
109
123
  }
110
124
 
111
125
  function meshTextureCoords(node: MeshNode | DrawableMesh, image: SkImage): Point[] {
@@ -120,14 +134,41 @@ function meshShader(image: SkImage): SkShader {
120
134
  return image.makeShaderOptions(TileMode.Decal, TileMode.Decal, FilterMode.Linear, MipmapMode.None);
121
135
  }
122
136
 
123
- function prepareNode(node: AssetNode, images: AssetImages, shaders: Record<string, SkShader>, shadersByImage: Map<SkImage, SkShader>): DrawableNode {
137
+ function makeParagraph(node: AssetTextNode, text: string, provider?: SkTypefaceFontProvider): SkParagraph {
138
+ 'worklet';
139
+ const builder = Skia.ParagraphBuilder.Make({
140
+ textDirection: node.direction === 'rtl' ? TextDirection.RTL : TextDirection.LTR,
141
+ textAlign: node.align === 'center' ? TextAlign.Center : node.align === 'end' ? TextAlign.End : TextAlign.Start,
142
+ maxLines: node.maxLines ?? 1,
143
+ ellipsis: '…',
144
+ }, node.fonts?.length ? provider : undefined);
145
+ builder.pushStyle({
146
+ color: Skia.Color(node.fill), fontSize: node.fontSize,
147
+ ...(node.fonts?.length ? { fontFamilies: [...node.fonts] } : {}),
148
+ });
149
+ builder.addText(text);
150
+ const paragraph = builder.build();
151
+ paragraph.layout(node.width);
152
+ return paragraph;
153
+ }
154
+
155
+ function prepareNode(
156
+ node: AssetNode, images: AssetImages, shaders: Record<string, SkShader>, shadersByImage: Map<SkImage, SkShader>,
157
+ provider: SkTypefaceFontProvider | undefined, textBindings: Set<string>, palette: Palette,
158
+ ): DrawableNode {
159
+ if (node.kind === 'text') {
160
+ if (typeof node.text === 'string') return { ...node, paragraph: makeParagraph(node, node.text, provider) };
161
+ textBindings.add(node.text.value);
162
+ return node;
163
+ }
124
164
  const commands = node.kind === 'group' ? node.clip : node.kind === 'path' ? node.commands : undefined;
125
165
  const prepared = commands?.every(([, ...coordinates]) => coordinates.every((value) => typeof value === 'number'))
126
166
  ? makePath(commands, {})
127
167
  : undefined;
128
168
  if (node.kind === 'group') {
129
169
  const { points: _points, ...drawing } = node;
130
- return { ...drawing, preparedClip: prepared, children: node.children.map((child) => prepareNode(child, images, shaders, shadersByImage)) };
170
+ return { ...drawing, preparedClip: prepared, children: node.children.map((child) =>
171
+ prepareNode(child, images, shaders, shadersByImage, provider, textBindings, palette)) };
131
172
  }
132
173
  if (node.kind === 'mesh') {
133
174
  const image = images[node.image];
@@ -138,7 +179,7 @@ function prepareNode(node: AssetNode, images: AssetImages, shaders: Record<strin
138
179
  }
139
180
  const pins = node.pins && Object.values(node.pins).filter((pin) => pin.children?.length).map((pin) => ({
140
181
  ...pin,
141
- children: pin.children!.map((child) => prepareNode(child, images, shaders, shadersByImage)),
182
+ children: pin.children!.map((child) => prepareNode(child, images, shaders, shadersByImage, provider, textBindings, palette)),
142
183
  }));
143
184
  const fixed = node.vertices.every(([x, y]) => typeof x === 'number' && typeof y === 'number');
144
185
  return {
@@ -147,15 +188,35 @@ function prepareNode(node: AssetNode, images: AssetImages, shaders: Record<strin
147
188
  textureCoords: image ? meshTextureCoords(node, image) : undefined,
148
189
  };
149
190
  }
150
- return { ...node, preparedPath: prepared, preparedPaint: preparePaint(node) };
191
+ return { ...node, preparedPath: prepared, preparedPaint: preparePaint(node, palette) };
151
192
  }
152
193
 
153
194
  /** Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose. */
154
195
  export function prepareAssetDrawing(asset: MotionAsset, images: AssetImages = {}): DrawableAsset {
155
196
  const shaders: Record<string, SkShader> = {};
156
197
  const shadersByImage = new Map<SkImage, SkShader>();
157
- const nodes = asset.artboard.nodes.map((node) => prepareNode(node, images, shaders, shadersByImage));
158
- return { channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders };
198
+ let fontProvider: SkTypefaceFontProvider | undefined;
199
+ for (const [name, uri] of Object.entries(asset.fonts ?? {})) {
200
+ fontProvider ??= Skia.TypefaceFontProvider.Make();
201
+ const data = Skia.Data.fromBase64(uri.slice(uri.indexOf(',') + 1));
202
+ // Match the renamed factory while retaining the Skia 3.0 peer floor.
203
+ const factory = Skia.Typeface as {
204
+ MakeFromData?: (data: SkData) => SkTypeface | null;
205
+ MakeFreeTypeFaceFromData?: (data: SkData) => SkTypeface | null;
206
+ };
207
+ const typeface = factory.MakeFromData ? factory.MakeFromData(data) : factory.MakeFreeTypeFaceFromData?.(data);
208
+ if (!typeface) throw new Error(`fonts.${name}: Skia could not decode the font`);
209
+ fontProvider.registerFont(typeface, name);
210
+ }
211
+ const textBindings = new Set<string>();
212
+ const palette = asset.palette ?? {};
213
+ const nodes = asset.artboard.nodes.map((node) => prepareNode(node, images, shaders, shadersByImage, fontProvider, textBindings, palette));
214
+ return {
215
+ channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders,
216
+ ...(fontProvider && { fontProvider }),
217
+ ...(textBindings.size && { textBindings: [...textBindings] }),
218
+ ...(asset.palette && { palette }),
219
+ };
159
220
  }
160
221
 
161
222
  /** Warmed images may be different native objects. Prepare their shaders with the same geometry. */
@@ -183,20 +244,56 @@ function drawMesh(canvas: SkCanvas, node: DrawableMesh, channels: Channels, imag
183
244
  canvas.drawVertices(mesh, BlendMode.SrcOver, paint);
184
245
  }
185
246
 
186
- function drawNodes(canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders: AssetMeshShaders, insetX = 0, insetY = 0): void {
247
+ function drawStroke(
248
+ canvas: SkCanvas, path: SkPath, stroke: AssetStroke, alpha: number, feather: number, channels: Channels, palette: Palette,
249
+ ): void {
250
+ 'worklet';
251
+ const width = Math.min(4096, read(stroke.width, channels));
252
+ if (!(width > 0)) return;
253
+ const start = Math.max(0, Math.min(1, read(stroke.trim?.start, channels)));
254
+ const end = Math.max(0, Math.min(1, read(stroke.trim?.end, channels, 1)));
255
+ if (end <= start) return;
256
+ const trimmed = start === 0 && end === 1 ? path : Skia.Path.Trim(path, start, end, false);
257
+ if (!trimmed) return;
258
+ const paint = Skia.Paint();
259
+ paint.setAntiAlias(true);
260
+ const color = Skia.Color(resolveAssetColor(stroke.color, palette));
261
+ paint.setColor(color);
262
+ paint.setAlphaf(alpha * color[3]!);
263
+ paint.setStyle(PaintStyle.Stroke);
264
+ paint.setStrokeWidth(width);
265
+ paint.setStrokeCap(stroke.cap === 'round' ? StrokeCap.Round : stroke.cap === 'square' ? StrokeCap.Square : StrokeCap.Butt);
266
+ paint.setStrokeJoin(stroke.join === 'round' ? StrokeJoin.Round : stroke.join === 'bevel' ? StrokeJoin.Bevel : StrokeJoin.Miter);
267
+ if (stroke.dash) paint.setPathEffect(Skia.PathEffect.MakeDash([...stroke.dash.intervals], read(stroke.dash.phase, channels)));
268
+ if (feather > 0) paint.setMaskFilter(Skia.MaskFilter.MakeBlur(BlurStyle.Normal, feather, true));
269
+ canvas.drawPath(trimmed, paint);
270
+ }
271
+
272
+ function drawNodes(
273
+ canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders: AssetMeshShaders,
274
+ values: TextValues, fonts: SkTypefaceFontProvider | undefined, palette: Palette, layout?: ReturnType<typeof fitAsset>,
275
+ ): void {
187
276
  'worklet';
188
277
  for (const node of nodes) {
189
278
  if (node.kind === 'group') {
190
- const offset = anchorOffset(node.anchor, insetX, insetY);
279
+ const offset = fittedAnchorOffset(node.anchor, layout);
191
280
  canvas.save();
192
281
  canvas.translate(read(node.x, channels) + offset.x, read(node.y, channels) + offset.y);
193
282
  canvas.rotate(read(node.rotation, channels), 0, 0);
194
283
  canvas.scale(read(node.scaleX, channels, 1), read(node.scaleY, channels, 1));
195
284
  if (node.clip) canvas.clipPath(node.preparedClip ?? makePath(node.clip, channels), ClipOp.Intersect, true);
196
- drawNodes(canvas, node.children, channels, images, shaders);
285
+ drawNodes(canvas, node.children, channels, images, shaders, values, fonts, palette);
197
286
  canvas.restore();
198
287
  continue;
199
288
  }
289
+ if (node.kind === 'text') {
290
+ const content = typeof node.text === 'string' ? node.text : values[node.text.value] ?? '';
291
+ if (content) {
292
+ const paragraph = node.paragraph ?? makeParagraph(node, content, fonts);
293
+ paragraph.paint(canvas, read(node.x, channels), read(node.y, channels));
294
+ }
295
+ continue;
296
+ }
200
297
  const alpha = Math.min(1, Math.max(0, read(node.opacity, channels, 1)));
201
298
  if (node.kind === 'mesh') {
202
299
  const image = images[node.image];
@@ -206,14 +303,20 @@ function drawNodes(canvas: SkCanvas, nodes: readonly DrawableNode[], channels: C
206
303
  const { x, y } = meshPinPosition(node, pin, channels);
207
304
  canvas.save();
208
305
  canvas.translate(x, y);
209
- drawNodes(canvas, pin.children, channels, images, shaders);
306
+ drawNodes(canvas, pin.children, channels, images, shaders, values, fonts, palette);
210
307
  canvas.restore();
211
308
  }
212
309
  }
213
310
  continue;
214
311
  }
215
312
  if (!alpha) continue;
216
- const paint = node.preparedPaint ?? makePaint(node, alpha, channels);
313
+ if (node.kind === 'path') {
314
+ const path = node.preparedPath ?? makePath(node.commands, channels);
315
+ if (node.fill) canvas.drawPath(path, node.preparedPaint ?? makePaint(node, alpha, channels, palette));
316
+ if (node.stroke) drawStroke(canvas, path, node.stroke, alpha, Math.min(MAX_FEATHER, read(node.feather, channels)), channels, palette);
317
+ continue;
318
+ }
319
+ const paint = node.preparedPaint ?? makePaint(node, alpha, channels, palette);
217
320
  if (node.kind === 'image') {
218
321
  const image = images[node.image];
219
322
  const width = read(node.width, channels);
@@ -227,10 +330,6 @@ function drawNodes(canvas: SkCanvas, nodes: readonly DrawableNode[], channels: C
227
330
  );
228
331
  continue;
229
332
  }
230
- if (node.kind === 'path') {
231
- canvas.drawPath(node.preparedPath ?? makePath(node.commands, channels), paint);
232
- continue;
233
- }
234
333
  const w = read(node.width, channels);
235
334
  const h = read(node.height, channels);
236
335
  if (w <= 0 || h <= 0) continue;
@@ -244,19 +343,24 @@ function drawNodes(canvas: SkCanvas, nodes: readonly DrawableNode[], channels: C
244
343
  }
245
344
 
246
345
  /** Draw the resolved pose inside a viewport, preserving artboard coordinates and aspect ratio. */
247
- export function drawAsset(canvas: SkCanvas, asset: DrawableAsset, pose: Channels, width: number, height: number, images: AssetImages = {}): void {
346
+ export function drawAsset(
347
+ canvas: SkCanvas, asset: DrawableAsset, pose: Channels, width: number, height: number,
348
+ images: AssetImages = {}, values: TextValues = {}, options?: AssetLayoutOptions,
349
+ ): void {
248
350
  'worklet';
249
351
  if (width <= 0 || height <= 0) return;
250
352
  const board = asset.artboard;
251
- const { scale, insetX, insetY } = layoutAsset(board, width, height);
353
+ const layout = fitAsset(board, width, height, options);
354
+ const { scale, offsetX, offsetY, spaceX, spaceY } = layout;
252
355
  const anchored = board.nodes.some((node) => node.kind === 'group' && node.anchor);
253
356
  canvas.save();
254
- canvas.translate(insetX * scale, insetY * scale);
357
+ if (spaceX < 0 || spaceY < 0) canvas.clipRect(Skia.XYWHRect(0, 0, width, height), ClipOp.Intersect, true);
358
+ canvas.translate(offsetX * scale, offsetY * scale);
255
359
  canvas.scale(scale, scale);
256
360
  const bounds = anchored
257
- ? Skia.XYWHRect(-insetX, -insetY, board.width + 2 * insetX, board.height + 2 * insetY)
361
+ ? Skia.XYWHRect(-offsetX, -offsetY, board.width + spaceX, board.height + spaceY)
258
362
  : Skia.XYWHRect(0, 0, board.width, board.height);
259
363
  canvas.clipRect(bounds, ClipOp.Intersect, true);
260
- drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, asset.meshShaders ?? {}, insetX, insetY);
364
+ drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, asset.meshShaders ?? {}, values, asset.fontProvider, asset.palette ?? {}, layout);
261
365
  canvas.restore();
262
366
  }
@@ -1,21 +1,4 @@
1
- const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2
-
3
- function decodeBase64Slice(encoded: string): Uint8Array {
4
- const bytes = new Uint8Array(encoded.length * 3 / 4);
5
- let length = 0;
6
- let bits = 0;
7
- let value = 0;
8
- for (const char of encoded) {
9
- if (char === '=') break;
10
- value = (value << 6) | ALPHABET.indexOf(char);
11
- bits += 6;
12
- if (bits >= 8) {
13
- bits -= 8;
14
- bytes[length++] = (value >>> bits) & 255;
15
- }
16
- }
17
- return bytes.subarray(0, length);
18
- }
1
+ import { decodeBase64 } from './base64';
19
2
 
20
3
  /** Check the embedded image header before passing its bytes to a renderer. */
21
4
  export function imageSize(uri: unknown): { width: number; height: number } | null {
@@ -25,8 +8,8 @@ export function imageSize(uri: unknown): { width: number; height: number } | nul
25
8
  const encoded = match[2]!;
26
9
  const padding = encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0;
27
10
  const size = encoded.length * 3 / 4 - padding;
28
- const prefix = decodeBase64Slice(encoded.slice(0, 40));
29
- const suffix = decodeBase64Slice(encoded.slice(-20)).subarray(-12);
11
+ const prefix = decodeBase64(encoded.slice(0, 40));
12
+ const suffix = decodeBase64(encoded.slice(-20)).subarray(-12);
30
13
  return sizeFromParts(match[1]!, prefix, suffix, size);
31
14
  }
32
15
 
@@ -1,4 +1,6 @@
1
1
  export type AssetAnchor = { x?: 'left' | 'center' | 'right'; y?: 'top' | 'center' | 'bottom' };
2
+ export type AssetFit = 'contain' | 'cover' | 'scaleDown' | 'none';
3
+ export type AssetLayoutOptions = { fit?: AssetFit; alignment?: AssetAnchor };
2
4
 
3
5
  type Size = { width: number; height: number };
4
6
 
@@ -13,6 +15,31 @@ export function layoutAsset(artboard: Size, width: number, height: number) {
13
15
  };
14
16
  }
15
17
 
18
+ /** Resolve an oriented viewport in artboard units. Signed offsets also handle cover clipping. */
19
+ export function fitAsset(artboard: Size, width: number, height: number, options: AssetLayoutOptions = {}) {
20
+ 'worklet';
21
+ const contain = layoutAsset(artboard, width, height);
22
+ const { fit = 'contain', alignment } = options;
23
+ const scale = fit === 'cover' ? Math.max(width / artboard.width, height / artboard.height)
24
+ : fit === 'none' ? 1 : fit === 'scaleDown' ? Math.min(1, contain.scale) : contain.scale;
25
+ const spaceX = fit === 'contain' ? contain.insetX * 2 : width / scale - artboard.width;
26
+ const spaceY = fit === 'contain' ? contain.insetY * 2 : height / scale - artboard.height;
27
+ const fractionX = alignment?.x === 'left' ? 0 : alignment?.x === 'right' ? 1 : 0.5;
28
+ const fractionY = alignment?.y === 'top' ? 0 : alignment?.y === 'bottom' ? 1 : 0.5;
29
+ return { scale, spaceX, spaceY, offsetX: spaceX * fractionX, offsetY: spaceY * fractionY };
30
+ }
31
+
32
+ export function fittedAnchorOffset(anchor: AssetAnchor | undefined, layout: ReturnType<typeof fitAsset> | undefined) {
33
+ 'worklet';
34
+ if (!layout) return { x: 0, y: 0 };
35
+ const dx = anchor?.x === 'left' ? 0 : anchor?.x === 'right' ? layout.spaceX : layout.spaceX / 2;
36
+ const dy = anchor?.y === 'top' ? 0 : anchor?.y === 'bottom' ? layout.spaceY : layout.spaceY / 2;
37
+ return {
38
+ x: anchor?.x && layout.spaceX > 0 ? dx - layout.offsetX : 0,
39
+ y: anchor?.y && layout.spaceY > 0 ? dy - layout.offsetY : 0,
40
+ };
41
+ }
42
+
16
43
  export function anchorOffset(anchor: AssetAnchor | undefined, insetX: number, insetY: number) {
17
44
  'worklet';
18
45
  return {
@@ -0,0 +1,70 @@
1
+ import type { SkImage } from 'react-native-skia';
2
+ import { assetClips, bindAssetPalette, parseAsset, type MotionAsset } from './asset';
3
+ import { decodeAssetImages, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
4
+
5
+ let nextAssetKey = 0;
6
+
7
+ export type LoadedMotionAsset = Readonly<{
8
+ key: number;
9
+ machine: MotionAsset['machine'];
10
+ markers: MotionAsset['markers'];
11
+ drawing: DrawableAsset;
12
+ images: AssetImages;
13
+ clips: ReturnType<typeof assetClips>;
14
+ semantics?: MotionAsset['semantics'];
15
+ audio?: MotionAsset['audio'];
16
+ }>;
17
+
18
+ /** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
19
+ export type MotionPrepareOptions = { artboard?: string; imageSlots?: AssetImages; palette?: Readonly<Record<string, string>> };
20
+
21
+ export function loadMotionAsset(source: string, { artboard, imageSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
22
+ const asset = bindAssetPalette(parseAsset(source, artboard), palette);
23
+ const images = decodeAssetImages(asset, imageSlots);
24
+ return {
25
+ key: nextAssetKey++,
26
+ machine: asset.machine,
27
+ markers: asset.markers,
28
+ drawing: prepareAssetDrawing(asset, images),
29
+ images,
30
+ clips: assetClips(asset),
31
+ semantics: asset.semantics,
32
+ audio: asset.audio,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Prepare a file before mounting it. Skia versions with asynchronous raster decoding perform
38
+ * that work off the JS thread. Upload is opt-in and can retain textures until the file is released.
39
+ */
40
+ export async function preloadMotionAsset(
41
+ source: string | LoadedMotionAsset,
42
+ { uploadImages = false, ...options }: MotionPrepareOptions & { uploadImages?: boolean } = {},
43
+ ): Promise<LoadedMotionAsset> {
44
+ const loaded = typeof source === 'string' ? loadMotionAsset(source, options) : source;
45
+ const warmed = new Map<SkImage, SkImage>();
46
+ const images: [string, SkImage][] = [];
47
+ let changed = false;
48
+ for (const [name, image] of Object.entries(loaded.images)) {
49
+ let ready = warmed.get(image);
50
+ if (!ready) {
51
+ // Neither method is available at the 3.0 peer dependency floor.
52
+ const preloadable = image as SkImage & { makeRasterImage?: () => Promise<SkImage> };
53
+ ready = await preloadable.makeRasterImage?.() ?? image;
54
+ if (uploadImages) {
55
+ const uploadable = ready as SkImage & { makeTextureImage?: () => SkImage };
56
+ try {
57
+ ready = uploadable.makeTextureImage?.() ?? ready;
58
+ } catch {
59
+ // A reduced or unsupported backend can still upload the raster image when drawn.
60
+ }
61
+ }
62
+ warmed.set(image, ready);
63
+ }
64
+ images.push([name, ready]);
65
+ changed ||= ready !== image;
66
+ }
67
+ if (!warmed.size) return loaded;
68
+ const ready = Object.fromEntries(images);
69
+ return { ...loaded, images: ready, drawing: changed ? rebindAssetMeshShaders(loaded.drawing, ready) : loaded.drawing };
70
+ }