# Auto-layout

> Arrange diagrams automatically with layered, tree, force-directed and grid layouts, animate the result, and run the same layout engines on a server.

`layout()` positions every node for you. Use it when you load a graph without coordinates, after users add many nodes, or behind an "Arrange" button like the one in this demo.

**Live demo: Order fulfilment flow** (runs on the HTML version of this page). Source of `demos/diagram-flow.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
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();
  };
}
```

```ts
await diagram.layout({ type: 'layered', direction: 'LR', spacing: { node: 36, layer: 72 }, animate: true });
diagram.zoomToFit({ maxZoom: 1 });
```

## Layout types

| Type | Algorithm | Use it for |
| --- | --- | --- |
| `'layered'` (default) | Sugiyama-style layering: cycles are broken, nodes are assigned to layers by longest path, crossings are reduced with barycenter sweeps and swaps, and nodes are aligned and compacted within each layer. Disconnected parts are packed side by side. | Flowcharts, approval workflows, pipelines, state machines. |
| `'tree'` | A tidy tree with subtrees separated by their contours and parents centered over their children. A forest is laid out tree by tree. | Org charts, file and category trees, decision trees. |
| `'force'` | Deterministic force-directed (Fruchterman–Reingold) with overlap removal. The same input always gives the same picture. | Network topologies and relationship maps up to a few hundred nodes. |
| `'grid'` | Equal cells in rows, or in columns for `LR` and `RL`. | Palettes, inventories, unconnected items. |

## Options

| Option | Default | Description |
| --- | --- | --- |
| `type` | `'layered'` | One of the four types above. |
| `direction` | `'TB'` | `'TB'` (top to bottom), `'BT'`, `'LR'` (left to right) or `'RL'`. Used by `layered`, `tree` and `grid`. |
| `spacing` | per type | A number, or `{ node, layer }`. `node` is the gap between neighbours, `layer` the gap between layers or tree levels. A single number sets `node` and uses 1.5 times it for `layer`. |
| `animate` | `false` | Tween nodes to their new positions over about 320 ms. Skipped when the user prefers reduced motion. |
| `columns` | square-ish | `grid` only: items per row (or per column for `LR` and `RL`). |
| `iterations` | `300` | `force` only: simulation steps. |

Default spacing per type:

| Type | `node` | `layer` |
| --- | --- | --- |
| `layered` | 40 | 64 |
| `tree` | 32 | 64 |
| `force` | 48 | (not used) |
| `grid` | 32 | (not used) |

An unknown `type` logs a warning and does nothing; an unknown `direction` logs a warning and uses `'TB'`.

## How layout treats your diagram

- **Top-level nodes are the units.** A group or swimlane moves as one block with its children inside, and edges to children count as edges to their top-level container.
- **The diagram stays where it was.** The new arrangement keeps the top-left corner of the old one, so the view does not jump. Call `zoomToFit()` afterwards if the size changed a lot.
- **One undo step.** A layout is recorded as a single history entry labelled "Auto layout" and emits `nodesChange` with `source: 'layout'`, so you can tell it apart from user drags.
- **It works in read-only mode**, because read-only only blocks user edits.

`layout()` returns a promise that resolves when the nodes are in place, after the animation when `animate` is on. Starting a new layout while one is animating replaces it.

## Org chart example

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

const people = [
  ['ceo', 'Maria Lopez, CEO', null],
  ['cto', 'Daniel Okafor, CTO', 'ceo'],
  ['cfo', 'Aiko Tanaka, CFO', 'ceo'],
  ['eng-platform', 'Platform team', 'cto'],
  ['eng-apps', 'Applications team', 'cto'],
  ['finance-ap', 'Accounts payable', 'cfo'],
] as const;

const nodes: DiagramNode[] = people.map(([id, label]) => ({ id, label, x: 0, y: 0, width: 200, height: 56 }));
const edges: DiagramEdge[] = people
  .filter(([, , manager]) => manager !== null)
  .map(([id, , manager]) => ({ id: `${manager}-${id}`, source: { node: manager! }, target: { node: id } }));

const chart = createDiagram(container, { nodes, edges, readOnly: true, ariaLabel: 'Leadership org chart' });
await chart.layout({ type: 'tree', direction: 'TB', spacing: { node: 24, layer: 56 } });
chart.zoomToFit();
```

## Standalone layout functions

The layout engines are pure functions exported for servers, workers and tests. They take nodes with `id`, `width` and `height` (positions are ignored) and edges with `source` and `target` ids, and return a `Map` from node id to the **top-left corner** of the node.

```ts
import { layeredLayout, runLayout } from '@birchui/diagram';

const nodes = [
  { id: 'ceo', width: 180, height: 60 },
  { id: 'cto', width: 180, height: 60 },
  { id: 'cfo', width: 180, height: 60 },
  { id: 'eng', width: 180, height: 60 },
  { id: 'ops', width: 180, height: 60 },
];
const edges = [
  { source: 'ceo', target: 'cto' },
  { source: 'ceo', target: 'cfo' },
  { source: 'cto', target: 'eng' },
  { source: 'cto', target: 'ops' },
];

const { positions, layers, crossings } = layeredLayout(nodes, edges, { direction: 'TB' });
const gridPositions = runLayout(nodes, edges, { type: 'grid', columns: 2 });
```

Here `layers` is `[['ceo'], ['cto', 'cfo'], ['eng', 'ops']]`, `crossings` is `0`, and `positions.get('eng')` is `{ x: 0, y: 248 }`.

| Function | Options | Returns |
| --- | --- | --- |
| `layeredLayout(nodes, edges, options?)` | `direction`, `nodeSpacing` (40), `layerSpacing` (64), `sweeps` (16 crossing-reduction passes), `componentSpacing` | `{ positions, layers, crossings }` |
| `treeLayout(nodes, edges, options?)` | `direction`, `nodeSpacing` (32), `levelSpacing` (64) | `Map<string, Point>` |
| `forceLayout(nodes, edges, options?)` | `spacing` (48), `iterations` (300), `seed` (7) | `Map<string, Point>` |
| `gridLayout(nodes, options?)` | `direction`, `spacing` (32), `columns` | `Map<string, Point>` |
| `runLayout(nodes, edges, options?)` | the same options as `diagram.layout()`, without `animate` | `Map<string, Point>` |

A server can lay out a graph once and store coordinates, so every client opens it instantly:

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

export function arrangeWorkflow(steps: WorkflowStep[], transitions: Transition[]) {
  const positions = runLayout(
    steps.map((step) => ({ id: step.id, width: 160, height: 64 })),
    transitions.map((t) => ({ source: t.from, target: t.to })),
    { type: 'layered', direction: 'LR' },
  );
  return steps.map((step) => ({ id: step.id, label: step.name, ...positions.get(step.id)! }));
}
```

Self-edges and duplicate edges are ignored by the engines.

## Next steps

- [Routing](https://docs.birchui.com/diagram/routing.md) for how edges follow the new positions.
- [Interaction](https://docs.birchui.com/diagram/interaction.md#pan-zoom-and-fit) for `zoomToFit`.
