/** * The Action envelope (API §1.2) — a graph-plane primitive, not a context (rule * 5). Holds the `Action` type (public — it appears in every write/dispatch * hook signature) and the `useAction` stateful-callable factory (internal): a * render-stable callable whose pending/error/result snapshot is re-stamped each * render, safe in deps arrays. */ import { useCallback, useEffect, useReducer, useRef } from 'react' /** The stateful callable every write/dispatch hook returns. */ export interface Action { /** Invoke; rejects on failure AND records it on `.error`. */ (...args: A): Promise /** ≥1 invocation in flight (the OR across concurrent calls). */ readonly pending: boolean /** Last rejection; cleared when the next invocation starts. */ readonly error: unknown /** Last successful resolution. */ readonly result: R | undefined /** Clears error/result. */ reset(): void } /** Same shape, minus `readonly`, so the render step can stamp the snapshot on. */ interface MutableAction { (...args: A): Promise pending: boolean error: unknown result: R | undefined reset(): void } interface ActionSnapshot { readonly pending: boolean readonly error: unknown readonly result: R | undefined } const IDLE_SNAPSHOT: ActionSnapshot = { pending: false, error: undefined, result: undefined, } type ActionEvent = | { readonly type: 'start' } | { readonly type: 'resolve'; readonly value: R; readonly inFlight: number } | { readonly type: 'reject'; readonly error: unknown; readonly inFlight: number } | { readonly type: 'reset' } function actionReducer(state: ActionSnapshot, event: ActionEvent): ActionSnapshot { switch (event.type) { case 'start': // §1.2: a new invocation clears the error and keeps the last result. return { pending: true, error: undefined, result: state.result } case 'resolve': // Latest settlement wins: a success records the result and clears error. return { pending: event.inFlight > 0, error: undefined, result: event.value } case 'reject': return { pending: event.inFlight > 0, error: event.error, result: state.result } case 'reset': return { pending: state.pending, error: undefined, result: undefined } } } /** * Wrap an async function in the Action envelope. Concurrent invocations are * allowed — each returns its own promise; `pending` is the OR of the in-flight * count and `result`/`error` reflect the latest settlement. The callable keeps * ONE identity for the hook's lifetime (safe in deps arrays); its snapshot * fields are re-stamped each render, so reads stay current across settlements. */ export function useAction(fn: (...args: A) => Promise): Action { // Latest-closure ref so the stable callable always dispatches the current fn. const fnRef = useRef(fn) fnRef.current = fn const [snapshot, dispatch] = useReducer(actionReducer, IDLE_SNAPSHOT as ActionSnapshot) const inFlight = useRef(0) const alive = useRef(true) useEffect(() => { alive.current = true return () => { alive.current = false } }, []) const call = useCallback((...args: A): Promise => { inFlight.current += 1 dispatch({ type: 'start' }) let promise: Promise try { promise = Promise.resolve(fnRef.current(...args)) } catch (err) { promise = Promise.reject(err) } void promise.then( (value) => { inFlight.current -= 1 if (alive.current) dispatch({ type: 'resolve', value, inFlight: inFlight.current }) }, (err: unknown) => { inFlight.current -= 1 if (alive.current) dispatch({ type: 'reject', error: err, inFlight: inFlight.current }) }, ) return promise }, []) const reset = useCallback(() => dispatch({ type: 'reset' }), []) // One render-stable callable: built once (call/reset are themselves stable), // then its snapshot fields re-stamped every render. Re-renders are driven by // the reducer, so the stamped pending/error/result stay fresh WITHOUT minting // a new function identity — the documented "safe in deps arrays" guarantee. const actionRef = useRef | null>(null) if (actionRef.current === null) { const action = ((...args: A) => call(...args)) as MutableAction action.reset = reset actionRef.current = action } const action = actionRef.current action.pending = snapshot.pending action.error = snapshot.error action.result = snapshot.result return action as Action }