# Services

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**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `enabled` | `boolean` |  | Enable/disable all animations globally |
| `reducedMotion` | `boolean` |  | Respect 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 |
| `animationSpeed` | `number` |  | Global speed multiplier (0.5 = half speed, 2 = double speed) |
| `autoDetectMotionPreference` | `boolean` |  | Auto-detect and respect system motion preferences |
| `performanceMode` | `boolean` |  | Performance mode (simplifies animations) |
| `batterySavingMode` | `boolean` |  | Battery saving mode (disables expensive animations) |
| `respectBatteryStatus` | `boolean` |  | Auto-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). |
| `lazyLoadCSS` | `boolean` |  | Lazy load CSS (only inject when first animation is used) |

### `AnimationEventData`

Animation event data

```ts
interface AnimationEventData
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `animationName` | `string` |  | Animation name |
| `element` | `HTMLElement` |  | Element the animation is applied to |
| `type` | `AnimationLifecycleEvent` |  | Event type |
| `elapsedTime` | `number` |  | Elapsed time when event occurred |
| `pseudoElement?` | `string` |  | Pseudo-element (if applicable) |
| `originalEvent` | `AnimationEvent` |  | Original AnimationEvent |
| `timestamp` | `number` |  | Timestamp |

### `AnimationMetrics`

Performance metrics snapshot

```ts
interface AnimationMetrics
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `fps` | `number` |  | Current frames per second |
| `averageFps` | `number` |  | Average FPS over monitoring period |
| `minFps` | `number` |  | Minimum FPS recorded |
| `maxFps` | `number` |  | Maximum FPS recorded |
| `animatedElementCount` | `number` |  | Number of currently animated elements |
| `animatedNodeCount` | `number` |  | Number of animated nodes |
| `animatedEdgeCount` | `number` |  | Number of animated edges |
| `frameDrops` | `number` |  | Total frame drops detected |
| `memoryUsage?` | `number` |  | Memory usage (if available) |
| `cpuUsage?` | `number` |  | CPU usage estimate (0-100) |
| `timestamp` | `number` |  | Timestamp of metrics |
| `monitoringDuration` | `number` |  | Monitoring duration in seconds |

### `AnimationStepOptions`

Animation step options

```ts
interface AnimationStepOptions
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `duration?` | `string` |  | Animation duration |
| `timingFunction?` | `string` |  | Timing function |
| `delay?` | `string` |  | Delay before starting |
| `iterationCount?` | `string` |  | Iteration count |
| `direction?` | `string` |  | Direction |
| `fillMode?` | `string` |  | Fill mode |

### `AppliedAnimation`

Applied animation instance

```ts
interface AppliedAnimation
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` |  |  |
| `element` | `HTMLElement` |  |  |
| `startTime` | `number` |  |  |
| `definition` | `CustomAnimationDefinition` |  |  |

### `CustomAnimationDefinition`

Custom animation definition

```ts
interface CustomAnimationDefinition
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` |  | Unique name for the animation |
| `keyframes` | `string` |  | CSS keyframes definition |
| `duration?` | `string` |  | Animation duration (e.g., '1s', '500ms') |
| `timingFunction?` | `string` |  | Timing function (e.g., 'ease', 'linear', 'ease-in-out') |
| `iterationCount?` | `string` |  | Iteration count (e.g., 'infinite', '3', '1') |
| `direction?` | `string` |  | Animation direction (e.g., 'normal', 'reverse', 'alternate') |
| `fillMode?` | `string` |  | Fill mode (e.g., 'none', 'forwards', 'backwards', 'both') |
| `delay?` | `string` |  | Delay before animation starts (e.g., '0s', '200ms') |
| `playState?` | `string` |  | Play state (e.g., 'running', 'paused') |
| `willChange?` | `string[]` |  | CSS properties that will change (for will-change hint) |
| `description?` | `string` |  | Description 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**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `minFps` | `number` |  | Minimum acceptable FPS (default: 30) |
| `maxAnimatedElements` | `number` |  | Maximum animated elements before warning (default: 100) |
| `maxFrameDrops` | `number` |  | Maximum frame drops before warning (default: 10) |
| `maxMemoryMB` | `number` |  | Maximum memory usage in MB (default: 100) |
| `maxFrameTime` | `number` |  | Maximum frame time in ms (default: 50) |

### `PerformanceWarningEvent`

Performance warning event

```ts
interface PerformanceWarningEvent
```

**Properties**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `PerformanceWarning` |  |  |
| `message` | `string` |  |  |
| `metrics` | `AnimationMetrics` |  |  |
| `timestamp` | `number` |  |  |

## 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**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `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'`
