@haiyue/animation-spec 0.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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +190 -0
  3. package/SPECIFICATION.md +108 -0
  4. package/bin/hya-convert.mjs +31 -0
  5. package/dist/binary.d.ts +7 -0
  6. package/dist/chunks/types-l6nBVYwx.js +8 -0
  7. package/dist/chunks/types-l6nBVYwx.js.map +1 -0
  8. package/dist/errors.d.ts +7 -0
  9. package/dist/extensions.d.ts +19 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +2927 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/lottie-merge-path.d.ts +11 -0
  14. package/dist/lottie.d.ts +62 -0
  15. package/dist/lottie.js +2642 -0
  16. package/dist/lottie.js.map +1 -0
  17. package/dist/native3d/Animation3DError.d.ts +8 -0
  18. package/dist/native3d/Animation3DParser.d.ts +7 -0
  19. package/dist/native3d/Animation3DTypes.d.ts +285 -0
  20. package/dist/native3d/index.d.ts +5 -0
  21. package/dist/native3d.d.ts +2 -0
  22. package/dist/native3d.js +907 -0
  23. package/dist/native3d.js.map +1 -0
  24. package/dist/parser.d.ts +2 -0
  25. package/dist/state-machine.d.ts +130 -0
  26. package/dist/text-selector.d.ts +2 -0
  27. package/dist/types.d.ts +419 -0
  28. package/dist/validation.d.ts +32 -0
  29. package/package.json +69 -0
  30. package/schema/animation-3d-carrier.schema.json +73 -0
  31. package/schema/animation-3d-extension.schema.json +573 -0
  32. package/schema/animation-3d.contract.json +130 -0
  33. package/schema/animation.schema.json +611 -0
  34. package/schema/fixtures/native-3d-mixed-invalid.hya.json +50 -0
  35. package/schema/fixtures/native-3d-valid.hya.json +284 -0
  36. package/src/binary.ts +1441 -0
  37. package/src/errors.ts +18 -0
  38. package/src/extensions.ts +55 -0
  39. package/src/index.ts +90 -0
  40. package/src/lottie-merge-path.ts +204 -0
  41. package/src/lottie.ts +3073 -0
  42. package/src/native3d/Animation3DError.ts +20 -0
  43. package/src/native3d/Animation3DParser.ts +964 -0
  44. package/src/native3d/Animation3DTypes.ts +322 -0
  45. package/src/native3d/index.ts +14 -0
  46. package/src/native3d.ts +2 -0
  47. package/src/parser.ts +41 -0
  48. package/src/state-machine.ts +645 -0
  49. package/src/text-selector.ts +7 -0
  50. package/src/types.ts +483 -0
  51. package/src/validation.ts +1286 -0
  52. package/test/fixtures/basic-lottie.json +31 -0
package/src/errors.ts ADDED
@@ -0,0 +1,18 @@
1
+ export type AnimationFormatErrorCode =
2
+ | 'E_ANIMATION_INVALID_FORMAT'
3
+ | 'E_ANIMATION_UNSUPPORTED_VERSION'
4
+ | 'E_ANIMATION_LIMIT_EXCEEDED'
5
+ | 'E_ANIMATION_MISSING_EXTENSION'
6
+ | 'E_ANIMATION_INVALID_BINARY';
7
+
8
+ export class AnimationFormatError extends Error {
9
+ readonly name = 'AnimationFormatError';
10
+
11
+ constructor(
12
+ readonly code: AnimationFormatErrorCode,
13
+ message: string,
14
+ readonly path = '$',
15
+ ) {
16
+ super(`${message} (${path})`);
17
+ }
18
+ }
@@ -0,0 +1,55 @@
1
+ import { AnimationFormatError } from './errors';
2
+
3
+ export interface AnimationExtensionValidationContext {
4
+ readonly extension: string;
5
+ readonly path: string;
6
+ fail(message: string, path?: string): never;
7
+ }
8
+
9
+ export interface AnimationExtensionHandler {
10
+ /** Versioned identifier such as `org.example.particle@1`. */
11
+ readonly id: string;
12
+ validateComponent?(component: Readonly<Record<string, unknown>>, context: AnimationExtensionValidationContext): void;
13
+ validateDocument?(data: unknown, context: AnimationExtensionValidationContext): void;
14
+ }
15
+
16
+ export class AnimationExtensionRegistry {
17
+ private readonly _handlers = new Map<string, AnimationExtensionHandler>();
18
+
19
+ register(handler: AnimationExtensionHandler): () => void {
20
+ validateExtensionId(handler.id);
21
+ if (this._handlers.has(handler.id)) {
22
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', `Extension "${handler.id}" is already registered.`, '$.extensions');
23
+ }
24
+ this._handlers.set(handler.id, handler);
25
+ let active = true;
26
+ return () => {
27
+ if (!active) return;
28
+ active = false;
29
+ if (this._handlers.get(handler.id) === handler) this._handlers.delete(handler.id);
30
+ };
31
+ }
32
+
33
+ get(id: string): AnimationExtensionHandler | undefined {
34
+ return this._handlers.get(id);
35
+ }
36
+
37
+ has(id: string): boolean {
38
+ return this._handlers.has(id);
39
+ }
40
+ }
41
+
42
+ export function extensionIdFromComponentType(type: string): string | null {
43
+ return type === 'shape2d' || type === 'path2d' || type === 'sprite2d'
44
+ || type === 'text2d' || type === 'particle2d' || type === 'audio' ? null : type;
45
+ }
46
+
47
+ export function validateExtensionId(value: string): void {
48
+ if (!/^[a-z0-9]+(?:[.-][a-z0-9]+)+@[1-9][0-9]*$/i.test(value)) {
49
+ throw new AnimationFormatError(
50
+ 'E_ANIMATION_INVALID_FORMAT',
51
+ `Extension id "${value}" must be a namespaced id with a major version suffix.`,
52
+ '$.extensionsUsed',
53
+ );
54
+ }
55
+ }
package/src/index.ts ADDED
@@ -0,0 +1,90 @@
1
+ export {
2
+ ANIMATION_FILE_EXTENSION,
3
+ ANIMATION_FORMAT,
4
+ ANIMATION_MIME_TYPE,
5
+ ANIMATION_VERSION,
6
+ ANIMATION_VECTOR_SHAPE_EXTENSION_ID,
7
+ } from './types';
8
+ export type {
9
+ AnimationBinaryResource,
10
+ AnimationAudioComponent,
11
+ AnimationAudioResource,
12
+ AnimationCanvas,
13
+ AnimationComponent,
14
+ AnimationCoordinateSystem,
15
+ AnimationComposite,
16
+ AnimationCompositeKind,
17
+ AnimationCompositeLayer,
18
+ AnimationCompositeMode,
19
+ AnimationCompositeOperation,
20
+ AnimationCompositeStack,
21
+ AnimationDocument,
22
+ AnimationEndBehavior,
23
+ AnimationExtensionComponent,
24
+ AnimationImageResource,
25
+ AnimationInterpolation,
26
+ AnimationLayerEffect,
27
+ AnimationTintEffect,
28
+ AnimationFillEffect,
29
+ AnimationOpacityEffect,
30
+ AnimationColorMatrixEffect,
31
+ AnimationBlurEffect,
32
+ AnimationDropShadowEffect,
33
+ AnimationFillRule,
34
+ AnimationNode,
35
+ AnimationParseLimits,
36
+ AnimationParseOptions,
37
+ AnimationPath2DComponent,
38
+ AnimationPathCommand,
39
+ AnimationParticle2DComponent,
40
+ AnimationResource,
41
+ AnimationShape2DComponent,
42
+ AnimationSource,
43
+ AnimationSprite2DComponent,
44
+ AnimationText2DComponent,
45
+ AnimationTextAnimator,
46
+ AnimationTextDocumentKeyframe,
47
+ AnimationTextRangeSelector,
48
+ AnimationTextSelectorShape,
49
+ AnimationTextSelectorUnits,
50
+ AnimationTrack,
51
+ AnimationTrackProperty,
52
+ AnimationTransform2D,
53
+ AnimationVectorGradientPaint,
54
+ AnimationVectorShapeComponent,
55
+ AnimationVectorSolidPaint,
56
+ AnimationVectorStrokePaint,
57
+ AnimationVectorValueTrack,
58
+ ParsedAnimation,
59
+ ParsedAnimationTrack,
60
+ } from './types';
61
+ export { AnimationFormatError } from './errors';
62
+ export type { AnimationFormatErrorCode } from './errors';
63
+ export { AnimationExtensionRegistry, extensionIdFromComponentType, validateExtensionId } from './extensions';
64
+ export type { AnimationExtensionHandler, AnimationExtensionValidationContext } from './extensions';
65
+ export { parseAnimation } from './parser';
66
+ export { decodeAnimationBinary, encodeAnimationBinary, isAnimationBinary } from './binary';
67
+ export {
68
+ HYA_STATE_MACHINE_CHANNEL_REGISTRY,
69
+ HYA_STATE_MACHINE_EXTENSION_ID,
70
+ hyaStateMachineChannelCapability,
71
+ parseHyaStateMachineExtension,
72
+ } from './state-machine';
73
+ export type {
74
+ HyaAnimationClipRange,
75
+ HyaStateMachineBindingMask,
76
+ HyaStateMachineBlendMode,
77
+ HyaStateMachineChannelCapability,
78
+ HyaStateMachineChannelId,
79
+ HyaStateMachineChannelKind,
80
+ HyaStateMachineChannelSupport,
81
+ HyaStateMachineCondition,
82
+ HyaStateMachineDefinition,
83
+ HyaStateMachineExtension,
84
+ HyaStateMachineLayer,
85
+ HyaStateMachineLoopMode,
86
+ HyaStateMachineMotion,
87
+ HyaStateMachineParameter,
88
+ HyaStateMachineState,
89
+ HyaStateMachineTransition,
90
+ } from './state-machine';
@@ -0,0 +1,204 @@
1
+ // polygon-clipping publishes root declarations, but its ESM bundle subpath has
2
+ // no adjacent .d.ts. Importing the ESM file avoids selecting the browser UMD
3
+ // build while the public root types below keep the call surface checked.
4
+ // @ts-expect-error The package does not map declarations for its ESM subpath.
5
+ import polygonClippingRuntime from 'polygon-clipping/dist/polygon-clipping.esm.js';
6
+ import type { MultiPolygon, Pair, Polygon } from 'polygon-clipping';
7
+
8
+ const polygonClipping = polygonClippingRuntime as typeof import('polygon-clipping');
9
+
10
+ export interface StaticVectorPath {
11
+ readonly commands: string;
12
+ readonly values: readonly number[] | Float32Array;
13
+ }
14
+
15
+ export type Matrix2D = readonly [number, number, number, number, number, number];
16
+
17
+ /** Performs Lottie Merge/Add/Subtract/Intersect/Exclude on static path operands. */
18
+ export function mergeStaticVectorPaths(
19
+ operands: readonly (readonly StaticVectorPath[])[],
20
+ mode: number,
21
+ ): StaticVectorPath | null {
22
+ const paths = operands.flat();
23
+ if (mode === 1) {
24
+ return paths.length === 0 ? null : {
25
+ commands: paths.map(path => path.commands).join(''),
26
+ values: paths.flatMap(path => Array.from(path.values)),
27
+ };
28
+ }
29
+ const geometries = operands.map(pathsToMultiPolygon).filter(geometry => geometry.length > 0);
30
+ if (geometries.length === 0) return null;
31
+ const [first, ...rest] = geometries;
32
+ const merged = mode === 2
33
+ ? polygonClipping.union(first!, ...rest)
34
+ : mode === 3
35
+ ? polygonClipping.difference(first!, ...rest)
36
+ : mode === 4
37
+ ? polygonClipping.intersection(first!, ...rest)
38
+ : polygonClipping.xor(first!, ...rest);
39
+ return multiPolygonToPath(merged);
40
+ }
41
+
42
+ export function identityMatrix(): Matrix2D {
43
+ return [1, 0, 0, 1, 0, 0];
44
+ }
45
+
46
+ export function translationMatrix(x: number, y: number): Matrix2D {
47
+ return [1, 0, 0, 1, x, y];
48
+ }
49
+
50
+ export function transformMatrix(position: number[], anchor: number[], scale: number[], rotation: number): Matrix2D {
51
+ const scaleX = (scale[0] ?? 100) / 100;
52
+ const scaleY = (scale[1] ?? 100) / 100;
53
+ const cosine = Math.cos(rotation);
54
+ const sine = Math.sin(rotation);
55
+ const a = cosine * scaleX;
56
+ const b = sine * scaleX;
57
+ const c = -sine * scaleY;
58
+ const d = cosine * scaleY;
59
+ const anchorX = anchor[0] ?? 0;
60
+ const anchorY = anchor[1] ?? 0;
61
+ return [
62
+ a, b, c, d,
63
+ (position[0] ?? 0) - a * anchorX - c * anchorY,
64
+ (position[1] ?? 0) - b * anchorX - d * anchorY,
65
+ ];
66
+ }
67
+
68
+ export function transformStaticPath(path: StaticVectorPath, matrix: Matrix2D): StaticVectorPath {
69
+ const [a, b, c, d, e, f] = matrix;
70
+ const values: number[] = [];
71
+ for (let index = 0; index < path.values.length; index += 2) {
72
+ const x = path.values[index] ?? 0;
73
+ const y = path.values[index + 1] ?? 0;
74
+ values.push(a * x + c * y + e, b * x + d * y + f);
75
+ }
76
+ return { commands: path.commands, values };
77
+ }
78
+
79
+ function pathsToMultiPolygon(paths: readonly StaticVectorPath[]): MultiPolygon {
80
+ const polygons: Polygon[] = paths.flatMap(path => flattenStaticPath(path).map(ring => [ring]));
81
+ if (polygons.length <= 1) return polygons;
82
+ return polygonClipping.union(polygons[0]!, ...polygons.slice(1));
83
+ }
84
+
85
+ function flattenStaticPath(path: StaticVectorPath, tolerance = 0.35): Pair[][] {
86
+ const rings: Pair[][] = [];
87
+ let valuesIndex = 0;
88
+ let ring: Pair[] = [];
89
+ let current: Pair = [0, 0];
90
+ const nextPair = (): Pair => [Number(path.values[valuesIndex++] ?? 0), Number(path.values[valuesIndex++] ?? 0)];
91
+ const finish = (): void => {
92
+ if (ring.length < 3) { ring = []; return; }
93
+ if (!samePair(ring[0]!, ring.at(-1)!)) ring.push([...ring[0]!] as Pair);
94
+ if (Math.abs(signedRingArea(ring)) > 1e-8) rings.push(ring);
95
+ ring = [];
96
+ };
97
+ for (const command of path.commands) {
98
+ if (command === 'M') {
99
+ finish();
100
+ current = nextPair();
101
+ ring.push(current);
102
+ } else if (command === 'L') {
103
+ current = nextPair();
104
+ ring.push(current);
105
+ } else if (command === 'C') {
106
+ const control1 = nextPair();
107
+ const control2 = nextPair();
108
+ const end = nextPair();
109
+ flattenCubic(current, control1, control2, end, tolerance, ring);
110
+ current = end;
111
+ } else if (command === 'Q') {
112
+ const control = nextPair();
113
+ const end = nextPair();
114
+ flattenQuadratic(current, control, end, tolerance, ring);
115
+ current = end;
116
+ } else if (command === 'Z') {
117
+ finish();
118
+ }
119
+ }
120
+ finish();
121
+ return rings;
122
+ }
123
+
124
+ function flattenCubic(
125
+ start: Pair,
126
+ control1: Pair,
127
+ control2: Pair,
128
+ end: Pair,
129
+ tolerance: number,
130
+ output: Pair[],
131
+ depth = 0,
132
+ ): void {
133
+ if (depth >= 10 || Math.max(pointLineDistance(control1, start, end), pointLineDistance(control2, start, end)) <= tolerance) {
134
+ output.push(end);
135
+ return;
136
+ }
137
+ const a = midpoint(start, control1);
138
+ const b = midpoint(control1, control2);
139
+ const c = midpoint(control2, end);
140
+ const d = midpoint(a, b);
141
+ const e = midpoint(b, c);
142
+ const middle = midpoint(d, e);
143
+ flattenCubic(start, a, d, middle, tolerance, output, depth + 1);
144
+ flattenCubic(middle, e, c, end, tolerance, output, depth + 1);
145
+ }
146
+
147
+ function flattenQuadratic(
148
+ start: Pair,
149
+ control: Pair,
150
+ end: Pair,
151
+ tolerance: number,
152
+ output: Pair[],
153
+ depth = 0,
154
+ ): void {
155
+ if (depth >= 10 || pointLineDistance(control, start, end) <= tolerance) {
156
+ output.push(end);
157
+ return;
158
+ }
159
+ const a = midpoint(start, control);
160
+ const b = midpoint(control, end);
161
+ const middle = midpoint(a, b);
162
+ flattenQuadratic(start, a, middle, tolerance, output, depth + 1);
163
+ flattenQuadratic(middle, b, end, tolerance, output, depth + 1);
164
+ }
165
+
166
+ function pointLineDistance(point: Pair, start: Pair, end: Pair): number {
167
+ const dx = end[0] - start[0];
168
+ const dy = end[1] - start[1];
169
+ const length = Math.hypot(dx, dy);
170
+ if (length <= 1e-12) return Math.hypot(point[0] - start[0], point[1] - start[1]);
171
+ return Math.abs(dy * point[0] - dx * point[1] + end[0] * start[1] - end[1] * start[0]) / length;
172
+ }
173
+
174
+ function midpoint(a: Pair, b: Pair): Pair {
175
+ return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
176
+ }
177
+
178
+ function signedRingArea(ring: readonly Pair[]): number {
179
+ let area = 0;
180
+ for (let index = 0; index + 1 < ring.length; index++) {
181
+ area += ring[index]![0] * ring[index + 1]![1] - ring[index + 1]![0] * ring[index]![1];
182
+ }
183
+ return area / 2;
184
+ }
185
+
186
+ function multiPolygonToPath(geometry: MultiPolygon): StaticVectorPath | null {
187
+ let commands = '';
188
+ const values: number[] = [];
189
+ for (const polygon of geometry) {
190
+ for (const sourceRing of polygon) {
191
+ const ring = sourceRing.length > 1 && samePair(sourceRing[0]!, sourceRing.at(-1)!)
192
+ ? sourceRing.slice(0, -1)
193
+ : sourceRing;
194
+ if (ring.length < 3) continue;
195
+ commands += `M${'L'.repeat(ring.length - 1)}Z`;
196
+ values.push(...ring.flat());
197
+ }
198
+ }
199
+ return commands ? { commands, values } : null;
200
+ }
201
+
202
+ function samePair(a: Pair, b: Pair): boolean {
203
+ return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
204
+ }