skia-motion-runtime 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the skia-motion authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE.md ADDED
@@ -0,0 +1,62 @@
1
+ # Notices
2
+
3
+ The motion docs in `docs/motion` and the files in `templates/motion` adapt code and rules from two MIT-licensed skills. Their licences follow, copied whole.
4
+
5
+ | This file | Adapts |
6
+ |---|---|
7
+ | templates/motion/motion.ts | rossark-motion-skill `templates/react-native/motion.ts` (track, flow, seg, wave, loop, bell, seeded, the curves); huashu-art-motion `scripts/engine/lib/motion.js` (`MO.bezier` solver, `MO.spring`) |
8
+ | templates/motion/clock.app.ts | rossark-motion-skill `templates/react-native/motion.ts` (useLoopClock, useOneShotClock) |
9
+ | templates/motion/liveFace.tsx | rossark-motion-skill `templates/react-native/liveFace.tsx` (lid, cheek, closed line, happy arc, lid clip); huashu-art-motion `scripts/engine/lib/toon.js` (the expression set: shock, happy, worry, mouth shapes) |
10
+ | docs/motion/principles.md, body.md | rossark-motion-skill `SKILL.md` §1–§8, §11 and `MOTION.md` |
11
+ | docs/motion/faces.md, idle.md | rossark-motion-skill `SKILL.md` §4–§5; huashu-art-motion `scripts/engine/lib/toon.js`, `rig_huashu.js`, `references/04-纯代码绘制.md`, `07-正面经验.md`, `镜头语言.md` |
12
+ | docs/motion/anticipation.md, body.md (timing tables) | ideas from LottieFiles motion-design (`director/disney-principles.md`, `reference/timing-easing-tables.md`, `patterns/entrance-exit.md`), written in our own words; that skill ships no licence file, so none of its text is copied |
13
+ | templates/motion/points.ts, templates/motion/moves.ts (morph and point motions) | morph and point-motion styles (paths and staggers of a point set morphing into another; the ways a point cloud arrives and leaves; the odometer's rolling digits) ported from Word Quran's own reels kit by its owner, MIT in this package. skac's package ships no onetake code; a project may load onetake's lib/motion.js through its config, and Word Quran holds the author's permission |
14
+ | templates/motion/clock.remotion.ts, docs/motion/remotion-and-app.md | the sRGB fix for Skia's WebGL drawing buffer, written for this package |
15
+
16
+ ## rossark-motion-skill
17
+
18
+ MIT License
19
+
20
+ Copyright (c) 2026 rossark0
21
+
22
+ Permission is hereby granted, free of charge, to any person obtaining a copy
23
+ of this software and associated documentation files (the "Software"), to deal
24
+ in the Software without restriction, including without limitation the rights
25
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
26
+ copies of the Software, and to permit persons to whom the Software is
27
+ furnished to do so, subject to the following conditions:
28
+
29
+ The above copyright notice and this permission notice shall be included in all
30
+ copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38
+ SOFTWARE.
39
+
40
+ ## huashu-art-motion
41
+
42
+ MIT License
43
+
44
+ Copyright (c) 2026 alchaincyf (花叔 · 花生)
45
+
46
+ Permission is hereby granted, free of charge, to any person obtaining a copy
47
+ of this software and associated documentation files (the "Software"), to deal
48
+ in the Software without restriction, including without limitation the rights
49
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
50
+ copies of the Software, and to permit persons to whom the Software is
51
+ furnished to do so, subject to the following conditions:
52
+
53
+ The above copyright notice and this permission notice shall be included in all
54
+ copies or substantial portions of the Software.
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
62
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "skia-motion-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "React Native and Expo player for interactive .skmotion assets",
4
+ "type": "module",
5
+ "main": "./runtime/mobile.tsx",
6
+ "types": "./runtime/mobile.tsx",
7
+ "exports": {
8
+ ".": "./runtime/mobile.tsx",
9
+ "./machine": "./runtime/index.ts",
10
+ "./expo": "./runtime/expo.ts",
11
+ "./expo-audio": "./runtime/expo-audio.ts"
12
+ },
13
+ "peerDependencies": {
14
+ "react": ">=19",
15
+ "react-native": ">=0.79",
16
+ "react-native-reanimated": ">=4",
17
+ "react-native-skia": ">=3.0.0",
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
+ }
33
+ },
34
+ "files": [
35
+ "LICENSE",
36
+ "NOTICE.md",
37
+ "runtime/asset-draw.ts",
38
+ "runtime/asset-image.ts",
39
+ "runtime/asset-layout.ts",
40
+ "runtime/asset-load.ts",
41
+ "runtime/asset-mesh.ts",
42
+ "runtime/asset.ts",
43
+ "runtime/base64.ts",
44
+ "runtime/expo.ts",
45
+ "runtime/expo-audio.ts",
46
+ "runtime/index.ts",
47
+ "runtime/machine-schema.d.ts",
48
+ "runtime/machine-schema.js",
49
+ "runtime/mobile.tsx",
50
+ "runtime/useMachine.ts",
51
+ "runtime/useMotionAsset.ts",
52
+ "runtime/version.ts",
53
+ "templates/motion/face.ts",
54
+ "templates/motion/machine.ts",
55
+ "templates/motion/motion.ts"
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
+ }
67
+ }
@@ -0,0 +1,366 @@
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';
7
+ import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
8
+
9
+ type Channels = Readonly<Record<string, number>>;
10
+ type Palette = Readonly<Record<string, string>>;
11
+ type Point = ReturnType<typeof meshPosition>;
12
+ type DrawablePin = Omit<MeshPin, 'children'> & { children: readonly DrawableNode[] };
13
+ type DrawableMesh = Omit<MeshNode, 'pins'> & {
14
+ pins?: readonly DrawablePin[];
15
+ fixedPositions?: Point[];
16
+ textureCoords?: Point[];
17
+ };
18
+ type DrawableNode =
19
+ | (Omit<Extract<AssetNode, { kind: 'group' }>, 'children'> & {
20
+ children: readonly DrawableNode[];
21
+ preparedClip?: SkPath;
22
+ })
23
+ | DrawableMesh
24
+ | (AssetTextNode & { paragraph?: SkParagraph })
25
+ | (DrawableShape & { preparedPath?: SkPath; preparedPaint?: SkPaint });
26
+
27
+ type DrawableShape = Exclude<AssetNode, { kind: 'group' | 'mesh' | 'text' }>;
28
+ type TextValues = Readonly<Record<string, string>>;
29
+
30
+ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
31
+ artboard: Omit<MotionAsset['artboard'], 'nodes'> & { nodes: readonly DrawableNode[] };
32
+ meshShaders?: AssetMeshShaders;
33
+ fontProvider?: SkTypefaceFontProvider;
34
+ textBindings?: readonly string[];
35
+ palette?: Palette;
36
+ };
37
+ export type AssetImages = Readonly<Record<string, SkImage>>;
38
+ export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
39
+
40
+ /** Decode on the JS thread once per loaded file. Only the native images enter the UI worklet. */
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
+ }
45
+ if (!asset.images) return {};
46
+ // Skia v3 renamed this factory after 3.0. Keep both names usable at the peer dependency floor.
47
+ const factory = Skia.Image as {
48
+ MakeFromEncoded?: (data: SkData) => SkImage | null;
49
+ MakeImageFromEncoded?: (data: SkData) => SkImage | null;
50
+ };
51
+ const byUri = new Map<string, SkImage>();
52
+ const embedded = asset.images;
53
+ const used = usedAssetImages(asset.artboard.nodes);
54
+ return Object.fromEntries(Array.from(used, (name) => {
55
+ if (Object.hasOwn(slots, name)) return [name, slots[name]!];
56
+ const uri = embedded[asset.imageSlots?.[name] ?? name]!;
57
+ const previous = byUri.get(uri);
58
+ if (previous) return [name, previous];
59
+ const data = Skia.Data.fromBase64(uri.slice(uri.indexOf(',') + 1));
60
+ const image = factory.MakeFromEncoded ? factory.MakeFromEncoded(data) : factory.MakeImageFromEncoded?.(data);
61
+ if (!image) throw new Error(`images.${name}: could not decode the embedded image`);
62
+ byUri.set(uri, image);
63
+ return [name, image];
64
+ }));
65
+ }
66
+
67
+ function read(value: string | number | undefined, channels: Channels, fallback = 0): number {
68
+ 'worklet';
69
+ if (value === undefined) return fallback;
70
+ return typeof value === 'string' ? channels[value]! : value;
71
+ }
72
+
73
+ function makePath(commands: readonly PathCommand[], channels: Channels) {
74
+ 'worklet';
75
+ const path = Skia.PathBuilder.Make();
76
+ for (const [op, ...coords] of commands) {
77
+ const args = coords.map((coord) => read(coord, channels));
78
+ if (op === 'M') path.moveTo(args[0]!, args[1]!);
79
+ else if (op === 'L') path.lineTo(args[0]!, args[1]!);
80
+ else if (op === 'Q') path.quadTo(args[0]!, args[1]!, args[2]!, args[3]!);
81
+ else if (op === 'C') path.cubicTo(args[0]!, args[1]!, args[2]!, args[3]!, args[4]!, args[5]!);
82
+ else path.close();
83
+ }
84
+ return path.detach();
85
+ }
86
+
87
+ function makePaint(node: DrawableShape, alpha: number, channels: Channels, palette: Palette): SkPaint {
88
+ 'worklet';
89
+ const paint = Skia.Paint();
90
+ paint.setAntiAlias(true);
91
+ if (node.kind === 'image') {
92
+ paint.setAlphaf(alpha);
93
+ return paint;
94
+ }
95
+ const feather = Math.min(MAX_FEATHER, read(node.feather, channels));
96
+ if (feather > 0) paint.setMaskFilter(Skia.MaskFilter.MakeBlur(BlurStyle.Normal, feather, true));
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));
100
+ paint.setColor(color);
101
+ paint.setAlphaf(alpha * color[3]!);
102
+ } else {
103
+ const light = node.fill;
104
+ const center = { x: read(light.x, channels), y: read(light.y, channels) };
105
+ const radius = Math.max(0.001, read(light.radius, channels));
106
+ const colors = light.colors.map((color) => Skia.Color(color));
107
+ paint.setShader(Skia.Shader.MakeRadialGradient(center, radius, colors, null, TileMode.Clamp));
108
+ paint.setAlphaf(alpha);
109
+ }
110
+ return paint;
111
+ }
112
+
113
+ function preparePaint(node: DrawableShape, palette: Palette): SkPaint | undefined {
114
+ if (typeof node.opacity === 'string' || node.opacity === 0) return undefined;
115
+ if (node.kind !== 'image') {
116
+ if (typeof node.feather === 'string') return undefined;
117
+ const light = node.fill;
118
+ if (!light || (typeof light !== 'string' && 'kind' in light && [light.x, light.y, light.radius].some((value) => typeof value === 'string'))) {
119
+ return undefined;
120
+ }
121
+ }
122
+ return makePaint(node, node.opacity ?? 1, {}, palette);
123
+ }
124
+
125
+ function meshTextureCoords(node: MeshNode | DrawableMesh, image: SkImage): Point[] {
126
+ 'worklet';
127
+ const width = image.width();
128
+ const height = image.height();
129
+ return node.vertices.map(([, , u, v]) => ({ x: u * width, y: v * height }));
130
+ }
131
+
132
+ function meshShader(image: SkImage): SkShader {
133
+ 'worklet';
134
+ return image.makeShaderOptions(TileMode.Decal, TileMode.Decal, FilterMode.Linear, MipmapMode.None);
135
+ }
136
+
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
+ }
164
+ const commands = node.kind === 'group' ? node.clip : node.kind === 'path' ? node.commands : undefined;
165
+ const prepared = commands?.every(([, ...coordinates]) => coordinates.every((value) => typeof value === 'number'))
166
+ ? makePath(commands, {})
167
+ : undefined;
168
+ if (node.kind === 'group') {
169
+ const { points: _points, ...drawing } = node;
170
+ return { ...drawing, preparedClip: prepared, children: node.children.map((child) =>
171
+ prepareNode(child, images, shaders, shadersByImage, provider, textBindings, palette)) };
172
+ }
173
+ if (node.kind === 'mesh') {
174
+ const image = images[node.image];
175
+ if (image && !Object.hasOwn(shaders, node.image)) {
176
+ const shader = shadersByImage.get(image) ?? meshShader(image);
177
+ shadersByImage.set(image, shader);
178
+ shaders[node.image] = shader;
179
+ }
180
+ const pins = node.pins && Object.values(node.pins).filter((pin) => pin.children?.length).map((pin) => ({
181
+ ...pin,
182
+ children: pin.children!.map((child) => prepareNode(child, images, shaders, shadersByImage, provider, textBindings, palette)),
183
+ }));
184
+ const fixed = node.vertices.every(([x, y]) => typeof x === 'number' && typeof y === 'number');
185
+ return {
186
+ ...node, pins,
187
+ fixedPositions: fixed ? node.vertices.map((vertex) => meshPosition(vertex, {})) : undefined,
188
+ textureCoords: image ? meshTextureCoords(node, image) : undefined,
189
+ };
190
+ }
191
+ return { ...node, preparedPath: prepared, preparedPaint: preparePaint(node, palette) };
192
+ }
193
+
194
+ /** Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose. */
195
+ export function prepareAssetDrawing(asset: MotionAsset, images: AssetImages = {}): DrawableAsset {
196
+ const shaders: Record<string, SkShader> = {};
197
+ const shadersByImage = new Map<SkImage, SkShader>();
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
+ };
220
+ }
221
+
222
+ /** Warmed images may be different native objects. Prepare their shaders with the same geometry. */
223
+ export function rebindAssetMeshShaders(drawing: DrawableAsset, images: AssetImages): DrawableAsset {
224
+ const names = Object.keys(drawing.meshShaders ?? {});
225
+ if (!names.length) return drawing;
226
+ const byImage = new Map<SkImage, SkShader>();
227
+ const meshShaders = Object.fromEntries(names.map((name) => {
228
+ const image = images[name]!;
229
+ const shader = byImage.get(image) ?? meshShader(image);
230
+ byImage.set(image, shader);
231
+ return [name, shader];
232
+ }));
233
+ return { ...drawing, meshShaders };
234
+ }
235
+
236
+ function drawMesh(canvas: SkCanvas, node: DrawableMesh, channels: Channels, image: SkImage, alpha: number, shader: SkShader | undefined) {
237
+ 'worklet';
238
+ const positions = node.fixedPositions ?? node.vertices.map((vertex) => meshPosition(vertex, channels));
239
+ const textures = node.textureCoords ?? meshTextureCoords(node, image);
240
+ const paint = Skia.Paint();
241
+ paint.setAlphaf(alpha);
242
+ paint.setShader(shader ?? meshShader(image));
243
+ const mesh = Skia.MakeVertices(VertexMode.Triangles, positions, textures, undefined, node.indices as number[]);
244
+ canvas.drawVertices(mesh, BlendMode.SrcOver, paint);
245
+ }
246
+
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 {
276
+ 'worklet';
277
+ for (const node of nodes) {
278
+ if (node.kind === 'group') {
279
+ const offset = fittedAnchorOffset(node.anchor, layout);
280
+ canvas.save();
281
+ canvas.translate(read(node.x, channels) + offset.x, read(node.y, channels) + offset.y);
282
+ canvas.rotate(read(node.rotation, channels), 0, 0);
283
+ canvas.scale(read(node.scaleX, channels, 1), read(node.scaleY, channels, 1));
284
+ if (node.clip) canvas.clipPath(node.preparedClip ?? makePath(node.clip, channels), ClipOp.Intersect, true);
285
+ drawNodes(canvas, node.children, channels, images, shaders, values, fonts, palette);
286
+ canvas.restore();
287
+ continue;
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
+ }
297
+ const alpha = Math.min(1, Math.max(0, read(node.opacity, channels, 1)));
298
+ if (node.kind === 'mesh') {
299
+ const image = images[node.image];
300
+ if (image && alpha) drawMesh(canvas, node, channels, image, alpha, shaders[node.image]);
301
+ if (node.pins) {
302
+ for (const pin of node.pins) {
303
+ const { x, y } = meshPinPosition(node, pin, channels);
304
+ canvas.save();
305
+ canvas.translate(x, y);
306
+ drawNodes(canvas, pin.children, channels, images, shaders, values, fonts, palette);
307
+ canvas.restore();
308
+ }
309
+ }
310
+ continue;
311
+ }
312
+ if (!alpha) continue;
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);
320
+ if (node.kind === 'image') {
321
+ const image = images[node.image];
322
+ const width = read(node.width, channels);
323
+ const height = read(node.height, channels);
324
+ if (!image || width <= 0 || height <= 0) continue;
325
+ canvas.drawImageRectOptions(
326
+ image,
327
+ Skia.XYWHRect(0, 0, image.width(), image.height()),
328
+ Skia.XYWHRect(read(node.x, channels), read(node.y, channels), width, height),
329
+ FilterMode.Linear, MipmapMode.None, paint,
330
+ );
331
+ continue;
332
+ }
333
+ const w = read(node.width, channels);
334
+ const h = read(node.height, channels);
335
+ if (w <= 0 || h <= 0) continue;
336
+ const rect = Skia.XYWHRect(read(node.x, channels), read(node.y, channels), w, h);
337
+ if (node.kind === 'ellipse') canvas.drawOval(rect, paint);
338
+ else {
339
+ const radius = Math.min(w / 2, h / 2, Math.max(0, read(node.radius, channels)));
340
+ canvas.drawRRect(Skia.RRectXY(rect, radius, radius), paint);
341
+ }
342
+ }
343
+ }
344
+
345
+ /** Draw the resolved pose inside a viewport, preserving artboard coordinates and aspect ratio. */
346
+ export function drawAsset(
347
+ canvas: SkCanvas, asset: DrawableAsset, pose: Channels, width: number, height: number,
348
+ images: AssetImages = {}, values: TextValues = {}, options?: AssetLayoutOptions,
349
+ ): void {
350
+ 'worklet';
351
+ if (width <= 0 || height <= 0) return;
352
+ const board = asset.artboard;
353
+ const layout = fitAsset(board, width, height, options);
354
+ const { scale, offsetX, offsetY, spaceX, spaceY } = layout;
355
+ const anchored = board.nodes.some((node) => node.kind === 'group' && node.anchor);
356
+ canvas.save();
357
+ if (spaceX < 0 || spaceY < 0) canvas.clipRect(Skia.XYWHRect(0, 0, width, height), ClipOp.Intersect, true);
358
+ canvas.translate(offsetX * scale, offsetY * scale);
359
+ canvas.scale(scale, scale);
360
+ const bounds = anchored
361
+ ? Skia.XYWHRect(-offsetX, -offsetY, board.width + spaceX, board.height + spaceY)
362
+ : Skia.XYWHRect(0, 0, board.width, board.height);
363
+ canvas.clipRect(bounds, ClipOp.Intersect, true);
364
+ drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, asset.meshShaders ?? {}, values, asset.fontProvider, asset.palette ?? {}, layout);
365
+ canvas.restore();
366
+ }
@@ -0,0 +1,47 @@
1
+ import { decodeBase64 } from './base64';
2
+
3
+ /** Check the embedded image header before passing its bytes to a renderer. */
4
+ export function imageSize(uri: unknown): { width: number; height: number } | null {
5
+ if (typeof uri !== 'string') return null;
6
+ const match = /^data:image\/(png|webp);base64,([A-Za-z0-9+/]+={0,2})$/.exec(uri);
7
+ if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) return null;
8
+ const encoded = match[2]!;
9
+ const padding = encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0;
10
+ const size = encoded.length * 3 / 4 - padding;
11
+ const prefix = decodeBase64(encoded.slice(0, 40));
12
+ const suffix = decodeBase64(encoded.slice(-20)).subarray(-12);
13
+ return sizeFromParts(match[1]!, prefix, suffix, size);
14
+ }
15
+
16
+ /** Validate source artwork in the authoring CLI without encoding it to base64 first. */
17
+ export function imageFileSize(format: string, data: Uint8Array): { width: number; height: number } | null {
18
+ return sizeFromParts(format, data.subarray(0, 30), data.subarray(-12), data.length);
19
+ }
20
+
21
+ function sizeFromParts(format: string, bytes: Uint8Array, tail: Uint8Array, size: number) {
22
+ const tag = (at: number) => String.fromCharCode(...bytes.subarray(at, at + 4));
23
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
24
+ if (format === 'png') {
25
+ if (size < 57 || view.getUint32(0) !== 0x89504e47 || view.getUint32(4) !== 0x0d0a1a0a || view.getUint32(8) !== 13 || tag(12) !== 'IHDR') return null;
26
+ const end = new DataView(tail.buffer, tail.byteOffset, tail.byteLength);
27
+ if (end.getUint32(0) !== 0 || end.getUint32(4) !== 0x49454e44 || end.getUint32(8) !== 0xae426082) return null;
28
+ return { width: view.getUint32(16), height: view.getUint32(20) };
29
+ }
30
+ if (format !== 'webp' || bytes.length < 25 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return null;
31
+ const chunkSize = view.getUint32(16, true);
32
+ if (view.getUint32(4, true) !== size - 8 || 20 + chunkSize + (chunkSize % 2) > size) return null;
33
+ const chunkType = tag(12);
34
+ if (chunkType === 'VP8X' && chunkSize === 10) {
35
+ if (size === 30 || (bytes[20]! & 2) !== 0) return null;
36
+ const word = (at: number) => bytes[at]! + 256 * bytes[at + 1]! + 65536 * bytes[at + 2]!;
37
+ return { width: 1 + word(24), height: 1 + word(27) };
38
+ }
39
+ if (chunkType === 'VP8L' && chunkSize >= 5 && bytes[20] === 0x2f) {
40
+ const size = view.getUint32(21, true);
41
+ return { width: 1 + (size & 0x3fff), height: 1 + ((size >>> 14) & 0x3fff) };
42
+ }
43
+ if (chunkType === 'VP8 ' && chunkSize >= 10 && bytes[23] === 0x9d && bytes[24] === 1 && bytes[25] === 0x2a) {
44
+ return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff };
45
+ }
46
+ return null;
47
+ }
@@ -0,0 +1,49 @@
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 };
4
+
5
+ type Size = { width: number; height: number };
6
+
7
+ /** Express the viewport's unused space on either side of the fitted artboard in artboard points. */
8
+ export function layoutAsset(artboard: Size, width: number, height: number) {
9
+ 'worklet';
10
+ const scale = Math.min(width / artboard.width, height / artboard.height);
11
+ return {
12
+ scale,
13
+ insetX: Math.max(0, (width / scale - artboard.width) / 2),
14
+ insetY: Math.max(0, (height / scale - artboard.height) / 2),
15
+ };
16
+ }
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
+
43
+ export function anchorOffset(anchor: AssetAnchor | undefined, insetX: number, insetY: number) {
44
+ 'worklet';
45
+ return {
46
+ x: anchor?.x === 'left' ? -insetX : anchor?.x === 'right' ? insetX : 0,
47
+ y: anchor?.y === 'top' ? -insetY : anchor?.y === 'bottom' ? insetY : 0,
48
+ };
49
+ }