skia-motion-runtime 3.1.1 → 3.2.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 +2 -1
- package/runtime/asset-binary.ts +149 -0
- package/runtime/asset-draw.ts +32 -17
- package/runtime/asset-image.ts +4 -0
- package/runtime/asset-load.ts +12 -6
- package/runtime/asset.ts +72 -26
- package/runtime/base64.ts +18 -0
- package/runtime/expo.ts +4 -1
- package/runtime/mobile.tsx +5 -2
- package/runtime/useMotionAsset.ts +22 -8
package/package.json
CHANGED
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
"files": [
|
|
35
35
|
"LICENSE",
|
|
36
36
|
"NOTICE.md",
|
|
37
|
+
"runtime/asset-binary.ts",
|
|
37
38
|
"runtime/asset-draw.ts",
|
|
38
39
|
"runtime/asset-image.ts",
|
|
39
40
|
"runtime/asset-layout.ts",
|
|
@@ -54,7 +55,7 @@
|
|
|
54
55
|
"templates/motion/machine.ts",
|
|
55
56
|
"templates/motion/motion.ts"
|
|
56
57
|
],
|
|
57
|
-
"version": "3.
|
|
58
|
+
"version": "3.2.0",
|
|
58
59
|
"license": "MIT",
|
|
59
60
|
"repository": {
|
|
60
61
|
"type": "git",
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { decodeBase64, encodeBase64 } from './base64';
|
|
2
|
+
|
|
3
|
+
export type MotionAssetData = string | Uint8Array;
|
|
4
|
+
export type ResourceBytes = { readonly mime: string; readonly bytes: Uint8Array };
|
|
5
|
+
export type AssetResource = string | ResourceBytes;
|
|
6
|
+
|
|
7
|
+
export function isResourceBytes(value: unknown): value is ResourceBytes {
|
|
8
|
+
return isRecord(value) && typeof value.mime === 'string' && value.bytes instanceof Uint8Array;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const HEADER_SIZE = 12;
|
|
12
|
+
const MAGIC = 0x534b4d4f; // SKMO
|
|
13
|
+
const VERSION = 1;
|
|
14
|
+
const MAX_RESOURCES = 4096;
|
|
15
|
+
const RESOURCE_KEYS = ['images', 'fonts', 'audio'] as const;
|
|
16
|
+
const RESOURCE_MIMES = new Set([
|
|
17
|
+
'image/png', 'image/webp', 'font/ttf', 'font/otf', 'audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac',
|
|
18
|
+
]);
|
|
19
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
20
|
+
value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
|
|
22
|
+
function invalid(message: string): never {
|
|
23
|
+
throw new Error(`invalid SKMO asset: ${message}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function isBinaryAsset(bytes: Uint8Array): boolean {
|
|
27
|
+
return bytes.length >= 4 && new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0) === MAGIC;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function decodeAssetText(bytes: Uint8Array): string {
|
|
31
|
+
if (typeof TextDecoder !== 'undefined') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
32
|
+
// Older React Native hosts may have no TextDecoder.
|
|
33
|
+
const chunks: string[] = [];
|
|
34
|
+
let chunk = '';
|
|
35
|
+
for (const byte of bytes) {
|
|
36
|
+
chunk += byte < 128 && byte !== 37 ? String.fromCharCode(byte) : '%' + byte.toString(16).padStart(2, '0');
|
|
37
|
+
if (chunk.length >= 8192) {
|
|
38
|
+
chunks.push(chunk);
|
|
39
|
+
chunk = '';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
chunks.push(chunk);
|
|
43
|
+
return decodeURIComponent(chunks.join('')).replace(/^\uFEFF/, '');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function mapResources(value: unknown, map: (value: unknown) => unknown): unknown {
|
|
47
|
+
if (!isRecord(value)) return value;
|
|
48
|
+
const result = { ...value };
|
|
49
|
+
for (const key of RESOURCE_KEYS) {
|
|
50
|
+
const resources = value[key];
|
|
51
|
+
if (isRecord(resources)) {
|
|
52
|
+
result[key] = Object.fromEntries(Object.entries(resources).map(([name, resource]) => [name, map(resource)]));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function mapFileResources(value: unknown, map: (value: unknown) => unknown): unknown {
|
|
59
|
+
const file = mapResources(value, map);
|
|
60
|
+
if (isRecord(file) && file.schema === 'skac.bundle/1' && isRecord(file.artboards)) {
|
|
61
|
+
file.artboards = Object.fromEntries(Object.entries(file.artboards).map(([name, board]) => [name, mapResources(board, map)]));
|
|
62
|
+
}
|
|
63
|
+
return file;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function resourceDataUri(resource: AssetResource, cache?: Map<ResourceBytes, string>): string {
|
|
67
|
+
if (typeof resource === 'string') return resource;
|
|
68
|
+
const cached = cache?.get(resource);
|
|
69
|
+
if (cached !== undefined) return cached;
|
|
70
|
+
const uri = `data:${resource.mime};base64,${encodeBase64(resource.bytes)}`;
|
|
71
|
+
cache?.set(resource, uri);
|
|
72
|
+
return uri;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function decodeBinaryAsset(bytes: Uint8Array, parseJSON: (text: string) => unknown): unknown {
|
|
76
|
+
if (bytes.length < HEADER_SIZE) invalid('truncated header');
|
|
77
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
78
|
+
if (view.getUint8(4) !== VERSION) invalid(`unsupported container version ${view.getUint8(4)}`);
|
|
79
|
+
if (view.getUint8(5) || view.getUint16(6)) invalid('unsupported header flags');
|
|
80
|
+
const manifestSize = view.getUint32(8, true);
|
|
81
|
+
const manifestEnd = HEADER_SIZE + manifestSize;
|
|
82
|
+
if (!manifestSize || manifestEnd > bytes.length) invalid('manifest length exceeds file bounds');
|
|
83
|
+
const manifest = parseJSON(decodeAssetText(bytes.subarray(HEADER_SIZE, manifestEnd)));
|
|
84
|
+
if (!isRecord(manifest) || Object.keys(manifest).length !== 2 || !isRecord(manifest.asset) ||
|
|
85
|
+
!Array.isArray(manifest.resources) || manifest.resources.length > MAX_RESOURCES) invalid('invalid manifest');
|
|
86
|
+
|
|
87
|
+
let offset = manifestEnd;
|
|
88
|
+
const resources: ResourceBytes[] = manifest.resources.map((entry: unknown) => {
|
|
89
|
+
if (!Array.isArray(entry) || entry.length !== 2) invalid('invalid resource entry');
|
|
90
|
+
const [mime, length] = entry;
|
|
91
|
+
if (!RESOURCE_MIMES.has(mime) || !Number.isSafeInteger(length) || length <= 0 || length > bytes.length - offset) {
|
|
92
|
+
invalid('resource type or length is invalid');
|
|
93
|
+
}
|
|
94
|
+
const resource = { mime, bytes: bytes.subarray(offset, offset + length) };
|
|
95
|
+
offset += length;
|
|
96
|
+
return resource;
|
|
97
|
+
});
|
|
98
|
+
if (offset !== bytes.length) invalid('unexpected trailing bytes');
|
|
99
|
+
return mapFileResources(manifest.asset, (index) => {
|
|
100
|
+
if (typeof index !== 'number' || !Number.isInteger(index) || !resources[index]) invalid('unknown resource index');
|
|
101
|
+
return resources[index]!;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The authoring CLI writes a validated legacy scene into an SKMO container. */
|
|
106
|
+
export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => Uint8Array, limit: number): Uint8Array {
|
|
107
|
+
const uriIndices = new Map<string, number>();
|
|
108
|
+
const payloadIndices = new Map<string, number[]>();
|
|
109
|
+
const payload: ResourceBytes[] = [];
|
|
110
|
+
const asset = mapFileResources(file, (resource) => {
|
|
111
|
+
if (typeof resource !== 'string') invalid('expected a data URI to pack');
|
|
112
|
+
const known = uriIndices.get(resource);
|
|
113
|
+
if (known !== undefined) return known;
|
|
114
|
+
const header = /^data:([^;,]+);base64,/.exec(resource);
|
|
115
|
+
if (!header || !RESOURCE_MIMES.has(header[1]!)) invalid('unsupported resource type');
|
|
116
|
+
const mime = header[1]!;
|
|
117
|
+
const bytes = decodeBase64(resource.slice(header[0].length));
|
|
118
|
+
// Use FNV-1a to narrow candidates, then compare every byte before reusing an entry.
|
|
119
|
+
let hash = 2166136261;
|
|
120
|
+
for (const byte of bytes) hash = Math.imul(hash ^ byte, 16777619);
|
|
121
|
+
const key = `${mime}:${bytes.length}:${hash}`;
|
|
122
|
+
const candidates = payloadIndices.get(key) ?? [];
|
|
123
|
+
let index = candidates.find((candidate) => bytes.every((byte, i) => byte === payload[candidate]!.bytes[i]));
|
|
124
|
+
if (index === undefined) {
|
|
125
|
+
index = payload.length;
|
|
126
|
+
if (index >= MAX_RESOURCES) invalid('too many resources');
|
|
127
|
+
payload.push({ mime, bytes });
|
|
128
|
+
candidates.push(index);
|
|
129
|
+
payloadIndices.set(key, candidates);
|
|
130
|
+
}
|
|
131
|
+
uriIndices.set(resource, index);
|
|
132
|
+
return index;
|
|
133
|
+
});
|
|
134
|
+
const manifest = encodeText(JSON.stringify({ asset, resources: payload.map(({ mime, bytes }) => [mime, bytes.length]) }));
|
|
135
|
+
const size = payload.reduce((total, { bytes }) => total + bytes.length, HEADER_SIZE + manifest.length);
|
|
136
|
+
if (size > limit) throw new Error('packed asset exceeds 1 MiB');
|
|
137
|
+
const result = new Uint8Array(size);
|
|
138
|
+
const view = new DataView(result.buffer);
|
|
139
|
+
view.setUint32(0, MAGIC);
|
|
140
|
+
view.setUint8(4, VERSION);
|
|
141
|
+
view.setUint32(8, manifest.length, true);
|
|
142
|
+
result.set(manifest, HEADER_SIZE);
|
|
143
|
+
let offset = HEADER_SIZE + manifest.length;
|
|
144
|
+
for (const resource of payload) {
|
|
145
|
+
result.set(resource.bytes, offset);
|
|
146
|
+
offset += resource.bytes.length;
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
package/runtime/asset-draw.ts
CHANGED
|
@@ -2,7 +2,8 @@ import {
|
|
|
2
2
|
BlendMode, BlurStyle, ClipOp, FilterMode, MipmapMode, PaintStyle, Skia, StrokeCap, StrokeJoin, TextAlign, TextDirection, TileMode, VertexMode,
|
|
3
3
|
type SkCanvas, type SkData, type SkImage, type SkPaint, type SkParagraph, type SkPath, type SkShader, type SkTypeface, type SkTypefaceFontProvider,
|
|
4
4
|
} from 'react-native-skia';
|
|
5
|
-
import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type MotionAsset, type PathCommand } from './asset';
|
|
5
|
+
import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type DrawableMotionAsset, type MotionAsset, type PathCommand } from './asset';
|
|
6
|
+
import type { AssetResource } from './asset-binary';
|
|
6
7
|
import { fitAsset, fittedAnchorOffset, type AssetLayoutOptions } from './asset-layout';
|
|
7
8
|
import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
|
|
8
9
|
|
|
@@ -37,8 +38,15 @@ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
|
|
|
37
38
|
export type AssetImages = Readonly<Record<string, SkImage>>;
|
|
38
39
|
export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
|
|
39
40
|
|
|
41
|
+
function skiaData(resource: AssetResource): SkData {
|
|
42
|
+
if (typeof resource === 'string') return Skia.Data.fromBase64(resource.slice(resource.indexOf(',') + 1));
|
|
43
|
+
const { bytes } = resource;
|
|
44
|
+
// Skia v3 reads the whole backing buffer. Give it only this resource.
|
|
45
|
+
return Skia.Data.fromBytes(bytes.byteOffset === 0 && bytes.length === bytes.buffer.byteLength ? bytes : new Uint8Array(bytes));
|
|
46
|
+
}
|
|
47
|
+
|
|
40
48
|
/** Decode on the JS thread once per loaded file. Only the native images enter the UI worklet. */
|
|
41
|
-
export function decodeAssetImages(asset:
|
|
49
|
+
export function decodeAssetImages(asset: DrawableMotionAsset, slots: AssetImages = {}): AssetImages {
|
|
42
50
|
for (const name of Object.keys(slots)) {
|
|
43
51
|
if (!asset.imageSlots || !Object.hasOwn(asset.imageSlots, name)) throw new Error(`Unknown motion image slot "${name}"`);
|
|
44
52
|
}
|
|
@@ -48,18 +56,18 @@ export function decodeAssetImages(asset: MotionAsset, slots: AssetImages = {}):
|
|
|
48
56
|
MakeFromEncoded?: (data: SkData) => SkImage | null;
|
|
49
57
|
MakeImageFromEncoded?: (data: SkData) => SkImage | null;
|
|
50
58
|
};
|
|
51
|
-
const
|
|
59
|
+
const byResource = new Map<AssetResource, SkImage>();
|
|
52
60
|
const embedded = asset.images;
|
|
53
61
|
const used = usedAssetImages(asset.artboard.nodes);
|
|
54
62
|
return Object.fromEntries(Array.from(used, (name) => {
|
|
55
63
|
if (Object.hasOwn(slots, name)) return [name, slots[name]!];
|
|
56
|
-
const
|
|
57
|
-
const previous =
|
|
64
|
+
const resource = embedded[asset.imageSlots?.[name] ?? name]!;
|
|
65
|
+
const previous = byResource.get(resource);
|
|
58
66
|
if (previous) return [name, previous];
|
|
59
|
-
const data =
|
|
67
|
+
const data = skiaData(resource);
|
|
60
68
|
const image = factory.MakeFromEncoded ? factory.MakeFromEncoded(data) : factory.MakeImageFromEncoded?.(data);
|
|
61
69
|
if (!image) throw new Error(`images.${name}: could not decode the embedded image`);
|
|
62
|
-
|
|
70
|
+
byResource.set(resource, image);
|
|
63
71
|
return [name, image];
|
|
64
72
|
}));
|
|
65
73
|
}
|
|
@@ -145,6 +153,7 @@ function makeParagraph(node: AssetTextNode, text: string, provider?: SkTypefaceF
|
|
|
145
153
|
builder.pushStyle({
|
|
146
154
|
color: Skia.Color(node.fill), fontSize: node.fontSize,
|
|
147
155
|
...(node.fonts?.length ? { fontFamilies: [...node.fonts] } : {}),
|
|
156
|
+
...(node.fontFeatures?.length ? { fontFeatures: [...node.fontFeatures] } : {}),
|
|
148
157
|
});
|
|
149
158
|
builder.addText(text);
|
|
150
159
|
const paragraph = builder.build();
|
|
@@ -192,20 +201,26 @@ function prepareNode(
|
|
|
192
201
|
}
|
|
193
202
|
|
|
194
203
|
/** Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose. */
|
|
195
|
-
export function prepareAssetDrawing(asset:
|
|
204
|
+
export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetImages = {}): DrawableAsset {
|
|
196
205
|
const shaders: Record<string, SkShader> = {};
|
|
197
206
|
const shadersByImage = new Map<SkImage, SkShader>();
|
|
198
207
|
let fontProvider: SkTypefaceFontProvider | undefined;
|
|
199
|
-
|
|
208
|
+
const typefaces = new Map<AssetResource, SkTypeface>();
|
|
209
|
+
for (const [name, resource] of Object.entries(asset.fonts ?? {})) {
|
|
200
210
|
fontProvider ??= Skia.TypefaceFontProvider.Make();
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
211
|
+
let typeface = typefaces.get(resource);
|
|
212
|
+
if (!typeface) {
|
|
213
|
+
const data = skiaData(resource);
|
|
214
|
+
// Match the renamed factory while retaining the Skia 3.0 peer floor.
|
|
215
|
+
const factory = Skia.Typeface as {
|
|
216
|
+
MakeFromData?: (data: SkData) => SkTypeface | null;
|
|
217
|
+
MakeFreeTypeFaceFromData?: (data: SkData) => SkTypeface | null;
|
|
218
|
+
};
|
|
219
|
+
const decoded = factory.MakeFromData ? factory.MakeFromData(data) : factory.MakeFreeTypeFaceFromData?.(data);
|
|
220
|
+
if (!decoded) throw new Error(`fonts.${name}: Skia could not decode the font`);
|
|
221
|
+
typefaces.set(resource, decoded);
|
|
222
|
+
typeface = decoded;
|
|
223
|
+
}
|
|
209
224
|
fontProvider.registerFont(typeface, name);
|
|
210
225
|
}
|
|
211
226
|
const textBindings = new Set<string>();
|
package/runtime/asset-image.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { decodeBase64 } from './base64';
|
|
2
|
+
import { isResourceBytes } from './asset-binary';
|
|
2
3
|
|
|
3
4
|
/** Check the embedded image header before passing its bytes to a renderer. */
|
|
4
5
|
export function imageSize(uri: unknown): { width: number; height: number } | null {
|
|
6
|
+
if (isResourceBytes(uri)) {
|
|
7
|
+
return uri.mime.startsWith('image/') ? imageFileSize(uri.mime.slice(6), uri.bytes) : null;
|
|
8
|
+
}
|
|
5
9
|
if (typeof uri !== 'string') return null;
|
|
6
10
|
const match = /^data:image\/(png|webp);base64,([A-Za-z0-9+/]+={0,2})$/.exec(uri);
|
|
7
11
|
if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) return null;
|
package/runtime/asset-load.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { SkImage } from 'react-native-skia';
|
|
2
|
-
import { assetClips, bindAssetPalette,
|
|
2
|
+
import { assetClips, bindAssetPalette, parseDrawableAsset, type MotionAsset } from './asset';
|
|
3
|
+
import { resourceDataUri, type MotionAssetData, type ResourceBytes } from './asset-binary';
|
|
3
4
|
import { decodeAssetImages, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
|
|
4
5
|
|
|
5
6
|
let nextAssetKey = 0;
|
|
@@ -18,9 +19,14 @@ export type LoadedMotionAsset = Readonly<{
|
|
|
18
19
|
/** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
|
|
19
20
|
export type MotionPrepareOptions = { artboard?: string; imageSlots?: AssetImages; palette?: Readonly<Record<string, string>> };
|
|
20
21
|
|
|
21
|
-
export function loadMotionAsset(source:
|
|
22
|
-
const asset = bindAssetPalette(
|
|
22
|
+
export function loadMotionAsset(source: MotionAssetData, { artboard, imageSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
|
|
23
|
+
const asset = bindAssetPalette(parseDrawableAsset(source, artboard), palette);
|
|
23
24
|
const images = decodeAssetImages(asset, imageSlots);
|
|
25
|
+
let audio: LoadedMotionAsset['audio'];
|
|
26
|
+
if (asset.audio) {
|
|
27
|
+
const uris = new Map<ResourceBytes, string>();
|
|
28
|
+
audio = Object.fromEntries(Object.entries(asset.audio).map(([name, resource]) => [name, resourceDataUri(resource, uris)]));
|
|
29
|
+
}
|
|
24
30
|
return {
|
|
25
31
|
key: nextAssetKey++,
|
|
26
32
|
machine: asset.machine,
|
|
@@ -29,7 +35,7 @@ export function loadMotionAsset(source: string, { artboard, imageSlots, palette
|
|
|
29
35
|
images,
|
|
30
36
|
clips: assetClips(asset),
|
|
31
37
|
semantics: asset.semantics,
|
|
32
|
-
audio
|
|
38
|
+
audio,
|
|
33
39
|
};
|
|
34
40
|
}
|
|
35
41
|
|
|
@@ -38,10 +44,10 @@ export function loadMotionAsset(source: string, { artboard, imageSlots, palette
|
|
|
38
44
|
* that work off the JS thread. Upload is opt-in and can retain textures until the file is released.
|
|
39
45
|
*/
|
|
40
46
|
export async function preloadMotionAsset(
|
|
41
|
-
source:
|
|
47
|
+
source: MotionAssetData | LoadedMotionAsset,
|
|
42
48
|
{ uploadImages = false, ...options }: MotionPrepareOptions & { uploadImages?: boolean } = {},
|
|
43
49
|
): Promise<LoadedMotionAsset> {
|
|
44
|
-
const loaded = typeof source === 'string' ? loadMotionAsset(source, options) : source;
|
|
50
|
+
const loaded = typeof source === 'string' || source instanceof Uint8Array ? loadMotionAsset(source, options) : source;
|
|
45
51
|
const warmed = new Map<SkImage, SkImage>();
|
|
46
52
|
const images: [string, SkImage][] = [];
|
|
47
53
|
let changed = false;
|
package/runtime/asset.ts
CHANGED
|
@@ -4,12 +4,13 @@ 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
6
|
import { decodeBase64 } from './base64';
|
|
7
|
+
import { decodeAssetText, decodeBinaryAsset, isBinaryAsset, isResourceBytes, mapFileResources, resourceDataUri, type AssetResource, type MotionAssetData, type ResourceBytes } from './asset-binary';
|
|
7
8
|
import type { MeshNode, MeshVertex } from './asset-mesh';
|
|
8
9
|
|
|
9
10
|
export const ASSET_SCHEMA = 'skac.asset/1';
|
|
10
11
|
export const ASSET_BUNDLE_SCHEMA = 'skac.bundle/1';
|
|
11
12
|
export const MAX_ASSET_BYTES = 1024 * 1024;
|
|
12
|
-
const MAX_ASSET_SOURCE_BYTES = 8 * MAX_ASSET_BYTES;
|
|
13
|
+
export const MAX_ASSET_SOURCE_BYTES = 8 * MAX_ASSET_BYTES;
|
|
13
14
|
export const MAX_FEATHER = 64;
|
|
14
15
|
|
|
15
16
|
export type Scalar = number | string;
|
|
@@ -49,9 +50,11 @@ type ImageNode = {
|
|
|
49
50
|
};
|
|
50
51
|
|
|
51
52
|
export type BoundText = string | { value: string };
|
|
53
|
+
type FontFeature = { name: string; value: number };
|
|
52
54
|
export type AssetTextNode = {
|
|
53
55
|
kind: 'text'; text: BoundText; x: Scalar; y: Scalar; width: number; fontSize: number; fill: string;
|
|
54
56
|
fonts?: readonly string[]; direction?: 'ltr' | 'rtl'; align?: 'start' | 'center' | 'end'; maxLines?: number;
|
|
57
|
+
fontFeatures?: readonly FontFeature[];
|
|
55
58
|
};
|
|
56
59
|
export type AssetSemantic = {
|
|
57
60
|
name: string; label: BoundText; role: 'button' | 'image' | 'text' | 'header';
|
|
@@ -63,31 +66,32 @@ export type AssetNode = Group | Shape | ImageNode | MeshNode | AssetTextNode;
|
|
|
63
66
|
export type AssetMarker = { name: string; layer: string; state: string; audio?: string };
|
|
64
67
|
export type AssetMarkerEvent = AssetMarker & { at: number };
|
|
65
68
|
export type AssetAttachment = { from: string; to: string; maxDistance: number };
|
|
66
|
-
export type MotionAsset<M extends Machine = Machine> = {
|
|
69
|
+
export type MotionAsset<M extends Machine = Machine, R extends AssetResource = string> = {
|
|
67
70
|
schema: typeof ASSET_SCHEMA;
|
|
68
71
|
name: string;
|
|
69
72
|
artboard: { width: number; height: number; nodes: readonly AssetNode[] };
|
|
70
73
|
channels: Readonly<Record<string, number>>;
|
|
71
|
-
images?: Readonly<Record<string,
|
|
74
|
+
images?: Readonly<Record<string, R>>;
|
|
72
75
|
imageSlots?: Readonly<Record<string, string>>;
|
|
73
76
|
palette?: Readonly<Record<string, string>>;
|
|
74
|
-
fonts?: Readonly<Record<string,
|
|
77
|
+
fonts?: Readonly<Record<string, R>>;
|
|
75
78
|
fontLicenses?: Readonly<Record<string, string>>;
|
|
76
|
-
audio?: Readonly<Record<string,
|
|
79
|
+
audio?: Readonly<Record<string, R>>;
|
|
77
80
|
semantics?: readonly AssetSemantic[];
|
|
78
81
|
clips: Readonly<Record<string, { ms: number; reducedAt?: number; tracks: Readonly<Record<string, Track>> }>>;
|
|
79
82
|
machine: M;
|
|
80
83
|
markers?: readonly AssetMarker[];
|
|
81
84
|
attachments?: readonly AssetAttachment[];
|
|
82
85
|
};
|
|
83
|
-
export type
|
|
86
|
+
export type DrawableMotionAsset = MotionAsset<Machine, AssetResource>;
|
|
87
|
+
export type MotionAssetFile<R extends AssetResource = string> = MotionAsset<Machine, R> | {
|
|
84
88
|
schema: typeof ASSET_BUNDLE_SCHEMA;
|
|
85
89
|
name: string;
|
|
86
90
|
defaultArtboard: string;
|
|
87
|
-
artboards: Readonly<Record<string, MotionAsset
|
|
88
|
-
fonts?: MotionAsset['fonts'];
|
|
91
|
+
artboards: Readonly<Record<string, MotionAsset<Machine, R>>>;
|
|
92
|
+
fonts?: MotionAsset<Machine, R>['fonts'];
|
|
89
93
|
fontLicenses?: MotionAsset['fontLicenses'];
|
|
90
|
-
audio?: MotionAsset['audio'];
|
|
94
|
+
audio?: MotionAsset<Machine, R>['audio'];
|
|
91
95
|
};
|
|
92
96
|
|
|
93
97
|
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
|
|
@@ -202,6 +206,11 @@ function resourceMap(value: unknown, at: string, pattern: RegExp) {
|
|
|
202
206
|
for (const [name, uri] of Object.entries(resources)) {
|
|
203
207
|
const key = `${at}.${name}`;
|
|
204
208
|
identifier(name, key);
|
|
209
|
+
if (isResourceBytes(uri)) {
|
|
210
|
+
if (!pattern.test(`data:${uri.mime};base64,AAAA`)) invalid(key, 'invalid embedded resource media type');
|
|
211
|
+
if (pattern === FONT_URI && !hasFontHeader(uri.bytes)) invalid(key, 'expected a TTF or OTF font header');
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
205
214
|
const match = typeof uri === 'string' ? pattern.exec(uri) : null;
|
|
206
215
|
if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) invalid(key, 'expected an embedded base64 data URI');
|
|
207
216
|
if (pattern === FONT_URI) {
|
|
@@ -290,7 +299,7 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
290
299
|
const { channels, images, imageSlots, points } = context;
|
|
291
300
|
const node = record(value, at);
|
|
292
301
|
if (node.kind === 'text') {
|
|
293
|
-
record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines']);
|
|
302
|
+
record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines', 'fontFeatures']);
|
|
294
303
|
checkText(node.text, `${at}.text`, context.values);
|
|
295
304
|
scalar(node.x, `${at}.x`, channels);
|
|
296
305
|
scalar(node.y, `${at}.y`, channels);
|
|
@@ -300,6 +309,21 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
300
309
|
if (node.fonts !== undefined) list(node.fonts, `${at}.fonts`, 8).forEach((name, i) => {
|
|
301
310
|
if (typeof name !== 'string' || !Object.hasOwn(context.fonts, name)) invalid(`${at}.fonts[${i}]`, 'unknown embedded font');
|
|
302
311
|
});
|
|
312
|
+
if (node.fontFeatures !== undefined) {
|
|
313
|
+
const names = new Set<string>();
|
|
314
|
+
list(node.fontFeatures, `${at}.fontFeatures`, 16).forEach((value, i) => {
|
|
315
|
+
const key = `${at}.fontFeatures[${i}]`;
|
|
316
|
+
const feature = record(value, key, ['name', 'value']);
|
|
317
|
+
if (typeof feature.name !== 'string' || !/^[a-zA-Z0-9]{4}$/.test(feature.name)) {
|
|
318
|
+
invalid(`${key}.name`, 'expected a four-character OpenType feature tag');
|
|
319
|
+
}
|
|
320
|
+
if (names.has(feature.name)) invalid(`${key}.name`, 'duplicate font feature');
|
|
321
|
+
names.add(feature.name);
|
|
322
|
+
if (!Number.isInteger(number(feature.value, `${key}.value`, 0, 65535))) {
|
|
323
|
+
invalid(`${key}.value`, 'expected an integer');
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
}
|
|
303
327
|
if (node.direction !== undefined && node.direction !== 'ltr' && node.direction !== 'rtl') invalid(`${at}.direction`, 'expected ltr or rtl');
|
|
304
328
|
if (node.align !== undefined && !['start', 'center', 'end'].includes(node.align as string)) invalid(`${at}.align`, 'expected start, center or end');
|
|
305
329
|
if (node.maxLines !== undefined && !Number.isInteger(number(node.maxLines, `${at}.maxLines`, 1, 16))) {
|
|
@@ -384,7 +408,7 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
|
|
|
384
408
|
colors.forEach((item, i) => color(item, `${at}.fill.colors[${i}]`));
|
|
385
409
|
}
|
|
386
410
|
|
|
387
|
-
function validateAsset(value: unknown):
|
|
411
|
+
function validateAsset(value: unknown): DrawableMotionAsset {
|
|
388
412
|
const data = record(value, 'asset', [
|
|
389
413
|
'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontLicenses', 'audio', 'semantics',
|
|
390
414
|
]);
|
|
@@ -503,7 +527,7 @@ function validateAsset(value: unknown): MotionAsset {
|
|
|
503
527
|
const { where, error, hint } = checked.problems[0]!;
|
|
504
528
|
invalid(where ? `machine.${where}` : 'machine', `${error}. ${hint}`);
|
|
505
529
|
}
|
|
506
|
-
const typed = data as
|
|
530
|
+
const typed = data as DrawableMotionAsset;
|
|
507
531
|
const names = new Set();
|
|
508
532
|
if (data.markers !== undefined) {
|
|
509
533
|
list(data.markers, 'markers', 256).forEach((item, i) => {
|
|
@@ -523,36 +547,53 @@ function validateAsset(value: unknown): MotionAsset {
|
|
|
523
547
|
return typed;
|
|
524
548
|
}
|
|
525
549
|
|
|
526
|
-
/**
|
|
527
|
-
export function parseAssetFile(
|
|
528
|
-
|
|
550
|
+
/** Read the portable scene as editable JSON-compatible data. */
|
|
551
|
+
export function parseAssetFile(source: MotionAssetData): MotionAssetFile {
|
|
552
|
+
const file = parseDrawableFile(source);
|
|
553
|
+
if (typeof source === 'string' || !isBinaryAsset(source)) return file as MotionAssetFile;
|
|
554
|
+
const uris = new Map<ResourceBytes, string>();
|
|
555
|
+
return mapFileResources(file, (value) => resourceDataUri(value as AssetResource, uris)) as MotionAssetFile;
|
|
529
556
|
}
|
|
530
557
|
|
|
531
558
|
/** The CLI may prune unused resources before enforcing the shipped limit. */
|
|
532
559
|
export function parseAssetSource(text: string): MotionAssetFile {
|
|
533
|
-
return
|
|
560
|
+
return parseAssetText(text, MAX_ASSET_SOURCE_BYTES) as MotionAssetFile;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function parseDrawableFile(source: MotionAssetData): MotionAssetFile<AssetResource> {
|
|
564
|
+
if (typeof source === 'string') return parseAssetText(source, MAX_ASSET_BYTES);
|
|
565
|
+
if (!(source instanceof Uint8Array) || source.length > MAX_ASSET_BYTES) invalid('asset', 'expected an asset of at most 1 MiB');
|
|
566
|
+
if (isBinaryAsset(source)) return validateAssetFile(decodeBinaryAsset(source, parseJSON));
|
|
567
|
+
return validateAssetFile(parseJSON(decodeAssetText(source)));
|
|
534
568
|
}
|
|
535
569
|
|
|
536
|
-
function
|
|
570
|
+
function parseAssetText(text: string, limit: number): MotionAssetFile<AssetResource> {
|
|
537
571
|
const message = `expected a JSON asset of at most ${limit / MAX_ASSET_BYTES} MiB`;
|
|
538
572
|
if (typeof text !== 'string' || text.length > limit) invalid('asset', message);
|
|
539
573
|
const bytes = encodeURI(text).replace(/%[0-9A-F]{2}/g, 'x').length;
|
|
540
574
|
if (bytes > limit) invalid('asset', message);
|
|
541
|
-
|
|
575
|
+
return validateAssetFile(parseJSON(text));
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function parseJSON(text: string): unknown {
|
|
579
|
+
return JSON.parse(text, (key, value: unknown) => {
|
|
542
580
|
if (RESERVED_KEYS.has(key)) invalid(key, 'reserved field name');
|
|
543
581
|
if (typeof value === 'number' && !Number.isFinite(value)) invalid(key, 'expected a finite number');
|
|
544
582
|
return value;
|
|
545
583
|
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function validateAssetFile(decoded: unknown): MotionAssetFile<AssetResource> {
|
|
546
587
|
const file = record(decoded, 'asset');
|
|
547
588
|
if (file.schema !== ASSET_BUNDLE_SCHEMA) return validateAsset(file);
|
|
548
589
|
record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontLicenses', 'audio']);
|
|
549
590
|
const name = identifier(file.name, 'bundle.name');
|
|
550
591
|
const defaultArtboard = identifier(file.defaultArtboard, 'bundle.defaultArtboard');
|
|
551
592
|
const artboards = record(file.artboards, 'bundle.artboards');
|
|
552
|
-
const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<
|
|
593
|
+
const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<DrawableMotionAsset['fonts']>;
|
|
553
594
|
checkFontLicenses(file.fontLicenses, fonts, 'bundle.fontLicenses');
|
|
554
595
|
const fontLicenses = file.fontLicenses as MotionAsset['fontLicenses'];
|
|
555
|
-
const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<
|
|
596
|
+
const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<DrawableMotionAsset['audio']>;
|
|
556
597
|
const entries = Object.entries(artboards);
|
|
557
598
|
if (entries.length < 1 || entries.length > 16) invalid('bundle.artboards', 'expected one to sixteen artboards');
|
|
558
599
|
if (!Object.hasOwn(artboards, defaultArtboard)) invalid('bundle.defaultArtboard', 'unknown artboard');
|
|
@@ -572,7 +613,7 @@ function parseAssetJSON(text: string, limit: number): MotionAssetFile {
|
|
|
572
613
|
...board, fonts: { ...fonts, ...localFonts },
|
|
573
614
|
fontLicenses: { ...fontLicenses, ...localLicenses }, audio: { ...audio, ...localAudio },
|
|
574
615
|
});
|
|
575
|
-
return [key, board as
|
|
616
|
+
return [key, board as DrawableMotionAsset];
|
|
576
617
|
} catch (error) {
|
|
577
618
|
invalid(`bundle.artboards.${key}`, (error as Error).message);
|
|
578
619
|
}
|
|
@@ -580,7 +621,7 @@ function parseAssetJSON(text: string, limit: number): MotionAssetFile {
|
|
|
580
621
|
};
|
|
581
622
|
}
|
|
582
623
|
|
|
583
|
-
export function selectArtboard(file: MotionAssetFile
|
|
624
|
+
export function selectArtboard<R extends AssetResource>(file: MotionAssetFile<R>, artboard?: string): MotionAsset<Machine, R> {
|
|
584
625
|
if (file.schema === ASSET_SCHEMA) {
|
|
585
626
|
if (artboard === undefined || artboard === file.name) return file;
|
|
586
627
|
invalid('artboard', `unknown artboard "${artboard}". Available: ${file.name}`);
|
|
@@ -598,8 +639,13 @@ export function selectArtboard(file: MotionAssetFile, artboard?: string): Motion
|
|
|
598
639
|
};
|
|
599
640
|
}
|
|
600
641
|
|
|
601
|
-
export function parseAsset(
|
|
602
|
-
return selectArtboard(parseAssetFile(
|
|
642
|
+
export function parseAsset(source: MotionAssetData, artboard?: string): MotionAsset {
|
|
643
|
+
return selectArtboard(parseAssetFile(source), artboard);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Decode a scene for drawing and preserve encoded image and font bytes for Skia. */
|
|
647
|
+
export function parseDrawableAsset(source: MotionAssetData, artboard?: string): DrawableMotionAsset {
|
|
648
|
+
return selectArtboard(parseDrawableFile(source), artboard);
|
|
603
649
|
}
|
|
604
650
|
|
|
605
651
|
export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<string, string>>): string {
|
|
@@ -607,7 +653,7 @@ export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<st
|
|
|
607
653
|
return typeof value === 'string' ? value : palette[value.palette]!;
|
|
608
654
|
}
|
|
609
655
|
|
|
610
|
-
export function bindAssetPalette(asset: MotionAsset, overrides?: Readonly<Record<string, string>>): MotionAsset {
|
|
656
|
+
export function bindAssetPalette<R extends AssetResource>(asset: MotionAsset<Machine, R>, overrides?: Readonly<Record<string, string>>): MotionAsset<Machine, R> {
|
|
611
657
|
if (!overrides) return asset;
|
|
612
658
|
for (const [name, value] of Object.entries(overrides)) {
|
|
613
659
|
if (!asset.palette || !Object.hasOwn(asset.palette, name)) invalid(`palette.${name}`, 'unknown palette entry');
|
|
@@ -653,7 +699,7 @@ function trackValue(track: Track, ms: number): number {
|
|
|
653
699
|
}
|
|
654
700
|
|
|
655
701
|
/** Adapt data tracks to the existing state-machine clip interface. */
|
|
656
|
-
export function assetClips(asset: MotionAsset): Clips {
|
|
702
|
+
export function assetClips(asset: Pick<MotionAsset, 'clips'>): Clips {
|
|
657
703
|
return Object.fromEntries(Object.entries(asset.clips).map(([name, { ms, reducedAt, tracks }]) => {
|
|
658
704
|
const channels = Object.entries(tracks);
|
|
659
705
|
return [name, {
|
package/runtime/base64.ts
CHANGED
|
@@ -17,3 +17,21 @@ export function decodeBase64(encoded: string): Uint8Array {
|
|
|
17
17
|
}
|
|
18
18
|
return bytes.subarray(0, length);
|
|
19
19
|
}
|
|
20
|
+
|
|
21
|
+
export function encodeBase64(bytes: Uint8Array): string {
|
|
22
|
+
const chunks: string[] = [];
|
|
23
|
+
let chunk = '';
|
|
24
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
25
|
+
const a = bytes[i]!;
|
|
26
|
+
const b = bytes[i + 1] ?? 0;
|
|
27
|
+
const c = bytes[i + 2] ?? 0;
|
|
28
|
+
chunk += ALPHABET[a >> 2]! + ALPHABET[((a & 3) << 4) | (b >> 4)]! +
|
|
29
|
+
(i + 1 < bytes.length ? ALPHABET[((b & 15) << 2) | (c >> 6)]! : '=') +
|
|
30
|
+
(i + 2 < bytes.length ? ALPHABET[c & 63]! : '=');
|
|
31
|
+
if (chunk.length >= 8192) {
|
|
32
|
+
chunks.push(chunk);
|
|
33
|
+
chunk = '';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return chunks.join('') + chunk;
|
|
37
|
+
}
|
package/runtime/expo.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Asset } from 'expo-asset';
|
|
2
2
|
import { File } from 'expo-file-system';
|
|
3
|
+
import { MAX_ASSET_BYTES } from './asset';
|
|
3
4
|
import { useMotionAsset, type MotionAssetOptions } from './useMotionAsset';
|
|
4
5
|
|
|
5
6
|
/** Read a .skmotion from Expo's Metro asset registry in a development or release build. */
|
|
@@ -10,7 +11,9 @@ export function useExpoMotionAsset(moduleId: number | null | undefined, options?
|
|
|
10
11
|
const asset = await Asset.fromModule(moduleId).downloadAsync();
|
|
11
12
|
if (signal.aborted) throw new Error('Motion asset load cancelled');
|
|
12
13
|
if (!asset.localUri) throw new Error('Expo did not produce a local motion file');
|
|
13
|
-
|
|
14
|
+
const file = new File(asset.localUri);
|
|
15
|
+
if (file.size > MAX_ASSET_BYTES) throw new Error('Motion asset exceeds 1 MiB');
|
|
16
|
+
return file.bytes();
|
|
14
17
|
},
|
|
15
18
|
}, options);
|
|
16
19
|
}
|
package/runtime/mobile.tsx
CHANGED
|
@@ -4,6 +4,7 @@ import { AppState, Pressable, StyleSheet, View, type LayoutChangeEvent, type Vie
|
|
|
4
4
|
import { Canvas, Picture, Skia, createPicture, type SkCanvas } from 'react-native-skia';
|
|
5
5
|
import { useAnimatedReaction, useDerivedValue, useSharedValue, type SharedValue } from 'react-native-reanimated';
|
|
6
6
|
import { assetMarkerEvents, type AssetMarkerEvent, type AssetSemantic } from './asset';
|
|
7
|
+
import type { MotionAssetData } from './asset-binary';
|
|
7
8
|
import { drawAsset, type AssetImages, type DrawableAsset } from './asset-draw';
|
|
8
9
|
import { loadMotionAsset, type LoadedMotionAsset } from './asset-load';
|
|
9
10
|
import { fitAsset, type AssetLayoutOptions } from './asset-layout';
|
|
@@ -11,6 +12,7 @@ import { useMachine, type MachineHandle, type MachineInputs, type MachineValues
|
|
|
11
12
|
import type { Machine, Pose, StateEntry } from '../templates/motion/machine';
|
|
12
13
|
|
|
13
14
|
export { parseAsset, parseAssetFile, selectArtboard, type MotionAsset, type MotionAssetFile, type AssetMarkerEvent } from './asset';
|
|
15
|
+
export type { MotionAssetData } from './asset-binary';
|
|
14
16
|
|
|
15
17
|
export { loadMotionAsset, preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
|
|
16
18
|
export { useMotionAsset, type MotionAssetOptions, type MotionAssetSource, type MotionAssetResult } from './useMotionAsset';
|
|
@@ -31,7 +33,7 @@ export type MotionPlayerProps<B extends MotionBindings = MotionBindings> = Pick<
|
|
|
31
33
|
'accessibilityHint' | 'accessibilityValue' | 'accessibilityState' |
|
|
32
34
|
'accessibilityActions' | 'onAccessibilityAction'
|
|
33
35
|
> & AssetLayoutOptions & {
|
|
34
|
-
source:
|
|
36
|
+
source: MotionAssetData | LoadedMotionAsset;
|
|
35
37
|
artboard?: string;
|
|
36
38
|
width?: number;
|
|
37
39
|
height?: number;
|
|
@@ -232,7 +234,8 @@ function SemanticRegion({ entry, label, artboard, viewport, layout, fire }: {
|
|
|
232
234
|
|
|
233
235
|
export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, artboard, ...props }, ref) {
|
|
234
236
|
// The inner hook owns one machine snapshot per loaded file. An updated file starts at t=0.
|
|
235
|
-
const loaded = useMemo(() => typeof source === 'string'
|
|
237
|
+
const loaded = useMemo(() => typeof source === 'string' || source instanceof Uint8Array
|
|
238
|
+
? loadMotionAsset(source, { artboard }) : source, [source, artboard]);
|
|
236
239
|
return <LoadedPlayer key={loaded.key} loaded={loaded} playerRef={ref} {...props} />;
|
|
237
240
|
}) as <B extends MotionBindings = MotionBindings>(props: MotionPlayerProps<B> & RefAttributes<MotionPlayerHandle<B>>) => ReactElement;
|
|
238
241
|
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { useEffect, useMemo, useState } from 'react';
|
|
2
2
|
import { preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
|
|
3
3
|
import type { AssetImages } from './asset-draw';
|
|
4
|
+
import type { MotionAssetData } from './asset-binary';
|
|
4
5
|
|
|
5
|
-
export type MotionAssetSource =
|
|
6
|
+
export type MotionAssetSource = MotionAssetData | { uri: string } | {
|
|
6
7
|
/** Stable identity for a custom loader. Change it when the source changes. */
|
|
7
8
|
key: string;
|
|
8
|
-
read: (signal: AbortSignal) => Promise<
|
|
9
|
+
read: (signal: AbortSignal) => Promise<MotionAssetData>;
|
|
9
10
|
};
|
|
10
11
|
export type MotionAssetOptions = MotionPrepareOptions & { uploadImages?: boolean };
|
|
11
12
|
type Failure = { status: 'error'; asset: null; error: Error };
|
|
@@ -23,7 +24,9 @@ type CacheEntry = {
|
|
|
23
24
|
// Cache prepared resources while subscribers own them. Each player creates its own machine snapshot.
|
|
24
25
|
const cache = new Map<string, CacheEntry>();
|
|
25
26
|
const imageIds = new WeakMap<object, number>();
|
|
27
|
+
const byteIds = new WeakMap<Uint8Array, number>();
|
|
26
28
|
let nextImageId = 0;
|
|
29
|
+
let nextByteId = 0;
|
|
27
30
|
const idle = { status: 'idle', asset: null, error: null } as const;
|
|
28
31
|
const loading = { status: 'loading', asset: null, error: null } as const;
|
|
29
32
|
|
|
@@ -40,11 +43,20 @@ function slotKey(images: AssetImages | undefined) {
|
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
async function readSource(source: MotionAssetSource, signal: AbortSignal) {
|
|
43
|
-
if (typeof source === 'string') return source;
|
|
46
|
+
if (typeof source === 'string' || source instanceof Uint8Array) return source;
|
|
44
47
|
if ('read' in source) return source.read(signal);
|
|
45
48
|
const response = await fetch(source.uri, { signal });
|
|
46
49
|
if (!response.ok) throw new Error(`Unable to load motion asset (HTTP ${response.status})`);
|
|
47
|
-
return response.
|
|
50
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function byteId(bytes: Uint8Array) {
|
|
54
|
+
let id = byteIds.get(bytes);
|
|
55
|
+
if (id === undefined) {
|
|
56
|
+
id = nextByteId++;
|
|
57
|
+
byteIds.set(bytes, id);
|
|
58
|
+
}
|
|
59
|
+
return id;
|
|
48
60
|
}
|
|
49
61
|
|
|
50
62
|
function retain(key: string, source: MotionAssetSource, options: MotionAssetOptions) {
|
|
@@ -54,9 +66,9 @@ function retain(key: string, source: MotionAssetSource, options: MotionAssetOpti
|
|
|
54
66
|
const signal = controller.signal;
|
|
55
67
|
const promise = Promise.resolve().then(async () => {
|
|
56
68
|
if (signal.aborted) throw new Error('Motion asset load cancelled');
|
|
57
|
-
const
|
|
69
|
+
const data = await readSource(source, signal);
|
|
58
70
|
if (signal.aborted) throw new Error('Motion asset load cancelled');
|
|
59
|
-
return preloadMotionAsset(
|
|
71
|
+
return preloadMotionAsset(data, options);
|
|
60
72
|
});
|
|
61
73
|
entry = { promise, controller, users: 0 };
|
|
62
74
|
const created = entry;
|
|
@@ -72,8 +84,10 @@ function retain(key: string, source: MotionAssetSource, options: MotionAssetOpti
|
|
|
72
84
|
/** Asynchronously load and share an asset. For Expo module IDs use the /expo entry point. */
|
|
73
85
|
export function useMotionAsset(source?: MotionAssetSource | null, options: MotionAssetOptions = {}): MotionAssetResult {
|
|
74
86
|
const { uploadImages = false, artboard, imageSlots, palette } = options;
|
|
75
|
-
const kind = source == null ? undefined : typeof source === 'string' ? 'text'
|
|
76
|
-
|
|
87
|
+
const kind = source == null ? undefined : typeof source === 'string' ? 'text'
|
|
88
|
+
: source instanceof Uint8Array ? 'bytes' : 'uri' in source ? 'uri' : 'custom';
|
|
89
|
+
const id = source == null || typeof source === 'string' ? source
|
|
90
|
+
: source instanceof Uint8Array ? byteId(source) : 'uri' in source ? source.uri : source.key;
|
|
77
91
|
const key = useMemo(() => kind === undefined ? undefined : JSON.stringify([
|
|
78
92
|
kind, id, uploadImages, artboard, slotKey(imageSlots),
|
|
79
93
|
Object.keys(palette ?? {}).sort().map((name) => [name, palette![name]]),
|