Skip to content

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).

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’s save for every tab, from the legacy saveGraphDocument, and from exportGraphJson).
  • hydrateDocument(doc) → runtime objects (called per tab from the store’s hydrate action, and on import).
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.

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:

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.

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.

  1. The WASM boundary is trivial — serde deserializes graph directly; it never has to touch React Flow types.
  2. Visual changes don’t dirty the schema — React Flow’s runtime fields (measured, internals.*, type, origin) never leak into the document.
  3. Ephemeral state is not persisted — selection (selected) and similar fields are excluded. (Pre-split, selected: true accidentally survived reloads — a latent bug the split fixes.)

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_VERSION stays 2 — 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 layout field) 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-document id). Import parses with parseDocument, not parseWorkspace — 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) → index 1
  • everything else (center-target, top) → index 0
  • absent → omitted (hydration falls back to a per-role default: source → center-source; target → top for directional vertices, center-target otherwise)

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).

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 in data.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) and black_dot (a filled dot — a phaseless Z spider, computed as z_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). With n inputs and m outputs the compute layer yields a 2^m × 2^n matrix; with no boundaries, a scalar. Boundaries must have degree ≤ 1 (validated at compute time — see Compute Layer), and carry a 0-indexed data.order per 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),
  • createGraphEdge and indexToHandleId (edge routing, via the directional flag).

Three predicates gate behaviour:

  • isSpiderType(type) — true for z, x, zbox, xbox. The single source of truth for “should this phase be parsed as a phase?” (see src/lib/phase/parser.ts). Note black_dot is not in it — its phase is forced to 0 at compute time.
  • isDirectionalVertex(type) — true for w, and. Gates the top-handle layout.
  • isBoundaryVertex(type) — true for input, 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.

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).

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 alert to 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).

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.

  • Auto-save is debounced (~2 s) in GraphEditor.tsx after nodes/edges or tabs/ activeTabId change (tab adds, renames, and switch-commits must persist too).
  • localStorage key: graph-board-document — holds the layout: "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.ts sanitizes 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.