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, React, Vue, Angular or Qwik 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 to the factories. Angular supplies the narrower WhiteboardHost from its canvas, camera and container.
createDrawTool, createRectangleTool, createEraserTool and createStrokeEditTool return tools to register with registerTool. The module below seeds visible ink using StrokeModel, adds a toolbar, and starts in eraser mode.
Install the packages for your binding in the quick start's project.
For JavaScript:
bashnpm install @grafloria/element @grafloria/engine @grafloria/renderer
For React:
bashnpm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer
For Vue:
bashnpm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer
For Angular:
bashnpm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer
For Qwik, follow the starter's use of development dependencies:
bashnpm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer
tsimport './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 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 and EdgeSpec. It gives the ink a diagram to annotate rather than an empty canvas.
tsimport 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 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.
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// 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<!-- 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// 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// 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 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
- Run the mounted board above; Eraser is active on load.
- Press on the red ink and sweep across it.
- 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 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.
- 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.
- 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.
- Select Navigate to deactivate all four tools and return pointer gestures to the canvas's built-in interaction.
The returned DrawTool, RectangleTool, EraserTool and 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 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 supplies world-space queries. createPortal pins the result panel to the screen; createViewportPortal places a note inside the camera-transformed HTML layer.
tsimport { 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 treats touching boundaries as an intersection. For a marquee, api.getIntersectingNodes(rect, { fully: true }) asks for complete enclosure instead. Follow Marquee selection for a rubber-band tool with Shift-add behavior, and Select, copy and add actions for selection state.
3. Bind a capability-scoped extension
Use 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.
tsimport { 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 validates compatibility and capability grants before activation. Its compatibility range refers to the extension API version, not the npm package version. 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 owns a diagram's contribution tables. RegistryScope overlays the global tables; absent names fall through. SHAPES and 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 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, 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.
tsimport { 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 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, whose contract includes apply(), applyIncremental() and validateOptions().
layoutService is the application-wide singleton alternative. DEFAULT_LAYOUT_NAME is 'auto', which selects an algorithm rather than naming a fixed one. runLayout runs a registry entry and commits its returned positions through setPosition(). 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 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 through AddNodeCommand. Use this installer instead of the grid toolbar when you want to demonstrate single-node placement.
tsimport './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 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 is the worker's message loop. The same engine.layout() call now returns positions calculated off the main thread.
tsimport { 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.
tsimport './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 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 for layout options and Preserve layout while editing for incremental placement policy.
Inspect a routing extension on the mounted diagram
Use an IRouter contribution when you need a named routing policy rather than a built-in edge option. This example delegates geometry to the shipped OrthogonalRouter, which calculates right-angle routes, and uses a Bézier connector to draw the result. See Route and edit edges for ordinary routing choices and interactive bend editing.
- Keep
src/board-data.tsfrom the whiteboard example and use this JavaScript entry instead of the whiteboard entry. - Press Inspect path to report the rendered link's control-point count and its simplified anchor count.
- Move either node, then press Inspect path again to query the updated geometry.
The engine owns the LiveReroutingEngine service that updates link paths on node movement and resize. PathSimplifier removes collinear points and simplifies a point array within a tolerance; the inspection below does not replace the link's stored path. ControlPointEditor extracts Bézier control points from the mounted link's segments.
tsimport './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 spatially indexes obstacles for region, point and line queries; StraightRouter returns a direct endpoint-to-endpoint line. distance returns the Euclidean distance between two points, and midpoint returns their midpoint.
Document migrations and transport contracts
A 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 to load once and protect newer edits.
A 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:
bashnpm install ws node relay.mjs
jsimport { 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 for the mounted client, event-driven connection status and transport cleanup.
Related extension layers
- Route and edit edges covers custom routers, live rerouting, path simplification and control-point editors on rendered links.
- Arrange ports and connect covers proximity candidates, snap configuration and undoable link commands.
- Validate connections covers validator registration, validity results and registry cleanup.
- Import Mermaid and draw.io covers parsing, AST transformation and text generation without duplicating the loader.
- Customize rendering contracts covers interaction, selection, highlighter, waypoint and in-place text editor layers.
Was this page helpful?