skia-motion-runtime 3.0.0 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +34 -13
- package/runtime/asset-draw.ts +136 -32
- package/runtime/asset-image.ts +3 -20
- package/runtime/asset-layout.ts +27 -0
- package/runtime/asset-load.ts +70 -0
- package/runtime/asset.ts +285 -20
- package/runtime/base64.ts +19 -0
- package/runtime/expo-audio.ts +72 -0
- package/runtime/expo.ts +16 -0
- package/runtime/machine-schema.js +3 -3
- package/runtime/mobile.tsx +215 -96
- package/runtime/useMachine.ts +87 -15
- package/runtime/useMotionAsset.ts +107 -0
- package/templates/motion/machine.ts +21 -14
package/runtime/asset.ts
CHANGED
|
@@ -3,10 +3,13 @@ import { EASE_IN, EASE_IN_OUT, EASE_OUT } from '../templates/motion/motion';
|
|
|
3
3
|
import type { Clips, Machine, StateEntry } from '../templates/motion/machine';
|
|
4
4
|
import type { AssetAnchor } from './asset-layout';
|
|
5
5
|
import { imageSize } from './asset-image';
|
|
6
|
+
import { decodeBase64 } from './base64';
|
|
6
7
|
import type { MeshNode, MeshVertex } from './asset-mesh';
|
|
7
8
|
|
|
8
9
|
export const ASSET_SCHEMA = 'skac.asset/1';
|
|
10
|
+
export const ASSET_BUNDLE_SCHEMA = 'skac.bundle/1';
|
|
9
11
|
export const MAX_ASSET_BYTES = 1024 * 1024;
|
|
12
|
+
const MAX_ASSET_SOURCE_BYTES = 8 * MAX_ASSET_BYTES;
|
|
10
13
|
export const MAX_FEATHER = 64;
|
|
11
14
|
|
|
12
15
|
export type Scalar = number | string;
|
|
@@ -18,7 +21,14 @@ export type PathCommand =
|
|
|
18
21
|
| readonly [op: 'Q', controlX: Scalar, controlY: Scalar, x: Scalar, y: Scalar]
|
|
19
22
|
| readonly [op: 'C', control1X: Scalar, control1Y: Scalar, control2X: Scalar, control2Y: Scalar, x: Scalar, y: Scalar]
|
|
20
23
|
| readonly [op: 'Z'];
|
|
21
|
-
type
|
|
24
|
+
export type AssetColor = string | { palette: string };
|
|
25
|
+
type Shade = AssetColor | { kind: 'radial'; x: Scalar; y: Scalar; radius: Scalar; colors: readonly [string, string] };
|
|
26
|
+
export type AssetStroke = {
|
|
27
|
+
color: AssetColor; width: Scalar;
|
|
28
|
+
cap?: 'butt' | 'round' | 'square'; join?: 'miter' | 'round' | 'bevel';
|
|
29
|
+
trim?: { start?: Scalar; end?: Scalar };
|
|
30
|
+
dash?: { intervals: readonly number[]; phase?: Scalar };
|
|
31
|
+
};
|
|
22
32
|
|
|
23
33
|
type Group = {
|
|
24
34
|
kind: 'group'; x?: Scalar; y?: Scalar; scaleX?: Scalar; scaleY?: Scalar; rotation?: Scalar;
|
|
@@ -27,10 +37,10 @@ type Group = {
|
|
|
27
37
|
points?: Readonly<Record<string, { x: Scalar; y: Scalar }>>;
|
|
28
38
|
children: readonly AssetNode[];
|
|
29
39
|
};
|
|
30
|
-
type Shape = {
|
|
31
|
-
| { kind: 'ellipse'; x: Scalar; y: Scalar; width: Scalar; height: Scalar }
|
|
32
|
-
| { kind: 'roundRect'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; radius: Scalar }
|
|
33
|
-
| { kind: 'path'; commands: readonly PathCommand[] }
|
|
40
|
+
type Shape = { opacity?: Scalar; feather?: Scalar } & (
|
|
41
|
+
| { kind: 'ellipse'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; fill: Shade }
|
|
42
|
+
| { kind: 'roundRect'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; radius: Scalar; fill: Shade }
|
|
43
|
+
| { kind: 'path'; commands: readonly PathCommand[]; fill?: Shade; stroke?: AssetStroke }
|
|
34
44
|
);
|
|
35
45
|
|
|
36
46
|
type ImageNode = {
|
|
@@ -38,8 +48,19 @@ type ImageNode = {
|
|
|
38
48
|
x: Scalar; y: Scalar; width: Scalar; height: Scalar;
|
|
39
49
|
};
|
|
40
50
|
|
|
41
|
-
export type
|
|
42
|
-
export type
|
|
51
|
+
export type BoundText = string | { value: string };
|
|
52
|
+
export type AssetTextNode = {
|
|
53
|
+
kind: 'text'; text: BoundText; x: Scalar; y: Scalar; width: number; fontSize: number; fill: string;
|
|
54
|
+
fonts?: readonly string[]; direction?: 'ltr' | 'rtl'; align?: 'start' | 'center' | 'end'; maxLines?: number;
|
|
55
|
+
};
|
|
56
|
+
export type AssetSemantic = {
|
|
57
|
+
name: string; label: BoundText; role: 'button' | 'image' | 'text' | 'header';
|
|
58
|
+
bounds: readonly [x: number, y: number, width: number, height: number];
|
|
59
|
+
trigger?: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type AssetNode = Group | Shape | ImageNode | MeshNode | AssetTextNode;
|
|
63
|
+
export type AssetMarker = { name: string; layer: string; state: string; audio?: string };
|
|
43
64
|
export type AssetMarkerEvent = AssetMarker & { at: number };
|
|
44
65
|
export type AssetAttachment = { from: string; to: string; maxDistance: number };
|
|
45
66
|
export type MotionAsset<M extends Machine = Machine> = {
|
|
@@ -48,14 +69,31 @@ export type MotionAsset<M extends Machine = Machine> = {
|
|
|
48
69
|
artboard: { width: number; height: number; nodes: readonly AssetNode[] };
|
|
49
70
|
channels: Readonly<Record<string, number>>;
|
|
50
71
|
images?: Readonly<Record<string, string>>;
|
|
72
|
+
imageSlots?: Readonly<Record<string, string>>;
|
|
73
|
+
palette?: Readonly<Record<string, string>>;
|
|
74
|
+
fonts?: Readonly<Record<string, string>>;
|
|
75
|
+
fontLicenses?: Readonly<Record<string, string>>;
|
|
76
|
+
audio?: Readonly<Record<string, string>>;
|
|
77
|
+
semantics?: readonly AssetSemantic[];
|
|
51
78
|
clips: Readonly<Record<string, { ms: number; reducedAt?: number; tracks: Readonly<Record<string, Track>> }>>;
|
|
52
79
|
machine: M;
|
|
53
80
|
markers?: readonly AssetMarker[];
|
|
54
81
|
attachments?: readonly AssetAttachment[];
|
|
55
82
|
};
|
|
83
|
+
export type MotionAssetFile = MotionAsset | {
|
|
84
|
+
schema: typeof ASSET_BUNDLE_SCHEMA;
|
|
85
|
+
name: string;
|
|
86
|
+
defaultArtboard: string;
|
|
87
|
+
artboards: Readonly<Record<string, MotionAsset>>;
|
|
88
|
+
fonts?: MotionAsset['fonts'];
|
|
89
|
+
fontLicenses?: MotionAsset['fontLicenses'];
|
|
90
|
+
audio?: MotionAsset['audio'];
|
|
91
|
+
};
|
|
56
92
|
|
|
57
93
|
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
|
|
58
94
|
const HEX_COLOR = /^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;
|
|
95
|
+
const FONT_URI = /^data:font\/(ttf|otf);base64,([A-Za-z0-9+/]+={0,2})$/;
|
|
96
|
+
const AUDIO_URI = /^data:audio\/(mpeg|wav|mp4|aac);base64,([A-Za-z0-9+/]+={0,2})$/;
|
|
59
97
|
const PATH_ARGUMENTS: Record<string, number> = { M: 2, L: 2, Q: 4, C: 6, Z: 0 };
|
|
60
98
|
const EASES = ['linear', 'in', 'out', 'inOut', 'hold'];
|
|
61
99
|
const RESERVED_KEYS = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype']);
|
|
@@ -114,9 +152,87 @@ function checkPath(value: unknown, at: string, channels: Record<string, unknown>
|
|
|
114
152
|
type NodeValidation = {
|
|
115
153
|
channels: Record<string, unknown>;
|
|
116
154
|
images: Record<string, unknown>;
|
|
155
|
+
imageSlots: Record<string, unknown>;
|
|
117
156
|
points: Set<string>;
|
|
157
|
+
fonts: Record<string, unknown>;
|
|
158
|
+
values: Record<string, unknown>;
|
|
159
|
+
palette: Record<string, unknown>;
|
|
118
160
|
};
|
|
119
161
|
|
|
162
|
+
function checkColor(value: unknown, at: string, palette: Record<string, unknown>): void {
|
|
163
|
+
if (typeof value === 'string') return color(value, at);
|
|
164
|
+
const name = identifier(record(value, at, ['palette']).palette, `${at}.palette`);
|
|
165
|
+
if (!Object.hasOwn(palette, name)) invalid(at, `unknown palette entry "${name}"`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function checkStroke(value: unknown, at: string, { channels, palette }: NodeValidation): void {
|
|
169
|
+
const stroke = record(value, at, ['color', 'width', 'cap', 'join', 'trim', 'dash']);
|
|
170
|
+
checkColor(stroke.color, `${at}.color`, palette);
|
|
171
|
+
scalar(stroke.width, `${at}.width`, channels, 0, 4096);
|
|
172
|
+
if (stroke.cap !== undefined && !['butt', 'round', 'square'].includes(stroke.cap as string)) invalid(`${at}.cap`, 'expected butt, round or square');
|
|
173
|
+
if (stroke.join !== undefined && !['miter', 'round', 'bevel'].includes(stroke.join as string)) invalid(`${at}.join`, 'expected miter, round or bevel');
|
|
174
|
+
if (stroke.trim !== undefined) {
|
|
175
|
+
const trim = record(stroke.trim, `${at}.trim`, ['start', 'end']);
|
|
176
|
+
for (const key of ['start', 'end']) if (trim[key] !== undefined) scalar(trim[key], `${at}.trim.${key}`, channels, 0, 1);
|
|
177
|
+
}
|
|
178
|
+
if (stroke.dash !== undefined) {
|
|
179
|
+
const dash = record(stroke.dash, `${at}.dash`, ['intervals', 'phase']);
|
|
180
|
+
const intervals = list(dash.intervals, `${at}.dash.intervals`, 32);
|
|
181
|
+
if (intervals.length < 2 || intervals.length % 2) invalid(`${at}.dash.intervals`, 'expected an even number of intervals');
|
|
182
|
+
intervals.forEach((interval, i) => number(interval, `${at}.dash.intervals[${i}]`, 0.001, 4096));
|
|
183
|
+
if (dash.phase !== undefined) scalar(dash.phase, `${at}.dash.phase`, channels);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function checkText(value: unknown, at: string, values: Record<string, unknown>): void {
|
|
188
|
+
if (typeof value === 'string') {
|
|
189
|
+
if (value.length > 4096) invalid(at, 'expected at most 4096 characters');
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const input = identifier(record(value, at, ['value']).value, `${at}.value`);
|
|
193
|
+
if ((values[input] as { type?: string } | undefined)?.type !== 'string') {
|
|
194
|
+
invalid(`${at}.value`, 'expected a string value from machine.values');
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function resourceMap(value: unknown, at: string, pattern: RegExp) {
|
|
199
|
+
if (value === undefined) return {};
|
|
200
|
+
const resources = record(value, at);
|
|
201
|
+
if (Object.keys(resources).length > 32) invalid(at, 'expected at most 32 resources');
|
|
202
|
+
for (const [name, uri] of Object.entries(resources)) {
|
|
203
|
+
const key = `${at}.${name}`;
|
|
204
|
+
identifier(name, key);
|
|
205
|
+
const match = typeof uri === 'string' ? pattern.exec(uri) : null;
|
|
206
|
+
if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) invalid(key, 'expected an embedded base64 data URI');
|
|
207
|
+
if (pattern === FONT_URI) {
|
|
208
|
+
const encoded = match[2]!;
|
|
209
|
+
const padding = encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0;
|
|
210
|
+
if (!hasFontHeader(decodeBase64(encoded.slice(0, 16)), encoded.length * 3 / 4 - padding)) {
|
|
211
|
+
invalid(key, 'expected a TTF or OTF font header');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return resources;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function hasFontHeader(bytes: Uint8Array, size = bytes.byteLength): boolean {
|
|
219
|
+
if (bytes.byteLength < 12) return false;
|
|
220
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
221
|
+
const format = view.getUint32(0);
|
|
222
|
+
const tables = view.getUint16(4);
|
|
223
|
+
return (format === 0x00010000 || format === 0x4f54544f || format === 0x74727565 || format === 0x74797031)
|
|
224
|
+
&& tables > 0 && 12 + 16 * tables <= size;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function checkFontLicenses(value: unknown, fonts: Record<string, unknown>, at: string): void {
|
|
228
|
+
if (value === undefined) return;
|
|
229
|
+
for (const [name, license] of Object.entries(record(value, at))) {
|
|
230
|
+
if (!Object.hasOwn(fonts, name) || typeof license !== 'string' || license.length > 16_384) {
|
|
231
|
+
invalid(`${at}.${name}`, 'expected a license of up to 16384 characters for a declared font');
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
120
236
|
function registerPoint(name: string, at: string, points: Set<string>): void {
|
|
121
237
|
identifier(name, at);
|
|
122
238
|
if (points.has(name)) invalid(at, 'duplicate point name');
|
|
@@ -171,8 +287,26 @@ function checkMesh(node: Record<string, unknown>, at: string, context: NodeValid
|
|
|
171
287
|
}
|
|
172
288
|
|
|
173
289
|
function checkNode(value: unknown, at: string, context: NodeValidation, depth: number): void {
|
|
174
|
-
const { channels, images, points } = context;
|
|
290
|
+
const { channels, images, imageSlots, points } = context;
|
|
175
291
|
const node = record(value, at);
|
|
292
|
+
if (node.kind === 'text') {
|
|
293
|
+
record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines']);
|
|
294
|
+
checkText(node.text, `${at}.text`, context.values);
|
|
295
|
+
scalar(node.x, `${at}.x`, channels);
|
|
296
|
+
scalar(node.y, `${at}.y`, channels);
|
|
297
|
+
number(node.width, `${at}.width`, 1, 4096);
|
|
298
|
+
number(node.fontSize, `${at}.fontSize`, 1, 512);
|
|
299
|
+
color(node.fill, `${at}.fill`);
|
|
300
|
+
if (node.fonts !== undefined) list(node.fonts, `${at}.fonts`, 8).forEach((name, i) => {
|
|
301
|
+
if (typeof name !== 'string' || !Object.hasOwn(context.fonts, name)) invalid(`${at}.fonts[${i}]`, 'unknown embedded font');
|
|
302
|
+
});
|
|
303
|
+
if (node.direction !== undefined && node.direction !== 'ltr' && node.direction !== 'rtl') invalid(`${at}.direction`, 'expected ltr or rtl');
|
|
304
|
+
if (node.align !== undefined && !['start', 'center', 'end'].includes(node.align as string)) invalid(`${at}.align`, 'expected start, center or end');
|
|
305
|
+
if (node.maxLines !== undefined && !Number.isInteger(number(node.maxLines, `${at}.maxLines`, 1, 16))) {
|
|
306
|
+
invalid(`${at}.maxLines`, 'expected an integer');
|
|
307
|
+
}
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
176
310
|
if (node.kind === 'group') {
|
|
177
311
|
record(node, at, ['kind', 'children', 'x', 'y', 'scaleX', 'scaleY', 'rotation', 'anchor', 'clip', 'points']);
|
|
178
312
|
for (const key of ['x', 'y', 'scaleX', 'scaleY', 'rotation']) {
|
|
@@ -203,7 +337,9 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
203
337
|
return;
|
|
204
338
|
}
|
|
205
339
|
if (node.kind === 'image' || node.kind === 'mesh') {
|
|
206
|
-
if (typeof node.image !== 'string' || !Object.hasOwn(images, node.image)
|
|
340
|
+
if (typeof node.image !== 'string' || (!Object.hasOwn(images, node.image) && !Object.hasOwn(imageSlots, node.image))) {
|
|
341
|
+
invalid(`${at}.image`, 'expected a name from images or imageSlots');
|
|
342
|
+
}
|
|
207
343
|
if (node.opacity !== undefined) scalar(node.opacity, `${at}.opacity`, channels, 0, 1);
|
|
208
344
|
if (node.kind === 'mesh') {
|
|
209
345
|
checkMesh(node, at, context, depth);
|
|
@@ -215,8 +351,9 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
215
351
|
return;
|
|
216
352
|
}
|
|
217
353
|
if (node.kind === 'path') {
|
|
218
|
-
record(node, at, ['kind', 'fill', 'opacity', 'feather', 'commands']);
|
|
354
|
+
record(node, at, ['kind', 'fill', 'opacity', 'feather', 'commands', 'stroke']);
|
|
219
355
|
checkPath(node.commands, `${at}.commands`, channels);
|
|
356
|
+
if (node.stroke !== undefined) checkStroke(node.stroke, `${at}.stroke`, context);
|
|
220
357
|
} else if (node.kind === 'ellipse' || node.kind === 'roundRect') {
|
|
221
358
|
const keys = ['kind', 'fill', 'opacity', 'feather', 'x', 'y', 'width', 'height'];
|
|
222
359
|
if (node.kind === 'roundRect') keys.push('radius');
|
|
@@ -224,14 +361,19 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
224
361
|
for (const key of ['x', 'y', 'width', 'height']) scalar(node[key], `${at}.${key}`, channels, key === 'x' || key === 'y' ? undefined : 0);
|
|
225
362
|
if (node.kind === 'roundRect') scalar(node.radius, `${at}.radius`, channels, 0);
|
|
226
363
|
} else {
|
|
227
|
-
invalid(`${at}.kind`, 'expected ellipse, roundRect, path, image, mesh or group');
|
|
364
|
+
invalid(`${at}.kind`, 'expected ellipse, roundRect, path, image, mesh, text or group');
|
|
228
365
|
}
|
|
229
366
|
if (node.opacity !== undefined) scalar(node.opacity, `${at}.opacity`, channels, 0, 1);
|
|
230
367
|
if (node.feather !== undefined) scalar(node.feather, `${at}.feather`, channels, 0, MAX_FEATHER);
|
|
368
|
+
if (node.kind === 'path' && node.fill === undefined && node.stroke !== undefined) return;
|
|
231
369
|
if (typeof node.fill === 'string') {
|
|
232
370
|
color(node.fill, `${at}.fill`);
|
|
233
371
|
return;
|
|
234
372
|
}
|
|
373
|
+
if (node.fill && typeof node.fill === 'object' && Object.hasOwn(node.fill, 'palette')) {
|
|
374
|
+
checkColor(node.fill, `${at}.fill`, context.palette);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
235
377
|
const fill = record(node.fill, `${at}.fill`, ['kind', 'x', 'y', 'radius', 'colors']);
|
|
236
378
|
if (fill.kind !== 'radial') invalid(`${at}.fill.kind`, 'expected radial');
|
|
237
379
|
scalar(fill.x, `${at}.fill.x`, channels);
|
|
@@ -243,15 +385,34 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
243
385
|
}
|
|
244
386
|
|
|
245
387
|
function validateAsset(value: unknown): MotionAsset {
|
|
246
|
-
const data = record(value, 'asset', [
|
|
388
|
+
const data = record(value, 'asset', [
|
|
389
|
+
'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontLicenses', 'audio', 'semantics',
|
|
390
|
+
]);
|
|
247
391
|
if (data.schema !== ASSET_SCHEMA) invalid('asset.schema', `this player reads ${ASSET_SCHEMA}`);
|
|
248
392
|
identifier(data.name, 'asset.name');
|
|
393
|
+
const machine = record(data.machine, 'machine');
|
|
394
|
+
const values = machine.values === undefined ? {} : record(machine.values, 'machine.values');
|
|
395
|
+
const fonts = resourceMap(data.fonts, 'fonts', FONT_URI);
|
|
396
|
+
checkFontLicenses(data.fontLicenses, fonts, 'fontLicenses');
|
|
397
|
+
const audio = resourceMap(data.audio, 'audio', AUDIO_URI);
|
|
398
|
+
const palette = data.palette === undefined ? {} : record(data.palette, 'palette');
|
|
399
|
+
for (const [name, value] of Object.entries(palette)) {
|
|
400
|
+
identifier(name, `palette.${name}`);
|
|
401
|
+
color(value, `palette.${name}`);
|
|
402
|
+
}
|
|
249
403
|
const channels = record(data.channels, 'channels');
|
|
250
404
|
for (const [name, value] of Object.entries(channels)) {
|
|
251
405
|
identifier(name, `channels.${name}`);
|
|
252
406
|
number(value, `channels.${name}`);
|
|
253
407
|
}
|
|
254
408
|
const images = data.images === undefined ? {} : record(data.images, 'images');
|
|
409
|
+
const imageSlots = data.imageSlots === undefined ? {} : record(data.imageSlots, 'imageSlots');
|
|
410
|
+
for (const [name, fallback] of Object.entries(imageSlots)) {
|
|
411
|
+
const at = `imageSlots.${name}`;
|
|
412
|
+
identifier(name, at);
|
|
413
|
+
if (Object.hasOwn(images, name)) invalid(at, 'the slot name must be distinct from its embedded fallback');
|
|
414
|
+
if (typeof fallback !== 'string' || !Object.hasOwn(images, fallback)) invalid(at, 'expected an embedded fallback from images');
|
|
415
|
+
}
|
|
255
416
|
let pixels = 0;
|
|
256
417
|
for (const [name, uri] of Object.entries(images)) {
|
|
257
418
|
const at = `images.${name}`;
|
|
@@ -268,8 +429,30 @@ function validateAsset(value: unknown): MotionAsset {
|
|
|
268
429
|
number(artboard.height, 'artboard.height', 1, 4096);
|
|
269
430
|
const nodes = list(artboard.nodes, 'artboard.nodes', 256);
|
|
270
431
|
if (!nodes.length) invalid('artboard.nodes', 'add at least one shape');
|
|
271
|
-
const context = { channels, images, points: new Set<string>() };
|
|
432
|
+
const context = { channels, images, imageSlots, fonts, values, palette, points: new Set<string>() };
|
|
272
433
|
nodes.forEach((node, i) => checkNode(node, `artboard.nodes[${i}]`, context, 0));
|
|
434
|
+
if (data.semantics !== undefined) {
|
|
435
|
+
const names = new Set<string>();
|
|
436
|
+
list(data.semantics, 'semantics', 64).forEach((item, i) => {
|
|
437
|
+
const at = `semantics[${i}]`;
|
|
438
|
+
const entry = record(item, at, ['name', 'role', 'label', 'bounds', 'trigger']);
|
|
439
|
+
const name = identifier(entry.name, `${at}.name`);
|
|
440
|
+
if (names.has(name)) invalid(`${at}.name`, 'duplicate semantic name');
|
|
441
|
+
names.add(name);
|
|
442
|
+
if (!['button', 'image', 'text', 'header'].includes(entry.role as string)) invalid(`${at}.role`, 'unknown role');
|
|
443
|
+
checkText(entry.label, `${at}.label`, values);
|
|
444
|
+
const bounds = list(entry.bounds, `${at}.bounds`, 4);
|
|
445
|
+
if (bounds.length !== 4) invalid(`${at}.bounds`, 'expected x, y, width and height');
|
|
446
|
+
bounds.forEach((side, index) => number(side, `${at}.bounds[${index}]`, index < 2 ? -4096 : 1, 4096));
|
|
447
|
+
if (entry.trigger !== undefined) {
|
|
448
|
+
const trigger = identifier(entry.trigger, `${at}.trigger`);
|
|
449
|
+
const property = values[trigger] as { type?: string; bind?: string } | undefined;
|
|
450
|
+
if (entry.role !== 'button' || property?.type !== 'trigger' || property.bind === 'out') {
|
|
451
|
+
invalid(`${at}.trigger`, 'expected a writable trigger on a button');
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
}
|
|
273
456
|
if (data.attachments !== undefined) {
|
|
274
457
|
list(data.attachments, 'attachments', 256).forEach((item, i) => {
|
|
275
458
|
const at = `attachments[${i}]`;
|
|
@@ -308,8 +491,7 @@ function validateAsset(value: unknown): MotionAsset {
|
|
|
308
491
|
});
|
|
309
492
|
}
|
|
310
493
|
}
|
|
311
|
-
|
|
312
|
-
if (machine.clocks !== undefined || machine.hits !== undefined) invalid('machine', 'this asset version uses frame clocks and host input');
|
|
494
|
+
if (machine.hits !== undefined) invalid('machine.hits', 'packed scenes use host input and semantic regions');
|
|
313
495
|
list(machine.layers, 'machine.layers', 32).forEach((value, i) => {
|
|
314
496
|
const at = `machine.layers[${i}]`;
|
|
315
497
|
const layer = record(value, at);
|
|
@@ -326,29 +508,112 @@ function validateAsset(value: unknown): MotionAsset {
|
|
|
326
508
|
if (data.markers !== undefined) {
|
|
327
509
|
list(data.markers, 'markers', 256).forEach((item, i) => {
|
|
328
510
|
const at = `markers[${i}]`;
|
|
329
|
-
const marker = record(item, at, ['name', 'layer', 'state']);
|
|
511
|
+
const marker = record(item, at, ['name', 'layer', 'state', 'audio']);
|
|
330
512
|
const name = identifier(marker.name, `${at}.name`);
|
|
331
513
|
if (names.has(name)) invalid(`${at}.name`, 'duplicate marker name');
|
|
332
514
|
names.add(name);
|
|
333
515
|
const layer = typed.machine.layers.find((layer) => layer.name === marker.layer);
|
|
334
516
|
const state = identifier(marker.state, `${at}.state`);
|
|
335
517
|
if (!layer || !Object.hasOwn(layer.states, state)) invalid(at, 'unknown layer or state');
|
|
518
|
+
if (marker.audio !== undefined && (typeof marker.audio !== 'string' || !Object.hasOwn(audio, marker.audio))) {
|
|
519
|
+
invalid(`${at}.audio`, 'unknown embedded audio cue');
|
|
520
|
+
}
|
|
336
521
|
});
|
|
337
522
|
}
|
|
338
523
|
return typed;
|
|
339
524
|
}
|
|
340
525
|
|
|
341
526
|
/** Decode the same data file on a React Native JS thread and in the CLI. */
|
|
342
|
-
export function
|
|
343
|
-
|
|
527
|
+
export function parseAssetFile(text: string): MotionAssetFile {
|
|
528
|
+
return parseAssetJSON(text, MAX_ASSET_BYTES);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** The CLI may prune unused resources before enforcing the shipped limit. */
|
|
532
|
+
export function parseAssetSource(text: string): MotionAssetFile {
|
|
533
|
+
return parseAssetJSON(text, MAX_ASSET_SOURCE_BYTES);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function parseAssetJSON(text: string, limit: number): MotionAssetFile {
|
|
537
|
+
const message = `expected a JSON asset of at most ${limit / MAX_ASSET_BYTES} MiB`;
|
|
538
|
+
if (typeof text !== 'string' || text.length > limit) invalid('asset', message);
|
|
344
539
|
const bytes = encodeURI(text).replace(/%[0-9A-F]{2}/g, 'x').length;
|
|
345
|
-
if (bytes >
|
|
540
|
+
if (bytes > limit) invalid('asset', message);
|
|
346
541
|
const decoded: unknown = JSON.parse(text, (key, value: unknown) => {
|
|
347
542
|
if (RESERVED_KEYS.has(key)) invalid(key, 'reserved field name');
|
|
348
543
|
if (typeof value === 'number' && !Number.isFinite(value)) invalid(key, 'expected a finite number');
|
|
349
544
|
return value;
|
|
350
545
|
});
|
|
351
|
-
|
|
546
|
+
const file = record(decoded, 'asset');
|
|
547
|
+
if (file.schema !== ASSET_BUNDLE_SCHEMA) return validateAsset(file);
|
|
548
|
+
record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontLicenses', 'audio']);
|
|
549
|
+
const name = identifier(file.name, 'bundle.name');
|
|
550
|
+
const defaultArtboard = identifier(file.defaultArtboard, 'bundle.defaultArtboard');
|
|
551
|
+
const artboards = record(file.artboards, 'bundle.artboards');
|
|
552
|
+
const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<MotionAsset['fonts']>;
|
|
553
|
+
checkFontLicenses(file.fontLicenses, fonts, 'bundle.fontLicenses');
|
|
554
|
+
const fontLicenses = file.fontLicenses as MotionAsset['fontLicenses'];
|
|
555
|
+
const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<MotionAsset['audio']>;
|
|
556
|
+
const entries = Object.entries(artboards);
|
|
557
|
+
if (entries.length < 1 || entries.length > 16) invalid('bundle.artboards', 'expected one to sixteen artboards');
|
|
558
|
+
if (!Object.hasOwn(artboards, defaultArtboard)) invalid('bundle.defaultArtboard', 'unknown artboard');
|
|
559
|
+
return {
|
|
560
|
+
schema: ASSET_BUNDLE_SCHEMA, name, defaultArtboard,
|
|
561
|
+
...(Object.keys(fonts).length && { fonts }),
|
|
562
|
+
...(fontLicenses && { fontLicenses }),
|
|
563
|
+
...(Object.keys(audio).length && { audio }),
|
|
564
|
+
artboards: Object.fromEntries(entries.map(([key, value]) => {
|
|
565
|
+
identifier(key, `bundle.artboards.${key}`);
|
|
566
|
+
try {
|
|
567
|
+
const board = record(value, `bundle.artboards.${key}`);
|
|
568
|
+
const localFonts = board.fonts === undefined ? {} : record(board.fonts, 'fonts');
|
|
569
|
+
const localAudio = board.audio === undefined ? {} : record(board.audio, 'audio');
|
|
570
|
+
const localLicenses = board.fontLicenses === undefined ? {} : record(board.fontLicenses, 'fontLicenses');
|
|
571
|
+
validateAsset({
|
|
572
|
+
...board, fonts: { ...fonts, ...localFonts },
|
|
573
|
+
fontLicenses: { ...fontLicenses, ...localLicenses }, audio: { ...audio, ...localAudio },
|
|
574
|
+
});
|
|
575
|
+
return [key, board as MotionAsset];
|
|
576
|
+
} catch (error) {
|
|
577
|
+
invalid(`bundle.artboards.${key}`, (error as Error).message);
|
|
578
|
+
}
|
|
579
|
+
})),
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export function selectArtboard(file: MotionAssetFile, artboard?: string): MotionAsset {
|
|
584
|
+
if (file.schema === ASSET_SCHEMA) {
|
|
585
|
+
if (artboard === undefined || artboard === file.name) return file;
|
|
586
|
+
invalid('artboard', `unknown artboard "${artboard}". Available: ${file.name}`);
|
|
587
|
+
}
|
|
588
|
+
const name = artboard ?? file.defaultArtboard;
|
|
589
|
+
if (!Object.hasOwn(file.artboards, name)) {
|
|
590
|
+
invalid('artboard', `unknown artboard "${name}". Available: ${Object.keys(file.artboards).join(', ')}`);
|
|
591
|
+
}
|
|
592
|
+
const selected = file.artboards[name]!;
|
|
593
|
+
return {
|
|
594
|
+
...selected,
|
|
595
|
+
...(file.fonts && { fonts: { ...file.fonts, ...selected.fonts } }),
|
|
596
|
+
...(file.fontLicenses && { fontLicenses: { ...file.fontLicenses, ...selected.fontLicenses } }),
|
|
597
|
+
...(file.audio && { audio: { ...file.audio, ...selected.audio } }),
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export function parseAsset(text: string, artboard?: string): MotionAsset {
|
|
602
|
+
return selectArtboard(parseAssetFile(text), artboard);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<string, string>>): string {
|
|
606
|
+
'worklet';
|
|
607
|
+
return typeof value === 'string' ? value : palette[value.palette]!;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
export function bindAssetPalette(asset: MotionAsset, overrides?: Readonly<Record<string, string>>): MotionAsset {
|
|
611
|
+
if (!overrides) return asset;
|
|
612
|
+
for (const [name, value] of Object.entries(overrides)) {
|
|
613
|
+
if (!asset.palette || !Object.hasOwn(asset.palette, name)) invalid(`palette.${name}`, 'unknown palette entry');
|
|
614
|
+
color(value, `palette.${name}`);
|
|
615
|
+
}
|
|
616
|
+
return { ...asset, palette: { ...asset.palette, ...overrides } };
|
|
352
617
|
}
|
|
353
618
|
|
|
354
619
|
/** Image names used by the drawing. Unreferenced library entries can be omitted from playback. */
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
2
|
+
|
|
3
|
+
/** Decode a validated base64 string on Node, Hermes, or the web. */
|
|
4
|
+
export function decodeBase64(encoded: string): Uint8Array {
|
|
5
|
+
const bytes = new Uint8Array(encoded.length * 3 / 4);
|
|
6
|
+
let length = 0;
|
|
7
|
+
let bits = 0;
|
|
8
|
+
let value = 0;
|
|
9
|
+
for (const char of encoded) {
|
|
10
|
+
if (char === '=') break;
|
|
11
|
+
value = (value << 6) | ALPHABET.indexOf(char);
|
|
12
|
+
bits += 6;
|
|
13
|
+
if (bits >= 8) {
|
|
14
|
+
bits -= 8;
|
|
15
|
+
bytes[length++] = (value >>> bits) & 255;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return bytes.subarray(0, length);
|
|
19
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef } from 'react';
|
|
2
|
+
import { createAudioPlayer, type AudioPlayer } from 'expo-audio';
|
|
3
|
+
import { File, Paths } from 'expo-file-system';
|
|
4
|
+
import type { LoadedMotionAsset } from './asset-load';
|
|
5
|
+
import { decodeBase64 } from './base64';
|
|
6
|
+
import type { MotionAudioCue } from './mobile';
|
|
7
|
+
|
|
8
|
+
const extensions: Record<string, string> = { mpeg: 'mp3', wav: 'wav', mp4: 'm4a', aac: 'aac' };
|
|
9
|
+
let sequence = 0;
|
|
10
|
+
|
|
11
|
+
type Prepared = {
|
|
12
|
+
file: File;
|
|
13
|
+
source: string;
|
|
14
|
+
ready: Promise<AudioPlayer | undefined>;
|
|
15
|
+
active: boolean;
|
|
16
|
+
revision: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** Prepare embedded cues and return the callback for MotionPlayer's onAudio prop. */
|
|
20
|
+
export function useExpoMotionAudio(
|
|
21
|
+
asset: LoadedMotionAsset | null | undefined,
|
|
22
|
+
{ enabled = true, onError }: { enabled?: boolean; onError?: (error: unknown) => void } = {},
|
|
23
|
+
) {
|
|
24
|
+
const sounds = useRef(new Map<string, Prepared>());
|
|
25
|
+
const onErrorRef = useRef(onError);
|
|
26
|
+
useEffect(() => { onErrorRef.current = onError; }, [onError]);
|
|
27
|
+
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
if (!enabled || !asset?.audio) return;
|
|
30
|
+
const loaded = new Map<string, Prepared>();
|
|
31
|
+
sounds.current = loaded;
|
|
32
|
+
const id = `${Date.now()}-${sequence++}`;
|
|
33
|
+
for (const [name, source] of Object.entries(asset.audio)) {
|
|
34
|
+
const header = /^data:audio\/(mpeg|wav|mp4|aac);base64,/.exec(source);
|
|
35
|
+
if (!header) continue;
|
|
36
|
+
const file = new File(Paths.cache, `skac-${id}-${name}.${extensions[header[1]!]}`);
|
|
37
|
+
const entry: Prepared = {
|
|
38
|
+
file, source, active: true, revision: 0,
|
|
39
|
+
ready: Promise.resolve().then(async () => {
|
|
40
|
+
if (!entry.active) return undefined;
|
|
41
|
+
await file.write(decodeBase64(source.slice(header[0].length)));
|
|
42
|
+
return entry.active ? createAudioPlayer({ uri: file.uri }) : undefined;
|
|
43
|
+
}).catch((error: unknown) => {
|
|
44
|
+
if (entry.active) onErrorRef.current?.(error);
|
|
45
|
+
return undefined;
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
loaded.set(name, entry);
|
|
49
|
+
}
|
|
50
|
+
return () => {
|
|
51
|
+
sounds.current = new Map();
|
|
52
|
+
for (const entry of loaded.values()) {
|
|
53
|
+
entry.active = false;
|
|
54
|
+
void entry.ready.then(async (player) => {
|
|
55
|
+
player?.remove();
|
|
56
|
+
if (entry.file.exists) await entry.file.delete();
|
|
57
|
+
}).catch((error: unknown) => onErrorRef.current?.(error));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}, [asset, enabled]);
|
|
61
|
+
|
|
62
|
+
return useCallback(({ name, source }: MotionAudioCue) => {
|
|
63
|
+
const entry = sounds.current.get(name);
|
|
64
|
+
if (!entry || entry.source !== source) return;
|
|
65
|
+
const revision = ++entry.revision;
|
|
66
|
+
void entry.ready.then(async (player) => {
|
|
67
|
+
if (!player || !entry.active || revision !== entry.revision) return;
|
|
68
|
+
await player.seekTo(0);
|
|
69
|
+
if (entry.active && revision === entry.revision) player.play();
|
|
70
|
+
}).catch((error: unknown) => { if (entry.active) onErrorRef.current?.(error); });
|
|
71
|
+
}, []);
|
|
72
|
+
}
|
package/runtime/expo.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Asset } from 'expo-asset';
|
|
2
|
+
import { File } from 'expo-file-system';
|
|
3
|
+
import { useMotionAsset, type MotionAssetOptions } from './useMotionAsset';
|
|
4
|
+
|
|
5
|
+
/** Read a .skmotion from Expo's Metro asset registry in a development or release build. */
|
|
6
|
+
export function useExpoMotionAsset(moduleId: number | null | undefined, options?: MotionAssetOptions) {
|
|
7
|
+
return useMotionAsset(moduleId == null ? null : {
|
|
8
|
+
key: `expo-module:${moduleId}`,
|
|
9
|
+
async read(signal) {
|
|
10
|
+
const asset = await Asset.fromModule(moduleId).downloadAsync();
|
|
11
|
+
if (signal.aborted) throw new Error('Motion asset load cancelled');
|
|
12
|
+
if (!asset.localUri) throw new Error('Expo did not produce a local motion file');
|
|
13
|
+
return new File(asset.localUri).text();
|
|
14
|
+
},
|
|
15
|
+
}, options);
|
|
16
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The schema and graph validator are shared by the CLI and the mobile asset loader.
|
|
2
2
|
export const SCHEMA = 'skac.machine/1';
|
|
3
|
-
export const VALUE_TYPES = ['boolean', 'number', 'enum', 'trigger'];
|
|
3
|
+
export const VALUE_TYPES = ['boolean', 'number', 'enum', 'trigger', 'string'];
|
|
4
4
|
export const BINDS = ['in', 'out', 'both'];
|
|
5
5
|
export const LOOPS = ['once', 'loop', 'pingpong'];
|
|
6
6
|
export const EASES = ['linear', 'out', 'inOut', 'in'];
|
|
@@ -58,7 +58,7 @@ export const validateMachine = (m, { clips, clipNames = clips && Object.keys(cli
|
|
|
58
58
|
const where = `values.${name}`;
|
|
59
59
|
if (!isObj(v)) { bad(where, 'a value is not an object', 'like {"type": "boolean", "default": false}'); continue; }
|
|
60
60
|
unknownKeys(v, KEYS.value, where);
|
|
61
|
-
if (!VALUE_TYPES.includes(v.type)) { bad(where, `type ${JSON.stringify(v.type)} is not one of ${VALUE_TYPES.join(', ')}`, '
|
|
61
|
+
if (!VALUE_TYPES.includes(v.type)) { bad(where, `type ${JSON.stringify(v.type)} is not one of ${VALUE_TYPES.join(', ')}`, 'choose a supported value type'); continue; }
|
|
62
62
|
if (v.bind !== undefined && !BINDS.includes(v.bind)) bad(where, `bind ${JSON.stringify(v.bind)} is not one of ${BINDS.join(', ')}`, '"in": the app writes it; "out": the machine writes it and the app reads it; "both"');
|
|
63
63
|
if (v.type === 'enum') {
|
|
64
64
|
if (!Array.isArray(v.options) || v.options.length < 2 || !v.options.every((o) => typeof o === 'string')) {
|
|
@@ -89,7 +89,7 @@ export const validateMachine = (m, { clips, clipNames = clips && Object.keys(cli
|
|
|
89
89
|
// A literal or a value name on the right of a condition or action, checked against the type it must have.
|
|
90
90
|
const operand = (rhs, type, where, options, assignment = false) => {
|
|
91
91
|
const enumOptions = type === 'enum' && Array.isArray(options) ? options : undefined;
|
|
92
|
-
if (typeof rhs === 'string' && values
|
|
92
|
+
if (typeof rhs === 'string' && Object.hasOwn(values, rhs) && !enumOptions?.includes(rhs)) {
|
|
93
93
|
if (valueType(rhs) !== type) bad(where, `"${rhs}" is a ${valueType(rhs)}, compared with a ${type}`, 'compare values of one type');
|
|
94
94
|
else if (assignment && enumOptions && Array.isArray(values[rhs].options)) {
|
|
95
95
|
const missing = values[rhs].options.filter((option) => !enumOptions.includes(option));
|