Skip to content

State Management

All graph state lives in a single Zustand store, useGraphStore (src/store/graph-store.ts); there is no local component state for graph data. This page documents the store’s shape, how tabs are represented, how React Flow is wired to it, and the undo/redo policy.

The store holds:

  • nodes: VertexNode[], edges: GraphEdge[] — the runtime React Flow objects (the single source of truth the renderer reads).
  • mode: EditorMode — "select" | "add-vertex" | "add-edge". setMode keeps the selection on every switch; entering add-edge merges the selected vertices into pendingEdgeSources (pre-select, then switch, to seed sources), and leaving add-edge clears pendingEdgeSources.
  • pendingEdgeSources: string[] — vertex IDs staged as edge sources in Add edge mode.
  • selectedVertexType, selectedEdgeKind — the vertex type / edge kind staged for the next creation (the add-vertex and add-edge menus).
  • tabs: TabRecord[], activeTabId: string — the tab workspace. See “Tabs” below; the TabRecord type lives in graph-store.ts.
  • title, createdAt, hasHydrated — title and createdAt mirror the active tab’s name and creation time (see “Tabs” below).
  • clipboard — session-scoped, never persisted. Holds a copy/cut subgraph; ids are re-minted and positions offset by PASTE_OFFSET_STEP (24 px) per paste.
  • validationErrors — per-vertex pre-compute validation results, keyed by vertex id so each node’s renderer selects only its own slice. Ephemeral: cleared/replaced on every compute, never persisted, and excluded from the undo history (see below).
  • confirmDialogue, isHelpOpen, isIntroOpen, isExportOpen, isPropertiesOpen — UI flags kept in the store so keyboard and toolbar share one source of truth. isIntroOpen drives the first-run intro guide (see Onboarding); isExportOpen drives the export-format chooser dialog (see Graph Model § Export); isPropertiesOpen drives the graph-properties dialog.

Actions are stable references on the store; components subscribe with useGraphStore((s) => s.x) selectors, using useShallow for multi-field bundles.

The editor is multi-tab. Each TabRecord (in graph-store.ts) holds id, name (which doubles as the persisted v2 document title), nodes, edges, createdAt, a session-only viewport (pan/zoom — see Viewport & Camera), and a session-only zundo history ({ pastStates, futureStates }).

The active tab’s graph lives in the root nodes/edges/title/createdAt slices. Every existing action reads those slices, so tab records are authoritative only for inactive tabs. switchTab / addTab / closeTab are the only places data moves between the two, through activateTab:

  1. Pause the temporal store — the switch itself must not become an undo entry.
  2. Commit the outgoing tab: write the live nodes/edges and the current { pastStates, futureStates } back into its record.
  3. set the incoming tab’s slices into the root fields, resetting transient work-in-progress (mode → select, pendingEdgeSources → [], validationErrors → cleared).
  4. Install the incoming tab’s undo tree via temporal.setState({ pastStates, futureStates }), then resume.

Without the pause, tab A’s graph would land in tab B’s history and the first undo in B would resurrect A’s nodes. The swap is also why undo/redo keep working unmodified — the toolbar buttons and shortcuts read useGraphStore.temporal, which always holds the active tab’s tree.

Other tab behaviours:

  • addTab names tabs "Tab N" (next free number), copies the current camera, and activates the new tab; renameTab updates the record and mirrors the root title when the tab is active; closeTab asks confirmDialogue for non-empty tabs, never closes the last tab (it is replaced with a fresh empty one), and switches to the left neighbour when the active tab closes.
  • switchAdjacentTab backs the ⌘/Ctrl+Shift+[ / ] shortcuts.
  • The clipboard and the vertex/edge palette are workspace-wide (shared); reset clears only the active tab (keeps its name, keeps the clipboard).
  • Stale React Flow changes after a switch are no-ops by construction: xyflow emits remove changes for the ids that vanished from the nodes prop, and applyReactiveFlowChanges skips batches whose result carries the same elements as the current slice (isSameSlice) — otherwise every switch would land a spurious entry on the incoming tab’s undo stack.

React Flow runs controlled: nodes/edges come from the store, and the two change handlers route straight back into store actions:

onNodesChange: (changes) => applyReactiveFlowChanges({...}),
onEdgesChange: (changes) => applyReactiveFlowChanges({...}),

applyReactiveFlowChanges (graph-store.ts) splits a batch of React Flow changes into two streams with different undo policies — this is the crux of the undo model:

  • Structural changes (type === "remove") are applied with normal undo tracking, so deleting a node is undoable.
  • Visual changes (position, dimensions, select toggles) are applied with the temporal store paused, so they never land on the undo stack individually.

The structural stream is applied first so the visual apply sees the post-deletion slice.

Undo/redo comes from zundo’s temporal middleware, wrapped around the store:

export const useGraphStore = create<GraphStore>()(
temporal((set, get) => ({ ... }), {
partialize,
equality: (a, b) => a.nodes === b.nodes && a.edges === b.edges,
limit: 50,
}),
);
  • partialize snapshots only { nodes, edges } — UI flags, clipboard, validationErrors, title, and mode are excluded from history.
  • equality compares the partialized slice by reference on each field. This is load-bearing: Zustand set always produces a new state object, so the default Object.is would push a pastState for every set — including UI-only actions like setMode. The no-op paths of selectAllElements / clearAllSelections deliberately return the original array references to exploit this.
  • limit: 50 caps the history to 50 entries.
  • The temporal store is accessed as useGraphStore.temporal (a separate Zustand store). Toolbar undo/redo buttons subscribe to pastStates.length / futureStates.length to enable/disable themselves.

For continuous edits (dragging a vertex, dragging the rotation slider), you don’t want one undo entry per intermediate frame. The pattern, implemented in makeGestureController(), is:

  1. On gesture start — capture a pre-gesture snapshot of { nodes, edges }, then temporal.getState().pause().
  2. During the gesture — keep committing to the store (so the canvas updates live); because tracking is paused, no history entries are created.
  3. On gesture end — resume(), then manually push the pre-gesture snapshot into pastStates and clear futureStates. Undo therefore restores to the pre-gesture state.

Two gesture controllers are instantiated at module scope: dragGesture (for onNodeDragStart/onNodeDragStop) and vertexPropertyEditGesture (for the property panel’s onVertexPropertyEditStart/onVertexPropertyEditEnd). Each owns its own snapshot so overlapping gestures can’t trample each other’s pre-state. Future continuous-edit controls (slider, colour picker, etc.) should reuse this pattern rather than inventing a new one.

temporal.getState().clear() is called on:

  • hydrate() (initial load from localStorage) — every tab starts with an empty tree; undo history is session-only and is never persisted,
  • reset() (the Reset button) — clears the active tab’s tree (the live tree is the active tab’s by construction, and the tab record’s stashed tree is emptied alongside its graph).

Closing a tab also discards its stashed tree — the history dies with the tab, which is why a non-empty close asks for confirmation. Import is an exception on purpose: merging is a normal structural mutation, so it stays on the undo stack of the active tab and ⌘/Ctrl+Z removes the imported nodes (see Saving & Loading).

Pure selectors live in src/store/selectors.ts: selectSelectedNodeIds, hasSelection, and nodesById.

  • nodesById(state.nodes) returns a Map<id, VertexNode>, memoized in a module-level WeakMap keyed on the array reference — it rebuilds only when nodes changes identity, giving O(1) per-node access without rebuilding on every store update. Use this for per-id lookups, not nodes.find(...) — the .find approach made every drag O(n²), because the selector runs on every store update for every mounted vertex. VertexNode and StraightCenterEdge both read rotation through nodesById.
  • Selectors that return primitives (number, string, boolean) re-render the subscriber only when the value changes — prefer this shape for hot paths (e.g. reading a single vertex’s rotation).
  1. Add the action to the GraphStore type.
  2. Implement it in the temporal(...)({ ... }) body. If it mutates nodes/edges, prefer calling a pure helper in operations.ts and set-ing the result, so the logic is unit-testable without standing up a store.
  3. If the action is destructive or replaces the graph, decide whether to clear history (useGraphStore.temporal.getState().clear()).
  4. Components pick it up with const action = useGraphStore((s) => s.action).

See Graph Model for the document format and the persistence boundary these actions ultimately write to.