# Diagram API and events

> Every option, method, event and exported function of Birch UI Diagram, with defaults and payloads.

This page is the complete reference for `@birchui/diagram`. The generated type reference is on the [package API page](https://docs.birchui.com/api/diagram.md).

```ts
import {
  createDiagram,
  diagramDefinition,
  DIAGRAM_EVENT_NAMES,
  diagramStyles,
  BUILT_IN_SHAPES,
  BUILT_IN_TYPES,
  FOUR_PORTS,
  layeredLayout,
  treeLayout,
  forceLayout,
  gridLayout,
  runLayout,
  routeOrthogonal,
  SpatialIndex,
} from '@birchui/diagram';
```

| Export | Description |
| --- | --- |
| `createDiagram(container, options?)` | Renders a diagram into `container` and returns a `DiagramApi`. Throws a `TypeError` when `container` is not an element or `options` is not an object. |
| `diagramDefinition` | The widget definition (name `BirchDiagram`, tag `birchui-diagram`, factory and the 11 events) for the adapters' generic factories. See [Use it in your framework](https://docs.birchui.com/diagram/overview.md#use-it-in-your-framework). |
| `DIAGRAM_EVENT_NAMES` | The list of event names. |
| `diagramStyles` | The stylesheet as a string. |
| `BUILT_IN_TYPES`, `BUILT_IN_SHAPES`, `FOUR_PORTS` | Built-in type names, their default sizes and shapes, and the default port set. |
| `layeredLayout`, `treeLayout`, `forceLayout`, `gridLayout`, `runLayout` | Standalone layout engines. See [Layout](https://docs.birchui.com/diagram/layout.md#standalone-layout-functions). |
| `routeOrthogonal` | The standalone orthogonal router. See [Routing](https://docs.birchui.com/diagram/routing.md#the-router-on-its-own). |
| `SpatialIndex` | The grid-based spatial index used for viewport and hit-test queries. |

`createDiagram<TNodeData, TEdgeData>` is generic over the `data` of your nodes and edges, which types every node, edge, payload and template argument.

## Options

Pass options to `createDiagram`, or change them later with `update(partial)`. All options are optional. An invalid value logs one console warning and the default is used.

### Model

| Option | Default | Description |
| --- | --- | --- |
| `nodes` | `[]` | Nodes. See [Nodes and edges](https://docs.birchui.com/diagram/nodes-and-edges.md). Changing it with `update()` loads a new document and clears the history. |
| `edges` | `[]` | Edges. Same rule as `nodes`. |
| `nodeTypes` | `{}` | Custom node types. See [Node templates](https://docs.birchui.com/diagram/node-templates.md). |
| `defaultNodeType` | `'rounded'` | Type for nodes without `type`. |
| `defaultEdge` | `{ router: 'orthogonal', markerEnd: 'arrow', markerStart: 'none' }` | Defaults for `router`, `markerEnd`, `markerStart` and `style` of every edge. |
| `createId` | `'node-1'`, `'edge-1'`, … | `(kind: 'node' \| 'edge') => string` for ids of pasted nodes and new edges. |

### Viewport and canvas

| Option | Default | Description |
| --- | --- | --- |
| `viewport` | fitted | Initial `{ x, y, zoom }`. |
| `fitOnInit` | `true` | Fit the initial nodes on screen (up to 100%) when no `viewport` is given. |
| `minZoom`, `maxZoom` | `0.05`, `4` | Zoom limits. |
| `width`, `height` | from the container | Fixed size in pixels. |
| `grid` | dots every 20 units, snapping on | `false`, `true` or `{ size, style: 'dots' \| 'lines' \| 'none', snap }`. |
| `guides` | `true` | Alignment guides while moving and resizing. |
| `minimap` | `true` | Show the minimap. |
| `controls` | `true` | Show the toolbar. |
| `listView` | `false` | Show the list view instead of the canvas. |
| `wheelMode` | `'zoom'` | `'zoom'` or `'pan'`. See [Wheel mode](https://docs.birchui.com/diagram/interaction.md#wheel-mode-and-background-drag). |
| `backgroundDrag` | `'pan'` | `'pan'` or `'marquee'`. |
| `overviewThreshold` | `1200` | Visible node count above which the overview drawing is used. See [Performance](https://docs.birchui.com/diagram/performance.md#overview-mode). |

### Editing

| Option | Default | Description |
| --- | --- | --- |
| `readOnly` | `false` | Block every user edit. The API keeps working. |
| `validateConnection` | none | `({ source, target, edgeId? }) => boolean`; return `false` to refuse a connection. |
| `historyLimit` | `200` | Undo steps kept. |
| `routing` | `{ padding: 16, bendPenalty: 24, cornerRadius: 6 }` | Orthogonal routing settings. See [Routing](https://docs.birchui.com/diagram/routing.md#the-orthogonal-router). |

### Appearance and licensing

| Option | Default | Description |
| --- | --- | --- |
| `theme` | inherited | `'light'`, `'dark'` or `'auto'`. Without it the page theme applies. |
| `ariaLabel` | `'Diagram'` | Accessible name of the diagram. |
| `injectStyles` | `true` | `false` skips injecting the stylesheet; import `@birchui/diagram/styles.css` yourself. |
| `licenseKey` | none | License key for this diagram, or call `setLicenseKey` once. See [Licensing](https://docs.birchui.com/getting-started/licensing.md). |

**`DiagramOptions`** (interface from `@birchui/diagram`, full reference: https://docs.birchui.com/api/diagram.md)

```ts
interface DiagramOptions<TNodeData = DiagramData, TEdgeData = DiagramData>
```

| Property | Type | Description |
| --- | --- | --- |
| `nodes?` | `DiagramNode<TNodeData>[]` |  |
| `edges?` | `DiagramEdge<TEdgeData>[]` |  |
| `nodeTypes?` | `Record<string, NodeTypeDefinition<TNodeData>>` |  |
| `defaultNodeType?` | `string` |  |
| `defaultEdge?` | `Partial<Pick<DiagramEdge<TEdgeData>, 'router' \| 'markerEnd' \| 'markerStart' \| 'style'>>` |  |
| `viewport?` | `Viewport` |  |
| `fitOnInit?` | `boolean` |  |
| `minZoom?` | `number` |  |
| `maxZoom?` | `number` |  |
| `width?` | `number` |  |
| `height?` | `number` |  |
| `grid?` | `boolean \| GridOptions` |  |
| `guides?` | `boolean` |  |
| `minimap?` | `boolean` |  |
| `controls?` | `boolean` |  |
| `listView?` | `boolean` |  |
| `readOnly?` | `boolean` |  |
| `theme?` | `DiagramTheme` |  |
| `ariaLabel?` | `string` |  |
| `wheelMode?` | `WheelMode` |  |
| `backgroundDrag?` | `BackgroundDrag` |  |
| `routing?` | `RoutingOptions` |  |
| `overviewThreshold?` | `number` |  |
| `historyLimit?` | `number` |  |
| `validateConnection?` | `(request: ConnectionRequest) => boolean` |  |
| `createId?` | `(kind: 'node' \| 'edge') => string` |  |
| `licenseKey?` | `string` |  |
| `injectStyles?` | `boolean` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |

## Methods

`DiagramApi` includes the widget contract (`element`, `update(partial)`, `on(event, listener)` returning an unsubscribe function, and `destroy()`) plus:

### Model

| Method | Returns | Description |
| --- | --- | --- |
| `setNodes(nodes)`, `setEdges(edges)` | `void` | Replace the model. Clears the history. |
| `addNodes(node \| nodes)` | `void` | Add nodes as one undo step. |
| `updateNode(id, patch)` | `DiagramNode \| undefined` | Merge a patch and return the new node. |
| `removeNodes(id \| ids)` | `void` | Remove nodes, their descendants and their edges. |
| `addEdges(edge \| edges)` | `void` | Add edges. |
| `updateEdge(id, patch)` | `DiagramEdge \| undefined` | Merge a patch and return the new edge. |
| `removeEdges(id \| ids)` | `void` | Remove edges. |
| `getNodes()`, `getEdges()` | arrays | Copies of the model. |
| `getNode(id)`, `getEdge(id)` | item or `undefined` | Copy of one item. |
| `getEdgeRoute(id)` | `Point[]` | The edge's current path points. |
| `setCollapsed(groupId, collapsed)` | `void` | Collapse or expand a container. |

### Selection and editing

| Method | Returns | Description |
| --- | --- | --- |
| `select({ nodes?, edges? }, { additive? })` | `void` | Select items, optionally adding to the selection. |
| `getSelection()` | `{ nodes, edges }` | Selected ids. |
| `clearSelection()` | `void` | Clear the selection. |
| `editLabel(id)` | `void` | Open the inline label editor for a node or edge. |
| `undo()`, `redo()` | `boolean` | Undo or redo one step; `false` when there is none. |
| `canUndo()`, `canRedo()` | `boolean` | Whether a step is available. |

### Viewport

| Method | Returns | Description |
| --- | --- | --- |
| `zoomIn()`, `zoomOut()` | `void` | Zoom by 1.25 or 0.8. |
| `zoomTo(zoom, center?)` | `void` | Set the zoom, optionally around a point. |
| `zoomToFit({ padding?, maxZoom?, nodes? })` | `void` | Fit all or the listed nodes. |
| `zoomToSelection()` | `void` | Fit the selected nodes. |
| `centerOn(nodeId)` | `void` | Center a node. |
| `getViewport()`, `setViewport(partial)` | `Viewport` / `void` | Read or change `{ x, y, zoom }`. |
| `screenToDiagram(point)`, `diagramToScreen(point)` | `Point` | Convert between client coordinates and diagram units. |

### Layout and files

| Method | Returns | Description |
| --- | --- | --- |
| `layout({ type?, direction?, spacing?, animate?, columns?, iterations? })` | `Promise<void>` | Auto-layout as one undo step. See [Layout](https://docs.birchui.com/diagram/layout.md). |
| `toJSON()` | `DiagramDocument` | The model and viewport as a JSON document. |
| `fromJSON(document \| string)` | `void` | Load a document. Clears the history. |
| `toSVG(options?)` | `string` | SVG export. |
| `toPNG(options?)` | `Promise<Blob>` | PNG export. |

API edits are undoable and emit change events with `source: 'api'`; they also work in read-only mode.

**`DiagramApi`** (interface from `@birchui/diagram`, full reference: https://docs.birchui.com/api/diagram.md)

```ts
interface DiagramApi<TNodeData = DiagramData, TEdgeData = DiagramData> extends Widget< DiagramOptions<TNodeData, TEdgeData>, DiagramEvents<TNodeData, TEdgeData> >
```

| Property | Type | Description |
| --- | --- | --- |
| `setNodes` | `(nodes: DiagramNode<TNodeData>[]) => void` |  |
| `setEdges` | `(edges: DiagramEdge<TEdgeData>[]) => void` |  |
| `addNodes` | `(nodes: DiagramNode<TNodeData> \| DiagramNode<TNodeData>[]) => void` |  |
| `updateNode` | `(id: string, patch: Partial<Omit<DiagramNode<TNodeData>, 'id'>>) => DiagramNode<TNodeData> \| undefined` |  |
| `removeNodes` | `(ids: string \| string[]) => void` |  |
| `addEdges` | `(edges: DiagramEdge<TEdgeData> \| DiagramEdge<TEdgeData>[]) => void` |  |
| `updateEdge` | `(id: string, patch: Partial<Omit<DiagramEdge<TEdgeData>, 'id'>>) => DiagramEdge<TEdgeData> \| undefined` |  |
| `removeEdges` | `(ids: string \| string[]) => void` |  |
| `getNodes` | `() => DiagramNode<TNodeData>[]` |  |
| `getEdges` | `() => DiagramEdge<TEdgeData>[]` |  |
| `getNode` | `(id: string) => DiagramNode<TNodeData> \| undefined` |  |
| `getEdge` | `(id: string) => DiagramEdge<TEdgeData> \| undefined` |  |
| `getEdgeRoute` | `(id: string) => Point[]` |  |
| `select` | `(selection: Partial<DiagramSelection>, options?: { additive?: boolean }) => void` |  |
| `getSelection` | `() => DiagramSelection` |  |
| `clearSelection` | `() => void` |  |
| `setCollapsed` | `(groupId: string, collapsed: boolean) => void` |  |
| `editLabel` | `(id: string) => void` |  |
| `undo` | `() => boolean` |  |
| `redo` | `() => boolean` |  |
| `canUndo` | `() => boolean` |  |
| `canRedo` | `() => boolean` |  |
| `zoomIn` | `() => void` |  |
| `zoomOut` | `() => void` |  |
| `zoomTo` | `(zoom: number, center?: Point) => void` |  |
| `zoomToFit` | `(options?: ZoomToFitOptions) => void` |  |
| `zoomToSelection` | `() => void` |  |
| `centerOn` | `(nodeId: string) => void` |  |
| `getViewport` | `() => Viewport` |  |
| `setViewport` | `(viewport: Partial<Viewport>) => void` |  |
| `layout` | `(options?: LayoutOptions) => Promise<void>` |  |
| `toJSON` | `() => DiagramDocument<TNodeData, TEdgeData>` |  |
| `fromJSON` | `(document: DiagramDocument<TNodeData, TEdgeData> \| string) => void` |  |
| `toSVG` | `(options?: SvgExportOptions) => string` |  |
| `toPNG` | `(options?: PngExportOptions) => Promise<Blob>` |  |
| `screenToDiagram` | `(point: Point) => Point` |  |
| `diagramToScreen` | `(point: Point) => Point` |  |
| `readonly element` | `HTMLElement` | Inherited from Widget. |
| `update` | `(options: Partial<DiagramOptions<TNodeData, TEdgeData>>) => void` | Inherited from Widget. |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` | Inherited from Widget. |
| `destroy` | `() => void` | Inherited from Widget. |

## Events

Subscribe with `on(event, listener)`. A listener that throws is caught and reported with `console.error`, so it never breaks the diagram. In framework adapters the same events are `on…` props (React, Solid), kebab-case listeners (Vue), outputs (Angular), `on` handlers of the Svelte action, or kebab-case `CustomEvent`s on a custom element.

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ api }` | Once, in a microtask after `createDiagram` returns. |
| `nodeClick` | `{ node, point, domEvent }` | A node is clicked. |
| `nodeDoubleClick` | `{ node, point, domEvent }` | A node is double-clicked (the label editor also opens unless read-only). |
| `edgeClick` | `{ edge, point, domEvent }` | An edge is clicked. |
| `selectionChange` | `{ nodes, edges }` | The selection changed. |
| `nodesChange` | `{ changes, source }` | Nodes were added, removed, moved, resized or updated. |
| `edgesChange` | `{ changes, source }` | Edges were added, removed or updated. |
| `connect` | `{ edge, source, target, isReconnect }` | The user created or reconnected an edge. |
| `viewportChange` | `{ viewport }` | The view was panned or zoomed. |
| `contextMenu` | `{ target, node?, edge?, point, domEvent }` | Right-click on a node, an edge or the canvas. Listening suppresses the browser menu. |
| `historyChange` | `{ canUndo, canRedo, undoLabel?, redoLabel? }` | The undo history changed, including when it is cleared. |

`changes` entries are `{ type, id, before?, after? }` with `type` `'add'`, `'remove'`, `'move'`, `'resize'` or `'update'` (edges: `'add'`, `'remove'` or `'update'`). `source` is `'user'`, `'api'`, `'history'` (undo and redo) or `'layout'`. `point` is in diagram units. Loading a document with `setNodes`, `setEdges`, `fromJSON` or `update({ nodes, edges })` emits `historyChange` only.

**`DiagramEvents`** (interface from `@birchui/diagram`, full reference: https://docs.birchui.com/api/diagram.md)

```ts
interface DiagramEvents<TNodeData = DiagramData, TEdgeData = DiagramData>
```

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ api: DiagramApi<TNodeData, TEdgeData> }` |  |
| `nodeClick` | `PointerContext & { node: DiagramNode<TNodeData> }` |  |
| `nodeDoubleClick` | `PointerContext & { node: DiagramNode<TNodeData> }` |  |
| `edgeClick` | `PointerContext & { edge: DiagramEdge<TEdgeData> }` |  |
| `selectionChange` | `DiagramSelection` |  |
| `nodesChange` | `{ changes: NodeChange<TNodeData>[]; source: ChangeSource }` |  |
| `edgesChange` | `{ changes: EdgeChange<TEdgeData>[]; source: ChangeSource }` |  |
| `connect` | `{ edge: DiagramEdge<TEdgeData>; source: EdgeEnd; target: EdgeEnd; isReconnect: boolean }` |  |
| `viewportChange` | `{ viewport: Viewport }` |  |
| `contextMenu` | `PointerContext & { target: 'node' \| 'edge' \| 'canvas'; node?: DiagramNode<TNodeData>; edge?: DiagramEdge<TEdgeData>; }` |  |
| `historyChange` | `{ canUndo: boolean; canRedo: boolean; undoLabel?: string; redoLabel?: string }` |  |

## Types

| Type | Description |
| --- | --- |
| `DiagramOptions`, `DiagramApi`, `DiagramEvents` | Options, API and event payload map, generic over node and edge data. |
| `DiagramNode`, `DiagramEdge`, `DiagramPort`, `EdgeEnd` | The model. |
| `NodeStyle`, `EdgeStyle`, `EdgeMarker`, `EdgeRouter`, `PortSide` | Styling and routing values. |
| `NodeTypeDefinition`, `NodeRenderContext`, `NodeShape`, `BuiltInNodeType` | Node types and templates. |
| `DiagramDocument`, `SvgExportOptions`, `PngExportOptions` | Files. |
| `NodeChange`, `EdgeChange`, `ChangeKind`, `ChangeSource`, `DiagramSelection`, `PointerContext`, `ConnectionRequest` | Event payloads and validator input. |
| `LayoutOptions`, `LayoutType`, `LayoutDirection`, `LayoutSpacing` | `layout()` options. |
| `LayeredLayoutOptions`, `LayeredLayoutResult`, `TreeLayoutOptions`, `ForceLayoutOptions`, `GridLayoutOptions`, `RunLayoutOptions`, `LayoutNodeInput`, `LayoutEdgeInput` | Standalone layout functions. |
| `OrthogonalRouteInput`, `RouteEndpoint`, `RoutingOptions` | Routing. |
| `Viewport`, `ZoomToFitOptions`, `GridOptions`, `GridStyle`, `WheelMode`, `BackgroundDrag`, `DiagramTheme`, `Point`, `Size`, `Rect`, `DiagramData` | Everything else. |

## Styling hooks

The root element has the class `lq-diagram`, plus `lq-theme-light`, `lq-theme-dark` or `lq-theme-auto` when `theme` is set, `lq-diagram--readonly`, `lq-diagram--list`, `lq-diagram--overview` and `lq-diagram--connecting` while those states apply. Nodes have `lq-diagram-node` and `lq-diagram-node--<type>`, plus `--selected`, `--container`, `--collapsed`, `--valid-target` and `--invalid-target`; HTML template wrappers are `lq-diagram-html-node`. Theme with the shared `--lq-*` tokens and diagram tokens such as `--lq-diagram-accent`, `--lq-diagram-node-bg`, `--lq-diagram-node-border`, `--lq-diagram-edge`, `--lq-diagram-grid-color`, `--lq-diagram-guide` and `--lq-diagram-selection`. See the shared [theming guide](https://docs.birchui.com/grid/theming.md).
