Graph Model
This page documents the data model: the runtime objects React Flow consumes, the persisted
document format, and the conversion between them. The source of truth for these types is
src/lib/graph/types.ts (a barrel over src/lib/graph/type/ — editor-types.ts,
vertex-types.ts, edge-types.ts); the registries and behaviour predicates live in
src/lib/graph/vertex-registry.ts and src/lib/graph/edge-registry.ts; the conversion logic is
in src/lib/serialisation/ (document.ts, parse.ts).
Two layers, one model
Section titled “Two layers, one model”There are two representations of the same graph, kept deliberately separate:
| Layer | Type | Lives in | Contains |
|---|---|---|---|
| Runtime | VertexNode, GraphEdge |
the store + React Flow | Position, React Flow plumbing, selected, rotation, visual label/labelLocation |
| Persisted | GraphDocument ({ graph, view }, schema v2) |
localStorage + JSON files |
Only stable, meaningful data |
The runtime layer holds React Flow’s own object types, with everything the renderer needs at
runtime. The persisted layer is the contract that crosses the serialization boundary — and
the WASM compute boundary, since the compute layer consumes doc.graph directly. Conversion
happens only in src/lib/serialisation/, via two functions:
projectToDocument(runtime)→GraphDocument(called from the store’ssavefor every tab, from the legacysaveGraphDocument, and fromexportGraphJson).hydrateDocument(doc)→ runtime objects (called per tab from the store’shydrateaction, and on import).
Runtime types
Section titled “Runtime types”type VertexData = { phase: string; // phase expression — compute input for spider types vertexType: VertexType; order?: number; // boundary axis order (input/output only), 0-indexed};
// React Flow Node, plus the view-slice fields that ride outside `data`.type VertexNode = Node<VertexData, "vertex"> & { rotation: number; // degrees, CSS-only label: string; // visual annotation; "" = not shown labelLocation: LabelLocation; // "top" | "bottom" | "left" | "right" | "none"};
type GraphEdge = Edge<{ kind: EdgeKind }>; // kind lives in `data` (graph slice)rotation, label, and labelLocation live outside data deliberately: they are visual
concerns and belong in the view slice, not in VertexData (which is part of the graph slice
that the compute layer consumes). phase was called label in schema v1 — the v1→v2 migration
in src/lib/serialisation/parse.ts renames data.label → data.phase on load/import.
The persisted document (v2)
Section titled “The persisted document (v2)”type GraphDocument = { schemaVersion: number; // CURRENT_SCHEMA_VERSION = 2 id: string; // PERSISTED_IDS: "local-document" | "exported-document" title: string; graph: GraphSlice; // graph-theoretic only view: ViewSlice; // visual only createdAt: string; // stamped once, survives across saves updatedAt: string; // stamped on save};The document is split into two parallel slices, keyed by the same node/edge ids:
graph — graph-theoretic only
Section titled “graph — graph-theoretic only”type GraphSlice = { nodes: { id: string; data: { phase: string; vertexType: VertexType; order?: number }; }[]; edges: { id: string; source: string; target: string; sourceHandle?: number; targetHandle?: number; data?: { kind?: EdgeKind }; }[];};This is what computation (and any external researcher’s tooling) consumes: nothing visual,
nothing React-Flow-shaped. sourceHandle / targetHandle are numeric indices (0 = top,
1 = bottom), not React Flow handle-id strings. order is the 0-indexed boundary-axis order
(input and output ordered independently) that fixes the final axis order of the contracted
tensor (Rust plan §5.4). data.kind is the edge kind — additive-optional: legacy docs hydrate
to default.
view — visual only
Section titled “view — visual only”type ViewSlice = { nodes: { id: string; position: { x; y }; rotation?: number; // degrees label?: string; // KaTeX-enabled visual annotation labelLocation?: LabelLocation; // "top" | "bottom" | "left" | "right" | "none" }[]; edges: { id: string }[];};Position, rotation, and the visual label today; future edge curvature, group colours, and edge
labels go here. The renderer rebuilds runtime objects by joining graph + view on node/edge
id.
Why the split?
Section titled “Why the split?”- The WASM boundary is trivial —
serdedeserializesgraphdirectly; it never has to touch React Flow types. - Visual changes don’t dirty the schema — React Flow’s runtime fields (
measured,internals.*,type,origin) never leak into the document. - Ephemeral state is not persisted — selection (
selected) and similar fields are excluded. (Pre-split,selected: trueaccidentally survived reloads — a latent bug the split fixes.)
The tabs workspace (storage layout)
Section titled “The tabs workspace (storage layout)”The editor is multi-tab, but the document format is unchanged: each tab is a plain v2
GraphDocument, with the tab name stored as the document’s title and the tab id as the
document’s id. localStorage["graph-board-document"] therefore holds a wrapper — a storage
layout, not a schema version:
type TabsStorageLayout = { layout: "tabs"; activeTabId: string; tabs: { id: string; document: GraphDocument }[];};The wrapper types live in src/lib/graph/type/editor-types.ts (GraphWorkspace,
TabsStorageLayout, with STORAGE_LAYOUT_TABS as the discriminator) and are read/written by
parseWorkspace / saveGraphWorkspace / loadGraphWorkspace in src/lib/serialisation/. Points
worth knowing:
CURRENT_SCHEMA_VERSIONstays2— the graph/view shape did not change, and the per-document v1→v2 migration still runs for every tab.- Legacy payloads (a bare v1/v2 document with no
layoutfield) load as a one-tab workspace keyed by the document’s own id — old saved data keeps working. - Export never emits the wrapper:
exportGraph("json")writes a single v2 document for the active tab (mean-centered,exported-documentid). Import parses withparseDocument, notparseWorkspace— a wrapper is not a graph, so importing one fails with a clear message. - The per-tab undo histories and camera viewports are session-only — the wrapper carries only the documents.
Handles: runtime ids ↔ persisted indices
Section titled “Handles: runtime ids ↔ persisted indices”React Flow handle ids are centralised in type/vertex-types.ts:
export const HANDLE_IDS = { centerSource: "center-source", // transparent overlay at the body centre, source slot centerTarget: "center-target", // transparent overlay at the body centre, target slot top: "top", // visible dot, directional target} as const;These are the contract between the edge layer (createGraphEdge in operations.ts), the
serializer, and the renderer (VertexNode, StraightCenterEdge) — no string literals elsewhere.
On the persisted side, handles become numeric indices via handleIdToIndex /
indexToHandleId in src/lib/serialisation/document.ts:
center-source(the bottom source slot) → index1- everything else (
center-target,top) → index0 - absent → omitted (hydration falls back to a per-role default: source →
center-source; target →topfor directional vertices,center-targetotherwise)
Directional vertices (W, And gate) use the top handle for incoming edges; indexToHandleId
reconstructs the right id at hydration time using the target vertex’s directional flag
(consulted from VERTEX_TYPE_MAP).
Vertex types
Section titled “Vertex types”type VertexType = | "z" | "empty" | "x" | "w" | "h" | "zbox" | "xbox" | "and" | "black_dot" | "input" | "output";Eleven types, grouped by role:
- Spiders (phase-bearing,
isSpiderType) —z,x,zbox,xbox. The phase expression lives indata.phase. - Directional (
isDirectionalVertex) —w(the copy generator),and(the And gate). One input at the top, fan-out outputs at the bottom. - Boxes (fixed arity) —
h, the Hadamard box, always arity 2. - Plain markers —
empty(isolated → scalar 1, wired → identity) andblack_dot(a filled dot — a phaseless Z spider, computed asz_spider(arity, 0); its label is decoration only). - Boundary (
isBoundaryVertex) —input,output: not tensors, but vertices that declare the open legs of the resulting tensor (each leg dimension 2). Withninputs andmoutputs the compute layer yields a2^m × 2^nmatrix; with no boundaries, a scalar. Boundaries must have degree ≤ 1 (validated at compute time — see Compute Layer), and carry a 0-indexeddata.orderper type group that fixes the result’s axis order.
VERTEX_TYPES / VERTEX_TYPE_MAP in src/lib/graph/vertex-registry.ts is the single source
of truth for each type’s shape, colour, size, default phase, glyph, and directional flag.
Consumers:
VertexNode(renderer),VertexSwatch,VertexTypeMenu,VertexPropertyPanel(UI),createGraphEdgeandindexToHandleId(edge routing, via thedirectionalflag).
Three predicates gate behaviour:
isSpiderType(type)—trueforz,x,zbox,xbox. The single source of truth for “should this phase be parsed as a phase?” (seesrc/lib/phase/parser.ts). Noteblack_dotis not in it — its phase is forced to 0 at compute time.isDirectionalVertex(type)—trueforw,and. Gates the top-handle layout.isBoundaryVertex(type)—trueforinput,output. Gates the degree-≤-1 rule and the open-leg declaration consumed by the compute layer.
When adding or changing a vertex type, edit VERTEX_TYPES and these three predicates only —
every consumer picks up the change.
Phases and the visual label
Section titled “Phases and the visual label”For spider/box types (isSpiderType === true) the graph-slice data.phase carries the phase
expression, not a free-form name. For the other types the phase is decoration only.
- A phase wrapped in
$...$or$$...$$is rendered with KaTeX (src/lib/label/renderLabel.ts) and parsed as a phase (src/lib/phase/parser.ts). Anything else renders as plain text. - An empty phase on a spider means phase 0 (identity).
- Phase grammar (v1, numeric only): numbers,
\pi/π/pi/PI,+ - * / ( ), unary+/-; the Unicode−(U+2212),×(U+00D7),÷(U+00F7) are accepted as- * /. Free variables (\alpha, …) are errors in v1; symbolic arithmetic is Phase 6.
The visual label is separate and lives in the view slice (NodeView.label +
labelLocation, runtime fields node.label / node.labelLocation — like rotation). It is a
KaTeX-enabled annotation shown near the node (default location: top); purely visual — the compute
layer never sees it.
The Rust compute layer ports the same grammar (crates/zxw/src/phase.rs) so phases parse
identically on both sides of the WASM boundary; the shared fixture
crates/zxw/tests/fixtures/phase_grammar.json pins it (see
Labels & Phases).
Parsing and validation
Section titled “Parsing and validation”parseDocument in src/lib/serialisation/parse.ts validates the v2 { graph, view } shape. It is
shared by the import path (importGraphJson) and by parseWorkspace — the load path, which accepts
either a tabs wrapper or a legacy single document (see “The tabs workspace” above) — so the two
paths can’t drift in robustness. Both return a discriminated { ok, ... } result rather than
throwing, so callers pick their own failure policy:
- Load is soft: a corrupt or future-schema document logs a warning and falls back to an empty document (never crashes the editor on reload).
- Import is loud: a bad file — or one whose node/edge elements are structurally broken —
surfaces an
alertto the user and leaves the current graph untouched.
Forward-incompatible schemaVersion values are rejected explicitly rather than silently accepted.
The v1→v2 migration renames data.label → data.phase (preserving order and other optional
fields). When the document shape changes again, bump CURRENT_SCHEMA_VERSION and add a migration
step in parse.ts (parseDocument runs it for both the load and import paths).
Export formats
Section titled “Export formats”The Export toolbar button opens a format chooser (ExportDialog, driven by isExportOpen in
the store). The chooser lists every format registered in EXPORT_FORMATS
(src/lib/serialisation/formats.ts) — the registry is the single source of truth for a format’s
label, description, file extension, and MIME type:
| Format | Extension | Status |
|---|---|---|
json |
.json |
Implemented — the native { graph, view } v2 document (see above). |
tikz |
.tikz |
Implemented — LaTeX tikzpicture (see Saving & Loading for embedding it in a document). |
zxlive |
.zxlive |
Placeholder — spec TBD. |
QASM |
.qasm |
Placeholder — spec TBD. |
exportGraph(formatId) (store action) resolves the format via getExportFormat, calls its
serialize(params) (the per-format serializers live one file per format in
src/lib/serialisation/export-*.ts), and hands the resulting string to saveTextFileWithPicker
(src/lib/download.ts). Placeholder serializers share placeholder.ts — they emit a
clearly-marked non-empty file so the picker flow works end-to-end before the real spec lands.
Persistence gotchas
Section titled “Persistence gotchas”- Auto-save is debounced (~2 s) in
GraphEditor.tsxafternodes/edgesortabs/activeTabIdchange (tab adds, renames, and switch-commits must persist too). localStoragekey:graph-board-document— holds thelayout: "tabs"wrapper (see above).- All storage functions guard
typeof window === "undefined"for SSR safety. - JSON export (
exportGraph("json")→exportGraphJson→download.ts) prefers the File System Access API (window.showSaveFilePicker) and falls back to an anchor-download.filename.tssanitizes the title into a safe filename. - Import merges into the active tab’s graph: existing nodes/edges are kept, colliding
imported ids are re-minted (and their edges remapped), dangling edges are dropped, and every
imported position is offset by
IMPORT_OFFSET_STEP(48) plus the viewport centre and left selected. It stays on the undo stack (undo removes the merge) and relies on the debounced autosave rather than persisting immediately. The active tab keeps its own id and name regardless of the imported file’s.
See Contributing for the conventions and gotchas that apply when editing any of this.