import { createContext, useContext, useEffect, useRef, type ReactNode } from "react"; import { WorkerRunner, type Runner } from "@plate-dyn/core"; const RunnerContext = createContext(null); /** * Provides one numbl runner to a tree of components. By default a WorkerRunner * is created lazily; pass `runner` to share or substitute one. */ export function RunnerProvider({ children, runner }: { children: ReactNode; runner?: Runner }) { const ref = useRef(null); if (!ref.current) ref.current = runner ?? new WorkerRunner(); useEffect(() => { const r = ref.current; return () => { // Dispose terminates the worker; the runner recreates one on the next run, // so React StrictMode's mount-unmount-mount cycle is harmless. r?.dispose(); }; }, []); return {children}; } export function useRunner(): Runner { const r = useContext(RunnerContext); if (!r) throw new Error("useRunner must be used inside a RunnerProvider"); return r; }