# dotLottie iOS Player API Reference
API reference for the dotLottie iOS player. Covers DotLottiePlayerView (SwiftUI), DotLottiePlayerUIView (UIKit/AppKit), DotLottieAnimation, WebGPU views, config, enums, protocols, and state machine controls.

# dotLottie iOS Player API Reference

The iOS player provides three ways to display animations:

- **`DotLottiePlayerView`** — A SwiftUI view with a builder-pattern modifier API.
- **`DotLottiePlayerUIView`** — A UIKit/AppKit view with property-based API.
- **`DotLottieAnimation`** — A lower-level view model that can be used with `.view()`.

For applications that require the WebGPU-based renderer, two additional views are available:

- **`DotLottieWebGPUPlayerView`** — A SwiftUI view backed by the WebGPU (Metal) renderer (iOS and macOS only, experimental).
- **`DotLottieWebGPUView`** — A UIKit/AppKit view backed by the WebGPU (Metal) renderer (iOS and macOS only, experimental).

## DotLottiePlayerView (SwiftUI)

A SwiftUI view for displaying Lottie and dotLottie animations. Uses a declarative modifier API.

### Initializers

| Initializer                          | Description                                                                               |
| ------------------------------------ | ----------------------------------------------------------------------------------------- |
| `init(animation:)`                   | Create a player with a `DotLottieAnimation` instance.                                     |
| `init(_ loadAnimation:)`             | Create a player with an async closure that returns a `DotLottieAnimation`.                |
| `init(_ loadAnimation:placeholder:)` | Create a player with an async closure and a custom placeholder view shown during loading. |

### Modifiers

All modifiers return `Self` and can be chained.

| Modifier                                      | Description                                                                        |
| --------------------------------------------- | ---------------------------------------------------------------------------------- |
| `.configure(_:)`                              | Apply a configuration closure to the underlying `DotLottiePlayerUIView`.           |
| `.looping()`                                  | Enable looping playback.                                                           |
| `.playing()`                                  | Set the playback state to playing (play once).                                     |
| `.paused()`                                   | Set the playback state to paused.                                                  |
| `.loopMode(_:)`                               | Set the loop mode (`DotLottieLoopMode`).                                           |
| `.playbackMode(_:)`                           | Set the playback mode (`DotLottiePlaybackMode`).                                   |
| `.animationSpeed(_:)`                         | Set the playback speed multiplier.                                                 |
| `.configuration(_:)`                          | Apply an `AnimationConfig` to the player.                                          |
| `.animationDidLoad(_:)`                       | Register a callback invoked when the animation finishes loading.                   |
| `.currentProgress(_:)`                        | Set the current playback progress (0.0–1.0). Pauses playback.                      |
| `.currentFrame(_:)`                           | Set the current frame number. Pauses playback.                                     |
| `.mode(_:)`                                   | Set the playback `Mode` (forward, reverse, bounce, reverseBounce).                 |
| `.useFrameInterpolation(_:)`                  | Enable or disable frame interpolation.                                             |
| `.segments(_:)`                               | Set the playback segment as a `(Float, Float)` range.                              |
| `.reloadAnimationTrigger(_:showPlaceholder:)` | Trigger a reload of the animation. Optionally shows the placeholder during reload. |

### Example

```swift
import SwiftUI
import DotLottie

struct ContentView: View {
    var body: some View {
        DotLottiePlayerView(animation: DotLottieAnimation(
            fileName: "animation",
            config: AnimationConfig(autoplay: true, loop: true)
        ))
        .looping()
        .playing()
        .animationSpeed(1.5)
        .frame(width: 300, height: 300)
    }
}
```

#### Async loading with placeholder

```swift
DotLottiePlayerView({
    try await DotLottieAnimation(
        webURL: "https://example.com/animation.lottie",
        config: AnimationConfig(autoplay: true, loop: true)
    )
}, placeholder: {
    ProgressView()
})
.looping()
.playing()
```

## DotLottiePlayerUIView (UIKit / AppKit)

A `UIView` (iOS) / `NSView` (macOS) for displaying Lottie and dotLottie animations with a property-based API.

### Initializers

| Initializer                            | Description                                                                |
| -------------------------------------- | -------------------------------------------------------------------------- |
| `init(dotLottieAnimation:config:)`     | Create a player with an existing `DotLottieAnimation` and optional config. |
| `init(name:bundle:config:completion:)` | Load an animation by file name from a bundle.                              |
| `init(filePath:config:completion:)`    | Load an animation from a file path.                                        |
| `init(url:config:session:completion:)` | Load an animation from a URL.                                              |
| `init(animationData:config:)`          | Load an animation from a JSON string.                                      |
| `init(dotLottieData:config:)`          | Load an animation from raw `.lottie` `Data`.                               |

### Properties

| Property                | Type                                                                                 | Description                                           |
| ----------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------- |
| `dotLottieAnimation`    | `DotLottieAnimation?`                                                                | The underlying animation instance.                    |
| `config`                | `AnimationConfig`                                                                    | The current animation configuration.                  |
| `isAnimationPlaying`    | `Bool`                                                                               | Whether the animation is currently playing.           |
| `isAnimationPaused`     | `Bool`                                                                               | Whether the animation is currently paused.            |
| `isAnimationStopped`    | `Bool`                                                                               | Whether the animation is currently stopped.           |
| `loopMode`              | `DotLottieLoopMode`                                                                  | The current loop mode (`.playOnce` or `.loop`).       |
| `animationSpeed`        | `CGFloat`                                                                            | The current playback speed multiplier.                |
| `currentProgress`       | `CGFloat`                                                                            | The current playback progress (0.0–1.0).              |
| `currentFrame`          | `CGFloat`                                                                            | The current frame number.                             |
| `totalFrames`           | `CGFloat`                                                                            | The total number of frames.                           |
| `duration`              | `TimeInterval`                                                                       | The total animation duration in seconds.              |
| `mode`                  | `Mode`                                                                               | The current playback mode.                            |
| `useFrameInterpolation` | `Bool`                                                                               | Whether frame interpolation is enabled.               |
| `segments`              | `(Float, Float)?`                                                                    | The current playback segment range.                   |
| `animationLoaded`       | `((_ playerView: DotLottiePlayerUIView, _ animation: DotLottieAnimation?) -> Void)?` | Callback invoked when the animation finishes loading. |

### Playback Methods

| Method                                    | Return Type | Description                                                  |
| ----------------------------------------- | ----------- | ------------------------------------------------------------ |
| `play()`                                  | `Bool`      | Begin playback.                                              |
| `pause()`                                 | `Bool`      | Pause playback.                                              |
| `stop()`                                  | `Bool`      | Stop playback and reset to the initial frame.                |
| `play(fromFrame:)`                        | `Bool`      | Begin playback from a specific frame.                        |
| `play(fromProgress:)`                     | `Bool`      | Begin playback from a specific progress value (0.0–1.0).     |
| `play(fromProgress:toProgress:loopMode:)` | `Bool`      | Play between two progress values with an optional loop mode. |
| `play(fromFrame:toFrame:loopMode:)`       | `Bool`      | Play between two frame numbers with an optional loop mode.   |
| `play(marker:loopMode:)`                  | `Bool`      | Play a named marker segment with an optional loop mode.      |
| `play(fromMarker:toMarker:loopMode:)`     | `Bool`      | Play between two named markers with an optional loop mode.   |
| `setFrame(_:)`                            | `Bool`      | Seek to a specific frame.                                    |
| `setProgress(_:)`                         | `Bool`      | Seek to a specific progress value (0.0–1.0).                 |

### Marker Methods

| Method                          | Return Type | Description                                    |
| ------------------------------- | ----------- | ---------------------------------------------- |
| `markers()`                     | `[Marker]`  | Returns all markers in the animation.          |
| `setMarker(_:)`                 | `Void`      | Set the active marker for playback.            |
| `progressTime(forMarker:)`      | `CGFloat?`  | Get the progress time for a named marker.      |
| `frameTime(forMarker:)`         | `CGFloat?`  | Get the frame time for a named marker.         |
| `durationFrameTime(forMarker:)` | `CGFloat?`  | Get the duration in frames for a named marker. |

### Animation & Manifest Methods

| Method                 | Return Type | Description                                                            |
| ---------------------- | ----------- | ---------------------------------------------------------------------- |
| `loadAnimation(byId:)` | `Void`      | Load a specific animation by ID from a multi-animation `.lottie` file. |
| `manifest()`           | `Manifest?` | Returns the `.lottie` file manifest.                                   |

### State Machine Methods

| Method                                    | Return Type        | Description                                             |
| ----------------------------------------- | ------------------ | ------------------------------------------------------- |
| `isStateMachine()`                        | `Bool`             | Returns whether the .lottie contains any state machine. |
| `startStateMachine(id:openUrlPolicy:)`    | `Bool`             | Load and start a state machine by ID (convenience).     |
| `stateMachineLoad(id:)`                   | `Bool`             | Load a state machine by ID.                             |
| `stateMachineLoadData(_:)`                | `Bool`             | Load a state machine from a JSON string.                |
| `stateMachineStart()`                     | `Bool`             | Start the loaded state machine.                         |
| `stateMachineStop()`                      | `Bool`             | Stop the active state machine.                          |
| `stateMachinePostEvent(_:force:)`         | `Void`             | Post a typed `Event` to the state machine.              |
| `stateMachinePostClickEvent(at:)`         | `Void`             | Post a click event at a position.                       |
| `stateMachinePostPointerDownEvent(at:)`   | `Void`             | Post a pointer down event at a position.                |
| `stateMachinePostPointerUpEvent(at:)`     | `Void`             | Post a pointer up event at a position.                  |
| `stateMachinePostPointerMoveEvent(at:)`   | `Void`             | Post a pointer move event at a position.                |
| `stateMachinePostPointerEnterEvent(at:)`  | `Void`             | Post a pointer enter event at a position.               |
| `stateMachinePostPointerExitEvent(at:)`   | `Void`             | Post a pointer exit event at a position.                |
| `stateMachineCurrentState()`              | `String`           | Returns the name of the current state.                  |
| `stateMachineFrameworkSetup()`            | `[String]`         | Returns framework setup event names.                    |
| `stateMachineGetInputs()`                 | `[String: String]` | Returns all state machine inputs and their types.       |
| `stateMachineSetNumericInput(key:value:)` | `Bool`             | Set a numeric input value.                              |
| `stateMachineSetBooleanInput(key:value:)` | `Bool`             | Set a boolean input value.                              |
| `stateMachineSetStringInput(key:value:)`  | `Bool`             | Set a string input value.                               |
| `stateMachineGetNumericInput(key:)`       | `Float`            | Get a numeric input value.                              |
| `stateMachineGetBooleanInput(key:)`       | `Bool`             | Get a boolean input value.                              |
| `stateMachineGetStringInput(key:)`        | `String`           | Get a string input value.                               |
| `stateMachineSubscribe(_:)`               | `Bool`             | Subscribe a `StateMachineObserver`.                     |
| `stateMachineUnsubscribe(_:)`             | `Bool`             | Unsubscribe a `StateMachineObserver`.                   |

### Example

```swift
import UIKit
import DotLottie

class ViewController: UIViewController {
    var playerView: DotLottiePlayerUIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        playerView = DotLottiePlayerUIView(
            name: "animation",
            config: AnimationConfig(autoplay: true, loop: true)
        )
        playerView.frame = CGRect(x: 50, y: 100, width: 300, height: 300)
        view.addSubview(playerView)

        playerView.animationLoaded = { [weak self] playerView, animation in
            print("Animation loaded!")
        }
    }
}
```

---

## DotLottieAnimation

A lower-level view model for animation playback. Can be used with `.view()`.

### Initializers

| Initializer                     | Description                                                      |
| ------------------------------- | ---------------------------------------------------------------- |
| `init(fileName:bundle:config:)` | Load an animation by file name from a bundle (default: `.main`). |
| `init(webURL:config:)`          | Load an animation from a web URL.                                |
| `init(animationData:config:)`   | Load an animation from a Lottie JSON string.                     |
| `init(dotLottieData:config:)`   | Load from raw `.lottie` `Data`.                                  |
| `init(lottieData:config:)`      | Load from raw Lottie JSON `Data`.                                |

### AnimationConfig

`AnimationConfig` defines the playback settings passed to any initializer.

| Property                | Type              | Default        | Description                                                                                                                       |
| ----------------------- | ----------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `autoplay`              | `Bool?`           | `false`        | Autoplay the animation on load.                                                                                                   |
| `loop`                  | `Bool?`           | `false`        | Loop the animation.                                                                                                               |
| `loopCount`             | `Int?`            | `0`            | Number of times to loop. `0` means infinite when `loop` is `true`.                                                                |
| `speed`                 | `Float?`          | `1.0`          | Playback speed multiplier.                                                                                                        |
| `mode`                  | `Mode?`           | `.forward`     | Playback mode: `forward`, `reverse`, `bounce`, `reverseBounce`.                                                                   |
| `width`                 | `Int?`            | `512`          | Override animation render width in pixels.                                                                                        |
| `height`                | `Int?`            | `512`          | Override animation render height in pixels.                                                                                       |
| `segments`              | `(Float, Float)?` | `nil`          | Play between an interval of frames.                                                                                               |
| `backgroundColor`       | `CIImage?`        | `.clear`       | Background color of the animation canvas. Not available on watchOS.                                                               |
| `useFrameInterpolation` | `Bool?`           | `false`        | Interpolate between frames. Useful for smooth playback at slow speeds.                                                            |
| `marker`                | `String?`         | `nil`          | Named marker to play on load.                                                                                                     |
| `layout`                | `Layout?`         | contain/center | Animation layout configuration. See [Layout Configuration](/en/runtimes/distributions/ios/v0.x/usage-guide#layout-configuration). |
| `themeId`               | `String?`         | `nil`          | Theme ID to apply on load.                                                                                                        |
| `animationId`           | `String?`         | `""`           | Animation ID for multi-animation `.lottie` files.                                                                                 |
| `stateMachineId`        | `String?`         | `""`           | State machine ID to auto-load on initialization.                                                                                  |

### Properties

| Property                  | Type             | Description                                             |
| ------------------------- | ---------------- | ------------------------------------------------------- |
| `framerate`               | `Int`            | The animation's frame rate (published).                 |
| `currentFrame()`          | `Float`          | The currently displayed frame number.                   |
| `currentProgress()`       | `Float`          | Current playback progress (0.0–1.0).                    |
| `duration()`              | `Float`          | Total animation duration in seconds.                    |
| `totalFrames()`           | `Float`          | Total number of frames.                                 |
| `loop()`                  | `Bool`           | Whether looping is enabled.                             |
| `speed()`                 | `Float`          | Current playback speed multiplier.                      |
| `loopCount()`             | `Int`            | Number of completed loop iterations.                    |
| `mode()`                  | `Mode`           | Current playback mode.                                  |
| `isPaused()`              | `Bool`           | Whether the animation is paused.                        |
| `isStopped()`             | `Bool`           | Whether the animation is stopped.                       |
| `isPlaying()`             | `Bool`           | Whether the animation is playing.                       |
| `isLoaded()`              | `Bool`           | Whether the animation has loaded successfully.          |
| `isStateMachineRunning()` | `Bool`           | Whether a state machine is currently running.           |
| `error()`                 | `Bool`           | Whether the animation has errored.                      |
| `errorMessage()`          | `String`         | Error message string, if any.                           |
| `manifest()`              | `Manifest?`      | The `.lottie` manifest.                                 |
| `segments()`              | `(Float, Float)` | Current playback segment (start, end) frames.           |
| `backgroundColor()`       | `CIImage`        | Current background color. Not available on watchOS.     |
| `autoplay()`              | `Bool`           | Whether autoplay is enabled.                            |
| `useFrameInterpolation()` | `Bool`           | Whether frame interpolation is enabled.                 |
| `layout()`                | `Layout`         | The current layout (fit and alignment).                 |
| `markers()`               | `[Marker]`       | Markers in the animation. See [Marker](#marker-struct). |
| `activeThemeId()`         | `String`         | The active theme ID.                                    |
| `activeAnimationId()`     | `String`         | The active animation ID.                                |

### Playback Methods

| Method                         | Return Type | Description                                                       |
| ------------------------------ | ----------- | ----------------------------------------------------------------- |
| `play()`                       | `Bool`      | Begin playback from the current position.                         |
| `pause()`                      | `Bool`      | Pause without resetting position.                                 |
| `stop()`                       | `Bool`      | Stop and return to the initial frame.                             |
| `play(fromFrame:)`             | `Bool`      | Start playback from a specific frame.                             |
| `play(fromProgress:)`          | `Bool`      | Start playback from a specific progress value (0.0–1.0).          |
| `setFrame(frame:)`             | `Bool`      | Seek to a specific frame.                                         |
| `setProgress(progress:)`       | `Bool`      | Seek to a specific progress value (0.0–1.0).                      |
| `setSpeed(speed:)`             | `Void`      | Set the playback speed multiplier (`Float`).                      |
| `setLoop(loop:)`               | `Void`      | Enable or disable looping.                                        |
| `setMode(mode:)`               | `Void`      | Set the playback mode.                                            |
| `setMarker(marker:)`           | `Void`      | Set the active marker for playback.                               |
| `setSegments(segments:)`       | `Void`      | Set the start and end frame range.                                |
| `setAutoplay(autoplay:)`       | `Void`      | Enable or disable autoplay.                                       |
| `setFrameInterpolation(_:)`    | `Void`      | Enable or disable frame interpolation.                            |
| `setLayout(layout:)`           | `Void`      | Update the animation fit and alignment.                           |
| `setBackgroundColor(bgColor:)` | `Void`      | Set the background color. Not available on watchOS.               |
| `resize(width:height:)`        | `Void`      | Manually resize the animation render canvas.                      |
| `render()`                     | `Bool`      | Force a render of the current frame.                              |
| `tick(dt:)`                    | `CGImage?`  | Advance by `dt` milliseconds and return a frame image if changed. |
| `frameImage()`                 | `CGImage?`  | Render the current frame without advancing time.                  |

### Animation Management

| Method                  | Return Type | Description                                        |
| ----------------------- | ----------- | -------------------------------------------------- |
| `loadAnimationById(_:)` | `Void`      | Load a specific animation by ID from the manifest. |

### Theming & Slots

| Method                                 | Return Type | Description                                 |
| -------------------------------------- | ----------- | ------------------------------------------- |
| `setTheme(_:)`                         | `Bool`      | Apply a theme by ID.                        |
| `setThemeData(_:)`                     | `Bool`      | Apply theme data from a JSON string.        |
| `resetTheme()`                         | `Bool`      | Remove the applied theme.                   |
| `setSlots(_:)`                         | `Bool`      | Apply slot data from a JSON string.         |
| `clearSlots()`                         | `Bool`      | Clear all slots.                            |
| `clearSlot(slotId:)`                   | `Bool`      | Clear a specific slot.                      |
| `setColorSlot(slotId:r:g:b:)`          | `Bool`      | Set a color slot with RGB values (0.0–1.0). |
| `setScalarSlot(slotId:value:)`         | `Bool`      | Set a scalar slot value.                    |
| `setTextSlot(slotId:text:)`            | `Bool`      | Set a text slot value.                      |
| `setVectorSlot(slotId:x:y:)`           | `Bool`      | Set a vector slot value.                    |
| `setPositionSlot(slotId:x:y:)`         | `Bool`      | Set a position slot value.                  |
| `setImageSlotPath(slotId:path:)`       | `Bool`      | Set an image slot from a file path.         |
| `setImageSlotDataUrl(slotId:dataUrl:)` | `Bool`      | Set an image slot from a data URL.          |

### Observer Methods

| Method                   | Return Type | Description                                  |
| ------------------------ | ----------- | -------------------------------------------- |
| `subscribe(observer:)`   | `Void`      | Subscribe an `Observer` to animation events. |
| `unsubscribe(observer:)` | `Void`      | Unsubscribe an `Observer`.                   |

### State Machine Methods

| Method                                    | Return Type        | Description                                   |
| ----------------------------------------- | ------------------ | --------------------------------------------- |
| `stateMachineLoad(id:)`                   | `Bool`             | Load a state machine by ID from the manifest. |
| `stateMachineLoadData(_:)`                | `Bool`             | Load a state machine from a JSON string.      |
| `stateMachineStart(openUrlPolicy:)`       | `Bool`             | Start the loaded state machine.               |
| `stateMachineStart(id:openUrlPolicy:)`    | `Bool`             | Load and start a state machine in one call.   |
| `stateMachineStop()`                      | `Bool`             | Stop the active state machine.                |
| `stateMachineCurrentState()`              | `String`           | Get the name of the current state.            |
| `getStateMachine(_:)`                     | `String`           | Get a state machine definition JSON by ID.    |
| `stateMachinePostEvent(_:force:)`         | `Void`             | Post a typed `Event` to the state machine.    |
| `stateMachineFire(event:)`                | `Void`             | Fire a named event string.                    |
| `stateMachineSubscribe(_:)`               | `Bool`             | Subscribe a `StateMachineObserver`.           |
| `stateMachineUnsubscribe(_:)`             | `Bool`             | Unsubscribe a `StateMachineObserver`.         |
| `stateMachineFrameworkSetup()`            | `[String]`         | Get framework setup event names.              |
| `stateMachineGetInputs()`                 | `[String: String]` | Get all inputs and their types.               |
| `stateMachineSetBooleanInput(key:value:)` | `Bool`             | Set a boolean input.                          |
| `stateMachineSetNumericInput(key:value:)` | `Bool`             | Set a numeric input.                          |
| `stateMachineSetStringInput(key:value:)`  | `Bool`             | Set a string input.                           |
| `stateMachineGetBooleanInput(key:)`       | `Bool`             | Get a boolean input value.                    |
| `stateMachineGetNumericInput(key:)`       | `Float`            | Get a numeric input value.                    |
| `stateMachineGetStringInput(key:)`        | `String`           | Get a string input value.                     |

---

## WebGPU Views

The WebGPU views use an alternative renderer and are available as a separate integration path. Use these when you specifically need the WebGPU-based rendering backend.

### DotLottieWebGPUPlayerView (SwiftUI)

`DotLottieWebGPUPlayerView` is a SwiftUI `View` (conforming to `ViewRepresentable`) that wraps `DotLottieWebGPUView` for use in SwiftUI hierarchies.

#### Initializers

| Initializer                                   | Description                                                                                                           |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `init(fileName:bundle:config:onViewCreated:)` | Load a `.lottie` or `.json` animation by file name from a bundle.                                                     |
| `init(animationData:config:onViewCreated:)`   | Load an animation from a Lottie JSON string.                                                                          |
| `init(webURL:config:onViewCreated:)`          | Load a `.lottie` or `.json` animation from a remote URL. The file is fetched asynchronously once the view is created. |

#### Parameters

**`init(fileName:bundle:config:onViewCreated:)`**

| Parameter       | Type                               | Default    | Description                                                        |
| --------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------ |
| `fileName`      | `String`                           | —          | The name of the animation file in the bundle (without extension).  |
| `bundle`        | `Bundle`                           | `.main`    | The bundle to search for the animation file.                       |
| `config`        | `Config`                           | `Config()` | Playback configuration.                                            |
| `onViewCreated` | `((DotLottieWebGPUView) -> Void)?` | `nil`      | Optional callback invoked with the underlying view after creation. |

**`init(animationData:config:onViewCreated:)`**

| Parameter       | Type                               | Default    | Description                                                        |
| --------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------ |
| `animationData` | `String`                           | —          | A Lottie JSON string.                                              |
| `config`        | `Config`                           | `Config()` | Playback configuration.                                            |
| `onViewCreated` | `((DotLottieWebGPUView) -> Void)?` | `nil`      | Optional callback invoked with the underlying view after creation. |

**`init(webURL:config:onViewCreated:)`**

| Parameter       | Type                               | Default    | Description                                                                                                                                                                           |
| --------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `webURL`        | `String`                           | —          | A URL string pointing to a remote `.lottie` or `.json` animation. The format is inferred from the URL: paths containing `.lottie` are loaded as dotLottie, all others as Lottie JSON. |
| `config`        | `Config`                           | `Config()` | Playback configuration.                                                                                                                                                               |
| `onViewCreated` | `((DotLottieWebGPUView) -> Void)?` | `nil`      | Optional callback invoked with the underlying view after creation.                                                                                                                    |

#### Example

```swift
import SwiftUI
import DotLottie

struct WebGPUAnimationView: View {
    var body: some View {
        // Load from the app bundle
        DotLottieWebGPUPlayerView(
            fileName: "animation",
            config: Config()
        )
        .frame(width: 300, height: 300)
    }
}
```

```swift
import SwiftUI
import DotLottie

struct WebGPURemoteAnimationView: View {
    var body: some View {
        // Load from a remote URL
        DotLottieWebGPUPlayerView(
            webURL: "https://assets.lottiefiles.com/samples/animation.lottie",
            config: Config()
        )
        .frame(width: 300, height: 300)
    }
}
```

Use `onViewCreated` to obtain a reference to the underlying `DotLottieWebGPUView` for imperative control:

```swift
import SwiftUI
import DotLottie

struct WebGPUControlledView: View {
    @State private var gpuView: DotLottieWebGPUView?

    var body: some View {
        VStack {
            DotLottieWebGPUPlayerView(
                webURL: "https://assets.lottiefiles.com/samples/animation.lottie",
                config: Config(),
                onViewCreated: { view in
                    gpuView = view
                }
            )
            .frame(width: 300, height: 300)
        }
    }
}
```

---

### DotLottieWebGPUView (UIKit / AppKit)

`DotLottieWebGPUView` is the underlying platform view (`UIView` on iOS, `NSView` on macOS) that drives the WebGPU renderer. You can use it directly in UIKit or AppKit, or obtain a reference to it via the `onViewCreated` callback of `DotLottieWebGPUPlayerView`.

#### Loading Methods

| Method                            | Return Type | Description                                                                                                                                                                           |
| --------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `loadAnimation(fileName:bundle:)` | `Bool`      | Load a `.lottie` or `.json` animation by file name from a bundle.                                                                                                                     |
| `loadAnimationData(_:)`           | `Void`      | Load an animation from a Lottie JSON string.                                                                                                                                          |
| `loadDotlottie(data:)`            | `Void`      | Load an animation from raw `.lottie` `Data`.                                                                                                                                          |
| `loadAnimation(webURL:)`          | `Bool`      | Load a `.lottie` or `.json` animation from a remote URL. Returns `true` if the URL is valid and a fetch was started. Load success or failure is reported via the `Observer` protocol. |

#### `loadAnimation(webURL:)` Details

```swift
@discardableResult
public func loadAnimation(webURL: String) -> Bool
```

- The file is fetched asynchronously on a background task.
- The URL extension determines the load path: a URL containing `.lottie` is treated as dotLottie data; all other URLs are treated as Lottie JSON.
- A return value of `true` indicates the URL was valid and a network request was started. It does **not** indicate that the animation loaded successfully.
- Subscribe an `Observer` via `subscribe(observer:)` to receive `onLoad` and `onLoadError` callbacks once the fetch completes.

#### Observer Methods

| Method                 | Return Type | Description                                  |
| ---------------------- | ----------- | -------------------------------------------- |
| `subscribe(observer:)` | `Void`      | Subscribe an `Observer` to animation events. |

Subscribe to the `Observer` protocol (see [Observer](#observer)) to handle load results:

```swift
import DotLottie

class MyObserver: Observer {
    func onLoad() { print("WebGPU animation loaded") }
    func onLoadError() { print("WebGPU animation failed to load") }
    func onPlay() { }
    func onPause() { }
    func onStop() { }
    func onComplete() { }
    func onLoop(loopCount: UInt32) { }
    func onFrame(frameNo: Float) { }
    func onRender(frameNo: Float) { }
}

let gpuView = DotLottieWebGPUView()
let observer = MyObserver()
gpuView.subscribe(observer: observer)

// Returns true if URL is valid and fetch started; result delivered via observer
let started = gpuView.loadAnimation(webURL: "https://assets.lottiefiles.com/samples/animation.lottie")
```

---

## Enums

### Mode

```swift
public enum Mode {
    case forward
    case reverse
    case bounce
    case reverseBounce
}
```

### DotLottieLoopMode

Used by `DotLottiePlayerUIView` and `DotLottiePlayerView`.

```swift
public enum DotLottieLoopMode {
    /// Animation plays once then stops.
    case playOnce
    /// Animation loops from beginning to end until stopped.
    case loop
}
```

### DotLottiePlaybackMode

Used by `DotLottiePlayerView`.

```swift
public enum DotLottiePlaybackMode {
    case playing
    case paused
}
```

### Fit

Controls how the animation scales within its bounds.

```swift
public enum Fit {
    case contain
    case fill
    case cover
    case fitWidth
    case fitHeight
    case none
}
```

### Event

Used with `stateMachinePostEvent` to send typed events to a state machine.

```swift
public enum Event {
    case pointerDown(x: Float, y: Float)
    case pointerUp(x: Float, y: Float)
    case pointerMove(x: Float, y: Float)
    case pointerEnter(x: Float, y: Float)
    case pointerExit(x: Float, y: Float)
    case click(x: Float, y: Float)
    case onComplete
    case onLoopComplete
}
```

---

## Protocols

### Observer

Implement this protocol to receive animation playback events via `subscribe(observer:)`. Used by both `DotLottieAnimation` and `DotLottieWebGPUView`.

```swift
public protocol Observer {
    func onComplete()
    func onFrame(frameNo: Float)
    func onLoad()
    func onLoadError()
    func onLoop(loopCount: UInt32)
    func onPause()
    func onPlay()
    func onRender(frameNo: Float)
    func onStop()
}
```

### StateMachineObserver

Implement this protocol to receive state machine transition events via `stateMachineSubscribe(_:)`.

```swift
public protocol StateMachineObserver: AnyObject {
    func onTransition(previousState: String, newState: String)
    func onStateEntered(enteringState: String)
    func onStateExit(leavingState: String)
}
```

---

## Structs

### Marker

Returned by the `markers()` method.

```swift
public struct Marker {
    public var name: String
    public var time: Float
    public var duration: Float
}
```

### OpenUrlPolicy

Controls URL opening behavior in state machines.

```swift
public struct OpenUrlPolicy: Equatable, Hashable {
    public var requireUserInteraction: Bool  // default: true
    public var whitelist: [String]           // default: []

    public init(requireUserInteraction: Bool = true, whitelist: [String] = [])
}
```

### Manifest

Returned by the `manifest()` method. Contains metadata about the `.lottie` file.

#### Manifest

| Property        | Type                      | Description                                             |
| --------------- | ------------------------- | ------------------------------------------------------- |
| `generator`     | `String?`                 | Tool that generated the `.lottie` file.                 |
| `version`       | `String?`                 | dotLottie format version.                               |
| `animations`    | `[ManifestAnimation]`     | All animations bundled in the file.                     |
| `themes`        | `[ManifestTheme]?`        | All themes bundled in the file.                         |
| `stateMachines` | `[ManifestStateMachine]?` | All state machines bundled in the file.                 |
| `initial`       | `ManifestInitial?`        | Default animation and/or state machine to load on open. |

#### ManifestInitial

| Property       | Type      | Description                                 |
| -------------- | --------- | ------------------------------------------- |
| `stateMachine` | `String?` | ID of the state machine to load by default. |
| `animation`    | `String?` | ID of the animation to load by default.     |

#### ManifestAnimation

| Property       | Type        | Description                                         |
| -------------- | ----------- | --------------------------------------------------- |
| `id`           | `String`    | Animation identifier.                               |
| `name`         | `String?`   | Display name.                                       |
| `initialTheme` | `String?`   | Default theme ID applied when this animation loads. |
| `background`   | `String?`   | Background color.                                   |
| `themes`       | `[String]?` | IDs of themes compatible with this animation.       |

#### ManifestTheme

| Property | Type      | Description       |
| -------- | --------- | ----------------- |
| `id`     | `String`  | Theme identifier. |
| `name`   | `String?` | Display name.     |

#### ManifestStateMachine

| Property | Type      | Description               |
| -------- | --------- | ------------------------- |
| `id`     | `String`  | State machine identifier. |
| `name`   | `String?` | Display name.             |

### Layout

Controls how the animation fits and aligns within its view bounds.

```swift
public struct Layout {
    public var fit: Fit
    public var alignX: Float
    public var alignY: Float

    public init(fit: Fit = .contain, alignX: Float = 0.5, alignY: Float = 0.5)
}
```

| Property | Type    | Default    | Description                                                                                  |
| -------- | ------- | ---------- | -------------------------------------------------------------------------------------------- |
| `fit`    | `Fit`   | `.contain` | How the animation scales: `.contain`, `.cover`, `.fill`, `.fitWidth`, `.fitHeight`, `.none`. |
| `alignX` | `Float` | `0.5`      | Horizontal alignment. `0.0` = left, `0.5` = center, `1.0` = right.                           |
| `alignY` | `Float` | `0.5`      | Vertical alignment. `0.0` = top, `0.5` = center, `1.0` = bottom.                             |

### Config

`Config` is the lower-level configuration struct used directly by the WebGPU renderer and `DotLottiePlayer`.

| Property                | Type      | Default        | Description                                |
| ----------------------- | --------- | -------------- | ------------------------------------------ |
| `autoplay`              | `Bool`    | `false`        | Autoplay on load.                          |
| `loopAnimation`         | `Bool`    | `false`        | Loop the animation.                        |
| `loopCount`             | `UInt32`  | `0`            | Max loop count (`0` = infinite).           |
| `mode`                  | `Mode`    | `.forward`     | Playback mode.                             |
| `speed`                 | `Float`   | `1.0`          | Playback speed multiplier.                 |
| `useFrameInterpolation` | `Bool`    | `false`        | Enable frame interpolation.                |
| `segment`               | `[Float]` | `[]`           | Frame range `[start, end]`.                |
| `backgroundColor`       | `UInt32`  | `0`            | Background color as ARGB integer.          |
| `layout`                | `Layout`  | contain/center | Layout fit and alignment.                  |
| `marker`                | `String`  | `""`           | Named marker to activate.                  |
| `themeId`               | `String`  | `""`           | Theme ID to apply.                         |
| `stateMachineId`        | `String`  | `""`           | State machine ID to auto-start after load. |
| `animationId`           | `String`  | `""`           | Animation ID for multi-animation files.    |
