UNPKG

@lottiefiles/dotlottie-web

Version:
1,450 lines 62.6 kB
//#region src/event-manager.d.ts /** * Represents the different types of events that can be dispatched. */ type EventType = 'complete' | 'frame' | 'load' | 'loadError' | 'renderError' | 'loop' | 'pause' | 'play' | 'stop' | 'destroy' | 'freeze' | 'unfreeze' | 'render' | 'ready' | 'stateMachineStart' | 'stateMachineStop' | 'stateMachineTransition' | 'stateMachineStateEntered' | 'stateMachineStateExit' | 'stateMachineCustomEvent' | 'stateMachineError' | 'stateMachineBooleanInputValueChange' | 'stateMachineNumericInputValueChange' | 'stateMachineStringInputValueChange' | 'stateMachineInputFired' | 'stateMachineInternalMessage'; /** * Maps an event type string to its respective event interface. */ type EventByType<T extends EventType> = Extract<Event, { type: T; }>; /** * Base interface for all events. */ interface BaseEvent { type: EventType; } interface RenderEvent extends BaseEvent { currentFrame: number; type: 'render'; } interface FreezeEvent extends BaseEvent { type: 'freeze'; } interface UnfreezeEvent extends BaseEvent { type: 'unfreeze'; } interface DestroyEvent extends BaseEvent { type: 'destroy'; } /** * Event fired when a loop action occurs. */ interface LoopEvent extends BaseEvent { loopCount: number; type: 'loop'; } /** * Event fired during frame changes. */ interface FrameEvent extends BaseEvent { currentFrame: number; type: 'frame'; } /** * Event fired when a load action occurs. */ interface LoadEvent extends BaseEvent { type: 'load'; } /** * Event fired when a loading error occurs. */ interface LoadErrorEvent extends BaseEvent { error: Error; type: 'loadError'; } /** * Event fired when a loading error occurs. */ interface RenderErrorEvent extends BaseEvent { error: Error; type: 'renderError'; } /** * Event fired when a completion action occurs. */ interface CompleteEvent extends BaseEvent { type: 'complete'; } /** * Event fired when a pause action occurs. */ interface PauseEvent extends BaseEvent { type: 'pause'; } /** * Event fired when a play action occurs. */ interface PlayEvent extends BaseEvent { type: 'play'; } /** * Event fired when a stop action occurs. */ interface StopEvent extends BaseEvent { type: 'stop'; } /** * Event fired when a WASM module is initialized and ready. */ interface ReadyEvent extends BaseEvent { type: 'ready'; } interface StateMachineStartEvent extends BaseEvent { type: 'stateMachineStart'; } interface StateMachineStopEvent extends BaseEvent { type: 'stateMachineStop'; } interface StateMachineTransitionEvent extends BaseEvent { fromState: string; toState: string; type: 'stateMachineTransition'; } interface StateMachineStateEnteredEvent extends BaseEvent { state: string; type: 'stateMachineStateEntered'; } interface StateMachineStateExitEvent extends BaseEvent { state: string; type: 'stateMachineStateExit'; } interface StateMachineCustomEvent extends BaseEvent { eventName: string; type: 'stateMachineCustomEvent'; } interface StateMachineErrorEvent extends BaseEvent { error: string; type: 'stateMachineError'; } interface StateMachineBooleanInputValueChangeEvent extends BaseEvent { inputName: string; newValue: boolean; oldValue: boolean; type: 'stateMachineBooleanInputValueChange'; } interface StateMachineNumericInputValueChangeEvent extends BaseEvent { inputName: string; newValue: number; oldValue: number; type: 'stateMachineNumericInputValueChange'; } interface StateMachineStringInputValueChangeEvent extends BaseEvent { inputName: string; newValue: string; oldValue: string; type: 'stateMachineStringInputValueChange'; } interface StateMachineInputFiredEvent extends BaseEvent { inputName: string; type: 'stateMachineInputFired'; } interface StateMachineInternalMessage extends BaseEvent { message: string; type: 'stateMachineInternalMessage'; } /** * Type representing all possible event types. */ type Event = LoopEvent | FrameEvent | LoadEvent | LoadErrorEvent | RenderErrorEvent | CompleteEvent | PauseEvent | PlayEvent | StopEvent | DestroyEvent | FreezeEvent | UnfreezeEvent | RenderEvent | ReadyEvent | StateMachineStartEvent | StateMachineStopEvent | StateMachineTransitionEvent | StateMachineStateEnteredEvent | StateMachineStateExitEvent | StateMachineCustomEvent | StateMachineErrorEvent | StateMachineBooleanInputValueChangeEvent | StateMachineNumericInputValueChangeEvent | StateMachineStringInputValueChangeEvent | StateMachineInputFiredEvent | StateMachineInternalMessage; type EventListener<T extends EventType> = (event: EventByType<T>) => void; /** * Manages registration and dispatching of event listeners. */ declare class EventManager { private readonly _eventListeners; addEventListener<T extends EventType>(type: T, listener: EventListener<T>): void; removeEventListener<T extends EventType>(type: T, listener?: EventListener<T>): void; dispatch<T extends EventType>(event: EventByType<T>): void; removeAllEventListeners(): void; } //#endregion //#region src/types.d.ts /** * 3x3 transformation matrix for the entire animation on the canvas. * Represented as a flattened 9-element tuple in row-major order: [m00, m01, m02, m10, m11, m12, m20, m21, m22]. * Used for affine transformations (translation, rotation, scale, skew) applied to the whole animation. */ type Transform = [number, number, number, number, number, number, number, number, number]; /** * Animation marker representing a named section within a Lottie animation. */ interface Marker { name: string; time: number; duration: number; } /** * Configuration for canvas rendering behavior. * Controls how the animation is rendered and when rendering is optimized. */ interface RenderConfig { /** * Automatically resize canvas when container size changes. * Set to true to maintain responsiveness without manual resize calls. */ autoResize?: boolean; /** * Pixel density multiplier for high-DPI displays. * Higher values increase quality but use more memory. Defaults to window.devicePixelRatio. */ devicePixelRatio?: number; /** * Pause rendering when canvas is outside the viewport. * Set to true (default) to improve performance when animation isn't visible. */ freezeOnOffscreen?: boolean; /** * Rendering quality level (0-100). * Lower values reduce quality but improve performance on resource-constrained devices. */ quality?: number; } /** * Animation playback direction mode. * Determines how frames are sequenced: forward, reverse, or alternating (bounce) modes. */ type Mode = 'forward' | 'reverse' | 'bounce' | 'reverse-bounce'; /** * Animation data format accepted by the player. * Can be a JSON string, binary ArrayBuffer, or parsed JSON object. */ type Data = string | ArrayBuffer | Record<string, unknown>; /** * Layout fit mode determining how animation scales to canvas. * Controls scaling behavior similar to CSS object-fit property. */ type Fit = 'contain' | 'cover' | 'fill' | 'none' | 'fit-width' | 'fit-height'; /** * Layout configuration for positioning and scaling animations within the canvas. * Determines how the animation fits and aligns within the available space. */ interface Layout { /** * Alignment position as [x, y] coordinates in 0-1 range. * [0.5, 0.5] centers the animation, [0, 0] is top-left, [1, 1] is bottom-right. */ align?: [number, number]; /** * Fit mode controlling how animation scales to canvas dimensions. * Defaults to 'contain' to show the full animation without cropping. */ fit?: Fit; } /** * Dimensions of a rendering surface for custom canvas implementations. * Used when providing a custom render surface instead of HTMLCanvasElement. */ interface RenderSurface { /** Height of the render surface in pixels */ height: number; /** Width of the render surface in pixels */ width: number; } /** * Main configuration object for initializing a DotLottie player. * Specifies the animation source, playback behavior, rendering options, and canvas target. */ interface Config { /** * ID of the specific animation to play from a multi-animation dotLottie file. * Leave undefined for single-animation files or to play the default animation. */ animationId?: string; /** * Automatically start playback once the animation is loaded. * Set to true for animations that should play immediately without user interaction. */ autoplay?: boolean; /** * Background color as a CSS color string (e.g., '#FFFFFF' or 'transparent'). * Applied to the canvas element or as a fill behind the animation. */ backgroundColor?: string; /** * Target canvas element for rendering. * Can be HTMLCanvasElement, OffscreenCanvas, or custom RenderSurface with dimensions. */ canvas?: HTMLCanvasElement | OffscreenCanvas | RenderSurface; /** * Animation data to load directly. * Use this to load from a string, ArrayBuffer, or parsed JSON instead of fetching from src. */ data?: Data; /** * Layout configuration for positioning and scaling the animation. * Controls fit mode and alignment within the canvas. */ layout?: Layout; /** * Enable continuous looping of the animation. * Set to true to repeat indefinitely, or use loopCount for a specific number of loops. */ loop?: boolean; /** * Number of additional times to replay the animation after the first play. * Requires `loop` to be true. A value of 0 means infinite replays; a positive value `n` means * the animation plays a total of `n + 1` times (initial play + `n` replays). */ loopCount?: number; /** * Named marker to use as the playback segment. * Plays only the portion of the animation defined by this marker instead of the full animation. */ marker?: string; /** * Playback direction mode. * Controls whether animation plays forward, reverse, or alternates (bounce). */ mode?: Mode; /** * Rendering configuration controlling canvas behavior. * Includes autoResize, devicePixelRatio, freezeOnOffscreen, and quality settings. */ renderConfig?: RenderConfig; /** * Frame range to play as [startFrame, endFrame]. * Restricts playback to a specific portion of the animation instead of the full sequence. */ segment?: [number, number]; /** * Playback speed multiplier. * 1 is normal speed, 2 is double speed, 0.5 is half speed. */ speed?: number; /** * URL to fetch the animation from. * Use this to load .lottie or .json files from a remote or local path. */ src?: string; /** * State machine security configuration. * Controls URL opening policies for state machine-driven animations. */ stateMachineConfig?: StateMachineConfig; /** * ID of the state machine to load and activate. * State machines enable interactive, event-driven animation behaviors. */ stateMachineId?: string; /** * ID of the theme to apply to the animation. * Themes modify colors and visual properties defined in the dotLottie manifest. */ themeId?: string; /** * Enable frame interpolation for smoother playback. * Set to true (default) for smoother animation, false for exact frame-by-frame playback. */ useFrameInterpolation?: boolean; } interface WebGLConfig extends Omit<Config, 'canvas'> { canvas: HTMLCanvasElement; } interface WebGPUConfig extends Omit<Config, 'canvas'> { canvas: HTMLCanvasElement; device?: GPUDevice; } interface StateMachineConfig { /** * Controls whether and which URLs can be opened by a state machine. * * - requireUserInteraction: When true, URLs open only after an explicit user action * (e.g., click/pointer down) on the animation. * - whitelist: List of allowed URL patterns. An empty list blocks all URLs. Use * "*" to allow all URLs. Wildcards are supported in host and path (e.g., * "*.example.com/*"). * * @example * ```typescript * // Require user interaction before opening any URL * openUrlPolicy: { requireUserInteraction: true, whitelist: ["*"] } * * // Block all URLs * openUrlPolicy: { whitelist: [] } * * // Allow all URLs * openUrlPolicy: { whitelist: ["*"] } * * // Allow a specific domain only * openUrlPolicy: { whitelist: ["https://example.com"] } * * // Allow subdomains and any path under lottiefiles.com * openUrlPolicy: { whitelist: ["*.lottiefiles.com/*"] } * ``` * * By default, URLs are denied and require user interaction. */ openUrlPolicy?: { requireUserInteraction?: boolean; whitelist?: string[]; }; } /** * dotLottie manifest containing metadata about available animations, themes, and state machines. * Included in .lottie files to describe the contents and relationships between components. */ interface Manifest { /** * List of animations available in this dotLottie file. * Each animation can have its own ID, themes, and background color. */ animations: Array<{ /** Background color for this animation */background?: string; /** Unique identifier for this animation */ id: string; /** Default theme to apply when this animation loads */ initialTheme?: string; /** List of theme IDs compatible with this animation */ themes?: string[]; }>; /** Tool or application that created this dotLottie file */ generator?: string; /** List of available state machines for interactive behavior */ stateMachines?: Array<{ id: string; }>; /** List of available themes that can modify animation appearance */ themes?: Array<{ id: string; }>; /** dotLottie specification version */ version?: string; } /** * Bezier easing handle for keyframe interpolation */ interface BezierHandle { x: number | number[]; y: number | number[]; } /** * Keyframe in Lottie native format * The value type (Color, Vector, number, etc.) */ interface Keyframe<T> { /** Hold keyframe - no interpolation to next keyframe */ h?: 0 | 1; /** Incoming bezier handle (optional, for easing) */ i?: BezierHandle; /** Outgoing bezier handle (optional, for easing) */ o?: BezierHandle; /** Start value at this keyframe */ s: T; /** Time (frame number) */ t: number; } /** * Color as RGB or RGBA array with values normalized to [0, 1] * @example [1, 0, 0] // red * @example [1, 0, 0, 0.5] // red with 50% opacity */ type Color = [number, number, number] | [number, number, number, number]; /** * Color slot value - static color or array of keyframes * @example Static: [1, 0, 0, 1] // red * @example Animated: [\{ t: 0, s: [1, 0, 0, 1] \}, \{ t: 60, s: [0, 0, 1, 1] \}] */ type ColorSlotValue = Color | Array<Keyframe<Color>>; /** * Scalar slot value - static number or array of keyframes (rotation, opacity, etc.) * @example Static: 45 * @example Animated: [\{ t: 0, s: 0 \}, \{ t: 60, s: 360 \}] */ type ScalarSlotValue = number | Array<Keyframe<number>>; /** * Vector as 2D or 3D point * @example [100, 100] // 2D vector * @example [100, 100, 0] // 3D vector */ type Vector = [number, number] | [number, number, number]; /** * Vector slot value - static vector or array of keyframes * Used for both "vector" and "position" slot types * @example Static: [100, 100] * @example Animated: [\{ t: 0, s: [0, 0] \}, \{ t: 60, s: [100, 100] \}] */ type VectorSlotValue = Vector | Array<Keyframe<Vector>>; /** * Gradient as raw Lottie flat array format. * Color stops (4 floats each): [offset, r, g, b, offset, r, g, b, ...] * Opacity stops (2 floats each, appended after color stops): [...color stops, offset, alpha, offset, alpha, ...] * All values are in [0, 1] range. * Expected array size: 4 * colorStopCount + 2 * opacityStopCount * @example Without opacity: [0, 1, 0, 0, 1, 0, 0, 1] // red to blue gradient (2 color stops) * @example With opacity: [0, 1, 0, 0, 1, 0, 0, 1, 0, 0.8, 1, 1] // red to blue, 80% -> 100% opacity */ type Gradient = number[]; /** * Gradient slot value - static gradient or array of keyframes * @example Static without opacity: [0, 1, 0, 0, 1, 0, 0, 1] * @example Static with opacity: [0, 1, 0, 0, 1, 0, 0, 1, 0, 0.8, 1, 1] * @example Animated: [\{ t: 0, s: [0, 1, 0, 0, 1, 0, 0, 1] \}] */ type GradientSlotValue = Gradient | Array<Keyframe<Gradient>>; /** * Text document properties * @see https://lottiefiles.github.io/lottie-docs/text/#text-document */ interface TextDocument { /** Font family */ f?: string; /** Fill color [r, g, b] or [r, g, b, a] in [0, 1] range */ fc?: Color; /** Justify: 0=left, 1=right, 2=center */ j?: 0 | 1 | 2; /** Line height */ lh?: number; /** Font size */ s?: number; /** Stroke color [r, g, b] or [r, g, b, a] in [0, 1] range */ sc?: Color; /** Stroke width */ sw?: number; /** Text content (newlines encoded with carriage return) */ t?: string; /** Tracking (letter spacing) */ tr?: number; } /** * Text slot value - always static (text documents don't support animation) * @example \{ t: 'Hello', s: 24, fc: [0,0,0,1] \} */ type TextSlotValue = TextDocument; /** * Slot type string as returned by the core */ type SlotType = 'color' | 'gradient' | 'image' | 'text' | 'scalar' | 'vector'; /** * Base properties shared by all theme keyframes. */ interface ThemeBaseKeyframe { /** Timeline position in animation frames */ frame: number; /** When true, holds value without interpolation until next keyframe */ hold?: boolean; /** Incoming Bézier handle for easing into this keyframe */ inTangent?: BezierHandle; /** Outgoing Bézier handle for easing out of this keyframe */ outTangent?: BezierHandle; } /** * Color keyframe for animated color transitions. */ interface ThemeColorKeyframe extends ThemeBaseKeyframe { /** Color value as normalized RGB or RGBA (0-1 range) */ value: Color; } /** * Scalar keyframe for animated numeric properties. */ interface ThemeScalarKeyframe extends ThemeBaseKeyframe { /** Numeric value at this keyframe */ value: number; } /** * Position keyframe for animated position properties. */ interface ThemePositionKeyframe extends ThemeBaseKeyframe { /** Position as 2D or 3D coordinates */ value: Vector; /** Incoming tangent for spatial interpolation (curved paths) */ valueInTangent?: number[]; /** Outgoing tangent for spatial interpolation (curved paths) */ valueOutTangent?: number[]; } /** * Vector keyframe for animated vector properties (scale, size, etc.). */ interface ThemeVectorKeyframe extends ThemeBaseKeyframe { /** Vector value as [x, y] or [x, y, z] */ value: Vector; } /** * Gradient color stop definition. */ interface ThemeGradientStop { /** Color as RGB or RGBA (0-1 range) */ color: Color; /** Position along gradient line (0-1) */ offset: number; } /** * Gradient keyframe for animated gradient transitions. */ interface ThemeGradientKeyframe extends ThemeBaseKeyframe { /** Array of gradient stops at this keyframe */ value: ThemeGradientStop[]; } /** * Text justification options. */ type ThemeTextJustify = 'Left' | 'Right' | 'Center' | 'JustifyLastLeft' | 'JustifyLastRight' | 'JustifyLastCenter' | 'JustifyLastFull'; /** * Text capitalization styles. */ type ThemeTextCaps = 'Regular' | 'AllCaps' | 'SmallCaps'; /** * Text document properties for theme text rules. * Uses descriptive property names as per dotLottie v2.0 spec. * @see https://dotlottie.io/spec/2.0/#text-document */ interface ThemeTextDocument { /** Vertical baseline offset in pixels */ baselineShift?: number; /** Fill color as RGB or RGBA (0-1 range) */ fillColor?: Color; /** Font family name */ fontName?: string; /** Font size in points */ fontSize?: number; /** Text alignment and justification */ justify?: ThemeTextJustify; /** Line height spacing multiplier */ lineHeight?: number; /** Stroke color as RGB or RGBA (0-1 range) */ strokeColor?: Color; /** When true, stroke renders over fill */ strokeOverFill?: boolean; /** Stroke width in pixels */ strokeWidth?: number; /** Text content to display */ text?: string; /** Text capitalization style */ textCaps?: ThemeTextCaps; /** Letter spacing in 1/1000 em units */ tracking?: number; /** Text wrap box position [x, y] */ wrapPosition?: [number, number]; /** Text wrap bounding box [width, height] */ wrapSize?: [number, number]; } /** * Text keyframe for animated text document properties. */ interface ThemeTextKeyframe { /** Timeline position in animation frames */ frame: number; /** Text document configuration at this keyframe */ value: ThemeTextDocument; } /** * Image value for theme image rules. */ interface ThemeImageValue { /** Display height in pixels */ height?: number; /** Reference to image in dotLottie package (i/ folder) */ id?: string; /** External URL or data URI (fallback if id not found) */ url?: string; /** Display width in pixels */ width?: number; } /** * Base properties shared by all theme rules. */ interface ThemeBaseRule { /** Limit rule to specific animations (omit to apply to all) */ animations?: string[]; /** Lottie expression for dynamic values */ expression?: string; /** Slot ID in the Lottie animation (case-sensitive) */ id: string; } /** * Color rule for overriding color properties (fill, stroke, text color). */ interface ThemeColorRule extends ThemeBaseRule { /** Animated color keyframes */ keyframes?: ThemeColorKeyframe[]; type: 'Color'; /** Static color value (RGB or RGBA, 0-1 range) */ value?: Color; } /** * Scalar rule for overriding numeric properties (opacity, stroke width, rotation). */ interface ThemeScalarRule extends ThemeBaseRule { /** Animated scalar keyframes */ keyframes?: ThemeScalarKeyframe[]; type: 'Scalar'; /** Static numeric value */ value?: number; } /** * Position rule for overriding position properties. */ interface ThemePositionRule extends ThemeBaseRule { /** Animated position keyframes */ keyframes?: ThemePositionKeyframe[]; type: 'Position'; /** Static position (2D or 3D coordinates) */ value?: Vector; } /** * Vector rule for overriding vector properties (scale, size). */ interface ThemeVectorRule extends ThemeBaseRule { /** Animated vector keyframes */ keyframes?: ThemeVectorKeyframe[]; type: 'Vector'; /** Static vector value */ value?: Vector; } /** * Gradient rule for overriding gradient properties. */ interface ThemeGradientRule extends ThemeBaseRule { /** Animated gradient keyframes */ keyframes?: ThemeGradientKeyframe[]; type: 'Gradient'; /** Static gradient (array of color stops) */ value?: ThemeGradientStop[]; } /** * Image rule for overriding image assets. */ interface ThemeImageRule extends ThemeBaseRule { type: 'Image'; /** Image replacement configuration (required for Image rules) */ value: ThemeImageValue; } /** * Text rule for overriding text document properties. */ interface ThemeTextRule extends ThemeBaseRule { /** Animated text keyframes */ keyframes?: ThemeTextKeyframe[]; type: 'Text'; /** Static text document configuration */ value?: ThemeTextDocument; } /** * Union of all theme rule types. */ type ThemeRule = ThemeColorRule | ThemeScalarRule | ThemePositionRule | ThemeVectorRule | ThemeGradientRule | ThemeImageRule | ThemeTextRule; /** * Theme definition for customizing Lottie animation properties. * Themes override animated properties mapped to Lottie Slots. * @see https://dotlottie.io/spec/2.0/#themes * * @example * ```typescript * const theme: Theme = { * rules: [ * { * id: 'background_color', * type: 'Color', * value: [0.2, 0.4, 0.8] // Blue * }, * { * id: 'title_text', * type: 'Text', * value: { * text: 'Hello World', * fontSize: 48, * fillColor: [1, 1, 1] * } * } * ] * }; * * dotLottie.setThemeData(theme); * ``` */ interface Theme { /** Array of rules defining property overrides */ rules: ThemeRule[]; } //#endregion //#region src/core/dotlottie-player.d.ts /** * Playback direction / bounce mode. */ declare enum Mode$1 { Forward = 0, Reverse = 1, Bounce = 2, ReverseBounce = 3 } declare class DotLottiePlayerWasm { free(): void; constructor(); /** * Load a Lottie JSON animation. Sets up the rendering target automatically. */ load_animation(data: string, width: number, height: number): boolean; /** * Load a .lottie archive from raw bytes. */ load_dotlottie_data(data: Uint8Array, width: number, height: number): boolean; /** * Load an animation from an already-loaded .lottie archive by its ID. */ load_animation_from_id(id: string, width: number, height: number): boolean; /** * Advance time and render. Call once per `requestAnimationFrame`. */ tick(): boolean; /** * Render the current frame without advancing time. */ render(): boolean; /** * Clear the canvas to the background colour. */ clear(): void; /** * Resize the canvas. For the SW renderer this also resizes the pixel buffer. */ resize(width: number, height: number): boolean; /** * Zero-copy `Uint8Array` view into WASM linear memory. * * **Use the returned array immediately.** Do not store the reference across * any call that may reallocate the buffer (e.g. `resize` / `load_animation` * with different dimensions). */ get_pixel_buffer(): Uint8Array; play(): boolean; pause(): boolean; stop(): boolean; is_playing(): boolean; is_paused(): boolean; is_stopped(): boolean; is_loaded(): boolean; is_complete(): boolean; is_tweening(): boolean; current_frame(): number; total_frames(): number; request_frame(): number; set_frame(no: number): boolean; seek(no: number): boolean; duration(): number; segment_duration(): number; current_loop_count(): number; reset_current_loop_count(): void; width(): number; height(): number; /** * `[width, height]` of the animation in its native coordinate space. */ animation_size(): Float32Array; mode(): Mode$1; set_mode(mode: Mode$1): void; speed(): number; set_speed(speed: number): void; loop_animation(): boolean; set_loop(v: boolean): void; loop_count(): number; set_loop_count(n: number): void; autoplay(): boolean; set_autoplay(v: boolean): void; use_frame_interpolation(): boolean; set_use_frame_interpolation(v: boolean): void; background_color(): number; /** * Set background colour (`0xAARRGGBB`). */ set_background_color(color: number): boolean; /** * Clear the background colour (transparent). */ clear_background_color(): boolean; set_quality(quality: number): boolean; has_segment(): boolean; segment_start(): number; segment_end(): number; set_segment(start: number, end: number): boolean; clear_segment(): boolean; /** * Set the layout. * * `fit` is one of `"contain"`, `"fill"`, `"cover"`, `"fit-width"`, * `"fit-height"`, `"none"`. `align_x` / `align_y` are in [0, 1]. */ set_layout(fit: string, align_x: number, align_y: number): boolean; layout_fit(): string; layout_align_x(): number; layout_align_y(): number; set_viewport(x: number, y: number, w: number, h: number): boolean; /** * Set a color slot (`r`, `g`, `b` in [0, 1]). */ set_color_slot(id: string, r: number, g: number, b: number): boolean; set_scalar_slot(id: string, value: number): boolean; set_text_slot(id: string, text: string): boolean; set_vector_slot(id: string, x: number, y: number): boolean; set_position_slot(id: string, x: number, y: number): boolean; clear_slots(): boolean; clear_slot(id: string): boolean; /** * Set multiple slots at once from a JSON string. */ set_slots_str(json: string): boolean; /** * Set a single slot by ID from a JSON value string. */ set_slot_str(id: string, json: string): boolean; /** * Get the JSON value of a single slot by ID, or `undefined` if not found. */ get_slot_str(id: string): string | undefined; /** * Get all slots as a JSON object string. */ get_slots_str(): string; /** * Get all slot IDs as a JS array. */ get_slot_ids(): any; /** * Get the type string of a slot, or `undefined` if not found. */ get_slot_type(id: string): string | undefined; /** * Reset a slot to its default value from the animation. */ reset_slot(id: string): boolean; /** * Reset all slots to their default values from the animation. */ reset_slots(): boolean; intersect(x: number, y: number, layer_name: string): boolean; /** * Returns `[x, y, width, height]` of the layer's bounding box. */ get_layer_bounds(layer_name: string): Float32Array; /** * Returns the current affine transform as a flat `Float32Array`. */ get_transform(): Float32Array; set_transform(data: Float32Array): boolean; /** * Tween to `to` frame. `duration` in seconds; pass `undefined` for default. */ tween(to: number, duration?: number | null): boolean; /** * Tween with a cubic-bezier easing (`e0..e3`). */ tween_with_easing(to: number, duration: number | null | undefined, e0: number, e1: number, e2: number, e3: number): boolean; tween_stop(): boolean; tween_update(progress?: number | null): boolean; tween_to_marker(marker: string, duration?: number | null): boolean; /** * Returns an array of `{ name, time, duration }` objects. */ markers(): any; /** * Returns an array of marker name strings. */ marker_names(): any; /** * Name of the currently active marker, or `undefined` if none. */ current_marker(): string | undefined; set_marker(name: string): void; clear_marker(): void; /** * Poll the next player event. Returns `null` if the queue is empty, * otherwise a plain JS object with a `type` string field and optional * payload fields (`frameNo`, `loopCount`). */ poll_event(): any; emit_on_loop(): void; load_font(name: string, data: Uint8Array): boolean; static unload_font(name: string): boolean; set_theme(id: string): boolean; reset_theme(): boolean; set_theme_data(data: string): boolean; theme_id(): string | undefined; animation_id(): string | undefined; /** * Returns the animation manifest as a JSON string, or empty string if unavailable. */ manifest_string(): string; /** * Returns the raw JSON definition of a state machine by ID, or `undefined`. */ get_state_machine(id: string): string | undefined; /** * Returns the ID of the currently active state machine, or `undefined`. */ state_machine_id(): string | undefined; /** * Load a state machine from a JSON definition string. Returns `true` on * success. The engine is kept alive inside the player and interacted * with via the `sm_*` methods. */ state_machine_load(definition: string): boolean; /** * Load a state machine from a .lottie archive by state-machine ID. */ state_machine_load_from_id(id: string): boolean; /** * Unload the active state machine. */ state_machine_unload(): void; /** * Fire a named event into the state machine. */ sm_fire(event: string): boolean; sm_set_numeric_input(key: string, value: number): boolean; sm_get_numeric_input(key: string): number | undefined; sm_set_string_input(key: string, value: string): boolean; sm_get_string_input(key: string): string | undefined; sm_set_boolean_input(key: string, value: boolean): boolean; sm_get_boolean_input(key: string): boolean | undefined; sm_reset_input(key: string): void; /** * Poll the next state machine event. Returns `null` if the queue is empty, * otherwise a JS object with a `type` field and optional payload. */ sm_poll_event(): any; /** * Start the state machine with an open-URL policy. */ sm_start(require_user_interaction: boolean, whitelist: any[]): boolean; /** * Stop the state machine. */ sm_stop(): boolean; /** * Get the current status of the state machine as a string. */ sm_status(): string; /** * Get the name of the current state. */ sm_current_state(): string; /** * Override the current state. */ sm_override_current_state(state: string, immediate: boolean): boolean; /** * Returns the framework setup listeners as a JS array of strings. */ sm_framework_setup(): any; /** * Returns all state machine inputs as a JS array of strings. */ sm_get_inputs(): any; sm_post_click(x: number, y: number): void; sm_post_pointer_down(x: number, y: number): void; sm_post_pointer_up(x: number, y: number): void; sm_post_pointer_move(x: number, y: number): void; sm_post_pointer_enter(x: number, y: number): void; sm_post_pointer_exit(x: number, y: number): void; /** * Poll the next state machine internal event. Returns `null` if the * queue is empty, otherwise a JS object `{ type: "Message", message }`. */ sm_poll_internal_event(): any; /** * Advance the state machine by one tick. Returns `false` if no state machine * is loaded, otherwise `true` (even if the machine is stopped or errored). */ sm_tick(): boolean; } //#endregion //#region src/dotlottie.d.ts declare class DotLottie { protected _canvas: HTMLCanvasElement | OffscreenCanvas | RenderSurface | null; private _pendingLoad; protected _context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null; private readonly _eventManager; private _animationFrameId; private readonly _frameManager; protected _dotLottieCore: DotLottiePlayerWasm | null; private _stateMachineId; private _stateMachineConfig; private _isStateMachineRunning; protected _renderConfig: RenderConfig; private _isFrozen; private _backgroundColor; private _boundOnClick; private _boundOnPointerUp; private _boundOnPointerDown; private _boundOnPointerMove; private _boundOnPointerEnter; private _boundOnPointerLeave; private _bufferMismatchCount; private _lastExpectedBufferSize; private _marker; /** * Creates a new DotLottie player instance for rendering Lottie animations. * Initializes the WASM module, event system, and loads animation if src or data is provided in config. * @param config - Configuration object specifying animation source, playback settings, and rendering options */ constructor(config: Config); protected _initWasm(): Promise<void>; protected _createCore(): DotLottiePlayerWasm; protected _onCoreCreated(): void; private _drainPlayerEvents; private _drainSmEvents; private _dispatchError; private _fetchData; private _loadFromData; private _loadFromSrc; /** * Gets the raw pixel buffer containing the rendered animation frame. * Returns RGBA pixel data as a Uint8Array for advanced image processing or custom rendering. */ get buffer(): Uint8Array | null; /** * Gets the ID of the currently active animation from a multi-animation dotLottie file. * Returns undefined if no specific animation is active or for single-animation files. */ get activeAnimationId(): string | undefined; /** * Gets the ID of the currently active theme applied to the animation. * Returns undefined if no theme is active. Themes modify colors and visual properties. */ get activeThemeId(): string | undefined; /** * Gets the current layout configuration for positioning and scaling the animation. * Includes fit mode (contain, cover, fill, etc.) and alignment [x, y] values (0-1 range). */ get layout(): Layout | undefined; /** * Gets the currently active marker name if a marker-based segment is set. * Returns undefined if no marker is active. Use setMarker() to activate a named segment. */ get marker(): string | undefined; /** * Gets the animation manifest containing metadata about animations, themes, and states. * Returns null if no manifest is available or if the loaded animation doesn't include one. */ get manifest(): Manifest | null; /** * Gets the current rendering configuration. * Includes settings like devicePixelRatio, autoResize, and freezeOnOffscreen. */ get renderConfig(): RenderConfig; /** * Gets the currently active playback segment as [startFrame, endFrame]. * If no segment is set, returns undefined and the full animation plays. */ get segment(): [number, number] | undefined; /** * Gets the current loop configuration. * Returns true if the animation is set to loop continuously. */ get loop(): boolean; /** * Gets the current playback mode. * Determines playback direction: 'forward', 'reverse', 'bounce' (forward then reverse), or 'reverse-bounce'. */ get mode(): Mode; /** * Indicates whether rendering is currently frozen. * True when freeze() has been called and the rendering loop is paused to save resources. */ get isFrozen(): boolean; /** * Indicates whether a state machine is currently active and running. * True after stateMachineStart() is called and until stateMachineStop() is called. */ get isStateMachineRunning(): boolean; /** * Gets the current background color. * Returns the background color as a string (e.g., '#FFFFFF' or 'transparent'). */ get backgroundColor(): string; /** * Gets the autoplay configuration. * Returns true if the animation is configured to start playing automatically when loaded. */ get autoplay(): boolean; /** * Gets the frame interpolation setting. * Returns true if frame interpolation is enabled for smoother animation playback. */ get useFrameInterpolation(): boolean; /** * Gets the current playback speed. * Returns the speed multiplier (1 = normal speed, 2 = double speed, 0.5 = half speed). */ get speed(): number; /** * Indicates whether the WASM module and core player have been initialized. * Check this before performing operations that require the player to be ready. */ get isReady(): boolean; /** * Indicates whether an animation has been successfully loaded and is ready for playback. * Check this before calling play() or other playback methods to ensure the animation is ready. */ get isLoaded(): boolean; /** * Indicates whether the animation is currently playing. * True when animation is actively playing, false when paused, stopped, or not started. */ get isPlaying(): boolean; /** * Indicates whether the animation is currently paused. * True when pause() has been called and animation is not playing or stopped. */ get isPaused(): boolean; /** * Indicates whether the animation is currently stopped. * True when stop() has been called or animation hasn't started yet. */ get isStopped(): boolean; /** * Gets the current frame number of the animation. * Useful for tracking playback position or implementing custom frame displays. Rounded to 2 decimal places. */ get currentFrame(): number; /** * Gets the number of times the animation has completed a loop during the current playback. * Increments each time the animation completes one full cycle. */ get loopCount(): number; /** * Gets the total number of frames in the animation. * Use with currentFrame to calculate playback progress as a percentage. */ get totalFrames(): number; /** * Gets the total duration of the animation in seconds. * Represents the time to play from the first frame to the last at normal speed (speed = 1). */ get duration(): number; /** * Gets the duration of the currently active segment in seconds. * If no segment is set, returns the full animation duration. */ get segmentDuration(): number; /** * Gets the canvas element used for rendering the animation. * Returns the HTMLCanvasElement, OffscreenCanvas, or RenderSurface set during initialization. */ get canvas(): HTMLCanvasElement | OffscreenCanvas | RenderSurface | null; /** * Dynamically loads a new animation, replacing the current one if any. * Stops current playback, cleans up resources, and loads from the provided src or data. * @param config - Configuration for the new animation (all Config properties except canvas) */ load(config: Omit<Config, 'canvas'>): void; protected _draw(): void; private _cleanupCanvas; private _initializeCanvas; protected _setupRendererOnCanvas(): void; private _stopAnimationLoop; private _startAnimationLoop; private _animationLoop; /** * Starts or resumes animation playback from the current frame. * Unfreezes rendering if frozen and starts the animation loop. Updates isPlaying state to true. */ play(): void; /** * Pauses animation playback at the current frame. * Stops the animation loop while preserving the current frame position. Updates isPaused state to true. */ pause(): void; /** * Stops animation playback and resets to the start frame. * Halts the animation loop and returns to the beginning. Updates isStopped state to true. */ stop(): void; /** * Seeks to a specific frame in the animation and renders it. * Useful for implementing custom scrubbing controls or precise frame positioning. * @param frame - The target frame number to seek to */ setFrame(frame: number): void; /** * Changes the animation playback speed. * Values above 1 speed up playback, below 1 slow it down. * @param speed - Playback speed multiplier (e.g., 2 for 2x speed, 0.5 for half speed) */ setSpeed(speed: number): void; /** * Changes the background color of the canvas or animation. * For HTMLCanvasElement, sets the CSS background. For other surfaces, renders behind the animation. * @param color - CSS color string (e.g., '#FFFFFF', 'rgba(0,0,0,0.5)', 'transparent') */ setBackgroundColor(color: string): void; /** * Enables or disables continuous looping of the animation. * When enabled with loopCount set to 0, animation repeats indefinitely. * @param loop - True to enable looping, false to play once */ setLoop(loop: boolean): void; /** * Sets the number of additional times to replay the animation after the first play. * Requires loop to be true. A value of 0 means infinite replays; a positive value n means * the animation plays a total of n + 1 times (initial play + n replays). * @param loopCount - Number of additional replays (0 = infinite, 1 = plays twice, 2 = plays three times, etc.) */ setLoopCount(loopCount: number): void; /** * Enables or disables frame interpolation for smoother playback. * When enabled, interpolates between frames. When disabled, shows exact frame-by-frame animation. * @param useFrameInterpolation - True for smooth interpolation, false for exact frames */ setUseFrameInterpolation(useFrameInterpolation: boolean): void; /** * Subscribes to animation events like play, pause, frame, complete, etc. * Use this to react to animation state changes and playback progress. * @param type - Event type to listen for (e.g., 'play', 'frame', 'complete') * @param listener - Callback function invoked when the event occurs */ addEventListener<T extends EventType>(type: T, listener: EventListener<T>): void; /** * Unsubscribes from animation events. * If no listener is provided, removes all listeners for the given event type. * @param type - Event type to stop listening for * @param listener - Specific callback to remove, or undefined to remove all */ removeEventListener<T extends EventType>(type: T, listener?: EventListener<T>): void; /** * Cleans up and destroys the player instance, releasing all resources. * Stops playback, removes event listeners, and frees WASM memory. Call when the player is no longer needed. */ destroy(): void; /** * Pauses the rendering loop without changing playback state. * Useful for reducing CPU/GPU usage when the animation is offscreen or hidden. Dispatches 'freeze' event. */ freeze(): void; /** * Resumes the rendering loop after being frozen. * Restarts frame rendering while maintaining the current playback state. Dispatches 'unfreeze' event. */ unfreeze(): void; /** * Recalculates and updates canvas dimensions based on current size. * Call this when the canvas container size changes to maintain proper rendering. Usually handled by autoResize. */ resize(): void; /** * Changes the canvas element used for rendering. * Useful for moving the animation to a different canvas without recreating the player instance. * @param canvas - New HTMLCanvasElement, OffscreenCanvas, or RenderSurface to render to */ setCanvas(canvas: HTMLCanvasElement | OffscreenCanvas | RenderSurface): void; /** * Applies a 3x3 transformation matrix to the entire animation on the canvas. * Use this to translate, rotate, scale, or skew the animation rendering. * @param transform - 9-element array representing the transformation matrix in row-major order * @returns True if transformation was applied successfully, false otherwise */ setTransform(transform: Transform): boolean; /** * Gets the 3x3 transformation matrix applied to the animation. * Returns a 9-element array representing affine transformations (translation, rotation, scale, skew). * @returns Transform array of 9 numbers, or undefined if not available */ getTransform(): Transform | undefined; /** * Sets a frame range to play instead of the full animation. * Useful for playing specific sections or creating animation sequences from subsections. * @param startFrame - Starting frame number (inclusive) * @param endFrame - Ending frame number (inclusive) */ setSegment(startFrame: number, endFrame: number): void; /** * Changes the playback direction mode. * Controls whether animation plays forward, in reverse, or alternates (bounce). * @param mode - Playback mode: 'forward', 'reverse', 'bounce', or 'reverse-bounce' */ setMode(mode: Mode): void; /** * Updates rendering configuration like autoResize, devicePixelRatio, and freezeOnOffscreen. * Dynamically changes how the canvas behaves without reloading the animation. * @param config - Partial RenderConfig with properties to update */ setRenderConfig(config: RenderConfig): void; /** * Switches to a different animation within a multi-animation dotLottie file. * Use this to load a different animation by its ID without creating a new player instance. * @param animationId - ID of the animation to load (must exist in the manifest) */ loadAnimation(animationId: string): void; /** * Activates a named marker to play only that marked segment. * Markers define named sections within an animation. Use markers() to list available markers. * @param marker - Name of the marker to activate */ setMarker(marker: string): void; /** * Gets all markers defined in the animation with their time and duration. * Markers represent named sections that can be played using setMarker(). * @returns Array of marker objects with name, time, and duration properties */ markers(): Marker[]; /** * Applies a theme to the animation, modifying colors and visual properties. * Themes are predefined in the dotLottie manifest. Returns true if theme was successfully loaded. * @param themeId - ID of the theme to apply (must exist in manifest) * @returns True if theme loaded successfully, false otherwise */ setTheme(themeId: string): boolean; /** * Removes the currently applied theme and restores original animation colors. * Use this to revert to the default appearance after applying a theme. * @returns True if theme was reset successfully, false otherwise */ resetTheme(): boolean; /** * Applies a custom theme from theme data instead of manifest theme ID. * Useful for dynamically generated or user-created themes not in the manifest. * * @param themeData - Theme data as a JSON string or a structured Theme object * @returns True if theme loaded successfully, false otherwise */ setThemeData(themeData: Theme | string): boolean; /** * Sets multiple slot values at once for parameterized animations. * Slots allow runtime customization of colors, text, images, or other properties. * @param slots - Object mapping slot IDs to their values */ setSlots(slots: Record<string, unknown>): void; /** * Check if value is an array of keyframes (has objects with 't' and 's' properties) */ private _isKeyframeArray; /** * Get all slot IDs in the animation * @returns Array of slot ID strings */ getSlotIds(): string[]; /** * Get the type of a slot * @param slotId - The slot ID to query * @returns The slot type ('color', 'gradient', 'text', 'scalar', 'vector', 'position', 'image') or undefined */ getSlotType(slotId: string): SlotType | undefined; /** * Get the current value of a slot * @param slotId - The slot ID to query * @returns The parsed slot value or undefined if not found */ getSlot(slotId: string): unknown; /** * Get all slots as an object with slot IDs as keys * @returns Object containing all slots, or empty object if not loaded */ getSlots(): Record<string, unknown>; /** * Set a color slot value * @param slotId - The slot ID to set * @param value - Static color [r, g, b, a] or array of keyframes * @returns true if successful */ setColorSlot(slotId: string, value: ColorSlotValue): boolean; /** * Set a scalar slot value (single number like rotation, opacity) * @param slotId - The slot ID to set * @param value - Static number or array of keyframes * @returns true if successful */ setScalarSlot(slotId: string, value: ScalarSlotValue): boolean; /** * Set a vector slot value (2D or 3D point for position, scale, etc.) * Handles both "vector" and "position" slot types * @param slotId - The slot ID to set * @param value - Static vecto