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.
Store shape
Section titled “Store shape”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".setModekeeps the selection on every switch; enteringadd-edgemerges the selected vertices intopendingEdgeSources(pre-select, then switch, to seed sources), and leavingadd-edgeclearspendingEdgeSources.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; theTabRecordtype lives ingraph-store.ts.title,createdAt,hasHydrated—titleandcreatedAtmirror 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 byPASTE_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.isIntroOpendrives the first-run intro guide (see Onboarding);isExportOpendrives the export-format chooser dialog (see Graph Model § Export);isPropertiesOpendrives 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:
- Pause the temporal store — the switch itself must not become an undo entry.
- Commit the outgoing tab: write the live
nodes/edgesand the current{ pastStates, futureStates }back into its record. setthe incoming tab’s slices into the root fields, resetting transient work-in-progress (mode→ select,pendingEdgeSources→[],validationErrors→ cleared).- 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:
addTabnames tabs"Tab N"(next free number), copies the current camera, and activates the new tab;renameTabupdates the record and mirrors the roottitlewhen the tab is active;closeTabasksconfirmDialoguefor 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.switchAdjacentTabbacks the⌘/Ctrl+Shift+[/]shortcuts.- The clipboard and the vertex/edge palette are workspace-wide (shared);
resetclears only the active tab (keeps its name, keeps the clipboard). - Stale React Flow changes after a switch are no-ops by construction: xyflow emits
removechanges for the ids that vanished from thenodesprop, andapplyReactiveFlowChangesskips 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.
Controlled React Flow
Section titled “Controlled React Flow”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 via zundo
Section titled “Undo / redo via zundo”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, }),);partializesnapshots only{ nodes, edges }— UI flags, clipboard,validationErrors,title, andmodeare excluded from history.equalitycompares the partialized slice by reference on each field. This is load-bearing: Zustandsetalways produces a new state object, so the defaultObject.iswould push a pastState for everyset— including UI-only actions likesetMode. The no-op paths ofselectAllElements/clearAllSelectionsdeliberately return the original array references to exploit this.limit: 50caps the history to 50 entries.- The temporal store is accessed as
useGraphStore.temporal(a separate Zustand store). Toolbar undo/redo buttons subscribe topastStates.length/futureStates.lengthto enable/disable themselves.
The gesture-controller pattern
Section titled “The gesture-controller pattern”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:
- On gesture start — capture a pre-gesture snapshot of
{ nodes, edges }, thentemporal.getState().pause(). - During the gesture — keep committing to the store (so the canvas updates live); because tracking is paused, no history entries are created.
- On gesture end —
resume(), then manually push the pre-gesture snapshot intopastStatesand clearfutureStates. 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.
When history is cleared
Section titled “When history is cleared”temporal.getState().clear() is called on:
hydrate()(initial load fromlocalStorage) — 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).
Selectors
Section titled “Selectors”Pure selectors live in src/store/selectors.ts: selectSelectedNodeIds, hasSelection, and
nodesById.
nodesById(state.nodes)returns aMap<id, VertexNode>, memoized in a module-levelWeakMapkeyed on the array reference — it rebuilds only whennodeschanges identity, giving O(1) per-node access without rebuilding on every store update. Use this for per-id lookups, notnodes.find(...)— the.findapproach made every drag O(n²), because the selector runs on every store update for every mounted vertex.VertexNodeandStraightCenterEdgeboth read rotation throughnodesById.- 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).
Adding a new store action
Section titled “Adding a new store action”- Add the action to the
GraphStoretype. - Implement it in the
temporal(...)({ ... })body. If it mutatesnodes/edges, prefer calling a pure helper inoperations.tsandset-ing the result, so the logic is unit-testable without standing up a store. - If the action is destructive or replaces the graph, decide whether to clear history
(
useGraphStore.temporal.getState().clear()). - 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.