/** * The real tree, behind the dynamic import. * * Everything that can throw at module-eval time lives here rather than in the * entry, so a throw is a caught `{ t: "error", phase: "module" }` instead of a * blank WebView. That is the whole reason this file is separate from * `NodeGraphDom.ts`. * * It renders exactly one code path: `KnobEnvelopeProvider` rebuilds the real * Preset / Surface / Intent stack out of the envelope the host serialized, and * `NodeGraphWeb` — the same component the web Storybook mounts — resolves its * own knobs from that rebuilt stack. There is no DOM-specific canvas. Design * 6.1's claim is that the rehydrated `ResolvedKnobs` deep-equals the host's, * and `envelope.spec.tsx` is what holds it to that. * * A fresh React root has no `TamaguiProvider` above it, so this file supplies * the config. It takes it as a PROP from the app's `'use dom'` entry and falls * back to whatever `createTamagui` already installed: the config is not JSON * and cannot cross the bridge, so it has to come from a module the consumer's * DOM entry imports — the same constraint that makes schemas register by id, * and the one that had this canvas dying of `Missing theme.` on both platforms * until design §9.3 was amended to say who owns the entry. */ import { getConfig } from "@tamagui/web"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { KnobEnvelopeProvider } from "../knobs/KnobEnvelopeProvider"; import { parseKnobEnvelope } from "../knobs/envelope"; import type { KnobEnvelope } from "../knobs/envelope"; import type { ConnectionVerdict, EdgeKindDefs, GraphCommand, GraphDocument, GraphSchema, NodeKindDefs, } from "../model/index"; import { getGraphSchema, parseDocument } from "../model/index"; import { demoGraphSchema } from "../react-flow/demoNodeBody"; import { demoGraphSchemaId } from "../react-flow/fixtures"; import { NodeGraphWeb } from "../react-flow/NodeGraphWeb"; import { mountedNodeCount, subscribeNodeCensus } from "../react-flow/nodeCensus"; import { GraphFaces } from "../theme/GraphFaces"; import type { GraphFaceStatus } from "../theme/GraphFaces"; import { GraphDomLayout } from "./GraphDomLayout"; import { probeRenderedFamily } from "../theme/faces"; import { xyflowVersion } from "../react-flow/xy"; import type { NodeGraphDomInnerProps, NodeGraphDomOptions } from "./NodeGraphDomShell"; import { readBootElapsedMs, graphReadySettleMs as settleGraceMs, stampBootStage } from "./boot"; import { createGraphEventEmitter, createRevEchoGate, isBenignCanvasError } from "./wire"; import type { FaceProbeWire, GraphEventWire, GraphFaceDeliveryWire } from "./wire"; // Module eval got here, which is the stage the fallback names when the failure // is further in. `faces` is stamped by `GraphFaces` in task 2.5; until that // lands, boot goes `script -> module -> provider -> flow -> ready` and the // forward-only stamp makes the skip harmless. stampBootStage("module"); type AnyDocument = GraphDocument; type AnySchema = GraphSchema; function parseOptions(json: string): NodeGraphDomOptions { try { const parsed: unknown = JSON.parse(json); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; return parsed as NodeGraphDomOptions; } catch { // Options are decoration around a canvas, never the canvas itself. A // malformed blob takes the defaults rather than the whole render. return {}; } } export function NodeGraphDomInner(props: NodeGraphDomInnerProps) { const { commands, documentJson, envelopeJson, onEvent, optionsJson, rev, schemaId } = props; const emitter = useMemo( () => createGraphEventEmitter({ send: (json) => void onEvent(json) }), [onEvent], ); useEffect(() => () => emitter.dispose(), [emitter]); const emit = useCallback((event: GraphEventWire) => emitter.emit(event), [emitter]); const gate = useRef(createRevEchoGate()).current; /** * `flow` — React Flow mounted and is reachable. Stamped from the command * bridge's own mount effect, which is the first moment that is true; it used * to be stamped by the bridge itself when the bridge lived in this file. */ const stampFlowStage = useCallback(() => { stampBootStage("flow"); }, []); const options = useMemo(() => parseOptions(optionsJson), [optionsJson]); /** * The package's own demo schema, registered HERE or nowhere. * * A schema's `render` is a component, so it cannot be JSON and cannot cross * the bridge: the only way a canvas gets one is a module the DOM BUNDLE * imports, and a DOM bundle is rooted at `NodeGraphDom.ts`. That is a real * constraint on every consumer — each app writes its own `'use dom'` entry * that imports its schema registration — but it left the package's own * `NodeGraph/NodeGraph` story with no canvas on device, because a story * cannot inject a module into a bundle rooted in this package. * * So exactly one id is special-cased, and only on a MISS. `demoNodeBody` is * reached through a dynamic import so it lands in its own chunk: a real * consumer registers their schema, never misses, and never fetches it. */ /** * The package's own demo schema, registered HERE or nowhere. * * A schema's `render` is a component, so it cannot be JSON and cannot cross * the bridge: the only way a canvas gets one is a module the DOM BUNDLE * imports, and a DOM bundle is rooted at `NodeGraphDom.ts`. That is a real * constraint on every consumer — each app writes its own `'use dom'` entry * that imports its schema registration — but it left the package's own * `NodeGraph/NodeGraph` story with no canvas on device, because a story * cannot inject a module into a bundle rooted in this package. * * Exactly one id is special-cased, and only on a MISS, so a consumer who * registers their own schema is never shadowed. * * STATIC, and it was a dynamic import until it was measured. A second * dynamic import makes Metro emit a shared `__common` chunk, and * `expo export`'s html serializer then dies with * `Asset not found: _expo/static/js/web/__common-.js` — exiting 0 and * writing nothing, which `verify-dom-bundle.mjs` catches and CI would not. * The embed build showed the chunk this bought: `demoNodeBody-.js` at * 5.6 KB. Five kilobytes is not worth a broken export. */ const demoSchema = useMemo( () => schemaId === demoGraphSchemaId ? (demoGraphSchema() as unknown as AnySchema) : undefined, [schemaId], ); /** * By id first, by value second — and BY VALUE IS NOW A LIST. * * `schemaId` is the only thing that crosses the bridge, so every mechanism * here is a lookup keyed by it. Three sources, in this order: * * 1. `registerGraphSchema`, the process-wide registry, for an app that would * rather import a registration module than thread a prop; * 2. `schemas` / `schema` from the app's own `'use dom'` entry; * 3. the package's own demo schema, only on a miss. * * `schemas` is the milestone-6 device-pass fix. The entry could supply * exactly ONE schema by value, so an app with two canvases had one that could * not render on device: measured on the iPhone 16e, `NodeGraph/Perf200` → * `Control` reported `no graph schema registered as "node-graph-demo-control"` * and painted nothing, and design §13.2 mandates that control condition in * every measurement session. * * The id MUST match. A silent substitution would render the wrong nodes and * report nothing, which is strictly worse than the fallback saying what is * missing — so this is a `Map` lookup and never a "take the first one". */ const supplied = useMemo(() => { const byId = new Map(); // The single-schema prop is written LAST so it wins a tie: an app that // passes both has said the singular one is the answer for its id. for (const candidate of [...(props.schemas ?? []), ...(props.schema ? [props.schema] : [])]) { byId.set(candidate.id, candidate as unknown as AnySchema); } return byId.get(schemaId); }, [props.schema, props.schemas, schemaId]); const schema = useMemo( () => (getGraphSchema(schemaId) as unknown as AnySchema | undefined) ?? supplied ?? demoSchema, [demoSchema, schemaId, supplied], ); const envelope = useMemo<{ value: KnobEnvelope } | { error: string }>(() => { try { return { value: parseKnobEnvelope(envelopeJson) }; } catch (error) { return { error: error instanceof Error ? error.message : String(error) }; } }, [envelopeJson]); const [document, setDocument] = useState(null); // The inbound half of echo suppression. A document whose rev this canvas // emitted itself is its own commit coming back, and applying it would fight // the drag that produced it. useEffect(() => { if (!schema) return; if (!gate.acceptInbound(rev)) return; const parsed = parseDocument(documentJson, schema, { dropUnknownKinds: options.dropUnknownKinds, }); if (parsed.ok) { setDocument(parsed.value); return; } emit({ t: "error", phase: "render", message: `document rejected: ${parsed.error.map((problem) => problem.message).join("; ")}`, }); }, [documentJson, emit, gate, options.dropUnknownKinds, rev, schema]); const onDocumentChange = useCallback( (next: AnyDocument, command: GraphCommand) => { setDocument(next); const proposed = rev + 1; gate.markEmitted(proposed); emit({ t: "commit", rev: proposed, commandsJson: JSON.stringify([command]) }); }, [emit, gate, rev], ); const onConnectionRefused = useCallback( (verdict: ConnectionVerdict) => { if (verdict.ok) return; emit({ t: "connectRefused", code: verdict.code, message: verdict.message }); }, [emit], ); /** * `window.onerror` and `unhandledrejection`, design 9.4 layer 5. * * The filter is the hard-won part: React Flow's own ResizeObserver trips its * loop notice on every layout pass, and treating that as fatal blanked the * canvas mid-drag in the gate. */ useEffect(() => { const onError = (event: ErrorEvent) => { if (isBenignCanvasError(event.message)) return; emit({ t: "error", phase: "runtime", message: event.message, stack: event.error instanceof Error ? event.error.stack : undefined, }); }; const onRejection = (event: PromiseRejectionEvent) => { const reason = event.reason; const message = reason instanceof Error ? reason.message : String(reason); if (isBenignCanvasError(message)) return; emit({ t: "error", phase: "runtime", message, stack: reason instanceof Error ? reason.stack : undefined, }); }; globalThis.addEventListener("error", onError); globalThis.addEventListener("unhandledrejection", onRejection); return () => { globalThis.removeEventListener("error", onError); globalThis.removeEventListener("unhandledrejection", onRejection); }; }, [emit]); /** * The one `createTamagui` already installed, not a new one. * * A fresh React root has no `TamaguiProvider` above it, and the config is not * JSON so it cannot cross the bridge — it has to come from a module the * consumer's DOM entry imports, the same constraint that makes schemas * register by id. `getConfig` THROWS when `createTamagui` has not run, and * `@tamagui/web`'s index does not re-export the `Maybe` variant, so the * try/catch is the supported way to ask. */ const config = useMemo(() => { if (props.config) return props.config; try { return getConfig(); } catch { return undefined; } }, [props.config]); /** * The two ways this file can refuse to render, computed rather than thrown, * so the refusal is reportable instead of a blank rectangle. */ const problem = useMemo(() => { if ("error" in envelope) return envelope.error; // Measured, not guessed: without this the first Tamagui component throws // `Missing theme.` from somewhere three components deep, and the reader has // no way to get from that to "the DOM entry never imported a config". if (!config) { return ( "no Tamagui config inside the DOM bundle — the app's `'use dom'` entry " + "must import its own tamagui config module and pass it to " + "NodeGraphDomShell as `config`, because a config is a live object and " + "cannot cross the bridge." ); } // Still fetching the chunk that would supply it. Reporting now would draw // the fallback over a canvas that is about to work. if (!schema) { return ( `no graph schema registered as ${JSON.stringify(schemaId)} — ` + "pass it to NodeGraphDomShell as `schema` or in `schemas`, or register it " + "with `registerGraphSchema` in a module BOTH the native screen and the DOM " + "entry import, because a node's `render` is a component and cannot cross " + "the bridge. An entry that renders more than one kind of canvas needs " + "`schemas`: only the id crosses." ); } return null; }, [config, envelope, schema, schemaId]); useEffect(() => { if (!problem) return; emit({ t: "error", phase: "render", message: problem }); }, [emit, problem]); /** * Design §6.3's control, run WHERE IT HAS TO RUN. * * The `FontProof` story runs the same probe, but a story renders on the * Hermes side and the canvas renders in a WebView — two font stacks, two * renderers, and only one of them is the thing AC-3 asks about. Measured on * the iPhone 16e: mounting `GraphFaces` in a native story throws * `View config getter callback for component 'style' must be a function`, * because a `