# Nodes and edges

> The diagram data model, covering nodes, the ten built-in shapes, ports, edges with markers and labels, groups and swimlanes, styles and editing the model from code.

A diagram is two arrays of plain objects: **nodes** and **edges**. Both are JSON-friendly, so they can come straight from your database and go back to it unchanged.

## Nodes

```ts
import type { DiagramNode } from '@birchui/diagram';

const nodes: DiagramNode[] = [
  { id: 'firewall', type: 'rectangle', x: 0, y: 120, label: 'Edge firewall' },
  { id: 'lb', type: 'rounded', x: 240, y: 120, label: 'Load balancer' },
  { id: 'db', type: 'cylinder', x: 480, y: 220, label: 'Orders database' },
];
```

| Field | Type | Description |
| --- | --- | --- |
| `id` | `string` | Unique identifier. Edges refer to it. |
| `x`, `y` | `number` | Top-left corner in diagram units. Coordinates are absolute, also for nodes inside groups. |
| `type` | `string` | A built-in type or one of your `nodeTypes`. Defaults to `defaultNodeType`, which is `'rounded'`. |
| `width`, `height` | `number` | Size. Defaults to the type's default size. |
| `label` | `string` | Text drawn in the node, edited in place, and used as its accessible name. |
| `ports` | `DiagramPort[]` | Connection points. Defaults to the type's ports, which for built-in types are one in the middle of each side. |
| `data` | `TData` | Your own data, typed through `DiagramNode<TData>`. Kept in JSON and passed to templates. |
| `style` | `NodeStyle` | Per-node colors and text style. |
| `parentId` | `string` | Puts the node inside a group or swimlane. |
| `collapsed` | `boolean` | Collapses a group. |
| `draggable`, `resizable`, `connectable` | `boolean` | Set `false` to stop users moving or resizing the node, or connecting to it. |

A node without finite `x` and `y` is placed at `0, 0` with a warning; [auto-layout](https://docs.birchui.com/diagram/layout.md) is the easy way to position nodes you load without coordinates. Nodes with a duplicate `id` are ignored with a warning.

## Built-in types

| Type | Shape | Default size | Typical use |
| --- | --- | --- | --- |
| `'rectangle'` | Rectangle | 160 × 64 | Process step |
| `'rounded'` | Rounded rectangle | 160 × 64 | Step (the default) |
| `'ellipse'` | Ellipse | 140 × 72 | Start, end or event |
| `'diamond'` | Diamond | 150 × 96 | Decision |
| `'parallelogram'` | Parallelogram | 170 × 64 | Input or output |
| `'cylinder'` | Cylinder | 120 × 84 | Database |
| `'document'` | Document with a wavy bottom edge | 150 × 80 | Document or report |
| `'note'` | Note with a folded corner | 170 × 90 | Annotation |
| `'swimlane'` | Container with a header | 720 × 200 | Lane per team or system |
| `'group'` | Container with a header | 400 × 260 | Collapsible group |

`BUILT_IN_TYPES` lists the names and `BUILT_IN_SHAPES` their default sizes, if you build a palette. For shapes of your own, see [Node templates](https://docs.birchui.com/diagram/node-templates.md).

```ts
import { BUILT_IN_SHAPES, BUILT_IN_TYPES } from '@birchui/diagram';

const palette = BUILT_IN_TYPES.filter((type) => type !== 'swimlane').map((type) => ({
  type,
  size: BUILT_IN_SHAPES[type].defaultSize,
}));
```

## Ports

Ports are the points edges attach to and users drag from to connect. A port has an `id`, a `side` (`'top'`, `'right'`, `'bottom'` or `'left'`), an optional `offset` from 0 to 1 along that side (default 0.5, the middle) and an optional `label` kept with the model.

```ts
const router: DiagramNode = {
  id: 'core-router',
  type: 'rectangle',
  x: 300,
  y: 80,
  width: 200,
  height: 80,
  label: 'Core router',
  ports: [
    { id: 'wan', side: 'top' },
    { id: 'lan1', side: 'bottom', offset: 0.25 },
    { id: 'lan2', side: 'bottom', offset: 0.5 },
    { id: 'lan3', side: 'bottom', offset: 0.75 },
  ],
};
```

`FOUR_PORTS` is the default set (`top`, `right`, `bottom`, `left`), handy as a starting point. Ports are hidden on collapsed groups, in read-only mode and on nodes with `connectable: false`.

## Edges

```ts
import type { DiagramEdge } from '@birchui/diagram';

const edges: DiagramEdge[] = [
  { id: 'fw-lb', source: { node: 'firewall' }, target: { node: 'lb' }, label: 'HTTPS' },
  { id: 'lb-db', source: { node: 'lb' }, target: { node: 'db', port: 'left' }, router: 'curved' },
  {
    id: 'replication',
    source: { node: 'db', port: 'right' },
    target: { node: 'db-replica', port: 'left' },
    label: 'replication',
    markerStart: 'circle',
    markerEnd: 'arrowOpen',
    style: { dash: '6 4', stroke: '#7c3aed' },
  },
];
```

| Field | Type | Description |
| --- | --- | --- |
| `id` | `string` | Unique identifier. |
| `source`, `target` | `{ node, port? }` | The connected nodes, and optionally a port on each. An end without a port attaches to the side that faces the other node. |
| `label` | `string` | Text at the middle of the edge, on a background pill. |
| `router` | `'orthogonal' \| 'straight' \| 'curved'` | How the path is drawn. See [Routing](https://docs.birchui.com/diagram/routing.md). |
| `markerEnd`, `markerStart` | `'arrow' \| 'arrowOpen' \| 'diamond' \| 'circle' \| 'none'` | Arrowheads. By default the end has `'arrow'` and the start `'none'`. |
| `style` | `EdgeStyle` | `stroke`, `strokeWidth`, `dash` (an SVG dash pattern such as `'4 3'`) and `color` (the label color). |
| `data` | `TData` | Your own data, typed through `DiagramEdge<TData>`. |

Edges that refer to a missing node are ignored with a warning. Set defaults for every edge with `defaultEdge`:

```ts
createDiagram(container, {
  nodes,
  edges,
  defaultEdge: { router: 'orthogonal', markerEnd: 'arrow', style: { stroke: '#475569', strokeWidth: 1.5 } },
});
```

## Groups and swimlanes

A node with `parentId` lives inside that container. Use the `'group'` type for collapsible clusters and `'swimlane'` for lanes per team or system; any node that has children also acts as a container.

```ts
const nodes: DiagramNode[] = [
  { id: 'lane-sales', type: 'swimlane', x: 0, y: 0, width: 900, height: 180, label: 'Sales' },
  { id: 'lane-finance', type: 'swimlane', x: 0, y: 200, width: 900, height: 180, label: 'Finance' },
  { id: 'quote', x: 60, y: 70, label: 'Prepare quote', parentId: 'lane-sales' },
  { id: 'discount', type: 'diamond', x: 300, y: 50, label: 'Discount over 15%?', parentId: 'lane-sales' },
  { id: 'approve', x: 300, y: 270, label: 'Approve discount', parentId: 'lane-finance' },
  { id: 'send', x: 620, y: 70, label: 'Send to customer', parentId: 'lane-sales' },
];
```

- **Coordinates stay absolute.** A child's `x` and `y` are in diagram units, not relative to its parent.
- **Moving a container moves its children**, and auto-layout treats each top-level container as one unit.
- **Collapsing** a group (the chevron in its header, <kbd>Alt</kbd>+<kbd>ArrowUp</kbd>, `setCollapsed(id, true)` or `collapsed: true`) shrinks it to its header, hides its children and redraws their edges to the group itself.
- **Dropping a node into a container** while dragging makes it a child; dragging it out makes it top-level again. Both are part of the same undo step as the move.
- Nesting can go several levels deep. A `parentId` that points to a missing node, the node itself or one of its descendants is ignored with a warning.

```ts
diagram.setCollapsed('lane-finance', true);
```

## Styles

`style` on a node sets `fill`, `stroke`, `strokeWidth`, `color` (text), `fontSize`, `fontWeight` and `dash`. Values are applied as CSS custom properties on the node, so they win over the theme without extra CSS.

```ts
diagram.updateNode('db', { style: { fill: '#fef3c7', stroke: '#b45309', strokeWidth: 2 } });
```

For styling that depends on your data, such as a red outline for failed services, prefer a [node template](https://docs.birchui.com/diagram/node-templates.md) or CSS on the class `lq-diagram-node--<type>` that every node carries.

## Editing the model from code

| Method | Description |
| --- | --- |
| `addNodes(node \| nodes)` | Add nodes. Duplicate ids are ignored with a warning. |
| `updateNode(id, patch)` | Merge `patch` into a node and return the new node. |
| `removeNodes(id \| ids)` | Remove nodes, their descendants and their edges. |
| `addEdges(edge \| edges)`, `updateEdge(id, patch)`, `removeEdges(id \| ids)` | The same for edges. |
| `getNodes()`, `getEdges()`, `getNode(id)`, `getEdge(id)` | Read copies of the current model. Changing them does not change the diagram. |
| `setCollapsed(groupId, collapsed)` | Collapse or expand a container. |
| `setNodes(nodes)`, `setEdges(edges)` | Replace the whole model. |

```ts
diagram.addNodes({ id: 'cache', type: 'cylinder', x: 480, y: 40, label: 'Redis cache' });
diagram.addEdges({ id: 'lb-cache', source: { node: 'lb' }, target: { node: 'cache' }, label: 'sessions' });
diagram.updateNode('lb', { label: 'Load balancer (active)' });
diagram.removeEdges('lb-db');
```

Each call is one undoable step and emits `nodesChange` or `edgesChange` with `source: 'api'`, so your save logic sees it. Edits through the API also work in read-only mode, which only blocks the user.

> **Warning**
>
> `setNodes`, `setEdges`, `fromJSON` and `update({ nodes, edges })` load a new document: they **clear the undo history** and do not emit `nodesChange` or `edgesChange`. Use them to open a different diagram, and the incremental methods above for changes to the current one.

## Next steps

- [Node templates](https://docs.birchui.com/diagram/node-templates.md) for custom node types.
- [Routing](https://docs.birchui.com/diagram/routing.md) for how edges find their way.
- [Serialization and export](https://docs.birchui.com/diagram/serialization.md) to save the model.
