|
| 1 | +import type { Machine, MachineSchema, Service } from "@zag-js/core" |
| 2 | +import type { NormalizeProps } from "@zag-js/types" |
| 3 | +import type { ReactiveController, ReactiveControllerHost } from "lit" |
| 4 | +import { normalizeProps, VanillaMachine } from "./lib" |
| 5 | +import { createId } from "./lib/create-id" |
| 6 | + |
| 7 | +export class ZagController<Api, T extends MachineSchema> implements ReactiveController { |
| 8 | + host: ReactiveControllerHost |
| 9 | + |
| 10 | + private id = createId() |
| 11 | + private connect: (service: Service<any>, normalize: NormalizeProps<any>) => Api |
| 12 | + |
| 13 | + machine: VanillaMachine<any> |
| 14 | + api: Api |
| 15 | + |
| 16 | + constructor( |
| 17 | + host: ReactiveControllerHost, |
| 18 | + connect: (service: Service<T>, normalize: NormalizeProps<any>) => Api, |
| 19 | + machine: Machine<T>, |
| 20 | + userProps: Partial<T["props"]> = {}, |
| 21 | + ) { |
| 22 | + // Store a reference to the host |
| 23 | + this.host = host |
| 24 | + // Register for lifecycle updates |
| 25 | + host.addController(this) |
| 26 | + |
| 27 | + this.connect = connect |
| 28 | + |
| 29 | + this.machine = new VanillaMachine(machine, { ...userProps, id: this.id }) |
| 30 | + this.api = this.connect(this.machine.service, normalizeProps) |
| 31 | + } |
| 32 | + |
| 33 | + hostConnected() { |
| 34 | + // Start the machine when the host is connected |
| 35 | + this.machine.subscribe(() => { |
| 36 | + this.api = this.connect(this.machine.service, normalizeProps) |
| 37 | + this.host.requestUpdate() |
| 38 | + }) |
| 39 | + this.machine.start() |
| 40 | + } |
| 41 | + hostDisconnected() { |
| 42 | + // Stop the machine when the host is disconnected |
| 43 | + this.machine.stop() |
| 44 | + } |
| 45 | +} |
0 commit comments