Diagram overviewDiagram
A flow and diagram editor for the browser with ports, orthogonal routing, auto-layout, groups and swimlanes, undo and redo, and SVG, PNG and JSON export.
Birch UI Diagram is an editor for flowcharts, approval workflows, network topologies, org charts and any other node-and-edge drawing. Users drag nodes, connect them from ports, edit labels in place and undo their mistakes. Your code loads and saves plain JSON, lays graphs out automatically and exports them as SVG or PNG.
It is written in plain TypeScript, renders to SVG with an HTML layer for rich node templates, and stays responsive with thousands of nodes. Like every Birch UI component it follows the shared widget contract, so it works in any framework.
Loading demo…
View source
Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.
import { createDiagram, type DiagramEdge, type DiagramNode, type LayoutDirection } from '@birchui/diagram';
import { button, docsTheme, field, layout, onDocsThemeChange } from './_shared';
export const meta = { title: 'Order fulfilment flow', height: 560 };
interface Step {
team: string;
}
const steps: [string, string, string, string][] = [
['received', 'Order received', 'ellipse', 'Storefront'],
['payment', 'Payment authorised?', 'diamond', 'Finance'],
['hold', 'Hold and notify customer', 'rounded', 'Support'],
['stock', 'In stock?', 'diamond', 'Warehouse'],
['backorder', 'Create backorder', 'rounded', 'Purchasing'],
['pick', 'Pick and pack', 'rounded', 'Warehouse'],
['label', 'Print shipping label', 'rounded', 'Warehouse'],
['ship', 'Hand over to carrier', 'rounded', 'Logistics'],
['invoice', 'Send invoice', 'document', 'Finance'],
['done', 'Order complete', 'ellipse', 'Storefront'],
];
const links: [string, string, string?][] = [
['received', 'payment'],
['payment', 'stock', 'Yes'],
['payment', 'hold', 'No'],
['stock', 'pick', 'Yes'],
['stock', 'backorder', 'No'],
['backorder', 'pick', 'Restocked'],
['pick', 'label'],
['label', 'ship'],
['ship', 'invoice'],
['invoice', 'done'],
];
function makeNodes(): DiagramNode<Step>[] {
return steps.map(([id, label, type, team], index) => ({
id,
label,
type,
x: (index % 3) * 220,
y: Math.floor(index / 3) * 140,
width: type === 'diamond' ? 170 : 180,
height: type === 'diamond' ? 90 : 60,
data: { team },
}));
}
function makeEdges(): DiagramEdge[] {
return links.map(([source, target, label], index) => ({
id: `e${index + 1}`,
source: { node: source },
target: { node: target },
label,
}));
}
export default function mount(el: HTMLElement): () => void {
const { toolbar, body, status } = layout(el);
const direction = document.createElement('select');
for (const [value, text] of [
['TB', 'Top to bottom'],
['LR', 'Left to right'],
]) {
direction.add(new Option(text, value));
}
const diagram = createDiagram<Step>(body, {
nodes: makeNodes(),
edges: makeEdges(),
defaultEdge: { router: 'orthogonal', markerEnd: 'arrow' },
grid: true,
guides: true,
minimap: true,
controls: true,
fitOnInit: true,
theme: docsTheme(),
ariaLabel: 'Order fulfilment flow',
});
const runLayout = () => {
status.textContent = 'Laying out…';
diagram
.layout({ type: 'layered', direction: direction.value as LayoutDirection, spacing: 48, animate: true })
.then(() => {
diagram.zoomToFit({ padding: 24 });
status.textContent = `Auto-layout applied (${direction.value}).`;
})
.catch((error: Error) => {
status.textContent = `Layout failed: ${error.message}`;
});
};
const undo = button('Undo', () => diagram.undo());
const redo = button('Redo', () => diagram.redo());
undo.disabled = redo.disabled = true;
toolbar.append(
field('Direction', direction),
button('Auto-layout', runLayout),
button('Fit', () => diagram.zoomToFit({ padding: 24 })),
undo,
redo,
);
const offs = [
diagram.on('nodeClick', ({ node }) => {
status.textContent = `${node.label ?? node.id} (owner: ${node.data?.team ?? 'unassigned'})`;
}),
diagram.on('connect', ({ source, target }) => {
status.textContent = `Connected ${source.node} to ${target.node}.`;
}),
diagram.on('historyChange', ({ canUndo, canRedo, undoLabel }) => {
undo.disabled = !canUndo;
redo.disabled = !canRedo;
if (undoLabel) status.textContent = `Last change: ${undoLabel}`;
}),
];
status.textContent = 'Drag steps, connect ports, or press Auto-layout.';
runLayout();
const stopTheme = onDocsThemeChange((theme) => diagram.update({ theme }));
return () => {
for (const off of offs) off();
stopTheme();
diagram.destroy();
};
}What it does#
- Nodes, edges, ports and groups: ten built-in shapes, including decisions, databases, documents, swimlanes and collapsible groups. See Nodes and edges.
- Custom node templates that return SVG or HTML, so a node can be a person card, a server tile or a form. See Node templates.
- Routing: orthogonal routes that avoid other nodes, straight lines and curves. See Routing.
- Auto-layout: layered (top-to-bottom or left-to-right), tree, force-directed and grid, also usable without a diagram on the page. See Layout.
- Editing: pan and zoom, a minimap, grid snapping and alignment guides, drag-to-connect with validation, inline labels, undo and redo, copy and paste, and a read-only mode. See Interaction.
- Files: JSON documents for saving, SVG and PNG for sharing. See Serialization and export.
- Scale: only visible items are in the DOM, and very large views switch to a lightweight overview drawing. See Performance.
- Accessibility: every node is focusable, everything works from the keyboard, and a list view presents the whole diagram as nested lists. See Keyboard and accessibility.
Install#
npm install @birchui/diagramThe package depends on @birchui/core and @birchui/license, which npm installs for you. Styles are injected the first time a diagram is created. To ship the CSS yourself, pass injectStyles: false and import it:
import '@birchui/diagram/styles.css';Create a diagram#
createDiagram(container, options) renders into an element you own and returns the diagram API. Every option is optional; with none you get an empty canvas the user can pan and zoom.
import { createDiagram, type DiagramEdge, type DiagramNode } from '@birchui/diagram';
const step = (id: string, label: string, type = 'rounded'): DiagramNode => ({ id, type, x: 0, y: 0, label });
const flow = (source: string, target: string, label?: string): DiagramEdge => ({
id: `${source}-${target}`,
source: { node: source },
target: { node: target },
label,
});
const diagram = createDiagram(document.getElementById('purchase-approval')!, {
ariaLabel: 'Purchase approval workflow',
height: 560,
nodes: [
step('request', 'Purchase request', 'ellipse'),
step('amount', 'Over $5,000?', 'diamond'),
step('manager', 'Manager approval'),
step('finance', 'Finance approval'),
step('erp', 'ERP purchase order', 'cylinder'),
step('order', 'Order placed', 'ellipse'),
],
edges: [
flow('request', 'amount'),
flow('amount', 'manager', 'no'),
flow('amount', 'finance', 'yes'),
flow('finance', 'manager', 'approved'),
flow('manager', 'erp', 'approved'),
flow('erp', 'order'),
],
validateConnection: ({ target }) => target.node !== 'request',
});
await diagram.layout({ type: 'layered', direction: 'LR', spacing: { node: 36, layer: 72 } });
diagram.zoomToFit({ maxZoom: 1 });
diagram.on('nodesChange', ({ changes, source }) => {
if (source === 'user') saveDraft(diagram.toJSON());
});The nodes start at 0, 0 because the layout places them. When your data already has coordinates, pass them and skip layout().
The widget contract#
createDiagram returns a DiagramApi, which includes the four members every Birch UI component shares:
| Member | What it does |
|---|---|
element |
The diagram's root element. |
update(partial) |
Applies only the options you pass, without recreating the diagram. |
on(event, listener) |
Subscribes to one of the 11 events and returns an unsubscribe function. Payloads are always objects. |
destroy() |
Removes the DOM and releases every listener, observer and animation frame. |
diagram.update({ readOnly: true, theme: 'dark' });
const stop = diagram.on('connect', ({ edge, isReconnect }) => {
console.info(`${isReconnect ? 'Reconnected' : 'Connected'} ${edge.source.node} to ${edge.target.node}`);
});
stop();
diagram.destroy();The API adds model editing (addNodes, updateNode, removeEdges), selection, history (undo, redo), viewport control (zoomToFit, centerOn), layout() and the file methods (toJSON, fromJSON, toSVG, toPNG). See API and events.
Activate your license#
Set the key once for every Birch UI widget on the page, before the first diagram is created, or pass it per instance:
import { setLicenseKey } from '@birchui/license';
setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE);createDiagram(container, { ...options, licenseKey: 'LQ1.…' });The diagram checks the key for the diagram product and passes its root element as the watermark host. Verification happens in the browser with no network call. A missing or invalid key never disables anything: it adds a small watermark to the diagram and logs one console warning, and on localhost the watermark is skipped. Changing licenseKey through update() re-checks it.
| Tier | Price, one-time |
|---|---|
| Developer (one named developer) | $399 |
| Team (up to 5 developers) | $1,499 |
| Company (unlimited developers) | $3,999 |
Birch UI Diagram is also included in Birch UI Complete. Colleagues who only build or deploy the app need no seat. See Pricing and Licensing and activation.
Use it in your framework#
The framework adapters do not ship a diagram component, but each exports the generic factory its own components are built with. Pass it diagramDefinition (tag name birchui-diagram) and you get a component that creates the diagram on mount, sends changed props to update() and forwards all 11 events.
import { createDiagram } from '@birchui/diagram';
const diagram = createDiagram(document.getElementById('network')!, { nodes, edges, height: 600 });
diagram.on('nodesChange', ({ source }) => {
if (source === 'user') saveTopology(diagram.toJSON());
});import { createReactComponent } from '@birchui/react';
import { diagramDefinition } from '@birchui/diagram';
export const BirchDiagram = createReactComponent(diagramDefinition);
export function NetworkMap({ nodes, edges }: NetworkMapProps) {
return (
<BirchDiagram
nodes={nodes}
edges={edges}
height={600}
onConnect={({ edge }) => saveLink(edge)}
/>
);
}<script setup lang="ts">
import { createVueComponent } from '@birchui/vue';
import { diagramDefinition, type DiagramEdge, type DiagramEvents, type DiagramNode } from '@birchui/diagram';
const BirchDiagram = createVueComponent(diagramDefinition);
defineProps<{ nodes: DiagramNode[]; edges: DiagramEdge[] }>();
function onConnect({ edge }: DiagramEvents['connect']) {
saveLink(edge);
}
</script>
<template>
<BirchDiagram :nodes="nodes" :edges="edges" :height="600" @connect="onConnect" />
</template>import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { injectBirchWidget, withOverrides, type WidgetOutputs } from '@birchui/angular';
import { diagramDefinition, type DiagramApi, type DiagramEvents, type DiagramOptions } from '@birchui/diagram';
@Component({
selector: 'app-diagram',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '',
styles: ':host { display: block; height: 600px; }',
})
export class DiagramComponent implements WidgetOutputs<DiagramEvents> {
readonly options = input<DiagramOptions>({});
readonly nodes = input<DiagramOptions['nodes']>();
readonly edges = input<DiagramOptions['edges']>();
readonly ready = output<DiagramEvents['ready']>();
readonly nodeClick = output<DiagramEvents['nodeClick']>();
readonly nodeDoubleClick = output<DiagramEvents['nodeDoubleClick']>();
readonly edgeClick = output<DiagramEvents['edgeClick']>();
readonly selectionChange = output<DiagramEvents['selectionChange']>();
readonly nodesChange = output<DiagramEvents['nodesChange']>();
readonly edgesChange = output<DiagramEvents['edgesChange']>();
readonly connect = output<DiagramEvents['connect']>();
readonly viewportChange = output<DiagramEvents['viewportChange']>();
readonly contextMenu = output<DiagramEvents['contextMenu']>();
readonly historyChange = output<DiagramEvents['historyChange']>();
private readonly widget = injectBirchWidget(diagramDefinition, this, () =>
withOverrides<DiagramOptions>(this.options(), { nodes: this.nodes(), edges: this.edges() }),
);
get api(): DiagramApi | undefined {
return this.widget.instance;
}
}<script lang="ts">
import { createSvelteAction } from '@birchui/svelte';
import { diagramDefinition, type DiagramApi, type DiagramEdge, type DiagramNode } from '@birchui/diagram';
const birchDiagram = createSvelteAction(diagramDefinition);
let { nodes, edges }: { nodes: DiagramNode[]; edges: DiagramEdge[] } = $props();
let api: DiagramApi | null = $state.raw(null);
</script>
<div
style="height: 600px"
use:birchDiagram={{
nodes,
edges,
on: { connect: ({ edge }) => saveLink(edge) },
onReady: (diagram) => (api = diagram),
}}
></div>import { createSolidComponent } from '@birchui/solid';
import { diagramDefinition } from '@birchui/diagram';
export const BirchDiagram = createSolidComponent(diagramDefinition);
export function NetworkMap(props: NetworkMapProps) {
return <BirchDiagram nodes={props.nodes} edges={props.edges} height={600} onConnect={({ edge }) => saveLink(edge)} />;
}<birchui-diagram id="network" height="600"></birchui-diagram>
<script type="module">
import { createElementClass } from '@birchui/element';
import { diagramDefinition } from '@birchui/diagram';
customElements.define(
'birchui-diagram',
createElementClass(diagramDefinition, {
optionKeys: ['nodes', 'edges', 'nodeTypes', 'readOnly'],
attributes: { height: 'number', theme: 'string', 'aria-label': 'string' },
requiredOptions: [],
}),
);
const diagram = document.getElementById('network');
diagram.nodes = nodes;
diagram.edges = edges;
diagram.addEventListener('nodes-change', ({ detail }) => saveTopology(diagram.api.toJSON(), detail));
</script>Notes per adapter:
- React and Solid: options are props, events are
on…props (onNodesChange,onConnect), andrefgives you theDiagramApi. - Vue: pass options as attributes or an
optionsobject. Events are kebab-case (@nodes-change,@connect). The component exposesapi. - Angular:
injectBirchWidgetneeds one output per event, so the wrapper declares all 11. Give the host element a height. - Svelte:
createSvelteActiongives you an action. Its parameter is the options pluson(handlers keyed by event name) andonReady. - Web Component:
createElementClassturns the definition into a custom element:optionKeysbecome properties,attributesare observed and converted to camelCase, andrequiredOptions: []creates the diagram as soon as the element is connected. Events are kebab-caseCustomEvents with the payload indetail, andelement.apiis theDiagramApi.
Passing new nodes or edges arrays through any adapter calls update({ nodes, edges }), which loads a new document and clears the undo history. Keep the arrays stable while the user edits, read changes from nodesChange and edgesChange, and replace them only when you load a different diagram. See Saving to a backend.
Next steps#
- Nodes and edges: the data model.
- Layout: arrange a graph automatically.
- Interaction: what users can do, and how to restrict it.
- Serialization and export: save, load and export.