import { b as Cmd, c as Sub, M as Machine } from '../core-sEWVgnpI.js'; import { H as HandlerFamily, P as PromiseHandlers, E as EngineRun, a as StoreAndOnError, c as HandlersFor, O as OnError } from '../runtime-types-f231H8Gq.js'; import { P as Postable } from '../loop-CKqoteig.js'; import '@standard-schema/spec'; /** * How a click reaches a run, in one place: both hooks build their `send` here. * * A view hands the run a Msg and waits for nothing. What the step ends with is * the run's to report, on its own sink; this file reports only what the run * cannot, because the Msg never reached it. */ /** What a `send` can be built on: a run with a line to post to, or only its own `dispatch`. */ type SendTarget = Postable | { dispatch(msg: M): Promise; }; /** * @packageDocumentation * @demlik/tea/react — React host adapter for `@demlik/tea`. * * The thinnest possible adapter that makes a tea machine consumable from a * React component. Three rules (PRD §"React adapter"): * * 1. The runtime is the source of truth, NOT React state. We subscribe via * `useSyncExternalStore`, reading a snapshot of the run's state. React * renders are driven by runtime state changes; React never owns the state. * 2. The runtime is kept per component-mount, not per render. It is keyed on * `[machine, opts.run, opts.ctx, opts.store]` — IDENTITY, not value. See * `docs/how-to/drive-from-react.md` for the ctx-identity footgun + fix. * 3. Concurrent React is the design target. `useSyncExternalStore` is the * React-blessed primitive for tearing-free external state. * * Client-only in v1 — components that call `useMachine` MUST be `"use client"`. * Server Components consume data via Relay/RSC as today; tea machines own * client-side stateful flows. No RSC streaming, no server-side state * hydration. Crossing this boundary is a v2 concern. */ /** * Options passed to `useMachine`. `run` is the engine's `run` — `run` from * `@demlik/tea/promise`, or `runIn(runtime)` from `@demlik/tea/effect`; the hook * imports no engine. `ctx` is required (every machine has one), `store` is * optional (omit it for volatile-state machines), and the handlers are the ones * `run` takes beside the machine: `interpret` (required once the machine emits * a Cmd) and the `subscribe` runners (required once the machine declares a Sub * type other than the built-in `timer`) — see {@link RunHandlers}. Same * requiredness as `run`, because it is the same type. They are typed by the * engine `run` belongs to (`F`, see {@link HandlerFamily}): Promise-returning * cells for the Promise engine's, `Effect`-returning cells and `Stream` runners * for the bridge's. * * **The handlers are read fresh, never memoized on.** A handler table written * inline in the component is a new object every render; keying the runtime on * it would reboot the machine on every render. So `useMachine` hands `run` a * table that looks each cell up on the latest render's `interpret` / * `subscribe` at the moment a Cmd runs or a Sub starts — a handler may close * over props and state freely. * * **Identity matters.** The runtime is keyed on `[machine, opts.run, * opts.ctx, opts.store]`. A new `ctx` reference rebuilds the runtime, and so * does a new `run` — pass the engine's own function, not an inline wrapper. Always `useMemo` * (or otherwise stabilize) the ctx at the call site. See README. * * Forgetting to is no longer silent: the replaced runtime's `stop()` reports * `RuntimeDiscardedError` under `phase: "discard"` when Cmds were still in * flight, which the substrate's default sink warns about (issue #365). */ type UseMachineOpts = { run: EngineRun; ctx: Ctx; } & StoreAndOnError & HandlersFor; /** * Build and own a run of `machine` for the lifetime of the component mount, on * the engine whose `run` the caller hands in. * * - Starts the run in an effect, never during render, and keys it on `[machine, * opts.run, opts.ctx, opts.store]`: the run is replaced when ANY of those * identities change. Until the run has its first State saved, `state` is * `init(null, ctx)`'s. * - Subscribes via `useSyncExternalStore` — tearing-free under React 18 * concurrent rendering. * - On unmount (or any dep change), calls `stop()` — drains the queue, up to * `disposeTimeoutMs`, runs every active sub cleanup, flushes state, and — if * Cmds were still in flight — reports `RuntimeDiscardedError` (`phase: * "discard"`) rather than dropping them silently. A handler that has not * returned by the limit is given up on and reported as a `DrainTimeoutNotice`. * * **Strict Mode:** its extra effect run on mount does nothing. One run starts, * `run` is called once, and each Sub starts once. * * **``** (React 19.2 and later): a hide stops the machine's Subs, and nothing else: their * cleanups run, and they start again on show. It is the same run across the hide, * so `state` keeps its value, `init` is not called again, and a Cmd in flight * lands and its answer folds, whether that comes during the hide or after the * show. A Msg dispatched while hidden folds at once, and any Cmd it emits runs. * * `send` stays the same function across a hide and show. A Msg sent * before the run has started, which on a tree first mounted hidden means before * its first show, waits for the run and folds when it starts. * A Msg still waiting at unmount, or sent afterwards, reaches `onError` as a * `DispatchDiscardedError` under `phase: "discard"`. Step failures go to the * run's `onError` once, under their own phase. * * Returns `[state, send]`, where `send(msg)` returns `undefined` immediately. * Read the rendered State for the outcome; there is no Promise to await. */ declare function useMachine(machine: Machine, opts: NoInfer> & FamilyOfRun): [S, (msg: M) => void]; /** * The `run` of `UseMachineOpts`, seen only for the family it says it takes. A * plain `run` says nothing, so the family is the Promise engine's. */ type FamilyOfRun = { readonly run: ((...args: never) => unknown) & { readonly "~demlik/tea/handlers"?: F; }; }; /** * Consume a booted run from either engine's `run`, or a hand-built * {@link ViewHandle} with a Promise-returning `dispatch`. * * Use this when the runtime is owned by something OTHER than the component — * a parent component, a test harness, a singleton. **The component does NOT * call `runtime.stop()` on unmount** — the caller owns the lifecycle. * * For component tests, build a run with the engine's `run` and a pre-seeded * store, await `ready`, then pass it here to render in any phase. * * Pass a selector as the second argument to read only part of the model: * `useRuntime(runtime, (state) => state.views[id])`. A runtime update redraws * this reader only when the selected value changes according to `Object.is`. * The selector should pick a part, not build a new object or array. A fresh * object on every read makes `useSyncExternalStore` see a change every time; * React warns that the snapshot should be cached and can loop. Pick stable * parts and derive new objects or arrays from them during render instead. * With a selector, pass options as the third argument. * * Returns `[state, send]` (or `[selected, send]` with a selector), where * `send(msg)` returns `undefined` immediately. It sends the whole run's Msg * and stays the same function for a given runtime, including selector changes. * Step failures go once to the run's own `onError`. `opts.onError` hears a * `DispatchDiscardedError` under `phase: "discard"` for a stopped run, or a * hand-built handle's dispatch failure under `phase: "follow-up"`. It defaults * to the default sink and is read fresh without replacing `send`. */ declare function useRuntime(runtime: ViewHandle, opts?: UseRuntimeOpts): [S, (msg: M) => void]; declare function useRuntime(runtime: ViewHandle, select: (state: S) => V, opts?: UseRuntimeOpts): [V, (msg: M) => void]; /** Options for `useRuntime`: the sink for a Msg that never reached the run. */ type UseRuntimeOpts = { /** Where a send to a stopped run, or a hand-built `dispatch`'s failure, is reported. Default: the default sink. */ readonly onError?: OnError; }; /** What `useRuntime` reads: a booted run from either engine's `run`, or a hand-built handle. */ type ViewHandle = { subscribe(listener: () => void): () => void; getState(): S; } & SendTarget; export { type UseMachineOpts, type UseRuntimeOpts, type ViewHandle, useMachine, useRuntime };