# Extend tools and execution

Use the shipped whiteboard tools to annotate a mounted diagram, then extend gesture arbitration, named layouts and document migrations when your application needs a different policy.

The diagram owns live models; the engine owns behavior. Use the component or instance for ordinary edits. Supply a tool, algorithm or extension when the component cannot express your policy as a prop.

These files build on the projects from the [JavaScript](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start) or [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start) quick start. Keep each starter's entry wiring, styles and configuration. The shared module runs in the browser after the canvas mounts; it does not register tools when imported.

## 1. Mount the shipped whiteboard tools

Pass a live [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) to the factories. Angular supplies the narrower [`WhiteboardHost`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-interfaces-v-w#whiteboardhost) from its canvas, camera and container.

[`createDrawTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-functions#createdrawtool), [`createRectangleTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-functions#createrectangletool), [`createEraserTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-functions#createerasertool) and [`createStrokeEditTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-functions#createstrokeedittool) return tools to register with [`registerTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#registertool). The module below seeds visible ink using [`StrokeModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-strokemodel), adds a toolbar, and starts in eraser mode.

Install the packages for your binding in the quick start's project.

For JavaScript:

```bash
npm install @grafloria/element @grafloria/engine @grafloria/renderer
```
For React:

```bash
npm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer
```
For Vue:

```bash
npm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer
```
For Angular:

```bash
npm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer
```
For Qwik, follow the starter's use of development dependencies:

```bash
npm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer
```

```ts title="src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import { StrokeModel } from '@grafloria/engine';
import {
  createDrawTool, createEraserTool, createRectangleTool,
  createStrokeEditTool, registerTool, once,
} from '@grafloria/renderer';
import type { WhiteboardHost } from '@grafloria/renderer';
import { nodes, edges } from './board-data';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 },
    { id: 'annotation', label: 'Review this connection' },
  ));

  const draw = createDrawTool(host, {
    color: '#e11d48', width: 5, simplifyEpsilon: 0.8,
  });
  const rectangle = createRectangleTool(host, {
    fill: '#dbeafe', label: 'New box',
  });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const unregister = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText =
    'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';

  function choose(active: typeof tools[number] | null): void {
    for (const tool of tools) tool.setActive(tool === active);
    for (const button of toolbar.querySelectorAll('button')) {
      button.setAttribute('aria-pressed', String(button.dataset['tool'] === active?.id));
    }
  }

  for (const [label, tool] of [
    ['Draw', draw], ['Rectangle', rectangle],
    ['Eraser', eraser], ['Edit ink', edit], ['Navigate', null],
  ] as const) {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.dataset['tool'] = tool?.id;
    button.onclick = () => choose(tool);
    toolbar.appendChild(button);
  }
  host.container.appendChild(toolbar);
  choose(eraser);

  return once(() => {
    for (const remove of unregister.reverse()) remove();
    for (const tool of tools) tool.dispose();
    toolbar.remove();
  });
}

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const close = document.createElement('button');
close.textContent = 'Close board';
const container = document.createElement('div');
container.style.cssText = 'width:100%;height:420px';
app.replaceChildren(close, container);
const instance = render({ nodes, edges }, container);
const cleanup = installWhiteboard(instance);
close.onclick = () => {
  cleanup();
  instance.dispose();
  app.replaceChildren();
};
```

Each binding below installs the tools in its mounted canvas. Its local installer runs only from initialization, and teardown runs when the view closes or unmounts.

[`once`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#once) makes the returned cleanup safe to call repeatedly. Use it in your framework's unmount hook, not immediately after installation.

The data module types both arrays with [`NodeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) and [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec). It gives the ink a diagram to annotate rather than an empty canvas.

```ts title="src/board-data.ts"
import type { NodeSpec, EdgeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = [
  { id: 'review', label: 'Review', position: { x: 80, y: 80 }, size: { width: 160, height: 70 } },
  { id: 'approve', label: 'Approve', position: { x: 340, y: 80 }, size: { width: 160, height: 70 } },
];
export const edges: EdgeSpec[] = [
  { id: 'review-approve', source: 'review', target: 'approve' },
];
```

Install the whiteboard tools when your binding's canvas initializes; see [Edit nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-nodes) for mounting and obtaining the live instance.

Add the component below to the quick start's existing application, retaining its entry file. The JavaScript entry retains its stylesheet import. Its explicit Close button tears down the view.

:::code-group
```ts title="JavaScript — src/main.ts"
// src/main.ts
import './style.css';
import { render } from '@grafloria/element';
import { nodes, edges } from './board-data';
import { StrokeModel } from '@grafloria/engine';
import { createDrawTool, createRectangleTool, createEraserTool, createStrokeEditTool, registerTool, once } from '@grafloria/renderer';
import type { WhiteboardHost } from '@grafloria/renderer';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 }, { id: 'annotation', label: 'Review this connection' },
  ));
  const draw = createDrawTool(host, { color: '#e11d48', width: 5, simplifyEpsilon: 0.8 });
  const rectangle = createRectangleTool(host, { fill: '#dbeafe', label: 'New box' });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const removeTools = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText = 'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';
  const buttons: HTMLButtonElement[] = [];
  function choose(index: number): void {
    tools.forEach((tool, i) => tool.setActive(i === index));
    buttons.forEach((button, i) => button.setAttribute('aria-pressed', String(i === index)));
  }
  ['Draw', 'Rectangle', 'Eraser', 'Edit ink', 'Navigate'].forEach((label, index) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.onclick = () => choose(index);
    buttons.push(button);
    toolbar.appendChild(button);
  });
  host.container.appendChild(toolbar);
  choose(2);
  return once(() => {
    removeTools.reverse().forEach(remove => remove());
    tools.forEach(tool => tool.dispose());
    toolbar.remove();
  });
}

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const close = document.createElement('button');
close.textContent = 'Close board';
const container = document.createElement('div');
container.style.cssText = 'width:100%;height:420px';
app.replaceChildren(close, container);
const instance = render({ nodes, edges }, container);
const cleanup = installWhiteboard(instance);
close.onclick = () => {
  cleanup();
  instance.dispose();
  container.remove();
  close.remove();
};
```
```tsx title="React — src/Whiteboard.tsx"
// src/Whiteboard.tsx
import { useCallback, useEffect, useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { nodes, edges } from './board-data';
import { StrokeModel } from '@grafloria/engine';
import { createDrawTool, createRectangleTool, createEraserTool, createStrokeEditTool, registerTool, once } from '@grafloria/renderer';
import type { WhiteboardHost } from '@grafloria/renderer';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 }, { id: 'annotation', label: 'Review this connection' },
  ));
  const draw = createDrawTool(host, { color: '#e11d48', width: 5, simplifyEpsilon: 0.8 });
  const rectangle = createRectangleTool(host, { fill: '#dbeafe', label: 'New box' });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const removeTools = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText = 'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';
  const buttons: HTMLButtonElement[] = [];
  function choose(index: number): void {
    tools.forEach((tool, i) => tool.setActive(i === index));
    buttons.forEach((button, i) => button.setAttribute('aria-pressed', String(i === index)));
  }
  ['Draw', 'Rectangle', 'Eraser', 'Edit ink', 'Navigate'].forEach((label, index) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.onclick = () => choose(index);
    buttons.push(button);
    toolbar.appendChild(button);
  });
  host.container.appendChild(toolbar);
  choose(2);
  return once(() => {
    removeTools.reverse().forEach(remove => remove());
    tools.forEach(tool => tool.dispose());
    toolbar.remove();
  });
}

export default function Whiteboard() {
  const cleanup = useRef<(() => void) | null>(null);
  const onInit = useCallback((instance: WhiteboardHost) => {
    cleanup.current?.();
    cleanup.current = installWhiteboard(instance);
  }, []);
  useEffect(() => () => { cleanup.current?.(); }, []);
  return <div style={{ height: 420 }}>
    <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
      style={{ height: '100%' }}
      onInit={onInit} />
  </div>;
}
```
```vue title="Vue — src/Whiteboard.vue"
<!-- src/Whiteboard.vue -->
<script setup lang="ts">
import { onUnmounted } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges } from './board-data';
import { StrokeModel } from '@grafloria/engine';
import { createDrawTool, createRectangleTool, createEraserTool, createStrokeEditTool, registerTool, once } from '@grafloria/renderer';
import type { WhiteboardHost } from '@grafloria/renderer';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 }, { id: 'annotation', label: 'Review this connection' },
  ));
  const draw = createDrawTool(host, { color: '#e11d48', width: 5, simplifyEpsilon: 0.8 });
  const rectangle = createRectangleTool(host, { fill: '#dbeafe', label: 'New box' });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const removeTools = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText = 'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';
  const buttons: HTMLButtonElement[] = [];
  function choose(index: number): void {
    tools.forEach((tool, i) => tool.setActive(i === index));
    buttons.forEach((button, i) => button.setAttribute('aria-pressed', String(i === index)));
  }
  ['Draw', 'Rectangle', 'Eraser', 'Edit ink', 'Navigate'].forEach((label, index) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.onclick = () => choose(index);
    buttons.push(button);
    toolbar.appendChild(button);
  });
  host.container.appendChild(toolbar);
  choose(2);
  return once(() => {
    removeTools.reverse().forEach(remove => remove());
    tools.forEach(tool => tool.dispose());
    toolbar.remove();
  });
}

let cleanup: (() => void) | undefined;
function onInit(instance: DiagramInstance) {
  cleanup?.();
  cleanup = installWhiteboard(instance);
}
onUnmounted(() => cleanup?.());
</script>

<template>
  <div style="height:420px">
    <GrafloriaFlow :default-nodes="nodes" :default-edges="edges"
      style="height:100%" @init="onInit" />
  </div>
</template>
```
```ts title="Angular — src/app/whiteboard.ts"
// src/app/whiteboard.ts
import { Component, ElementRef, viewChild } from '@angular/core';
import type { AfterViewInit, OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { WhiteboardHost } from '@grafloria/renderer';
import { nodes, edges } from '../board-data';
import { StrokeModel } from '@grafloria/engine';
import { createDrawTool, createRectangleTool, createEraserTool, createStrokeEditTool, registerTool, once } from '@grafloria/renderer';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 }, { id: 'annotation', label: 'Review this connection' },
  ));
  const draw = createDrawTool(host, { color: '#e11d48', width: 5, simplifyEpsilon: 0.8 });
  const rectangle = createRectangleTool(host, { fill: '#dbeafe', label: 'New box' });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const removeTools = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText = 'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';
  const buttons: HTMLButtonElement[] = [];
  function choose(index: number): void {
    tools.forEach((tool, i) => tool.setActive(i === index));
    buttons.forEach((button, i) => button.setAttribute('aria-pressed', String(i === index)));
  }
  ['Draw', 'Rectangle', 'Eraser', 'Edit ink', 'Navigate'].forEach((label, index) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.onclick = () => choose(index);
    buttons.push(button);
    toolbar.appendChild(button);
  });
  host.container.appendChild(toolbar);
  choose(2);
  return once(() => {
    removeTools.reverse().forEach(remove => remove());
    tools.forEach(tool => tool.dispose());
    toolbar.remove();
  });
}

@Component({
  selector: 'app-whiteboard',
  imports: [DiagramCanvasComponent],
  template: `
    <div #host style="height:420px">
      <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
        style="display:block;height:100%" />
    </div>`,
})
export class Whiteboard implements AfterViewInit, OnDestroy {
  nodes = nodes;
  edges = edges;
  private canvas = viewChild.required(DiagramCanvasComponent);
  private host = viewChild.required<ElementRef<HTMLElement>>('host');
  private cleanup?: () => void;

  ngAfterViewInit(): void {
    const canvas = this.canvas();
    const engine = canvas.activeEngine();
    const viewport = canvas.viewportController();
    const model = engine?.getDiagram();
    if (!engine || !viewport || !model) throw new Error('Canvas not initialized');
    const host: WhiteboardHost = {
      getModel: () => model,
      getEngine: () => engine,
      viewport,
      container: this.host().nativeElement,
      render: () => canvas.scheduleRender(),
    };
    this.cleanup = installWhiteboard(host);
  }

  ngOnDestroy(): void { this.cleanup?.(); }
}
```
```tsx title="Qwik — src/Whiteboard.tsx"
// src/Whiteboard.tsx
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import { nodes, edges } from './board-data';
import { StrokeModel } from '@grafloria/engine';
import { createDrawTool, createRectangleTool, createEraserTool, createStrokeEditTool, registerTool, once } from '@grafloria/renderer';
import type { WhiteboardHost } from '@grafloria/renderer';

function installWhiteboard(host: WhiteboardHost): () => void {
  host.getModel().addStroke(new StrokeModel(
    [{ x: 100, y: 220 }, { x: 180, y: 180 }, { x: 260, y: 220 }],
    { color: '#e11d48', width: 5 }, { id: 'annotation', label: 'Review this connection' },
  ));
  const draw = createDrawTool(host, { color: '#e11d48', width: 5, simplifyEpsilon: 0.8 });
  const rectangle = createRectangleTool(host, { fill: '#dbeafe', label: 'New box' });
  const eraser = createEraserTool(host, { radius: 12 });
  const edit = createStrokeEditTool(host);
  const tools = [draw, rectangle, eraser, edit];
  const removeTools = tools.map(tool => registerTool(tool));
  const toolbar = document.createElement('div');
  toolbar.style.cssText = 'position:absolute;top:8px;left:8px;z-index:30;display:flex;gap:8px';
  host.container.style.position = 'relative';
  const buttons: HTMLButtonElement[] = [];
  function choose(index: number): void {
    tools.forEach((tool, i) => tool.setActive(i === index));
    buttons.forEach((button, i) => button.setAttribute('aria-pressed', String(i === index)));
  }
  ['Draw', 'Rectangle', 'Eraser', 'Edit ink', 'Navigate'].forEach((label, index) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    button.onclick = () => choose(index);
    buttons.push(button);
    toolbar.appendChild(button);
  });
  host.container.appendChild(toolbar);
  choose(2);
  return once(() => {
    removeTools.reverse().forEach(remove => remove());
    tools.forEach(tool => tool.dispose());
    toolbar.remove();
  });
}

export default component$(() => {
  const teardown = useSignal<NoSerialize<() => void>>();
  useVisibleTask$(({ cleanup }) => {
    cleanup(() => teardown.value?.());
  });
  return <div style={{ height: '420px' }}>
    <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
      style={{ height: '100%' }}
      onInit$={instance => {
        teardown.value?.();
        teardown.value = noSerialize(installWhiteboard(instance));
      }} />
  </div>;
});
```
:::

For Qwik, put the data module at `src/board-data.ts`. The live cleanup function stays outside serialized state through `noSerialize()`; tool registration happens in the browser initialization callback. See [Qwik integration](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-resumable-integration) for resumable objects.

You see two connected boxes, a red chevron below them and five tool buttons.

Look below the Review-to-Approve connection for the red ink annotation; the five tool buttons sit above the boxes.

The React board places Review to the left of Approve, with an arrow between them and the red ink below.

Vue renders the same seeded diagram and toolbar.

The Qwik initialization callback installs the whiteboard tools on the live instance.

## Eraser

1. Run the mounted board above; **Eraser** is active on load.
2. Press on the red ink and sweep across it.
3. Release the pointer: the entire intersected stroke disappears.

The runnable eraser setup is `createEraserTool(host, { radius: 12 })` in each mounted example above. Its radius is measured in world units, and the sweep tests the segments between pointer samples. It removes whole stroke entities, not fragments of a line. With `getEngine()` supplied, the whole sweep commits through one command; Ctrl+Z or ⌘Z restores it in one undo step.

Try the [Eraser demo](https://grafloria.com/demos/whiteboard/eraser.html) to sweep across several strokes at once.

## Draw, create rectangles and edit ink

- Select **Draw**, press and drag, then release. The trace becomes one simplified vector stroke. The draw tool commits through the engine's command history. See [Freehand draw](https://grafloria.com/demos/whiteboard/freehand-draw.html).
- Select **Rectangle**, then drag a box. Release to create a labeled node with the configured fill—not an ink stroke. It participates in connections and layout. See [Rectangle tool](https://grafloria.com/demos/whiteboard/rectangle.html).
- Select **Edit ink**, press on an existing stroke and drag it. Release to commit a translation through one command. A press on empty canvas does not claim an ink-edit gesture. See [Stroke edit](https://grafloria.com/demos/whiteboard/stroke-edit.html).
- Select **Navigate** to deactivate all four tools and return pointer gestures to the canvas's built-in interaction.

The returned [`DrawTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#drawtool), [`RectangleTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#rectangletool), [`EraserTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#erasertool) and [`StrokeEditTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#strokeedittool) expose `setActive()` and `isActive()`. Keep at most one broad mode tool active. Ink editing has priority 2; drawing, rectangles and erasing have priority 1. If you keep editing active alongside an eraser, a press on ink goes to editing. The sample switches editing off when you choose Eraser.

### Options that change the result

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `DrawToolOptions.color` | `string` | `'#1f2933'` | Sets ink color. |
| `DrawToolOptions.width` | `number` | `3` | Sets nominal width in world units. |
| `DrawToolOptions.simplifyEpsilon` | `number` | Model's simplification tolerance | Sets the tolerance used at commit. |
| `RectangleToolOptions.fill` | `string` | Not supplied by the tool | Writes the node's fill style when supplied. |
| `RectangleToolOptions.label` | `string` | Not supplied | Writes the new node's label metadata. |
| `RectangleToolOptions.minSize` | `number` | `4` | Rejects a box whose width or height is below this world-unit size. |
| `EraserToolOptions.radius` | `number` | `8` | Adds reach around the swept segments. |
| `StrokeEditToolOptions.tolerance` | `number` | `6` | Adds reach to geometric ink hit-testing. |
| `active` on each tool's options | `boolean` | `true` | Lets the registered tool claim gestures. |

## 2. Implement a point-specific gesture claim

A [`CanvasTool`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-interfaces-a-t#canvastool) owns the entire gesture when its `hitTest()` wins. Supply an explicit priority and a narrow test rather than relying on registration order. Use `event.world` for model geometry; use `event.screen` for CSS-pixel feedback.

This optional module adds an Alt-press inspector. It does not move or select the node: it claims that gesture and reports the hit node's id in a panel. Call `installInspector(instance)` from the same initialization callback as the whiteboard, and call its returned cleanup on unmount.

[`createDiagramApi`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#creatediagramapi) supplies world-space queries. [`createPortal`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#createportal) pins the result panel to the screen; [`createViewportPortal`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#createviewportportal) places a note inside the camera-transformed HTML layer.

```ts title="src/inspector.ts"
import { boxesIntersect } from '@grafloria/engine';
import {
  createDiagramApi, createPortal, createViewportPortal,
  registerTool, once,
} from '@grafloria/renderer';
import type { CanvasTool, DiagramInstance } from '@grafloria/renderer';

export function installInspector(instance: DiagramInstance): () => void {
  const api = createDiagramApi(instance);
  const panel = createPortal(instance.container, { placement: 'bottom-right' });
  panel.element.textContent = 'Alt-press a node to inspect its id';
  const htmlLayer = instance.container.querySelector<HTMLElement>('.grafloria-html-layer');
  if (!htmlLayer) throw new Error('Missing HTML layer');
  const note = createViewportPortal(htmlLayer, { x: 80, y: 280 });
  note.element.textContent = 'World-space annotation';

  const tool: CanvasTool = {
    id: 'acme.inspect',
    priority: 3,
    hitTest: (event, hit) => event.modifiers.alt && Boolean(hit.node),
    onPointerDown: event => {
      const node = api.getNodeAt(event.world);
      if (!node) return;
      const box = node.getBoundingBox();
      const overlapping = api.getNodes().filter(other =>
        other.id !== node.id && boxesIntersect(box, other.getBoundingBox()));
      panel.element.textContent = `${node.id}: ${overlapping.length} overlapping boxes`;
    },
  };
  const remove = registerTool(tool);
  return once(() => {
    remove();
    note.dispose();
    panel.dispose();
    api.dispose();
  });
}
```

[`boxesIntersect`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-utils#boxesintersect) treats touching boundaries as an intersection. For a marquee, `api.getIntersectingNodes(rect, { fully: true })` asks for complete enclosure instead. Follow [Marquee selection](https://grafloria.com/demos/interaction/marquee-select.html) for a rubber-band tool with Shift-add behavior, and [Select, copy and add actions](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/selection-and-actions) for selection state.

## 3. Bind a capability-scoped extension

Use [`createExtensionHost`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#createextensionhost) when an extension contributes several registrations and needs one unload handle. Pass `instance.registry` for diagram-local shape and link contributions. Tools and connection validators use process-wide registrations, including the coordinate tool below; mount this example on a page with one diagram.

The sample grants only tools. Alt-pressing empty canvas reports its world coordinates through your callback; other presses fall through. Call this installer from your mounted instance's initialization callback and retain the returned cleanup.

```ts title="src/coordinate-extension.ts"
import { createExtensionHost } from '@grafloria/renderer';
import type { DiagramInstance } from '@grafloria/renderer';

export function installCoordinates(
  instance: DiagramInstance,
  report: (x: number, y: number) => void,
): () => void {
  const host = createExtensionHost({
    engine: instance.getEngine(),
    registry: instance.registry,
    root: instance.container,
    requestRender: () => instance.render(),
  });
  return host.register({
    manifest: {
      id: 'acme.coordinates', version: '1.0.0',
      engines: { grafloria: '^1.0.0' },
      capabilities: ['tools'],
    },
    activate({ capabilities }) {
      capabilities.tools.register({
        id: 'acme.coordinates', priority: 3,
        hitTest: (event, hit) => event.modifiers.alt && hit.empty,
        onPointerDown: event => report(event.world.x, event.world.y),
      });
    },
  });
}
```

[`ExtensionHost`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-classes#extensionhost) validates compatibility and capability grants before activation. Its compatibility range refers to the extension API version, not the npm package version. [`satisfies`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#satisfies) is the semver-range matcher behind that check. Tool registrations unwind when the extension unloads, restoring overridden tools. Use new, namespaced ids for template and animation contributions: unloading removes those entries rather than restoring previous definitions.

| Capability | Contribution |
| --- | --- |
| `'shapes'` | Node geometry. |
| `'links'` | Templates, markers, connectors, anchors and connection points. |
| `'routers'` | Routing algorithms on the engine. |
| `'templates'` | Node templates; the host must supply a template registry. |
| `'animations'` | Named animations. |
| `'tools'` | Gesture tools and connection validators. |
| `'panels'` | Screen-space, world-space and counter-scaled panels. |

[`DiagramRegistry`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-diagramregistry) owns a diagram's contribution tables. [`RegistryScope`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-classes#registryscope) overlays the global tables; absent names fall through. [`SHAPES`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-constants#shapes) and [`ANCHORS`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-constants#anchors) name two of those tables. Prefer the registry and capability methods over writing table entries yourself.

Engine plugins have a separate lifecycle: `engine.registerPlugin(plugin)` registers, installs and activates a plugin asynchronously; `engine.getPlugin(name)` returns a registered plugin or `undefined`.

## 4. Register a named layout

Use the component's `layout` prop for shipped algorithms. Register an algorithm only when you need to change how positions are calculated. The engine's `getLayoutRegistry()` returns a [`LayoutRegistry`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-classes#layoutregistry) with built-ins already present.

This installer adds a **Grid layout** button to a mounted instance. It registers a named layout using the shipped [`gridLayout`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-functions-a-t#gridlayout), then runs it through `engine.layout()`. Clicking the button places the nodes in two columns. A second button runs the service's shipped Dagre adapter top to bottom.

```ts title="src/grid-extension.ts"
import { gridLayout, LayoutService } from '@grafloria/engine';
import { once } from '@grafloria/renderer';
import type { DiagramInstance } from '@grafloria/renderer';

export function installGrid(instance: DiagramInstance): () => void {
  const engine = instance.getEngine();
  const registry = engine.getLayoutRegistry();
  const unregister = registry.register({
    name: 'acme-grid',
    async apply(diagram, options) {
      return gridLayout(diagram.getNodes(), diagram.getLinks(), options);
    },
  });
  const service = new LayoutService();
  engine.setLayoutService(service);
  const button = document.createElement('button');
  button.textContent = 'Grid layout';
  button.style.cssText = 'position:absolute;bottom:8px;left:8px;z-index:30';
  button.onclick = () => { void engine.layout('acme-grid', { columns: 2 }); };
  const adapterButton = document.createElement('button');
  adapterButton.textContent = 'Adapter layout';
  adapterButton.style.cssText = 'position:absolute;bottom:8px;left:120px;z-index:30';
  adapterButton.onclick = () => {
    void engine.applyLayout({ adapter: 'dagre', options: { direction: 'TB' } });
  };
  instance.container.append(button, adapterButton);
  return once(() => { button.remove(); adapterButton.remove(); unregister(); });
}
```

[`LayoutService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-classes#layoutservice) manages adapters for `engine.applyLayout()`; constructing it registers Dagre and ELK. `setLayoutService()` supplies that service to the engine. It is separate from named registry execution: `engine.layout()` does not need this setup. Use `service.registerAdapter()` for a custom [`LayoutAdapter`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-interfaces-i-l#layoutadapter), whose contract includes `apply()`, `applyIncremental()` and `validateOptions()`.

[`layoutService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-constants#layoutservice) is the application-wide singleton alternative. [`DEFAULT_LAYOUT_NAME`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-constants#defaultlayoutname) is `'auto'`, which selects an algorithm rather than naming a fixed one. [`runLayout`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-functions-a-t#runlayout) runs a registry entry and commits its returned positions through `setPosition()`. [`nodeSize`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-functions-a-t#nodesize) provides the footprint defaults used by portfolio layouts.

Grid fill directions are `'TB'` (left to right, then down), `'LR'` (top to bottom, then across), `'BT'` (mirrored vertical fill) and `'RL'` (mirrored horizontal fill). Grid layout ignores links.

### Place one node without arranging the whole graph

[`LayoutManager`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-classes#layoutmanager) answers a different question: where to put one new node. This installer adds a button that calculates placement against the mounted model, then adds a [`NodeModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-nodemodel) through [`AddNodeCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-a-r#addnodecommand). Use this installer instead of the grid toolbar when you want to demonstrate single-node placement.

```ts title="src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import { AddNodeCommand, LayoutManager, NodeModel } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges } from './board-data';

function installPlacement(instance: DiagramInstance): () => void {
  const model = instance.getModel();
  const manager = new LayoutManager(model);
  const button = document.createElement('button');
  button.textContent = 'Place a node';
  button.style.cssText = 'position:absolute;bottom:8px;left:120px;z-index:30';
  button.onclick = () => {
    const node = new NodeModel({
      id: crypto.randomUUID(), type: 'basic', size: { width: 140, height: 60 },
      position: { x: 0, y: 0 },
    });
    node.setMetadata('label', 'Placed node');
    const result = manager.calculatePlacement(node, instance.viewport.getViewport(), {
      node, spacing: 30, padding: 30,
    });
    if (!result.success) return;
    node.setPosition(result.position.x, result.position.y);
    void instance.getEngine().commandManager.execute(new AddNodeCommand(node));
  };
  instance.container.appendChild(button);
  return () => { button.remove(); manager.dispose(); };
}

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const container = document.createElement('div');
container.style.cssText = 'position:relative;width:100%;height:420px';
const close = document.createElement('button');
close.textContent = 'Close placement example';
app.replaceChildren(close, container);
const instance = render({ nodes, edges }, container);
const cleanup = installPlacement(instance);
close.onclick = () => {
  cleanup();
  instance.dispose();
  app.replaceChildren();
};
```

This entry retains the JavaScript quick start's stylesheet import. You see Review, Approve and the **Place a node** button; pressing the button adds a third box at the calculated position. Close runs the installer's cleanup before disposing the instance.

The manager's algorithm choices are `'grid'`, `'force-directed'`, `'hierarchical'` and `'hybrid'`. [`PlacementOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-interfaces-l-u#placementoptions) carries `node`, `viewport` and `existingNodes`; `calculatePlacement()` supplies those from its arguments and diagram, with optional overrides. `preferredPosition` is a position hint, `respectManualPositions` requests preservation of existing manual positions, `spacing` controls gaps and `padding` controls viewport margins. Their interpretation belongs to the selected placement algorithm; the grid placer above uses spacing and padding.

## 5. Move layout execution to a worker

Create the worker in your application and pass it to `engine.setLayoutPort()`. [`serveLayout`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-functions-a-t#servelayout) is the worker's message loop. The same `engine.layout()` call now returns positions calculated off the main thread.

```ts title="src/layout.worker.ts"
import { serveLayout } from '@grafloria/engine';

serveLayout(self);
```

The entry below mounts the two connected nodes and adds **Run worker layout** and **Cancel layout** buttons. Your bundler resolves the module worker URL; the engine does not construct a worker for you. Close runs cleanup when the view is removed.

```ts title="src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges } from './board-data';

function installWorkerLayout(instance: DiagramInstance): () => void {
  const engine = instance.getEngine();
  const worker = new Worker(new URL('./layout.worker.ts', import.meta.url), { type: 'module' });
  engine.setLayoutPort(worker);
  let controller: AbortController | undefined;
  const panel = document.createElement('div');
  panel.style.cssText = 'position:absolute;bottom:40px;left:8px;z-index:30';
  const run = document.createElement('button');
  run.textContent = 'Run worker layout';
  const cancel = document.createElement('button');
  cancel.textContent = 'Cancel layout';
  const status = document.createElement('output');
  run.onclick = async () => {
    run.disabled = true;
    controller = new AbortController();
    try {
      const result = await engine.layout('force', {
        iterations: 4000, signal: controller.signal,
        onProgress: progress => { status.textContent = `${Math.round(progress.progress * 100)}%`; },
      });
      status.textContent = result.partial ? `Partial: ${result.reason}` : 'Complete';
    } catch (error) {
      status.textContent = error instanceof Error ? error.message : String(error);
    } finally {
      run.disabled = false;
    }
  };
  cancel.onclick = () => controller?.abort();
  panel.append(run, cancel, status);
  instance.container.appendChild(panel);
  return () => {
    controller?.abort();
    engine.setLayoutPort(undefined);
    worker.terminate();
    panel.remove();
  };
}

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const container = document.createElement('div');
container.style.cssText = 'position:relative;width:100%;height:420px';
const close = document.createElement('button');
close.textContent = 'Close worker example';
app.replaceChildren(close, container);
const instance = render({ nodes, edges }, container);
const cleanup = installWorkerLayout(instance);
close.onclick = () => {
  cleanup();
  instance.dispose();
  app.replaceChildren();
};
```

Watch the progress output while the nodes rearrange. For this connected force graph, cancellation keeps the best-so-far positions and returns `partial: true`; `reason` is `'cancelled'`, `'timeout'` or `'iteration-cap'` for the corresponding early stop. A completed run has no early-stop reason. Mid-run cancellation requires a steppable adapter and a graph with at most one connected component. Disconnected graphs and opaque adapters check cancellation before execution, then run the entire layout and return `partial: false`. See [Off-thread layout](https://grafloria.com/demos/layout/off-thread-layout.html) for a larger graph.

A runtime-registered closure cannot cross `postMessage()`. A custom worker algorithm must exist in the worker bundle too: pass a `resolve` function to `serveLayout()` that returns its adapter by name. Without a worker port, execution resolves against the live engine registry. See [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram) for layout options and [Preserve layout while editing](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/incremental-layout) for incremental placement policy.

## Inspect a routing extension on the mounted diagram

Use an [`IRouter`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#irouter) contribution when you need a named routing policy rather than a built-in edge option. This example delegates geometry to the shipped [`OrthogonalRouter`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#orthogonalrouter), which calculates right-angle routes, and uses a Bézier connector to draw the result. See [Route and edit edges](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/route-and-edit-edges) for ordinary routing choices and interactive bend editing.

1. Keep `src/board-data.ts` from the whiteboard example and use this JavaScript entry instead of the whiteboard entry.
2. Press **Inspect path** to report the rendered link's control-point count and its simplified anchor count.
3. Move either node, then press **Inspect path** again to query the updated geometry.

The engine owns the [`LiveReroutingEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#livereroutingengine) service that updates link paths on node movement and resize. [`PathSimplifier`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#pathsimplifier) removes collinear points and simplifies a point array within a tolerance; the inspection below does not replace the link's stored path. [`ControlPointEditor`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-controlpointeditor) extracts Bézier control points from the mounted link's segments.

```ts title="src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import { OrthogonalRouter, PathSimplifier } from '@grafloria/engine';
import type { IRouter, LiveReroutingEngine } from '@grafloria/engine';
import { ControlPointEditor } from '@grafloria/renderer';
import { nodes, edges } from './board-data';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const container = document.createElement('div');
container.style.cssText = 'position:relative;width:100%;height:420px';
const inspect = document.createElement('button');
inspect.textContent = 'Inspect path';
const close = document.createElement('button');
close.textContent = 'Close routing example';
const output = document.createElement('output');
app.replaceChildren(inspect, close, output, container);
const instance = render({ nodes, edges }, container);
const engine = instance.getEngine();
const routing = engine.getRoutingEngine();
const orthogonal = new OrthogonalRouter();
const router: IRouter = {
  getName: () => 'acme-review',
  route: request => orthogonal.route(request),
};
routing.registerRouter(router.getName(), router);
instance.setEdges(edges.map(edge => ({
  ...edge, router: router.getName(), connector: 'bezier',
})));
engine.enableLiveRerouting();
const live: LiveReroutingEngine | null = engine.getLiveReroutingEngine();
if (!live) throw new Error('Live rerouting is not initialized');
const config = engine.getInteractionConfig().controlPointEditor;
if (!config) throw new Error('Control point editor is not configured');
const editor = new ControlPointEditor(config);
const simplifier = new PathSimplifier();
inspect.onclick = () => {
  const link = instance.getModel().getLink('review-approve');
  if (!link) throw new Error('Missing review-approve link');
  const controls = editor.getControlPoints(link.segments);
  const anchors = link.segments.flatMap(segment => [segment.from, segment.to]);
  const cleaned = simplifier.removeCollinearPoints(anchors);
  const simplified = simplifier.simplify(cleaned, 2);
  output.textContent =
    `${controls.length} control points; ${simplified.length} simplified anchors`;
};
close.onclick = () => {
  live.disable();
  routing.unregisterRouter(router.getName());
  instance.dispose();
  app.replaceChildren();
};
```

You see the connected Review and Approve boxes and an inspection button; the output appears when you press it. The registered router calculates geometry for that mounted connection, not for a separate routing model.

For other routing policies, [`ObstacleMap`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#obstaclemap) spatially indexes obstacles for region, point and line queries; [`StraightRouter`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-routing#straightrouter) returns a direct endpoint-to-endpoint line. [`distance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-utils#distance) returns the Euclidean distance between two points, and [`midpoint`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-utils#midpoint) returns their midpoint.

## Document migrations and transport contracts

A [`DiagramMigration`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-serialization#diagrammigration) is a pure document upgrade with `from`, `to`, `description` and `migrate(data)`. `registerDiagramMigration()` accepts exactly one schema-version step (`to === from + 1`) and rejects duplicate source versions. The loader runs the chain; missing steps and documents newer than the runtime throw rather than partially load. Keep application payload upgrades distinct from the engine's already-registered schema steps. Use the [document save and restore path](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore) to load once and protect newer edits.

A [`SyncTransport`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-sync-interfaces#synctransport) moves messages, not model edits. `send()` broadcasts to other peers and does not echo to the sender; while disconnected it is a no-op. `onMessage()` returns an unsubscribe. `onStatus()` reports `'connected'` and `'disconnected'`, which the synchronization adapter uses to catch up after reconnecting. `connect()` is idempotent, `disconnect()` allows reopening, and `close()` permanently tears down the transport. Start with the shipped WebSocket or BroadcastChannel transport rather than implementing conflict resolution in a new pipe.

### Run a WebSocket relay

The relay forwards frames verbatim to every other open socket. Run this complete server in Node, separately from the browser app:

```bash
npm install ws
node relay.mjs
```

```js title="relay.mjs"
import { WebSocketServer, WebSocket } from 'ws';

const server = new WebSocketServer({ host: '127.0.0.1', port: 8787 });
server.on('connection', socket => {
  socket.on('message', (data, isBinary) => {
    for (const peer of server.clients) {
      if (peer !== socket && peer.readyState === WebSocket.OPEN) {
        peer.send(data, { binary: isBinary });
      }
    }
  });
});
server.on('error', error => { console.error(error); });
```

Connect your browser client's WebSocket transport to `ws://127.0.0.1:8787`. This server treats all connected sockets as one development room. Add authentication, room membership, backpressure and persistence before using a relay in production. Follow [Sync collaborators](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/sync-collaborators) for the mounted client, event-driven connection status and transport cleanup.

## Related extension layers

- [Route and edit edges](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/route-and-edit-edges) covers custom routers, live rerouting, path simplification and control-point editors on rendered links.
- [Arrange ports and connect](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/ports-and-connection-gestures) covers proximity candidates, snap configuration and undoable link commands.
- [Validate connections](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/validate-connections) covers validator registration, validity results and registry cleanup.
- [Import Mermaid and draw.io](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/import-diagram-text) covers parsing, AST transformation and text generation without duplicating the loader.
- [Customize rendering contracts](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/custom-rendering) covers interaction, selection, highlighter, waypoint and in-place text editor layers.
