# Interaction

> Pan, zoom and fit, the minimap and toolbar, selection, moving with grid snapping and alignment guides, connecting with validation, inline labels, undo and redo, copy and paste, and read-only mode.

This page covers everything users can do in the diagram, the options that shape it, and the events that tell your code about it. For the full keyboard map, see [Keyboard and accessibility](https://docs.birchui.com/diagram/accessibility.md).

## Pan, zoom and fit

| Action | Mouse and trackpad | Touch | Keyboard |
| --- | --- | --- | --- |
| Pan | Drag the background, hold <kbd>Space</kbd> and drag, or drag with the middle button | Two fingers | Arrow keys with nothing selected |
| Zoom | Wheel (or <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + wheel), trackpad pinch, toolbar buttons | Pinch | <kbd>+</kbd> and <kbd>-</kbd> |
| Fit everything | Toolbar button | | <kbd>Shift</kbd>+<kbd>1</kbd> |
| Fit the selection | | | <kbd>Shift</kbd>+<kbd>2</kbd> |

Zoom is limited by `minZoom` (default `0.05`) and `maxZoom` (default `4`). When the diagram is created with nodes and no `viewport` option, it fits them on screen without zooming in beyond 100%; set `fitOnInit: false` to start at the origin instead.

### Wheel mode and background drag

| Option | Default | Description |
| --- | --- | --- |
| `wheelMode` | `'zoom'` | `'zoom'`: the wheel zooms around the pointer and <kbd>Shift</kbd>+wheel pans sideways. `'pan'`: the wheel pans in both directions, which suits trackpads, and <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+wheel (and trackpad pinch) zooms. |
| `backgroundDrag` | `'pan'` | `'marquee'` makes a plain drag on the background draw a selection rectangle; panning is then done with <kbd>Space</kbd>+drag, the middle button or the wheel. |

```ts
createDiagram(container, { nodes, edges, wheelMode: 'pan', backgroundDrag: 'marquee' });
```

### Viewport from code

| Method | Description |
| --- | --- |
| `zoomToFit({ padding?, maxZoom?, nodes? })` | Fit all nodes, or the listed ones, with `padding` (default 40 pixels). |
| `zoomToSelection()` | Fit the selected nodes, up to 200%. |
| `centerOn(nodeId)` | Center a node without changing the zoom. A node inside a collapsed group centers the group. |
| `zoomIn()`, `zoomOut()` | Zoom by a factor of 1.25 around the center. |
| `zoomTo(zoom, center?)` | Set an exact zoom, optionally around a point. |
| `getViewport()`, `setViewport({ x?, y?, zoom? })` | Read or set the pan offset and zoom. |
| `screenToDiagram(point)`, `diagramToScreen(point)` | Convert between client coordinates (as in `PointerEvent.clientX`) and diagram units. |

```ts
diagram.on('viewportChange', ({ viewport }) => {
  sessionStorage.setItem('fulfilment-viewport', JSON.stringify(viewport));
});

const saved = sessionStorage.getItem('fulfilment-viewport');
if (saved) diagram.setViewport(JSON.parse(saved));
```

## Toolbar and minimap

The toolbar (`controls`, on by default) has zoom in, zoom out, zoom to fit, a list view toggle and a minimap toggle. The minimap (`minimap`, on by default) shows the whole diagram with the visible area outlined; click or drag in it to move the view. Turn either off with `controls: false` or `minimap: false`, and build your own toolbar with the viewport methods above.

The background grid is on by default: dots every 20 units. Configure it with `grid`:

| `grid` value | Effect |
| --- | --- |
| `true` or omitted | Dots every 20 units, with snapping. |
| `{ size, style, snap }` | `size` in diagram units, `style` `'dots'`, `'lines'` or `'none'`, and `snap` on or off. |
| `false` | No grid and no grid snapping. |

## Selecting

- Click a node or edge to select it. <kbd>Shift</kbd>+click adds or removes it.
- <kbd>Shift</kbd>+drag on the background draws a marquee (or a plain drag with `backgroundDrag: 'marquee'`).
- <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>A</kbd> selects everything, <kbd>Escape</kbd> clears the selection.

```ts
diagram.select({ nodes: ['payment', 'pick'] });
diagram.select({ edges: ['payment-pick'] }, { additive: true });
const { nodes, edges } = diagram.getSelection();
diagram.clearSelection();

diagram.on('selectionChange', ({ nodes, edges }) => inspector.show(nodes, edges));
diagram.on('nodeClick', ({ node, point, domEvent }) => {
  if (domEvent.altKey) openStepDetails(node.id);
});
```

`nodeClick`, `nodeDoubleClick` and `edgeClick` carry the item, the `point` in diagram units and the native `domEvent`.

## Moving and resizing

Drag a node, or any of the selected nodes, to move them together. Hold <kbd>Shift</kbd> to lock the movement to one axis and <kbd>Alt</kbd> to move freely without snapping. The selected node shows resize handles; resizing snaps the same way. Arrow keys nudge the selection by 1 unit, or 10 with <kbd>Shift</kbd>.

While moving, nodes snap to the grid and to **alignment guides**: lines that appear when a node's edges or center line up with a nearby node. Set `guides: false` to turn guides off, and `grid: { snap: false }` to stop grid snapping.

Restrict individual nodes with `draggable: false` and `resizable: false`, or a whole node type with `resizable: false` in its [definition](https://docs.birchui.com/diagram/node-templates.md#register-a-node-type).

Moves, resizes and nudges emit `nodesChange` with `type: 'move'` or `'resize'` and `source: 'user'`.

## Connecting

Every node shows its ports when hovered or selected. Drag from a port onto another node or port to create an edge. While dragging, the target shows a green outline when the connection is allowed and a red dashed outline when it is not. Drag an end handle of a selected edge to reconnect it. From the keyboard, press <kbd>C</kbd> on a focused node; see [keyboard connect mode](https://docs.birchui.com/diagram/accessibility.md#connect-from-the-keyboard).

Some connections are always refused before your code is asked: self-loops, exact duplicates (same nodes and ports), and targets with `connectable: false`. Everything else goes through `validateConnection`:

```ts
const allowedTargets: Record<string, string[]> = {
  request: ['manager-review'],
  'manager-review': ['finance-review', 'approved', 'rejected'],
  'finance-review': ['approved', 'rejected'],
};

createDiagram(container, {
  nodes,
  edges,
  validateConnection: ({ source, target, edgeId }) => {
    if (edgeId && edgeId.startsWith('locked-')) return false;
    return allowedTargets[source.node]?.includes(target.node) ?? false;
  },
});
```

`validateConnection({ source, target, edgeId })` receives the two ends (`{ node, port? }`) and, when an existing edge is being reconnected, its `edgeId`. Return `false` to refuse. It runs while the user drags to color the target, so keep it fast. A validator that throws refuses the connection and logs the error.

A successful connection emits `edgesChange` (with `type: 'add'`, or `'update'` for a reconnect) followed by `connect`:

```ts
diagram.on('connect', ({ edge, source, target, isReconnect }) => {
  api.saveTransition({ id: edge.id, from: source.node, to: target.node, isReconnect });
});
```

New edges get ids such as `'edge-1'`, and pasted nodes ids such as `'node-1'`. Provide `createId(kind)` to use your own scheme; it must return a new unique string:

```ts
createDiagram(container, { createId: (kind) => `${kind}-${crypto.randomUUID()}` });
```

## Editing labels

Double-click a node or an edge, or press <kbd>Enter</kbd> or <kbd>F2</kbd> on the focused node or selected edge, to edit its label in place. In the editor, <kbd>Enter</kbd> saves, <kbd>Shift</kbd>+<kbd>Enter</kbd> adds a line break, <kbd>Escape</kbd> cancels, and clicking elsewhere saves. Saving an empty label removes it. Open the editor from code with `editLabel(id)`, for example right after adding a node:

```ts
diagram.addNodes({ id: 'step-new', x: 400, y: 200, label: 'New step' });
diagram.select({ nodes: ['step-new'] });
diagram.editLabel('step-new');
```

A double-click on a node also emits `nodeDoubleClick`, which you can use to open a details dialog instead.

## Undo and redo

Every change is recorded: user edits, API calls and layouts. <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Z</kbd> undoes, <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> or <kbd>Ctrl</kbd>+<kbd>Y</kbd> redoes.

- A drag, a resize, a paste and a layout are each one step, however many nodes they touch.
- Continuous edits merge: arrow-key nudges of the same selection within one second become a single "Move" step.
- The history keeps the last `historyLimit` steps (default 200).
- Undo and redo emit `nodesChange` and `edgesChange` with `source: 'history'`.

```ts
const undoButton = document.querySelector<HTMLButtonElement>('#undo')!;
const redoButton = document.querySelector<HTMLButtonElement>('#redo')!;

diagram.on('historyChange', ({ canUndo, canRedo, undoLabel, redoLabel }) => {
  undoButton.disabled = !canUndo;
  undoButton.title = undoLabel ? `Undo ${undoLabel.toLowerCase()}` : 'Undo';
  redoButton.disabled = !canRedo;
  redoButton.title = redoLabel ? `Redo ${redoLabel.toLowerCase()}` : 'Redo';
});

undoButton.addEventListener('click', () => diagram.undo());
redoButton.addEventListener('click', () => diagram.redo());
```

`undo()` and `redo()` return `false` when there is nothing to undo or redo. Step labels include "Move", "Delete", "Connect", "Edit label", "Paste" and "Auto layout".

> **Warning**
>
> `setNodes`, `setEdges`, `fromJSON` and `update({ nodes, edges })` load a new document and **clear the history**. They emit `historyChange` (with `canUndo: false`) but no `nodesChange` or `edgesChange`.

## Copy, cut, paste and duplicate

| Keys | Action |
| --- | --- |
| <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>C</kbd> | Copy the selected nodes, the children of selected groups, and the edges between copied nodes. |
| <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>X</kbd> | Copy and delete. |
| <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>V</kbd> | Paste with new ids, offset by 24 units more on each paste, and select the result. |
| <kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>D</kbd> | Duplicate the selection without touching the clipboard. |

The clipboard is internal to the page, not the system clipboard, and is shared between the diagrams on the page, so users can copy from a template library diagram into their own.

## Context menu

`contextMenu` fires on right-click with the `target` kind (`'node'`, `'edge'` or `'canvas'`), the item, the `point` in diagram units and the native event. The item under the pointer is selected first. The browser's own menu is suppressed only while you listen to this event:

```ts
diagram.on('contextMenu', ({ target, node, point, domEvent }) => {
  menu.open({
    x: domEvent.clientX,
    y: domEvent.clientY,
    items:
      target === 'node'
        ? [{ label: 'Rename', run: () => diagram.editLabel(node!.id) }, { label: 'Delete', run: () => diagram.removeNodes(node!.id) }]
        : [{ label: 'Add step here', run: () => diagram.addNodes({ id: crypto.randomUUID(), x: point.x, y: point.y, label: 'New step' }) }],
  });
});
```

## Read-only mode

`readOnly: true` keeps selection, panning, zooming, the minimap, keyboard navigation and the list view, and blocks every user edit: moving, resizing, connecting, label editing, deleting, pasting, undo and redo. Ports and resize handles are hidden. Toggle it at any time:

```ts
diagram.update({ readOnly: !currentUser.canEditWorkflows });
```

Read-only mode does not lock the API. `addNodes`, `updateNode`, `layout()` and the other methods still work, which is how a monitoring view updates node status while users only look.

## Next steps

- [Keyboard and accessibility](https://docs.birchui.com/diagram/accessibility.md) for the complete key map.
- [Serialization and export](https://docs.birchui.com/diagram/serialization.md) to save what users build.
