Save, load and auto-arrange diagramsDiagram
Persist diagrams as DiagramDocument JSON, restore them with fromJSON, lay out graphs that arrive without coordinates, and keep layout results out of your change log.
A workflow editor needs three things from storage: open a saved diagram exactly as the user left it, open a graph that came from another system and has no coordinates, and save edits without flooding the server. This recipe covers all three with toJSON(), fromJSON() and layout().
Steps#
- Load the saved
DiagramDocumentwithfromJSON(). If there is none, build nodes and edges from your data and runlayout(). - Save the whole document with
toJSON(), debounced, afternodesChangeandedgesChange. - Offer an Arrange button that runs
layout()again, as one undoable step.
Open a diagram#
import { createDiagram, type DiagramDocument, type DiagramEdge, type DiagramNode } from '@birchui/diagram';
interface WorkflowStep {
id: string;
name: string;
kind: 'start' | 'task' | 'decision' | 'end';
}
interface Transition {
from: string;
to: string;
label?: string;
}
const diagram = createDiagram(document.querySelector<HTMLElement>('#workflow')!, {
ariaLabel: 'Work order approval workflow',
});
const SHAPES = { start: 'ellipse', task: 'rectangle', decision: 'diamond', end: 'ellipse' } as const;
function nodesFrom(steps: WorkflowStep[]): DiagramNode[] {
return steps.map((step) => ({
id: step.id,
label: step.name,
type: SHAPES[step.kind],
x: 0,
y: 0,
width: step.kind === 'decision' ? 120 : 168,
height: step.kind === 'decision' ? 80 : 56,
data: { kind: step.kind },
}));
}
function edgesFrom(transitions: Transition[]): DiagramEdge[] {
return transitions.map((t) => ({
id: `${t.from}->${t.to}`,
source: { node: t.from },
target: { node: t.to },
label: t.label,
}));
}
export async function openWorkflow(workflowId: string) {
const response = await fetch(`/api/workflows/${workflowId}/diagram`);
if (response.ok) {
diagram.fromJSON((await response.json()) as DiagramDocument);
return;
}
const { steps, transitions } = (await fetch(`/api/workflows/${workflowId}`).then((r) => r.json())) as {
steps: WorkflowStep[];
transitions: Transition[];
};
diagram.update({ nodes: nodesFrom(steps), edges: edgesFrom(transitions) });
await diagram.layout({ type: 'layered', direction: 'LR', spacing: { node: 36, layer: 72 } });
diagram.zoomToFit();
}fromJSON() restores nodes, edges and the saved viewport. It accepts the object or its JSON string, drops invalid entries with a warning, and leaves the current diagram untouched when the input is not a valid document.
Save edits#
let saveTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleSave(workflowId: string) {
clearTimeout(saveTimer);
saveTimer = setTimeout(async () => {
const response = await fetch(`/api/workflows/${workflowId}/diagram`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(diagram.toJSON()),
});
statusLine.textContent = response.ok ? 'All changes saved' : 'Changes could not be saved';
}, 800);
}
diagram.on('nodesChange', () => scheduleSave(workflowId));
diagram.on('edgesChange', () => scheduleSave(workflowId));The document is small and versioned:
{
"format": "birchui-diagram",
"version": 1,
"nodes": [{ "id": "submitted", "x": 0, "y": 40, "type": "ellipse", "label": "Work order submitted", "data": { "kind": "start" } }],
"edges": [{ "id": "submitted->review", "source": { "node": "submitted" }, "target": { "node": "review" } }],
"viewport": { "x": 120, "y": 80, "zoom": 1 }
}Arrange on demand#
arrangeButton.addEventListener('click', async () => {
arrangeButton.disabled = true;
await diagram.layout({ type: 'layered', direction: 'LR', animate: true });
arrangeButton.disabled = false;
});
diagram.on('nodesChange', ({ source }) => {
if (source === 'layout') auditLog.push('Diagram rearranged');
});A layout is one history entry labelled "Auto layout", so Ctrl + Z puts every node back. It emits nodesChange with source: 'layout', which the autosave above saves like any other change.
Lay out on the server#
When workflows are created by another system, compute positions once on the server with the pure layout functions and store a complete document, so every client opens it instantly:
import { runLayout, type DiagramDocument } from '@birchui/diagram';
export function workflowDocument(steps: WorkflowStep[], transitions: Transition[]): DiagramDocument {
const sizes = steps.map((step) => ({
id: step.id,
width: step.kind === 'decision' ? 120 : 168,
height: step.kind === 'decision' ? 80 : 56,
}));
const positions = runLayout(
sizes,
transitions.map((t) => ({ source: t.from, target: t.to })),
{ type: 'layered', direction: 'LR' },
);
return {
format: 'birchui-diagram',
version: 1,
nodes: sizes.map((size) => {
const step = steps.find((s) => s.id === size.id)!;
return { ...size, ...positions.get(size.id)!, label: step.name, data: { kind: step.kind } };
}),
edges: transitions.map((t) => ({ id: `${t.from}->${t.to}`, source: { node: t.from }, target: { node: t.to }, label: t.label })),
};
}Pitfalls#
fromJSON()clears the undo history, likesetNodes,setEdgesandupdate({ nodes, edges }). Load once when the editor opens, not after every save.- Keep
dataserializable. Functions, class instances andDateobjects do not surviveJSON.stringify. Store dates as ISO strings. - Framework props. Do not feed every change back into a component's
nodesandedgesprops: each new array reloads the document. See Loading and framework state. - Sizes for layout. The layout engines place nodes by
widthandheight. Give nodes their real sizes before laying out, or they will overlap.