Skip to content
D
Documentation

Services

reference
7 min readUpdated

Import these from @grafloria/renderer.

Functions

createSequencer

Create a new animation sequencer

ts
function createSequencer(
  animationRegistry?: CustomAnimationRegistry,
  lifecycleManager?: AnimationLifecycleManager
): AnimationSequencer

fadeInSequence

Helper: Create a simple fade in sequence

ts
function fadeInSequence(elements: HTMLElement[], delay: number = 100): AnimationSequencer

getGlobalAnimationLifecycleManager

Get the global animation lifecycle manager

ts
function getGlobalAnimationLifecycleManager(): AnimationLifecycleManager

getGlobalCustomAnimationRegistry

Get the global custom animation registry

ts
function getGlobalCustomAnimationRegistry(): CustomAnimationRegistry

resetGlobalAnimationLifecycleManager

Reset the global lifecycle manager (useful for testing)

ts
function resetGlobalAnimationLifecycleManager(): void

resetGlobalCustomAnimationRegistry

Reset the global registry (useful for testing)

ts
function resetGlobalCustomAnimationRegistry(): void

staggerSequence

Helper: Create a stagger animation sequence

ts
function staggerSequence(
  elements: HTMLElement[],
  animationName: string,
  staggerDelay: number = 100,
  options?: AnimationStepOptions
): AnimationSequencer

Classes

AnimationLifecycleManager

Animation Lifecycle Manager

Manages lifecycle event listeners for CSS animations

ts
class AnimationLifecycleManager

Methods

  • constructor()
  • trackElement(element: HTMLElement): void — Track an element for animation events
  • untrackElement(element: HTMLElement): void — Untrack an element
  • on(eventType: AnimationLifecycleEvent, animationName: string, callback: LifecycleCallback): () => void — Listen to a specific animation lifecycle event
  • onAll(eventType: AnimationLifecycleEvent, callback: LifecycleCallback): () => void — Listen to all animations for a specific event type
  • onElement(element: HTMLElement, eventType: AnimationLifecycleEvent, callback: LifecycleCallback): () => void — Listen to animations on a specific element
  • off(eventType: AnimationLifecycleEvent, animationName: string): void — Remove all listeners for a specific animation
  • waitFor(animationName: string, element?: HTMLElement): Promise<AnimationEventData> — Wait for an animation to end Returns a promise that resolves when the animation ends
  • waitForElement(element: HTMLElement): Promise<AnimationEventData> — Wait for any animation to complete on an element
  • getTrackedElements(): HTMLElement[] — Get all tracked elements
  • isTracking(element: HTMLElement): boolean — Check if element is being tracked
  • destroy(): void — Cleanup: Remove all listeners and untrack all elements

AnimationPerformanceService

Animation Performance Service

Monitors animation performance and provides metrics

ts
class AnimationPerformanceService

Methods

  • constructor(thresholds?: Partial<PerformanceThresholds>)
  • startMonitoring(): void — Start performance monitoring
  • stopMonitoring(): void — Stop performance monitoring
  • getMetrics(): Readonly<AnimationMetrics> — Get current metrics
  • getFPSHistory(): number[] — Get FPS history
  • updateThresholds(thresholds: Partial<PerformanceThresholds>): void — Update performance thresholds
  • getThresholds(): Readonly<PerformanceThresholds> — Get current thresholds
  • onMetricsUpdate(listener: (metrics: AnimationMetrics) => void): () => void — Subscribe to metrics updates
  • onPerformanceWarning(listener: (warning: PerformanceWarningEvent) => void): () => void — Subscribe to performance warnings
  • reset(): void — Reset metrics
  • isMonitoring(): boolean — Check if monitoring is active
  • getSummary(): string — Get performance summary
  • destroy(): void — Cleanup

AnimationSequencer

Animation Sequencer

Manages sequences of animations

ts
class AnimationSequencer

Methods

  • constructor( animationRegistry?: CustomAnimationRegistry, lifecycleManager?: AnimationLifecycleManager )
  • add(element: HTMLElement, animationName: string, options?: AnimationStepOptions): this — Add a single animation step
  • parallel(animations: Array<{ element: HTMLElement; animationName: string; options?: AnimationStepOptions; }>): this — Add multiple animations to run in parallel
  • delay(duration: number): this — Add a delay
  • then(callback: () => void | Promise<void>): this — Add a callback step
  • onComplete(callback: () => void): this — Add completion callback
  • async play(): Promise<void> — Play the sequence
  • pause(): void — Pause the sequence
  • resume(): void — Resume the sequence
  • cancel(): void — Cancel the sequence
  • reset(): void — Reset the sequence
  • getState(): SequenceState — Get current state
  • getCurrentStepIndex(): number — Get current step index
  • getTotalSteps(): number — Get total number of steps
  • getSteps(): AnimationStep[] — Get all steps
  • clear(): void — Clear all steps
  • clone(): AnimationSequencer — Clone this sequencer (creates a new instance with the same steps)
  • exportToJSON(): string — Export sequence as JSON

AnimationService

AnimationService - Manages all diagram animations

Features:

  • Detects and respects prefers-reduced-motion
  • Provides global animation enable/disable
  • Generates animation CSS classes for nodes and links
  • Supports animation speed control
  • Performance and battery saving modes
ts
class AnimationService

Methods

  • constructor(config?: Partial<AnimationConfig>)
  • setEnabled(enabled: boolean): void — Enable or disable all animations globally
  • getConfig(): Readonly<AnimationConfig> — Get current configuration
  • updateConfig(config: Partial<AnimationConfig>): void — Update configuration (partial update)
  • getEdgeAnimationClass(link: LinkModel): string — Get animation CSS classes for an edge (link)
  • getNodeAnimationClass(node: NodeModel, useSVGVariant: boolean = false): string — Get animation CSS classes for a node
  • getAnimationDuration(baseDuration: number): number — Calculate animation duration with speed multiplier applied
  • pauseAllAnimations(): void — Pause all animations (for debugging or screenshots)
  • resumeAllAnimations(): void — Resume all animations
  • onConfigChange(listener: (config: AnimationConfig) => void): () => void — Add listener for configuration changes
  • resetConfig(): void — Reset configuration to defaults
  • injectCSS(): void — Inject animation CSS into the document This is called automatically when lazyLoadCSS is enabled and first animation is used
  • removeCSS(): void — Remove injected animation CSS from the document
  • isCSSInjected(): boolean — Check if CSS has been injected
  • destroy(): void — Cleanup: Remove event listeners and injected CSS

CustomAnimationRegistry

Custom Animation Registry

Manages custom animations and applies them to elements

ts
class CustomAnimationRegistry

Methods

  • constructor()
  • register(definition: CustomAnimationDefinition): void — Register a custom animation
  • unregister(name: string): boolean — Unregister a custom animation
  • get(name: string): CustomAnimationDefinition | undefined — Get animation definition
  • has(name: string): boolean — Check if animation exists
  • getAll(): CustomAnimationDefinition[] — Get all registered animations
  • getByTag(tag: string): CustomAnimationDefinition[] — Get animations by tag
  • getByTargetType(type: 'node' | 'edge' | 'both'): CustomAnimationDefinition[] — Get animations by target type
  • applyToElement(element: HTMLElement, animationName: string): boolean — Apply animation to an element
  • removeFromElement(element: HTMLElement, animationName: string): void — Remove animation from an element
  • onAnimationApplied(animationName: string, listener: (element: HTMLElement) => void): () => void — Subscribe to animation applications
  • getElementsWithAnimation(animationName: string): HTMLElement[] — Get all elements with a specific animation applied
  • getElementAnimations(element: HTMLElement): string[] — Get all animations applied to an element
  • clearElement(element: HTMLElement): void — Clear all animations from an element
  • clearAll(): void — Clear all animations
  • registerBatch(definitions: CustomAnimationDefinition[]): void — Batch register multiple animations
  • exportToJSON(): string — Export all animations as JSON
  • importFromJSON(json: string): void — Import animations from JSON
  • destroy(): void — Cleanup

Interfaces

AnimationConfig

ts
interface AnimationConfig

Properties

NameTypeDefaultDescription
enabledbooleanEnable/disable all animations globally
reducedMotionbooleanRespect user's prefers-reduced-motion system setting
defaultEdgeAnimation'marching-ants' | 'flow' | 'pulse' | 'none'Default animation type for edges
defaultNodeBorderAnimation'gradient' | 'pulse' | 'breathe' | 'shimmer' | 'none'Default border animation type for nodes
animationSpeednumberGlobal speed multiplier (0.5 = half speed, 2 = double speed)
autoDetectMotionPreferencebooleanAuto-detect and respect system motion preferences
performanceModebooleanPerformance mode (simplifies animations)
batterySavingModebooleanBattery saving mode (disables expensive animations)
respectBatteryStatusbooleanAuto-engage {@link batterySavingMode} from the (experimental) Battery Status API when the device is below 20% and not charging. Default true — but it is a HOST decision: with no off switch, a laptop dipping under 20% silently killed every edge animation (and turned the demo gallery's animation gates red on an unplugged machine — that is how this flag was born).
lazyLoadCSSbooleanLazy load CSS (only inject when first animation is used)

AnimationEventData

Animation event data

ts
interface AnimationEventData

Properties

NameTypeDefaultDescription
animationNamestringAnimation name
elementHTMLElementElement the animation is applied to
typeAnimationLifecycleEventEvent type
elapsedTimenumberElapsed time when event occurred
pseudoElement?stringPseudo-element (if applicable)
originalEventAnimationEventOriginal AnimationEvent
timestampnumberTimestamp

AnimationMetrics

Performance metrics snapshot

ts
interface AnimationMetrics

Properties

NameTypeDefaultDescription
fpsnumberCurrent frames per second
averageFpsnumberAverage FPS over monitoring period
minFpsnumberMinimum FPS recorded
maxFpsnumberMaximum FPS recorded
animatedElementCountnumberNumber of currently animated elements
animatedNodeCountnumberNumber of animated nodes
animatedEdgeCountnumberNumber of animated edges
frameDropsnumberTotal frame drops detected
memoryUsage?numberMemory usage (if available)
cpuUsage?numberCPU usage estimate (0-100)
timestampnumberTimestamp of metrics
monitoringDurationnumberMonitoring duration in seconds

AnimationStepOptions

Animation step options

ts
interface AnimationStepOptions

Properties

NameTypeDefaultDescription
duration?stringAnimation duration
timingFunction?stringTiming function
delay?stringDelay before starting
iterationCount?stringIteration count
direction?stringDirection
fillMode?stringFill mode

AppliedAnimation

Applied animation instance

ts
interface AppliedAnimation

Properties

NameTypeDefaultDescription
namestring
elementHTMLElement
startTimenumber
definitionCustomAnimationDefinition

CustomAnimationDefinition

Custom animation definition

ts
interface CustomAnimationDefinition

Properties

NameTypeDefaultDescription
namestringUnique name for the animation
keyframesstringCSS keyframes definition
duration?stringAnimation duration (e.g., '1s', '500ms')
timingFunction?stringTiming function (e.g., 'ease', 'linear', 'ease-in-out')
iterationCount?stringIteration count (e.g., 'infinite', '3', '1')
direction?stringAnimation direction (e.g., 'normal', 'reverse', 'alternate')
fillMode?stringFill mode (e.g., 'none', 'forwards', 'backwards', 'both')
delay?stringDelay before animation starts (e.g., '0s', '200ms')
playState?stringPlay state (e.g., 'running', 'paused')
willChange?string[]CSS properties that will change (for will-change hint)
description?stringDescription of the animation (for documentation)
tags?string[]Tags for categorization
targetType?'node' | 'edge' | 'both'Target type: 'node', 'edge', or 'both'

PerformanceThresholds

Performance threshold configuration

ts
interface PerformanceThresholds

Properties

NameTypeDefaultDescription
minFpsnumberMinimum acceptable FPS (default: 30)
maxAnimatedElementsnumberMaximum animated elements before warning (default: 100)
maxFrameDropsnumberMaximum frame drops before warning (default: 10)
maxMemoryMBnumberMaximum memory usage in MB (default: 100)
maxFrameTimenumberMaximum frame time in ms (default: 50)

PerformanceWarningEvent

Performance warning event

ts
interface PerformanceWarningEvent

Properties

NameTypeDefaultDescription
typePerformanceWarning
messagestring
metricsAnimationMetrics
timestampnumber

Types

AnimationLifecycleEvent

Also has every member of String, listed on its own entry.

Animation lifecycle event types

ts
type AnimationLifecycleEvent = 'start' | 'end' | 'iteration' | 'cancel';

AnimationStep

Animation step union type

ts
type AnimationStep = SingleAnimationStep | ParallelAnimationStep | DelayStep | CallbackStep;

Properties

NameTypeDefaultDescription
type'single'

LifecycleCallback

Lifecycle callback function

ts
type LifecycleCallback = (data: AnimationEventData) => void;

SequenceState

Also has every member of String, listed on its own entry.

Sequence playback state

ts
type SequenceState = 'idle' | 'playing' | 'paused' | 'completed' | 'cancelled';

Enums

PerformanceWarning

Performance warning types

ts
enum PerformanceWarning

Members

  • LOW_FPS = 'LOW_FPS'
  • HIGH_ELEMENT_COUNT = 'HIGH_ELEMENT_COUNT'
  • FRAME_DROPS = 'FRAME_DROPS'
  • HIGH_MEMORY = 'HIGH_MEMORY'
  • LONG_FRAMES = 'LONG_FRAMES'

Was this page helpful?

Services — Grafloria