@pixodesk/svg-animator-web 1.0.6

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.
@@ -0,0 +1,396 @@
1
+ type FillMode = 'forwards' | 'backwards' | 'both' | 'none';
2
+ type PlaybackDirection = 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
3
+ declare const PX_ANIM_SRC_ATTR_NAME = "data-px-animation-src";
4
+ declare const PX_ANIM_ATTR_NAME = "_px_animator";
5
+ /**
6
+ * Easing function definition.
7
+ * Can be a named reference to a predefined easing or a cubic-bezier array [x1, y1, x2, y2].
8
+ *
9
+ * @example "ease-in" | "easeOut" | [0.68, -0.55, 0.265, 1.55]
10
+ */
11
+ type PxEasingOrRef = string | [number, number, number, number];
12
+ /**
13
+ * A single animation keyframe defining the state at a specific point in time.
14
+ * Supports both full property names and short aliases for compact notation.
15
+ */
16
+ interface PxKeyframe {
17
+ /** Timestamp in milliseconds from animation start */
18
+ time?: number;
19
+ /** Short alias for "time" */
20
+ t?: number;
21
+ /** The value of the animated property at this keyframe */
22
+ value?: any;
23
+ /** Short alias for "value" */
24
+ v?: any;
25
+ /** Easing function to use when transitioning to this keyframe from the previous one */
26
+ easing?: PxEasingOrRef;
27
+ /** Short alias for "easing" */
28
+ e?: PxEasingOrRef;
29
+ }
30
+ /**
31
+ * Animation definition for a single CSS/SVG property.
32
+ * Contains an array of keyframes that define how the property changes over time.
33
+ */
34
+ interface PxPropertyAnimation {
35
+ /** Array of keyframes defining the animation timeline */
36
+ keyframes?: PxKeyframe[];
37
+ /** Short alias for "keyframes" */
38
+ kfs?: PxKeyframe[];
39
+ }
40
+ /**
41
+ * Complete animation definition containing one or more property animations.
42
+ * Each key is a CSS/SVG property name (e.g., "opacity", "scale", "rotate").
43
+ *
44
+ * @example
45
+ * {
46
+ * "opacity": { keyframes: [...] },
47
+ * "scale": { keyframes: [...] }
48
+ * }
49
+ */
50
+ interface PxAnimationDefinition {
51
+ [property: string]: PxPropertyAnimation;
52
+ }
53
+ /**
54
+ * Defines when and how an animation should be triggered.
55
+ */
56
+ interface PxTrigger {
57
+ /** Event that starts the animation */
58
+ startOn?: 'load' | 'mouseOver' | 'click' | 'scrollIntoView' | 'programmatic';
59
+ /** Action to take when the trigger condition is no longer met (e.g., mouse leaves) */
60
+ outAction?: 'continue' | 'pause' | 'reset' | 'reverse';
61
+ /** Percentage of element visibility required to trigger (0-1). Only applies to scrollIntoView. */
62
+ scrollIntoViewThreshold?: number;
63
+ }
64
+ /**
65
+ * Global animation configuration that applies to all animations in the document.
66
+ * Defines timing, playback behavior, and rendering strategy.
67
+ */
68
+ interface PxAnimatorConfig {
69
+ /** JavaScript animation implementation strategy */
70
+ mode?: "auto" | "webapi" | "frames";
71
+ /** Total animation duration in milliseconds */
72
+ duration?: number;
73
+ /** Delay before animation starts in milliseconds */
74
+ delay?: number;
75
+ /** Number of times to repeat the animation. Use "infinite" for endless loop. */
76
+ iterations?: number | "infinite";
77
+ /** Defines which values are applied before/after the animation */
78
+ fill?: FillMode;
79
+ /** Direction of animation playback */
80
+ direction?: PlaybackDirection;
81
+ /** Target frame rate for frame-based animations (only applicable when mode="frames") */
82
+ frameRate?: number;
83
+ /** Trigger configuration for when animation should start */
84
+ trigger?: PxTrigger;
85
+ debug?: boolean;
86
+ debugInstName?: string;
87
+ }
88
+ /**
89
+ * Reusable definitions library for easings, animations, and styles.
90
+ * Allows to define once and referencing by name.
91
+ */
92
+ interface PxDefs {
93
+ /** Named cubic-bezier easing functions */
94
+ easings?: {
95
+ [name: string]: [number, number, number, number];
96
+ };
97
+ /** Named animation definitions that can be referenced by elements */
98
+ animations?: {
99
+ [name: string]: PxAnimationDefinition;
100
+ };
101
+ /**
102
+ * FIXME - do we need it?
103
+ * Named style presets for common styling patterns
104
+ */
105
+ styles?: {
106
+ [name: string]: Record<string, string | number>;
107
+ };
108
+ }
109
+ /**
110
+ * Element animation specification.
111
+ * Can be:
112
+ * - A string referencing a named animation from defs
113
+ * - An array of named animation references
114
+ * - An inline PxAnimationDefinition object
115
+ * - A mixed array of references and inline definitions
116
+ *
117
+ * @example
118
+ * "fadeIn"
119
+ * ["fadeIn", "spin"]
120
+ * { opacity: { keyframes: [...] } }
121
+ * ["fadeIn", { scale: { keyframes: [...] } }]
122
+ */
123
+ type PxElementAnimation = string | string[] | PxAnimationDefinition | (string | PxAnimationDefinition)[];
124
+ /**
125
+ * Base interface for all SVG elements.
126
+ * Represents a node in the SVG tree with optional animations and children.
127
+ */
128
+ interface PxNode {
129
+ /** SVG element type (e.g., "circle", "rect", "path", "g") */
130
+ type: string;
131
+ /** Child elements (for container elements like <g>) */
132
+ children?: PxNode[];
133
+ /** Animation applied to this element */
134
+ animate?: PxElementAnimation;
135
+ /**
136
+ * FIXME - do we need it?
137
+ * Style applied to this element (named reference or inline object)
138
+ */
139
+ style?: string | Record<string, string | number>;
140
+ /** All other SVG attributes (cx, cy, r, fill, stroke, etc.) */
141
+ [key: string]: any;
142
+ }
143
+ /**
144
+ * Binds animations to existing DOM elements via CSS selectors.
145
+ * Used when the SVG tree is pre-rendered and animations are applied separately.
146
+ */
147
+ interface PxBinding {
148
+ /** ID targeting elements in the DOM (data-px-id="...") */
149
+ id: string;
150
+ /** Animation to apply to matched elements */
151
+ animate: PxElementAnimation;
152
+ }
153
+ /**
154
+ * Root SVG element containing the entire animated graphic.
155
+ * Extends PxNode with SVG-specific properties and global configuration.
156
+ */
157
+ interface PxSvgNode extends PxNode {
158
+ /** FIXME - do we need it?
159
+ * SVG viewport width */
160
+ width?: number;
161
+ /** FIXME - do we need it?
162
+ * SVG viewport height */
163
+ height?: number;
164
+ /** FIXME - do we need it?
165
+ * SVG viewBox attribute defining coordinate system */
166
+ viewBox?: string;
167
+ /** Global animation configuration */
168
+ animator?: PxAnimatorConfig;
169
+ /** Reusable definitions library */
170
+ defs?: PxDefs;
171
+ /** Animation bindings for pre-rendered DOM elements */
172
+ bindings?: PxBinding[];
173
+ design?: PxNode;
174
+ }
175
+ /**
176
+ * The complete animated SVG document.
177
+ * This is the root type for the entire file format.
178
+ */
179
+ interface PxAnimatedSvgDocument extends PxSvgNode {
180
+ }
181
+ /** A configuration object for animation lifecycle callbacks. */
182
+ interface PxAnimatorCallbacksConfig {
183
+ /** Callback executed when the animation starts or resumes. */
184
+ onPlay?: () => void;
185
+ /** Callback executed when the animation is paused. */
186
+ onPause?: () => void;
187
+ /** Callback executed when the animation is cancelled. */
188
+ onCancel?: () => void;
189
+ /** Callback executed when the animation finishes naturally. */
190
+ onFinish?: () => void;
191
+ /** Callback executed when the animation is removed. */
192
+ onRemove?: () => void;
193
+ }
194
+ type PxPoint2D = Array<number>;
195
+ /** Represents a vector path for SVG shape animations. */
196
+ interface PxBezierPath {
197
+ /** An array of vertex points [[x, y], ...]. */
198
+ v: Array<PxPoint2D>;
199
+ /** An array of 'in' tangent handles for each vertex [[x, y], ...]. */
200
+ i?: Array<PxPoint2D>;
201
+ /** An array of 'out' tangent handles for each vertex [[x, y], ...]. */
202
+ o?: Array<PxPoint2D>;
203
+ /** A boolean indicating if the path is closed. */
204
+ c?: boolean;
205
+ }
206
+ /** Basic animation controls common to all animator types. */
207
+ interface PxBasicAnimatorAPI {
208
+ isReady(): boolean;
209
+ /** Returns the root HTML element for the animation. */
210
+ getRootElement(): Element | null;
211
+ /** Returns true if the animation is currently running. */
212
+ isPlaying(): boolean;
213
+ /** Starts or resumes the animation. */
214
+ play(): void;
215
+ /** Pauses the animation at its current state. */
216
+ pause(): void;
217
+ /** Stops the animation and resets it to its initial state. */
218
+ cancel(): void;
219
+ }
220
+ /** The full programmatic control interface for an animation. */
221
+ interface PxAnimatorAPI extends PxBasicAnimatorAPI {
222
+ /** Jumps to the end of the animation and holds the final state. */
223
+ finish(): void;
224
+ /** Changes the speed of the animation. 1 is normal, 2 is double, -1 is reverse. */
225
+ setPlaybackRate(rate: number): void;
226
+ /** Returns the current playback time in milliseconds. */
227
+ getCurrentTime(): number | null;
228
+ /** Jumps to a specific time (in milliseconds) in the animation. */
229
+ setCurrentTime(time: number): void;
230
+ /** Stops the animation and cleans up all associated resources. */
231
+ destroy(): void;
232
+ }
233
+ declare function isPxElementFileFormat(fileJson: any): fileJson is PxAnimatedSvgDocument;
234
+ interface PxValidationResult {
235
+ valid: boolean;
236
+ errors: string[];
237
+ }
238
+ /**
239
+ * Deep validation of PxAnimatedSvgDocument.
240
+ * Validates all nested properties against their type definitions.
241
+ * @returns PxValidationResult with valid flag and array of error messages
242
+ */
243
+ declare function isPxElementFileFormatDeep(fileJson: any): PxValidationResult;
244
+ declare function getAnimatorConfig(doc: PxAnimatedSvgDocument): PxAnimatorConfig | undefined;
245
+ declare function getDefs(doc: PxAnimatedSvgDocument): PxDefs | undefined;
246
+ declare function getBindings(doc: PxAnimatedSvgDocument): PxBinding[] | undefined;
247
+ declare function getChildren(doc: PxAnimatedSvgDocument): PxNode[] | undefined;
248
+
249
+ /**
250
+ * Platform adapter interface for abstracting DOM-specific operations.
251
+ */
252
+ interface PxPlatformAdapter {
253
+ /** Check if the root element is still connected/mounted */
254
+ isConnected(): boolean;
255
+ /** Set an attribute on an element by id */
256
+ setAttribute(id: string, attrName: string, value: string): void;
257
+ }
258
+ /**
259
+ * Creates an animator instance that uses a frame loop for animations.
260
+ * This is the abstract/platform-agnostic version.
261
+ *
262
+ * @param adapter Platform adapter for DOM/environment operations.
263
+ * @param callbacks Optional lifecycle callbacks.
264
+ * @returns A PxAnimatorAPI instance.
265
+ */
266
+ declare function createBasicFrameLoopAnimator(doc: PxAnimatedSvgDocument, adapter: PxPlatformAdapter, callbacks?: PxAnimatorCallbacksConfig): PxAnimatorAPI;
267
+ /**
268
+ * Creates an animator instance that uses a requestAnimationFrame loop for animations.
269
+ * This is the browser DOM-specific version.
270
+ *
271
+ * @param {PxAnimatorCallbacksConfig=} callbacks Optional lifecycle callbacks.
272
+ * @param {Element=} rootElement Optional pre-rendered root element.
273
+ * @returns {PxAnimatorAPI} A PxAnimatorAPI instance.
274
+ */
275
+ declare function createFrameLoopAnimator(doc: PxAnimatedSvgDocument, adapter?: PxPlatformAdapter, callbacks?: PxAnimatorCallbacksConfig, rootElement?: Element | null): PxAnimatorAPI;
276
+
277
+ /**
278
+ * Regenerates all IDs in the document and updates references.
279
+ *
280
+ * This function:
281
+ * 1. Deep clones the document to avoid mutating the original
282
+ * 2. Traverses all nodes and regenerates IDs, keeping a mapping of old → new
283
+ * 3. Updates all references to old IDs in attributes:
284
+ * - Hash references: "#old-id" → "#new-id" (href, xlink:href)
285
+ * - URL references: "url(#old-id)" → "url(#new-id)" (fill, clip-path, mask, marker, etc.)
286
+ * - Style URL references: { offsetPath: "url(#old-id)" }
287
+ *
288
+ * @param doc - The animated SVG document to process
289
+ * @returns A new document with regenerated IDs
290
+ */
291
+ declare function generateNewIds(doc: PxAnimatedSvgDocument): PxAnimatedSvgDocument;
292
+ /**
293
+ * Creates an animator instance from an AnimatedSvgDocument.
294
+ *
295
+ * This function serves as the main entry point for the animation library. It automatically
296
+ * chooses the best animation engine available ('webapi' or 'frames') or can be
297
+ * forced to use a specific one.
298
+ *
299
+ * @param doc The animated SVG document.
300
+ * @param callbacks Optional object with callback functions for animation lifecycle events (play, pause, finish, etc.).
301
+ * @param containerElement Optional selector or element to render the SVG into.
302
+ * @returns An PxAnimatorAPI instance to programmatically control the animation.
303
+ */
304
+ declare function createAnimatorImpl(doc: PxAnimatedSvgDocument, adapter?: PxPlatformAdapter, callbacks?: PxAnimatorCallbacksConfig, containerElement?: string | Element): PxAnimatorAPI;
305
+ /**
306
+ * Creates an animator instance to control SVG animations.
307
+ * Accepts either a document object or a URL to fetch.
308
+ *
309
+ * @param docOrUrl The animated SVG document or URL to fetch it from.
310
+ * @param callbacks Optional object with callback functions for animation lifecycle events.
311
+ * @param containerElement Optional selector or element to render the SVG into.
312
+ * @returns An PxAnimatorAPI instance to programmatically control the animation.
313
+ */
314
+ declare function createAnimator(docOrUrl: PxAnimatedSvgDocument | string, adapter?: PxPlatformAdapter, callbacks?: PxAnimatorCallbacksConfig, containerElement?: string | Element): PxAnimatorAPI;
315
+ /**
316
+ * Scan and load for tags, e.g.
317
+ * <div data-px-animation-src="animation.json"></div>
318
+ */
319
+ declare function loadTagAnimators(): void;
320
+
321
+ /**
322
+ * Converts a color from a [r, g, b, a] array (where values are 0-1) to an rgba() or rgb() CSS string.
323
+ * @param color The color array.
324
+ */
325
+ declare function toRGBA(color: Array<number>): string;
326
+ declare const COLOUR_ATTR_NAMES: Set<string>;
327
+ declare const TRANSFORM_FN_NAMES: Set<string>;
328
+ declare const STYLE_ATTR_NAMES: Set<string>;
329
+ /**
330
+ * Converts a camelCase string to kebab-case.
331
+ * @param camel The camelCase string.
332
+ */
333
+ declare function camelCaseToKebabWordIfNeeded(camel: string): string;
334
+
335
+ /**
336
+ * Sets up event-based triggers for an animation.
337
+ *
338
+ * This function attaches event listeners to the animation's root element based on the
339
+ * provided configuration, allowing animations to be started by user interactions
340
+ * or visibility changes.
341
+ *
342
+ * ### Trigger Options (startOn):
343
+ * - 'load': Starts after the page loads.
344
+ * - 'mouseOver': Starts on mouse enter.
345
+ * - 'click': Toggles play/end action on click.
346
+ * - 'scrollIntoView': Starts when the element scrolls into the viewport.
347
+ * - 'programmatic': No automatic start. Must be controlled via the API.
348
+ *
349
+ * ### End Action Options (outAction):
350
+ * Defines behavior when the trigger condition ends (e.g., mouse leave).
351
+ * - 'continue': Animation continues playing.
352
+ * - 'pause': Pauses the animation.
353
+ * - 'reset': Cancels the animation, resetting it to the start.
354
+ * - 'reverse': Reverses the animation playback.
355
+ *
356
+ * @param {!PxAnimatorAPI} api The animator API instance to control.
357
+ * @param {!PxTrigger} config The trigger configuration object.
358
+ * @returns {!PxAnimatorAPI} The same animator API instance, for chaining.
359
+ */
360
+ declare function setupAnimationTriggers(api: PxAnimatorAPI, config: PxTrigger): PxAnimatorAPI;
361
+
362
+ /**
363
+ * Normalizes a PxAnimatedSvgDocument to a PxAnimatorConfig for the animation engines.
364
+ * This is the main entry point for converting the new API format to internal format.
365
+ * Resolves animation/easing references.
366
+ */
367
+ declare function getNormalisedBindings(doc: PxAnimatedSvgDocument): PxBinding[];
368
+ /**
369
+ * Calculates interpolated attribute values for an animation definition.
370
+ * @param animDef The animation definition (with resolved refs and normalized times)
371
+ * @param progress The current animation progress (0-1)
372
+ * @returns Object with computed attribute name/value pairs
373
+ */
374
+ declare function calcAnimationValues(animDef: PxAnimationDefinition, progress: number): Record<string, string>;
375
+
376
+ declare function getNormalizedProps(props: Record<string, any>): Record<string, any>;
377
+ /**
378
+ * Renders a PxNode tree to DOM elements.
379
+ */
380
+ declare function renderNode(node: PxNode, defs?: PxDefs): Element | null;
381
+
382
+ /**
383
+ * Creates an animator instance that uses the native Web Animations API.
384
+ *
385
+ * This is the preferred, more performant animator. It will return null if the
386
+ * animation configuration contains properties not supported by the browser's
387
+ * Web Animations API implementation, unless forceEvenIfHasUnsupportedAttrs is true.
388
+ *
389
+ * @param callbacks Optional lifecycle callbacks.
390
+ * @param rootElement Root element.
391
+ * @param forceEvenIfHasUnsupportedAttrs If true, an animator will be created even if some CSS properties are not supported.
392
+ * @returns An PxAnimatorAPI instance, or null if unsupported features are used and not forced.
393
+ */
394
+ declare function createWebApiAnimator(doc: PxAnimatedSvgDocument, callbacks?: PxAnimatorCallbacksConfig, rootElement?: Element | null, forceEvenIfHasUnsupportedAttrs?: boolean): PxAnimatorAPI | null;
395
+
396
+ export { COLOUR_ATTR_NAMES, type FillMode, PX_ANIM_ATTR_NAME, PX_ANIM_SRC_ATTR_NAME, type PlaybackDirection, type PxAnimatedSvgDocument, type PxAnimationDefinition, type PxAnimatorAPI, type PxAnimatorCallbacksConfig, type PxAnimatorConfig, type PxBezierPath, type PxBinding, type PxDefs, type PxElementAnimation, type PxKeyframe, type PxNode, type PxPlatformAdapter, type PxPropertyAnimation, type PxSvgNode, type PxTrigger, type PxValidationResult, STYLE_ATTR_NAMES, TRANSFORM_FN_NAMES, calcAnimationValues, camelCaseToKebabWordIfNeeded, createAnimator, createAnimatorImpl, createBasicFrameLoopAnimator, createFrameLoopAnimator, createWebApiAnimator, generateNewIds, getAnimatorConfig, getBindings, getChildren, getDefs, getNormalizedProps, isPxElementFileFormat, isPxElementFileFormatDeep, loadTagAnimators, getNormalisedBindings as normalizeDocument, renderNode, setupAnimationTriggers, toRGBA };