# Grafloria
# JavaScript quick start
Mount an editable diagram in plain JavaScript, give its host and nodes a size, and keep the live instance for later updates.
Grafloria uses one headless engine beneath its framework bindings. In JavaScript, [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core) mounts data into an element and returns a [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance) that you use for updates, events, and camera operations.
## Prerequisites
Use a browser-based JavaScript project with Node.js and npm. Install the published packages:
```bash
npm install @grafloria/element @grafloria/renderer @grafloria/engine
```
## 1. Create a sized host
Give the host a resolved height. Give each node a `size` with its width and height; `position` places it in the diagram.
```html
```
The host is now large enough for the renderer to paint; the JavaScript sample gives each box explicit dimensions.
## 2. Render real data
Put nodes and edges in the render specification. The specification is data, not a Mermaid-style text string. Each edge refers to its source and target node by ID.
```js title="main.js"
import { render } from '@grafloria/element';
const canvas = document.getElementById('canvas');
if (!(canvas instanceof HTMLElement)) {
throw new Error('The #canvas host is missing');
}
canvas.style.height = '480px';
const nodes = [
{
id: 'ingest',
position: { x: 60, y: 80 },
size: { width: 180, height: 80 },
data: { label: 'Ingest' },
},
{
id: 'publish',
position: { x: 380, y: 80 },
size: { width: 180, height: 80 },
data: { label: 'Publish' },
},
];
const edges = [
{ id: 'ingest-to-publish', source: 'ingest', target: 'publish' },
];
const api = render(
{ nodes, edges },
canvas,
);
api.fitView(40);
window.addEventListener('pagehide', () => api.dispose(), { once: true });
```
The mounted canvas shows two editable boxes, `Ingest` and `Publish`, joined by an edge. You can drag nodes, draw connections, pan, zoom, and use Cmd/Ctrl+Z to undo. `fitView(40)` frames the content with 40 pixels of padding.

The `api` variable is the live [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance), not a copy of the input data. Subscribe to an instance event and update the mounted data through the instance methods:
```js title="main.js"
import { render } from '@grafloria/element';
const nodes = [
{ id: 'ingest', position: { x: 60, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'publish', position: { x: 380, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
];
const edges = [{ id: 'ingest-to-publish', source: 'ingest', target: 'publish' }];
const canvas = document.getElementById('canvas');
if (!(canvas instanceof HTMLElement)) {
throw new Error('The #canvas host is missing');
}
canvas.style.height = '480px';
const api = render({ nodes, edges }, canvas);
const unsubscribe = api.on('nodes:change', ({ nodes: changedNodes }) => {
console.log('nodes in the live model:', changedNodes.length);
});
const nextNodes = [
...nodes,
{ id: 'archive', position: { x: 700, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Archive' } },
];
const nextEdges = [
...edges,
{ id: 'publish-to-archive', source: 'publish', target: 'archive' },
];
api.setEdges([]);
api.setNodes([]);
api.setNodes(nextNodes);
api.setEdges(nextEdges);
api.fitView(40);
window.addEventListener('pagehide', () => {
unsubscribe();
api.dispose();
}, { once: true });
```
The canvas now contains a third box and a second edge. The listener receives the live node-change payload; calling the returned function removes that listener.

When replacing edited data that reuses persistent IDs, clear the existing edges and nodes before applying the replacement. Reconciliation preserves existing live models, so applying replacement arrays alone can retain stale models.
## 3. Clean up with the page lifecycle
Dispose the instance when the host leaves the page. Do not dispose it immediately after mounting: disposal removes the live diagram. The first sample registers this cleanup with `pagehide`.
## Use the custom element instead
[`GrafloriaFlowElement`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core) is the web-component form of the same editor. Import the package once, put JSON data in its `nodes` and `edges` attributes, and give the element a height.
```html title="index.html"
```
This version shows the same editable two-node diagram without a framework component. Its `grafloria-connect` listener receives the connected link.

## What you have at the end
You have an editable, sized diagram backed by plain node and edge data, plus a live instance for fitting the view, listening for changes, replacing data, and disposing the renderer. The repository's [JavaScript starter](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/starters/javascript) uses the same mounting shape. Try it at the [JavaScript live demo](https://grafloria.com/javascript/).
For layout, themes, and other engine behavior, continue to [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works).
# React quick start
Render a typed, editable diagram in React, size its canvas, keep the graph in React state, and retain the mounted instance for imperative calls.
## The idea
[`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) renders node and edge data as an editable React canvas. The shared engine handles dragging, connecting, panning, and zooming.
## Prerequisites and installation
Use React 17, 18, or 19 with the matching `react-dom` version. Install the React binding and its peer packages:
```bash
npm install @grafloria/react @grafloria/engine @grafloria/renderer react react-dom @grafloria/element
```
## Build the diagram
1. Create `App.tsx` with typed node and edge arrays. [`NodeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-nodespec#nodespec) describes each box, and [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) connects node IDs.
2. Give the flow a real width and height through `style`. The component's canvas uses the host's resolved size; a host with no height renders no visible canvas.
3. Use [`useNodesState`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#usenodesstate) and [`useEdgesState`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#useedgesstate) for controlled state. Pass the third value from each tuple back to the corresponding change prop. This lets a drag update React state instead of snapping the node back to the previous render.
4. Capture the [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) in `onInit`. The button below calls `fitView()` on the mounted instance, framing the two nodes without rebuilding the component.
```tsx title="App.tsx"
import { useRef } from 'react';
import {
GrafloriaFlow,
useEdgesState,
useNodesState,
} from '@grafloria/react';
import type {
DiagramInstance,
EdgeSpec,
NodeSpec,
} from '@grafloria/react';
const initialNodes: NodeSpec[] = [
{
id: 'ingest',
position: { x: 60, y: 80 },
size: { width: 180, height: 80 },
data: { label: 'Ingest' },
},
{
id: 'publish',
position: { x: 380, y: 80 },
size: { width: 180, height: 80 },
data: { label: 'Publish' },
},
];
const initialEdges: EdgeSpec[] = [
{ id: 'ingest-to-publish', source: 'ingest', target: 'publish' },
];
export default function App() {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, , onEdgesChange] = useEdgesState(initialEdges);
const instanceRef = useRef(null);
function addNode() {
setNodes((current) => [
...current,
{
id: `node-${current.length}`,
position: { x: 220, y: 240 },
size: { width: 180, height: 80 },
data: { label: 'New step' },
},
]);
}
return (
{
instanceRef.current = instance;
}}
plugins
style={{ width: '100%', height: 480 }}
/>
);
}
```

The mounted result shows two labelled boxes joined by an edge in a 480-pixel-tall canvas. You can drag either box, pan, zoom, and draw connections. `plugins` adds the canvas controls, minimap, and background. Selecting **Fit view** calls the captured instance and frames the current content.
For a self-contained viewer or demo, use `defaultNodes` and `defaultEdges` instead. Those props seed the instance, which owns the data afterward; use controlled `nodes` and `edges` when another part of your application needs to persist or inspect the graph.
## Where next
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram) explains container sizing and presentation options.
- [State and data flow in React](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/instance-and-bindings) covers controlled versus uncontrolled ownership in more depth.
- [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) shows how to reach engine behavior through the instance.
- Try the [React starter](https://grafloria.com/react/) or inspect its [source](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/starters/react).
# Vue quick start
Render a typed Vue diagram, add slot-defined nodes, size its host, and keep the mounted instance available for imperative actions.
## What you build
[`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-vue#grafloriaflow) is the Vue surface over Grafloria's shared headless engine. The model is data, while the engine handles diagram behavior such as fitting the view. In this tutorial, the canvas shows two connected cards, a minimap and zoom controls, and a **Fit view** button.
## Prerequisites
- Vue 3.4 or later
- A Vue application using a bundler such as Vite
The Vue package declares Vue 3.4+, `@grafloria/engine` 0.3+, `@grafloria/renderer` 0.4.16+, and `@grafloria/element` 0.4.3+ as peer dependencies.
## 1. Install the packages
```bash
npm install @grafloria/vue @grafloria/engine @grafloria/renderer @grafloria/element vue
```
## 2. Mount a typed flow
Replace your `App.vue` with this component. [`NodeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-nodespec#nodespec) describes the boxes and [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) describes the connection between them.
```vue title="src/App.vue"
{{ data.title }}owner: {{ data.owner }}
```

The `style` gives the canvas both a width and a resolved height. The two `job` nodes render through `#node-job`, and the slot receives the node's data, so the canvas shows **Build** and **Deploy** as cards rather than stock rectangles. `v-model:nodes` and `v-model:edges` keep the Vue refs synchronized when the user edits the diagram. `plugins="true"` mounts the shipped minimap, zoom/fit controls, and background grid.
## 3. Use the instance
The `@init` event supplies the live [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) after the diagram mounts. The sample stores it and calls `fitView(24)` from the button; the view frames the diagram with 24 units of padding. The same instance exposes the model through `getModel()` and the behavior engine through `getEngine()` when a later feature needs those layers.
Do not call `fitView()` during teardown. The component disposes its instance when Vue unmounts it.
## Where next
- [Create custom nodes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/create-custom-nodes) for slot renderers and node behavior.
- [State, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) for the instance event surface and engine history.
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram) for the declarative `layout` prop.
- Open the [Vue demo gallery](https://grafloria.com/vue/) to run the Vue examples.
# Angular in 10 minutes
Mount a typed Angular canvas, inspect its engine, and add Grafloria's interaction and property panels.
The first idea is that one headless engine drives every framework binding. The Angular components provide the Angular surface; the engine owns diagram behavior such as interaction and history.
## Prerequisites
Use Angular 18.1 through 22 with a browser application. The package uses standalone components and works with zoneless change detection. You do not need an NgModule or a stylesheet import for this example.
## Install
```bash
npm install @grafloria/angular @angular/common @angular/core @angular/forms @angular/platform-browser @grafloria/engine @grafloria/renderer rxjs @grafloria/element
```
## 1. Mount a typed canvas
Import [`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent), and bind typed node and edge arrays.
```ts title="src/app/app.component.ts"
import { Component, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import { DiagramEngine } from '@grafloria/engine';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
@Component({
selector: 'app-root',
standalone: true,
imports: [DiagramCanvasComponent],
template: `
{{ engineStatus }}
`,
})
export class AppComponent {
readonly canvas = viewChild.required(DiagramCanvasComponent);
readonly engine = new DiagramEngine();
engineStatus = '';
nodes: NodeSpec[] = [
{
id: 'ingest',
position: { x: 60, y: 120 },
size: { width: 180, height: 80 },
data: { label: 'Ingest' },
},
{
id: 'publish',
position: { x: 380, y: 120 },
size: { width: 180, height: 80 },
data: { label: 'Publish' },
},
];
edges: EdgeSpec[] = [
{ id: 'ingest-to-publish', source: 'ingest', target: 'publish' },
];
showEngine(): void {
const activeEngine = this.canvas().activeEngine();
this.engineStatus = activeEngine ? 'Engine is mounted.' : 'Engine is unavailable.';
}
}
```
You get two connected nodes in a 420-pixel-high editor. `[plugins]="true"` adds the minimap, zoom and fit controls, and background grid. Drag a node, connect ports, pan, or zoom to edit the diagram.
The repository's Angular starter uses the same standalone canvas pattern. See its [source](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/starters/angular) or open the [live Angular demo](https://grafloria.com/angular/).
The [`GrafloriaDiagramComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-classes#grafloriadiagramcomponent) is the generic kit host. Use it when a shipped kit, rather than a hand-authored canvas model, defines the diagram:
```ts title="src/app/kit.component.ts"
import { Component } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import { erDiagram } from '@grafloria/element';
@Component({
selector: 'app-kit',
standalone: true,
imports: [GrafloriaDiagramComponent],
template: `
`,
})
export class KitComponent {
readonly spec = erDiagram({
entities: [
{
id: 'CUSTOMER',
name: 'Customer',
position: { x: 60, y: 80 },
columns: [{ name: 'id', type: 'int', pk: true }],
},
{
id: 'ORDER',
name: 'Order',
position: { x: 360, y: 80 },
columns: [{ name: 'id', type: 'int', pk: true }],
},
],
relationships: [{ from: 'CUSTOMER', to: 'ORDER', label: 'places' }],
});
}
```
This sample renders two table-shaped entities and their relationship in the sized host. The same component accepts the other shipped kit specs.
## 2. Access the mounted engine
The component exposes `activeEngine()` as a signal. It returns the engine bound to the canvas, or the engine the canvas created when you omit `[engine]`. Read it after the view exists; `viewChild.required` supplies the mounted component.
Clicking **Check engine** sets the status to `Engine is mounted.`. The canvas also exposes `undo()` and `redo()` for toolbar buttons; each returns a `Promise` and leaves the rendered diagram in the corresponding history state.
## 3. Add the built-in panels
Import [`InteractionConfigPanelComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-interactionconfigpanelcomponent#interactionconfigpanelcomponent) and [`PropertyPanelComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-propertypanelcomponent#propertypanelcomponent). Pass the same [`DiagramEngine`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine) to the interaction panel. The property panel is schema-driven, so mount it with no selection first; it renders its empty state until you provide selected nodes and a schema for their type.
```ts title="src/app/app.component.ts"
import { Component, viewChild } from '@angular/core';
import {
DiagramCanvasComponent,
InteractionConfigPanelComponent,
PropertyPanelComponent,
} from '@grafloria/angular';
import { DiagramEngine } from '@grafloria/engine';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
@Component({
selector: 'app-root',
standalone: true,
imports: [
DiagramCanvasComponent,
InteractionConfigPanelComponent,
PropertyPanelComponent,
],
template: `
`,
})
export class AppComponent {
readonly canvas = viewChild.required(DiagramCanvasComponent);
readonly engine = new DiagramEngine();
nodes: NodeSpec[] = [
{ id: 'ingest', position: { x: 60, y: 120 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'publish', position: { x: 380, y: 120 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
];
edges: EdgeSpec[] = [{ id: 'ingest-to-publish', source: 'ingest', target: 'publish' }];
}
```
The interaction panel opens expanded and lets the user change interaction mode, port visibility, connection-line style, and advanced toggles at runtime. The property panel is mounted without a selection in this sample. Later, bind `selectedNodes` to a node-shaped value and register a `PropertySchema` for that node type to display editable, validated fields; use `updateMode="deferred"` when changes belong behind Save and Cancel.
## What you have at the end
Your Angular app now has a typed, 100%-wide by 420-pixel-high canvas with two connected nodes, built-in canvas tools, an engine you can reach through the mounted component, a live interaction configuration panel, and the property-panel surface ready for a registered schema.
## Where next
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works) explains the engine, model, and bindings.
- [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) covers the shared history and the engine-level undo path.
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram) adds layout and explains when to call it again.
- [Create custom nodes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/create-custom-nodes) replaces default node rendering with Angular templates.
# Build a Qwik diagram
Render a resumable diagram with [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow) and keep its callbacks in QRLs.
## The first idea
Qwik is a thin binding over Grafloria's shared headless engine: you provide node and edge data to the component, and the engine renders and manages the diagram.
## Prerequisites
Use Qwik 1.x (`@builder.io/qwik` 1.5 or later) with a Qwik SSR application. The Qwik package is version 0.10.6 and requires `@grafloria/engine` 0.3.x, `@grafloria/renderer` 0.4.x, and `@grafloria/element` 0.4.x.
Install the binding and its peer packages:
```bash
npm install @grafloria/qwik @grafloria/engine @grafloria/renderer @builder.io/qwik @grafloria/element
```
## Render the flow
Create a route component such as `src/routes/index.tsx`. Type the data with `NodeSpec` and [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec), then bind the signal values to the flow. The [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) passed to `onInit$` gives you the mounted diagram handle.
```tsx title="src/routes/index.tsx"
import { component$, $, useSignal } from '@builder.io/qwik';
import {
GrafloriaFlow,
type DiagramInstance,
type EdgeSpec,
type NodeSpec,
} from '@grafloria/qwik';
export default component$(() => {
const nodes = useSignal([
{ id: 'start', position: { x: 80, y: 120 }, label: 'Start' },
{ id: 'finish', position: { x: 360, y: 120 }, label: 'Finish' },
]);
const edges = useSignal([
{ id: 'start-finish', source: 'start', target: 'finish' },
]);
const handleInit = $((instance: DiagramInstance) => {
instance.fitView();
});
const handleNodesChange = $((next: NodeSpec[]) => {
nodes.value = next;
});
return (
);
});
```

The mounted component renders two labelled boxes joined by a link. `fitView()` frames the content when the instance is ready, and `onNodesChange$` writes edited nodes back to the signal. The `$` suffix keeps both callbacks in QRLs that Qwik can load lazily.
1. Start the Qwik SSR dev server. In the Grafloria Qwik demo repository, use the SSR mode explicitly:
```bash
npx vite --config apps/demos-qwik/vite.config.ts --mode ssr
```
Open `http://localhost:4290/` in that repository, or start your own Qwik application with its normal SSR command. The server-rendered page contains the diagram host; Qwik resumes the component in the browser rather than walking the component tree through a hydration pass.
## What you have at the end
## Where to go next
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works) explains the shared engine, model, and instance.
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram) adds declarative layout.
- [Create custom nodes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/create-custom-nodes) maps node types to Qwik components.
- Try the [Qwik demos](https://grafloria.com/demos-qwik/) to see the binding running.
# How Grafloria works
Grafloria puts one headless engine underneath its JavaScript, React, Vue, Angular, and Qwik
surfaces. The engine owns behavior—commands, history, layout, validation, and collaboration—while
the model owns the diagram data.
```mermaid
flowchart TD
B["Framework binding"] --> I["DiagramInstance"]
I --> M["DiagramModel\nnodes, links, groups, viewport"]
I --> E["DiagramEngine\ncommands, layout, validation, history"]
M --> R["Renderer\npositions, routes, SVG"]
E --> R
```
## Start at the binding
Use the binding's canvas component when your application already uses a framework. The component
mounts a real diagram; its `nodes` and `edges` describe the initial or controlled graph, and its
instance callback gives you the shared handle.
### React
```tsx
import { GrafloriaFlow } from '@grafloria/react';
const nodes = [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'b', position: { x: 380, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
];
const edges = [{ id: 'e1', source: 'a', target: 'b' }];
export default function App() {
return (
instance.fitView()}
/>
);
}
```
The mounted canvas shows two connected nodes. `plugins` adds the minimap, zoom and fit controls,
and background grid. The `onInit` callback receives the live instance after mounting.
### Vue
```vue
```
Vue renders the same connected diagram. Use `v-model:nodes` and `v-model:edges` when the Vue
application owns the live arrays; use the `default-*` props when the canvas owns them after mount.
### Angular
```ts
import { Component } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
@Component({
selector: 'app-root',
imports: [DiagramCanvasComponent],
template: `
`,
})
export class AppComponent {
nodes = [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'b', position: { x: 380, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
];
edges = [{ id: 'e1', source: 'a', target: 'b' }];
}
```
[`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent)
uses Angular's two-way `nodes` and `edges` binding here. A drag changes the live model and writes
the next arrays back through those bindings.
### Qwik
```tsx
import { component$, $ } from '@builder.io/qwik';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik';
const nodes = [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'b', position: { x: 380, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
];
const edges = [{ id: 'e1', source: 'a', target: 'b' }];
export default component$(() => (
instance.fitView())}
/>
));
```
Qwik uses a QRL callback, but the callback receives the same instance and the canvas shows the same
graph. The binding is a thin surface over the shared engine rather than a separate graph engine.
## The model is the document
The model is the single source of truth. A [`DiagramModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-diagrammodel#diagrammodel)
contains nodes, links, groups, and viewport data. A node is a [`NodeModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-nodemodel#nodemodel);
an input edge uses [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec). A
[`GroupSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance#groupspec) describes a zone around child nodes.
Bindings turn plain specs into live models and reconcile later changes by id. Existing ids keep
their live objects, new ids create objects, and missing ids are removed. This lets selection,
listeners, and renderer state survive ordinary updates. The same document can be persisted,
snapshotted, exported, or shared.
For data queries, use `instance.getModel()`. For example, the model gives you `getNodes()`,
`getLinks()`, and `getGroups()` without reaching into the renderer.
## The instance is the shared handle
Plain JavaScript uses [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) to mount a data spec and return
the live [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance):
```ts
import { render } from '@grafloria/element';
const host = document.getElementById('canvas');
if (!host) throw new Error('Missing #canvas');
host.style.height = '400px';
const instance = render({
nodes: [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Ingest' } },
{ id: 'b', position: { x: 380, y: 80 }, size: { width: 180, height: 80 }, data: { label: 'Publish' } },
],
edges: [{ id: 'e1', source: 'a', target: 'b' }],
}, host);
instance.fitView();
instance.on('selection:change', ({ nodes }) => console.log(nodes));
```
Use the instance for specs, painting, events, camera, export, and text round-trips.
`setNodes()` and `setEdges()` reconcile data; `render()` queues a coalesced repaint and
`renderNow()` repaints synchronously; `fitView()` frames all content. Dispose the instance from
your application's unmount or close handler, not immediately after mounting.
## Geometry comes from layout and routing
Nodes, ports, links, groups, directions, and constraints express semantic intent. Rendering and
layout determine positions and paths. Use the [`DiagramEngine`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine)
for behavior below the instance:
```ts
import type { DiagramInstance } from '@grafloria/renderer';
async function arrange(instance: DiagramInstance): Promise {
await instance.getEngine().layout('elk');
instance.renderNow();
}
```
This lays out the already-mounted diagram and then paints the resulting geometry. Changing node
data does not re-run a declarative `layout` prop; call the engine's layout method explicitly and
repaint when you drive the instance yourself.
## Commands, history, and events
User gestures become commands on one history. Dragging, connecting, deleting, and grouping
therefore share undo and redo without application wiring. In React, Vue, and Qwik, reach the
engine through the instance; Angular's canvas also exposes its corresponding component methods.
```ts
import type { DiagramInstance } from '@grafloria/renderer';
async function undoAndRedo(instance: DiagramInstance): Promise {
await instance.getEngine().undo();
await instance.getEngine().redo();
}
```
The instance event map is the common event surface. `on()` returns an unsubscribe function, and
the framework bindings surface the same changes as React callbacks, Vue emits, Angular outputs,
or Qwik QRL callbacks. Use the component event first when the binding provides it; use
`instance.on()` for events that belong to the shared instance.
## Appearance and extension points
The renderer ships [`LIGHT_THEME`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes-constants#light_theme) and
[`DARK_THEME`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes-constants#dark_theme). Pass a theme to the component
or call `instance.setTheme()` to change the mounted diagram's appearance. The renderer also ships
[`registerTool`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-functions#registertool) for canvas tools; it returns a
disposer that restores the previous tool with the same id.
Use the shipped layout adapters, themes, commands, and validators before writing replacements.
The [live demo gallery](https://grafloria.com/demos) shows the same mounted surfaces in operation.
## Next steps
- [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document) for serialization and persistence.
- [Instance and bindings](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/instance-and-bindings) for controlled state.
- [Layout and routing](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/layout-and-routing) for geometry.
- [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) for history and event details.
# Model and document
Grafloria keeps one diagram model beneath every framework binding: nodes, links,
ports, groups, and viewport data are the persistent meaning of the diagram;
rendering and layout turn that meaning into geometry on screen.
## How the parts fit together
```mermaid
flowchart LR
S["Node and edge specs"] --> I["DiagramInstance"]
I --> M["DiagramModel"]
M --> N["nodes"]
M --> L["links and ports"]
M --> G["groups"]
M --> D["serialized document"]
D --> F["fromDocument()"]
F --> I
```
The framework component supplies initial or controlled specs. The mounted
[`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance)
owns the live diagram and gives you the model through `getModel()`. Use that
model for queries and persistence; use `getEngine()` for behavior such as
layout, validation, and undo.
## Nodes identify the things in the diagram
A [`NodeModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-nodemodel#nodemodel) has an ID, a
type, geometry, ports, style, and data. The ID is the stable identity used by
links and groups. Keep it when you update a node: reconciliation can then
update the existing live model instead of treating the item as a new one.
At the spec boundary, a node can carry `id`, `position`, `size`, `label`,
`data`, and `ports`. The four default ports are deterministic; add explicit
ports when a connection must use a particular direction or port identity.
The model exposes those ports for lookup, including `getPortBySide()` and
`getPort()`.
## Links express relationships, not pixels
An [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) names its
endpoints with `source` and `target`. Those values are node IDs. Set
`sourceHandle` or `targetHandle` to pin an endpoint to a port; a bare side such
as `'right'` is also accepted. Without a handle, the renderer chooses the
appropriate port-facing attachment as the nodes move.
`type`, `router`, `connector`, labels, styles, and waypoints describe link
intent. The model stores that intent, while routing and rendering calculate the
visible path. Do not persist a screen-space path as a substitute for the link's
endpoints.
## Groups add membership and containment
A [`GroupSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance#groupspec) is a zone with an
ID, an optional label, and child IDs. Its `bounds` can fix the frame; otherwise
the frame fits its children using `padding`. Children become group members and
move with the group. Groups can be nested and collapsed, so they are model
entities rather than a background rectangle.
The live [`GroupModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-groupmodel#groupmodel)
stores membership, collapse state, geometry, and layout configuration. Removing
a group through `setGroups()` keeps its boxes; it removes the zone, not the
nodes inside it.
## One document is the persistence boundary
The [`DiagramModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-diagrammodel#diagrammodel)
contains maps of nodes, links, and groups. Serialize that live model rather
than only the framework's input arrays: gestures and model-level details such
as ports, groups, metadata, and waypoints belong to the live model.
[`DiagramSerializer`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization#diagramserializer)
turns the model into a plain serialized object. `serializeEnvelope()` wraps it
in the portable document envelope when you need generator identity and related
document metadata. The document is data; renderer callbacks and other
post-render wiring are functions, so they are not in the file and must be
supplied again when a host reloads a custom or kit-based diagram.
## Save a mounted diagram and mount it again
This browser example creates two visible nodes and one link, saves the first
instance's model, and mounts a second instance from the saved JSON. Both hosts
have dimensions, so both diagrams paint.
```js
import { fromDocument, render } from '@grafloria/element';
import { DiagramSerializer } from '@grafloria/engine';
const nodes = [
{
id: 'intake',
type: 'rect',
position: { x: 40, y: 60 },
size: { width: 120, height: 48 },
label: 'Intake',
},
{
id: 'review',
type: 'rect',
position: { x: 260, y: 60 },
size: { width: 120, height: 48 },
label: 'Review',
},
];
const edges = [
{ id: 'intake-to-review', source: 'intake', target: 'review', label: 'checks' },
];
const firstHost = document.getElementById('first-diagram');
const secondHost = document.getElementById('second-diagram');
if (!firstHost || !secondHost) {
throw new Error('Both diagram hosts are required');
}
firstHost.style.height = '400px';
secondHost.style.height = '400px';
const first = render({ nodes, edges }, firstHost);
const saved = JSON.stringify(new DiagramSerializer().serialize(first.getModel()));
const loaded = fromDocument(saved);
const second = render({ nodes: [], edges: [] }, secondHost);
second.setNodes(loaded.nodes);
second.setEdges(loaded.edges);
first.renderNow();
second.renderNow();
```
The first call returns the live instance. The serializer reads its model, and
`fromDocument()` converts the saved object or JSON string back into a spec that
[`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) can mount. The second canvas
therefore receives the saved node IDs, link endpoints, labels, and geometry.
Provide any application-owned custom-node painter or kit wiring again when
loading a document; those callbacks are not serializable.
Use the instance for the rendered surface and its model for document data. If
you only project nodes and edges back into plain specs, details outside that
projection can be lost. Use the full document path when ports, groups, metadata,
or edited waypoints must survive.
## Related
- [Save and restore diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/save-and-restore-diagrams)
- [Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation)
- [Group nested diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/group-nested-diagrams)
- [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo)
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
# Instance and bindings
Grafloria has one headless engine behind its JavaScript, React, Vue, Angular, Qwik, and custom-element surfaces. Choose the surface that matches your host, then use the shared [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) when you need the live diagram.
## Choose the layer for the job
The model owns diagram data. The engine owns behavior. The binding connects those layers to your framework's lifecycle and state.
```mermaid
flowchart TB
UI["React / Vue / Angular / Qwik / HTML"] --> B["Framework binding"]
B --> I["DiagramInstance"]
I --> M["DiagramModel: nodes, links, groups, viewport"]
I --> E["DiagramEngine: commands, layout, validation, undo"]
M --> R["Renderer and layout: geometry and pixels"]
E --> R
```
| Need | Use | Why |
|---|---|---|
| Supply or replace nodes and edges | The binding's data props, or `setNodes()` / `setEdges()` on the instance | Specs are reconciled into live models. Persistent IDs keep existing live models. |
| Query nodes, links, groups, or selection | `instance.getModel()` | The model is the document's live source of truth. |
| Layout, validation, commands, or undo | `instance.getEngine()` | Behavior belongs to the engine, not the instance's data API. |
| Paint after a mutation | `render()` or `renderNow()` | `render()` queues a coalesced repaint; `renderNow()` paints synchronously when you must measure immediately. |
| Listen for changes | `instance.on()` or the binding's event props | Every binding exposes the same event map in its native idiom. |
| Read or change the camera | `instance.viewport` and `fitView()` | Viewport data is separate from node data. |
| Read comments | `getCommentStore()` | It returns the enabled comment store, or `null` when comments are disabled. |
Do not put engine behavior into framework state. Keep application state for data that the rest of your application owns, such as a saved document or an inspector selection. Keep the live diagram in the instance and subscribe to the events or hooks that your UI needs.
## The same instance from each surface
For plain JavaScript, [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) mounts a data spec and returns the instance immediately. Its target can be an element or a CSS selector; the spec is data, not Mermaid text.
```js
import { render } from '@grafloria/element';
const host = document.createElement('div');
host.id = 'diagram';
host.style.height = '240px';
document.body.append(host);
const api = render(
{
nodes: [
{ id: 'plan', position: { x: 40, y: 40 }, size: { width: 140, height: 56 }, label: 'Plan' },
{ id: 'ship', position: { x: 280, y: 40 }, size: { width: 140, height: 56 }, label: 'Ship' },
],
edges: [{ id: 'plan-ship', source: 'plan', target: 'ship' }],
},
host,
{ fitView: true },
);
const stopListening = api.on('selection:change', ({ nodes }) => {
console.log(`Selected ${nodes.length} node(s)`);
});
api.fitView(24);
```
The mounted host shows two boxes and a connecting edge. Selecting a box invokes the handler with the live selected models. `fitView()` frames both boxes; call `dispose()` from your host's teardown path rather than immediately after mounting in an application that still displays the diagram.
In React, [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) is the component surface. Its `onInit` callback supplies the same instance that `render()` returns. Use [`GrafloriaProvider`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaprovider) when a toolbar or inspector is outside the flow subtree, then read the handle with [`useGrafloria`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#usegrafloria). The subscription hooks expose framework state without copying the whole model into React.
```tsx
import {
GrafloriaFlow,
GrafloriaProvider,
useGrafloria,
useOnSelectionChange,
useSelection,
useViewport,
type DiagramInstance,
type EdgeSpec,
type NodeSpec,
} from '@grafloria/react';
import { useState } from 'react';
const nodes: NodeSpec[] = [
{ id: 'plan', position: { x: 40, y: 40 }, size: { width: 140, height: 56 }, label: 'Plan' },
{ id: 'ship', position: { x: 280, y: 40 }, size: { width: 140, height: 56 }, label: 'Ship' },
];
const edges: EdgeSpec[] = [{ id: 'plan-ship', source: 'plan', target: 'ship' }];
function Toolbar() {
const instance = useGrafloria();
const selection = useSelection();
const viewport = useViewport();
const [lastSelection, setLastSelection] = useState(0);
useOnSelectionChange(({ nodes: changedNodes }) => setLastSelection(changedNodes.length));
return (
zoom {viewport.zoom.toFixed(2)} selected {selection.nodes.length} node(s) last change {lastSelection}
);
}
```
The canvas renders inside the sized `div`; the toolbar reports the live zoom and selection, and the paragraph changes when the instance mounts. `defaultNodes` and `defaultEdges` seed an uncontrolled canvas. If application state must own the graph, pass `nodes` and `edges` together with `onNodesChange` and `onEdgesChange` instead. Do not mix controlled `nodes` with uncontrolled defaults: a stale controlled array can overwrite a user edit on the next render.
Vue exposes the same component-level idea through `GrafloriaFlow` props and emits, including `@selection-change` and `@connect`. Angular exposes controlled `[(nodes)]` / `[(edges)]` bindings and outputs such as `(viewportChanged)` and `(layoutDone)`. The custom element forwards the same instance events as bubbling `CustomEvent`s. The underlying model and engine do not change when the binding changes.
## Data, behavior, and rendering are different calls
Start with the instance, then descend only for the responsibility you need:
```ts
import type { DiagramInstance } from '@grafloria/renderer';
async function inspect(api: DiagramInstance): Promise {
const model = api.getModel();
const selected = model.getSelectedNodes();
const engine = api.getEngine();
const validation = engine.validateDiagram();
await engine.layout('elk');
api.renderNow();
console.log(selected, validation);
}
```
The first two calls query live data and behavior respectively; the layout call changes geometry through the engine; `renderNow()` makes the resulting pixels current before an immediate measurement. Undo is also an engine operation: call `api.getEngine().undo()`, not `api.undo()`.
For persistence, serialize the model rather than a framework's stale mirror. For text round-trips, use `exportText()` and `loadText()` on the instance. For a screenshot or document export, use the instance's export methods. These operations act on the mounted diagram, so they include edits made through gestures.
## Events and framework state
The instance event map is the common language:
```ts
import type { DiagramInstance } from '@grafloria/renderer';
function watch(api: DiagramInstance): () => void {
const stopNode = api.on('node:click', ({ node, world }) => {
console.log(node.id, world.x, world.y);
});
const stopViewport = api.on('viewport:change', ({ viewport, zoom }) => {
console.log(viewport, zoom);
});
return () => {
stopNode();
stopViewport();
};
}
```
`on()` returns an unsubscribe function. React callback props, Vue emits, Angular outputs, and element DOM events dress the same map in framework-native forms. Use the component event first when it exists; reach through `on()` when you need an instance event that the component does not expose.
For React UI, [`useSelection`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#useselection) is state for rendering an inspector, [`useViewport`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#useviewport) is state for a zoom badge or minimap, and [`useOnSelectionChange`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#useonselectionchange) is a callback for side effects. They subscribe to the live instance; they are not a second diagram model.
## A practical rule
Pass specs through the binding when the framework owns the document. Use the instance for the mounted diagram's events, camera, painting, export, and text conversion. Use `getModel()` for queries and `getEngine()` for commands, layout, validation, and undo. This keeps one document, one history, and one event map across every binding.
# Layout and routing
Grafloria keeps graph intent in the model and derives node positions and link paths when it lays out and renders the diagram. You describe relationships such as “connect `api` to `wallets`” and “avoid obstacles”; you do not need to store the pixels that satisfy those relationships.
## How the parts work together
```mermaid
flowchart LR
I["Nodes, groups, and edges"] --> M["DiagramModel: semantic document"]
M --> L["DiagramEngine.layout()"]
L --> P["Node positions"]
M --> R["Router"]
R --> Q["Link paths"]
P --> V["Rendered diagram"]
Q --> V
```
The model stores node and group relationships, ports, link endpoints, routing choices, and optional waypoints. A layout algorithm assigns positions from that information. The router then turns the endpoints and routing choice into a path. When a node moves, its links follow; an obstacle-avoiding route can recalculate around the new obstacle positions.
This separation also keeps persistence meaningful: save the document's intent and constraints, not a collection of coordinates that only describes one rendering.
## Describe relationships as data
Use [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) to mount a real diagram and receive its [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance). The sample uses an architecture layout so the nodes need no hand-written positions. The `source`, `target`, and `sourceHandle` fields express the relationship and attachment; `router` expresses how the path should travel.
```ts title="main.ts"
import { render } from '@grafloria/element';
const container = document.getElementById('diagram')!;
container.style.height = '400px';
const edges = [
{
id: 'api-to-wallets',
source: 'api',
target: 'wallets',
sourceHandle: 'right',
targetHandle: 'left',
router: 'avoid',
connector: 'rounded',
label: 'requests',
},
];
const instance = render(
{
layout: 'architecture',
nodes: [
{ id: 'api', label: 'API', size: { width: 150, height: 70 } },
{ id: 'wall', label: 'Obstacle', size: { width: 150, height: 110 } },
{ id: 'wallets', label: 'Wallets', size: { width: 150, height: 70 } },
],
edges,
},
container,
);
instance.fitView();
```
```html
```
The mounted instance shows labelled `API`, `Obstacle`, and `Wallets` nodes with a rounded, obstacle-aware `requests` link. `fitView()` frames the content in the sized container. The instance is the handle you keep when the application needs to repaint, query the model, or invoke the engine.
## Read `type` and `router` as separate decisions
An [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) answers two different questions:
- `type` describes the line's shape: direct, smooth, orthogonal, or bezier.
- `router` describes the path it takes: `straight`, `orthogonal`, `manhattan`, or `avoid`.
For example, an orthogonal edge can use the obstacle-avoiding router while retaining right-angle geometry:
```ts
const orthogonalEdge = {
source: 'api',
target: 'wallets',
type: 'orthogonal',
router: 'avoid',
connector: 'rounded',
};
```
Leave handles out when the renderer can choose the default port facing the other node. Use a port id or a side such as `'right'` when the attachment is part of the diagram's meaning. Use `waypoints` only when the document must preserve explicit interior bends; those points are world coordinates, not a replacement for the relationship between the endpoints.
## Choose and rerun a layout
The [`DiagramEngine`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine) owns layout behavior. Obtain it from the mounted instance and call `layout()` with a registered name and optional layout settings:
```ts
import { render } from '@grafloria/element';
const container = document.getElementById('diagram')!;
container.style.height = '400px';
const instance = render(
{
nodes: [
{ id: 'api', label: 'API' },
{ id: 'wallets', label: 'Wallets' },
],
edges: [{ source: 'api', target: 'wallets', router: 'avoid' }],
},
container,
);
async function layOutLeftToRight(): Promise {
const engine = instance.getEngine();
await engine.layout('dagre', { rankSpacing: 80 });
instance.renderNow();
}
void layOutLeftToRight();
```
The call commits new node positions to the live model and returns a layout result; the repaint then shows the new positions and recomputed link routes. Calling `engine.layout()` with no name selects the automatic layout, while an unknown name throws instead of silently doing nothing.
The built-in choices cover common graph shapes: use `elk` or `dagre` for layered flows, `tree` for hierarchies, `force` or `community` for networks, and `grid`, `circular`, or `radial` for catalogs. Use `architecture` when zones and their internal rows are part of the visual structure rather than a ranking problem.
## What belongs in the document
Store the facts that remain true when the drawing changes:
- node and group ids, labels, data, ports, and membership;
- link endpoints, endpoint handles, labels, connector and router choices;
- deliberate waypoints when a user-edited bend must round-trip.
Do not treat the current node positions or generated route polyline as the graph's business meaning. A layout recomputes positions from the graph, and a router recomputes paths from endpoints, obstacles, anchors, and waypoints. This is why the same document can be laid out again after loading, resizing, or moving a node.
For a hand-edited edge, the endpoint remains semantic and the saved `points` or `waypoints` preserve the user's route. Reconnecting an endpoint runs connection validation again; bending a path updates the model and remains undoable through the shared command history.
## Related pages
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram)
- [Edit and route edges](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/edit-and-route-edges)
- [Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation)
- [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document)
# Ports and validation
Ports are the connection points on a node. Their side, direction, data type, and
capacity describe the connections the graph can make.
## How the pieces fit together
For a domain graph, declare ports on the node. `side` places the port, `type`
sets whether it starts or ends a link, and `dataType` gives it a named data-flow
type. `shape` and `label` change its visible glyph and caption. Use
`maxConnections` for a simple cap; use `gating` when the rule also needs
directional connectability, allowed types, or self-link policy.
```ts
const nodes = [
{
id: 'transform',
position: { x: 80, y: 120 },
size: { width: 180, height: 100 },
label: 'Transform',
ports: [
{ id: 'in', side: 'left', type: 'input', dataType: 'frame' },
{ id: 'out', side: 'right', type: 'output', dataType: 'frame' },
{
id: 'errors',
side: 'bottom',
type: 'output',
maxConnections: 1,
shape: { shape: 'diamond', size: 12 },
label: { text: 'errors', layout: 'outside' },
},
],
},
];
```
The port glyphs appear on hover by default. Set the interaction option to
`portVisibility: 'always'` when the diagram needs to expose every connection
point continuously.
## Use data types for declarative compatibility
Register the data types once at application bootstrap with
[`portTypeRegistry`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-ports#porttyperegistry). A type may
list additional compatible types in `compatibleWith`; an exact name also
matches. Its `color` controls the port glyph colour.
```ts
import { portTypeRegistry } from '@grafloria/element';
portTypeRegistry.registerAll([
{ name: 'number', color: '#2563eb', compatibleWith: ['number'] },
{ name: 'string', color: '#9333ea', compatibleWith: ['string'] },
]);
```
A `number` output can therefore connect to a `number` input, while a
`number`-to-`string` attempt is refused during the drag. The matching port is
highlighted as a valid target, and the mismatched port is not; no link is
created for the refused attempt.
The same node and edge specs work in the Qwik binding through
[`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow). Give the component's
host a resolved height so the mounted canvas has visible space:
```tsx
import { component$ } from '@builder.io/qwik';
import { GrafloriaFlow, type EdgeSpec, type NodeSpec } from '@grafloria/qwik';
const nodes: NodeSpec[] = [
{
id: 'source',
position: { x: 80, y: 100 },
size: { width: 150, height: 70 },
label: 'Source',
ports: [{ id: 'out', side: 'right', type: 'output', dataType: 'number' }],
},
{
id: 'sink',
position: { x: 360, y: 100 },
size: { width: 150, height: 70 },
label: 'Sink',
ports: [{ id: 'in', side: 'left', type: 'input', dataType: 'number' }],
},
];
const edges: EdgeSpec[] = [];
export default component$(() => (
));
```
This component renders the same two typed ports as the element example. Its
`number` output can connect to its `number` input after the type is registered.
## See it running
The [typed ports demo](https://grafloria.com/demos/ports/typed-ports.html) shows
blue number ports, a purple string port, an accepted number-to-number link, and
a refused number-to-string drag.
The live demo shows the number ports in blue and the string port in purple;
the accepted number-to-number wire remains visible while the mismatched drag
is refused.
For a broader connection rule, see [Validate connections](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/validate-connections).
For edge endpoint and routing details, see [Edit and route edges](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/edit-and-route-edges).
For the model objects behind the rendered ports, see [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document).
# Commands, events, and undo
Grafloria records edits through the engine's command path and reports the resulting model change through the instance event map and your framework binding. This keeps the canvas and your application state synchronized without a second undo stack.
## One path from edit to state
The [DiagramInstance](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) is the handle shared by the framework wrappers. Its model stores nodes and edges; its [DiagramEngine](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine) owns commands, validation, and history.
```mermaid
flowchart LR
G["DiagramEngine.addNode()"] --> C["AddNodeCommand"]
C --> H["Engine history"]
H --> M["Diagram model"]
M --> E["Instance event map"]
E --> B["React callbacks, Vue emits, Angular outputs, or Qwik QRLs"]
B --> S["Application state"]
```
## Listen at the instance
Use `instance.on()` when you need the shared event map or when the event is not represented by a component callback. The call returns an unsubscribe function; call it when the owner of the listener is disposed.
```ts
import type { DiagramInstance } from '@grafloria/renderer';
export function watchDiagram(instance: DiagramInstance) {
const offNodes = instance.on('nodes:change', ({ nodes }) => {
console.log('nodes:', nodes.length);
});
const offSelection = instance.on('selection:change', ({ nodes, edges }) => {
console.log('selected:', nodes.length, edges.length);
});
return () => {
offNodes();
offSelection();
};
}
```
`nodes:change` reports the live node models after nodes are added, removed, or changed. `selection:change` reports the selected node and edge models. Other instance events include `edges:change`, `connect`, `reconnect`, `node:click`, `node:doubleclick`, `edge:click`, and `viewport:change`; their payloads describe the completed interaction in diagram coordinates where applicable.
## The same history in each framework
The event map stays the same; only the binding syntax changes.
### Vue
The Vue [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-vue#grafloriaflow) wrapper emits the same interactions in Vue form. Bind the controlled arrays with `v-model` and retain the instance from `@init`:
```vue
```

`v-model:nodes` receives the reverted array after undo, so the displayed nodes and Vue state describe the same document.
### Angular
Angular's [`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent) mirrors `undo()` and `redo()` as component methods. In controlled mode, two-way `nodes` and `edges` bindings receive model changes:
```html
```
Keep a template reference to the mounted component (`#canvas`) when using this form. For events that Angular does not expose as outputs, subscribe through the active engine's event bus rather than creating a separate history.
### Qwik
Qwik's `GrafloriaFlow` uses the same instance and data model, with QRL callback props. Use `onInit$` to retain the instance and `onNodesChange$` for the model callback in a Qwik component. The callback receives the reconciled models after undo or redo.
## Choose the edit path
Use the diagram model's direct operations for setup, import, and synchronization: those operations establish the document and do not represent a user's undoable action. Use the engine's command manager for an application-initiated edit that belongs in the user's history, such as a toolbar action or an assistant suggestion. A refused command does not enter history; in strict validation mode, an invalid result is reverted and is not recorded.
Do not call `undo()` on `DiagramInstance`; it is not an instance method. Call `instance.getEngine().undo()` instead. Angular's canvas component is the exception because it mirrors the method directly.
## Related pages
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [The model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document)
- [The DiagramInstance](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/instance-and-bindings)
- [Events and interaction](https://grafloria.com/learn/events-and-interaction/)
- [Commands and undo live guide](https://grafloria.com/learn/commands-and-undo/)
# Text and canvas
Grafloria keeps Mermaid-compatible text readable while a lossless sidecar carries the canvas document: semantic node types describe what each entity means, and the sidecar preserves geometry that Mermaid does not express.
## How the parts fit together
```mermaid
flowchart LR
text["Mermaid-compatible body"] --> parse["Text parser"]
sidecar["%%grafloria:document sidecar"] --> model["Live diagram model"]
parse --> model
model --> canvas["Rendered canvas"]
model --> export["Text + sidecar"]
```
The Mermaid body carries structure, labels, and diagram direction. Importing it creates typed entities such as `flowchart:process` and `flowchart:decision`; the renderer can therefore choose the corresponding glyphs and layout behavior. The text parser exposes this result through [`importDiagramText`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization#importdiagramtext), whose `diagram` is a live [`DiagramModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-diagrammodel#diagrammodel).
Grafloria's sidecar is a `%%grafloria:document` comment. Mermaid-compatible renderers ignore it, while Grafloria reads the serialized document from it. Positions, sizes, styles, ports, groups, and viewport data therefore survive an export/import round trip even though they are not part of ordinary Mermaid syntax.
## Put Mermaid text into a live canvas
Use [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) to mount a real canvas, then use the returned [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) to load text into that mounted diagram. `loadText()` reconciles the parsed result into the existing instance; it does not discard the renderer, listeners, plugins, or selection.
```ts
import { render } from '@grafloria/element';
const host = document.createElement('div');
host.id = 'canvas';
host.style.width = '800px';
host.style.height = '400px';
document.body.append(host);
const instance = render(
{
nodes: [
{
id: 'start',
label: 'Loading',
position: { x: 60, y: 80 },
size: { width: 150, height: 60 },
},
],
edges: [],
},
host,
);
const mermaid = `flowchart
start[Start] --> gate{Gate}
gate --> ship[Ship]`;
const loaded = instance.loadText(mermaid);
if (loaded.unsupported) {
throw new Error(`Unsupported diagram type: ${loaded.unsupported}`);
}
const firstNode = loaded.diagram.getNodes()[0];
if (!firstNode) {
throw new Error('The text contains no nodes');
}
instance.renderNow();
const exported = instance.exportText();
const status = document.getElementById('status');
if (status) {
status.textContent = `${firstNode.type}; sidecar: ${exported.includes('%%grafloria:document')}`;
}
```
With a host such as ``, the canvas shows `Start`, `Gate`, and `Ship` connected from left to right. The status reports `flowchart:process` for the first node and `sidecar: true`. The initial `Loading` node is reconciled away because the Mermaid text defines the current node set.
## Export and re-import
Call `instance.exportText()` after a user arranges the canvas. Its visible body remains Mermaid-compatible; by default, the output also contains the document sidecar and a body hash. Feeding that string to `loadText()` restores the document in the same live instance, including the canvas positions and other data that the body cannot represent.
When the body hash still matches, the default import preference uses the sidecar. If a person edits the Mermaid body, the returned result sets `bodyEdited` to `true`; the edited structure and labels take effect, while the sidecar remains the base for information the text cannot express. Check `sidecarInvalid` when a sidecar comment exists but its JSON is malformed. For a diagram type Grafloria recognises but does not support, `unsupported` identifies the type instead of silently treating it as another diagram.
The lower-level [`importDiagramText`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization#importdiagramtext) function is useful when parsing must happen before a canvas exists—for example, to inspect `source`, `bodyEdited`, or `unsupported`. Use the instance methods when the result belongs in a mounted canvas.
## What the text does not own
The Mermaid body is the human-readable semantic layer: entities, relationships, labels, shapes, and direction. The sidecar is the fidelity layer: exact model state needed to reproduce the canvas. A pure Mermaid file without a sidecar remains importable, but its layout and other non-Mermaid details follow the lossy text boundary rather than a previous canvas arrangement.
For a saved document whose full model is the source of truth, use the JSON document path and [`fromDocument`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#fromdocument) rather than projecting the model back into plain node and edge specs. For a text file meant to remain readable in Git and renderable by Mermaid, use the text path described here.
## Related
- [Round-trip Mermaid text](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/round-trip-mermaid-text)
- [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document)
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram)
- [Save and restore diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/save-and-restore-diagrams)
# Auto-layout a diagram
Use a layout algorithm when node positions come from the graph rather than from hand-authored coordinates. This page mounts the same pipeline in JavaScript, Angular, Qwik, React, and Vue, runs a named layout, and fits the result into the canvas.
## When to use it
Use auto-layout for pipelines, trees, networks, and other graphs whose geometry should follow their nodes and edges. The model remains the source of truth; the engine calculates positions and writes them back to the live diagram.
The layout entry point is [`DiagramEngine`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine). Use a named algorithm when you want a predictable choice, or omit the name to let `auto` classify the graph. The registered names include `auto`, `elk`, `dagre`, `layered`, `tree`, `grid`, `circular`, `radial`, `force`, `spectral`, and `community`.
## Prerequisites
Install the package for your binding and its rendering dependencies. The examples below use the current published versions: `@grafloria/engine` 0.3.18, `@grafloria/renderer` 0.4.19, `@grafloria/angular` 0.13.7, and `@grafloria/qwik`, `@grafloria/react`, or `@grafloria/vue` 0.10.6.
```bash
npm install @grafloria/engine @grafloria/renderer
```
Install the binding package as well when you use Angular, Qwik, React, or Vue.
## 1. Define a graph and run a layout
Give every node a size and an initial position. Starting the nodes at `(0, 0)` makes the result visible: the selected algorithm must separate them. Pass the graph to the binding, obtain the [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) when the canvas is ready, then call `getEngine().layout()` and `fitView()`.
:::code-group
```js title="JavaScript"
import { render } from '@grafloria/element';
const nodes = [
{ id: 'ingest', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Ingest' },
{ id: 'parse', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Parse' },
{ id: 'validate', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Validate' },
{ id: 'publish', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Publish' },
];
const edges = [
{ id: 'e1', source: 'ingest', target: 'parse' },
{ id: 'e2', source: 'parse', target: 'validate' },
{ id: 'e3', source: 'validate', target: 'publish' },
];
const container = document.getElementById('diagram');
if (!container) throw new Error('Missing #diagram');
container.style.height = '400px';
const instance = render({ nodes, edges }, container);
const engine = instance.getEngine();
async function arrange() {
await engine.layout('dagre', { nodeSpacing: 40, rankSpacing: 90 });
instance.renderNow();
instance.fitView(50);
}
arrange();
```
```ts title="Angular"
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
const nodes: NodeSpec[] = [
{ id: 'ingest', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Ingest' },
{ id: 'parse', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Parse' },
{ id: 'validate', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Validate' },
{ id: 'publish', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Publish' },
];
const edges: EdgeSpec[] = [
{ id: 'e1', source: 'ingest', target: 'parse' },
{ id: 'e2', source: 'parse', target: 'validate' },
{ id: 'e3', source: 'validate', target: 'publish' },
];
@Component({
standalone: true,
imports: [DiagramCanvasComponent],
template: '',
})
export class AutoLayoutComponent implements AfterViewInit {
readonly canvas = viewChild.required(DiagramCanvasComponent);
nodes = nodes;
edges = edges;
async ngAfterViewInit(): Promise {
await this.canvas().applyLayout({ name: 'dagre', options: { nodeSpacing: 40, rankSpacing: 90 } });
this.canvas().fitToContent();
}
}
```
```tsx title="Qwik"
import { component$, $ } from '@builder.io/qwik';
import { GrafloriaFlow, type EdgeSpec, type NodeSpec, type DiagramInstance } from '@grafloria/qwik';
const nodes: NodeSpec[] = [
{ id: 'ingest', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Ingest' },
{ id: 'parse', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Parse' },
{ id: 'validate', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Validate' },
{ id: 'publish', position: { x: 0, y: 0 }, size: { width: 130, height: 52 }, label: 'Publish' },
];
const edges: EdgeSpec[] = [
{ id: 'e1', source: 'ingest', target: 'parse' },
{ id: 'e2', source: 'parse', target: 'validate' },
{ id: 'e3', source: 'validate', target: 'publish' },
];
export default component$(() => (
```
:::





Each version renders the four-node pipeline with 40 units between neighboring nodes and 90 units between ranks. `renderNow()` repaints immediately after the engine changes positions; `fitView(50)` frames the complete graph with padding.
## 2. Let Grafloria choose
Use `auto` when the graph shape matters more than a fixed algorithm. The JavaScript form is an omitted name; the component bindings accept the string value.
```js
async function fitAutomaticLayout(instance) {
await instance.getEngine().layout();
instance.renderNow();
instance.fitView(50);
}
```
An unknown layout name throws an error listing the registered names. Use a registered name when your interface lets the reader choose an algorithm.
## Options that matter
| option | type | default | what it does |
| --- | --- | --- | --- |
| `nodeSpacing` | `number` | algorithm-specific | Sets spacing between neighboring nodes. |
| `rankSpacing` | `number` | algorithm-specific | Sets spacing between ranks. |
| `seed` | `number` | fixed layout seed | Makes a layout with the same graph reproducible. |
| `nested` | `boolean` | enabled when the diagram has groups | Controls nested-container layout; set `false` to opt out. |
The same options object goes to `engine.layout(name, options)`. The engine returns a layout result after it commits positions; the result includes the selected algorithm, seed, node positions, and bounds.
## Pitfall: ports are hidden by default
Ports are hidden until hover. If the layout is part of a persistent editing surface and readers need to see connection points, set `portVisibility: 'always'` when creating the diagram or update the live engine:
```js
function showPorts(instance) {
instance.getEngine().setInteractionConfig({ portVisibility: 'always' });
}
```
## See it running
Open the [auto-layout demo](https://grafloria.com/demos/layout/auto-layout.html) to switch between algorithms on a graph whose nodes begin stacked at the origin. The demo also checks that the layout commits positions, avoids overlaps, and produces different pictures for different engines.

For a graph with disconnected components, see the [layout portfolio demo](https://grafloria.com/demos/layout/layout-portfolio.html). For incremental changes that preserve the user's mental map, see [layout and routing](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/layout-and-routing).
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram)
- [Create custom nodes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/create-custom-nodes)
# Create custom nodes
Use a custom node when the inside of a node needs application-specific content. Keep a stable `id` for each node, give the node a real `size`, and let Grafloria keep ownership of selection, dragging, ports, routing, and serialization.
## Choose the rendering surface
- JavaScript uses [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) and a registered renderer.
- React uses [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) with `nodeTypes`.
- Vue uses `GrafloriaFlow` with a `#node-` slot.
- Angular uses [`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent) with an `ng-template` for the node type.
- Qwik uses [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow) with `nodeTypes`.
In the framework bindings, declaring a renderer for a node type opts matching nodes into the HTML layer. In JavaScript, set `custom: true` explicitly. In every case, the renderer fills a host whose geometry comes from `position` and `size`.
## Render a custom node
The following examples render two connected cards. Each card keeps its stable `id`; the engine still owns the edge and node behavior.
:::code-group
```js title="JavaScript"
import { Grafloria, render } from '@grafloria/element';
Grafloria.registerNodeType('card', (node, element) => {
const card = document.createElement('div');
card.style.cssText = 'height:100%;box-sizing:border-box;padding:12px;border:2px solid #4f46e5;border-radius:10px;background:#fff;font:14px system-ui';
const title = document.createElement('strong');
title.textContent = String(node.getData('title'));
card.append(title);
const id = document.createElement('div');
id.textContent = `node: ${node.id}`;
card.append(id);
element.append(card);
});
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '400px';
const instance = render({
nodes: [
{ id: 'build', type: 'card', custom: true, position: { x: 80, y: 100 }, size: { width: 220, height: 100 }, data: { title: 'Build' } },
{ id: 'deploy', type: 'card', custom: true, position: { x: 400, y: 100 }, size: { width: 220, height: 100 }, data: { title: 'Deploy' } },
],
edges: [{ id: 'build-to-deploy', source: 'build', target: 'deploy' }],
}, host);
```
```tsx title="React"
import { GrafloriaFlow } from '@grafloria/react';
import type { NodeProps } from '@grafloria/react';
function Card({ id, selected }: NodeProps) {
return
);
```
:::

The mounted result is two application-rendered cards joined by a routed edge. Select or drag either card: its host moves with the node, while the edge remains attached. In React and Qwik, `selected` changes the border; the engine supplies that state through [`NodeProps`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#nodeprops).
## Use the live model when needed
Framework renderers receive a live [`NodeModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-nodemodel#nodemodel). Use tracked setters for model changes, then repaint through the [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) when you need a synchronous frame:
```ts
import { render } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '400px';
const instance = render({
nodes: [{ id: 'build', position: { x: 80, y: 100 }, size: { width: 220, height: 100 } }],
}, host);
const node = instance.getModel().getNode('build');
if (!node) throw new Error('Missing build node');
node.setMetadata('label', 'Updated build');
instance.renderNow();
```
The instance returned by `render()` is the live handle. It also exposes the model that owns nodes and links, so the custom body does not need to implement selection, ports, or edge geometry.
## Add ports without putting handles in the body
Ports belong to the node spec, not to the custom component. Declare them when a connection must use named or typed endpoints:
```ts
const nodes = [{
id: 'build', type: 'card', custom: true,
position: { x: 80, y: 100 }, size: { width: 220, height: 100 },
ports: [
{ id: 'out', side: 'right', type: 'output', dataType: 'build' },
],
}];
```
## Pitfalls
- In JavaScript, omitting `custom: true` sends the node through the stock SVG path, so the registered renderer is never called. Register the type before mounting; a host that mounted without a renderer stays empty.
- Keep `position: { x, y }` and `size: { width, height }` on the spec. Top-level `x` and `y` are not node geometry.
- Make the custom root fill the box with `height: 100%` and `box-sizing: border-box`.
- A custom renderer runs at mount, not on every data mutation. Update DOM you own or use a component with its own reactive state. See [Build ER and UML diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/build-er-and-uml-diagrams) for the dashboard update pattern.
- Give the canvas parent a resolved height, or use [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram); a zero-height parent produces a blank canvas.
## See it running
Open the [custom-nodes demo](https://grafloria.com/demos/nodes/custom-nodes.html) to see custom bodies, dragging, ports, and connected edges together. The source is [custom-nodes.html](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/demos/nodes/custom-nodes.html).
Related: [Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation), [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document), and [Element versus render()](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/javascript-quick-start).
# Validate connections during a drag
Use a connection validator when your graph has rules that port direction alone does not express. The validator runs before the link is created: return `true` to allow the candidate, or return a string to veto it with a reason. In this example, an output may connect to an input, but never to another output.
## Install
JavaScript uses the element, renderer, and engine packages:
```bash
npm install @grafloria/element @grafloria/renderer @grafloria/engine
```
Install the binding package as well when you use Angular, Qwik, React, or Vue.
The [render](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) function mounts the graph and returns its live `DiagramInstance`. Use the [clearConnectionValidators](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-functions#clearconnectionvalidators) function before replacing a process-wide rule.
## Register the rule
The [connection validator](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-functions#registerconnectionvalidator) receives the candidate's source and target ports. Keep the returned disposer and remove the process-wide registration when the view unmounts.
The following rule allows an incomplete candidate, then rejects output-to-output connections with a readable reason:
```ts
import { registerConnectionValidator } from '@grafloria/renderer';
const disposeValidator = registerConnectionValidator(({ sourcePort, targetPort }) => {
if (!sourcePort || !targetPort) return true;
if (sourcePort.type === 'output' && targetPort.type === 'output') {
return 'an output cannot feed another output';
}
return true;
});
```
The disposer belongs in your component's unmount or effect cleanup, not immediately after setup. Registered validators are process-global, so leaving one active can change the rules on another canvas.
## Mount a graph
Give the host a resolved height. Hover over a node to reveal its ports, then drag **A (out)** to **C (out)**: the wire disappears and no edge is created. Drag it to **B (in)**: the connection remains on the canvas.
The Qwik binding uses [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow), and its `onInit$` callback receives the shared [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance). The other bindings expose the same instance through their own init callback.
:::code-group
```js title="JavaScript"
import { render } from '@grafloria/element';
import { registerConnectionValidator, clearConnectionValidators } from '@grafloria/renderer';
const nodes = [
{
id: 'a', position: { x: 120, y: 260 }, size: { width: 120, height: 70 }, label: 'A (out)',
ports: [{ id: 'ao', side: 'right', type: 'output' }],
},
{
id: 'b', position: { x: 640, y: 140 }, size: { width: 120, height: 70 }, label: 'B (in)',
ports: [{ id: 'bi', side: 'left', type: 'input' }],
},
{
id: 'c', position: { x: 640, y: 400 }, size: { width: 120, height: 70 }, label: 'C (out)',
ports: [{ id: 'co', side: 'left', type: 'output' }],
},
];
const host = document.createElement('div');
host.id = 'canvas';
document.body.append(host);
host.style.height = '100vh';
const disposeValidator = registerConnectionValidator(({ sourcePort, targetPort }) => {
if (!sourcePort || !targetPort) return true;
if (sourcePort.type === 'output' && targetPort.type === 'output') {
return 'an output cannot feed another output';
}
return true;
});
const instance = render({ nodes, edges: [] }, host);
instance.renderNow();
window.addEventListener('pagehide', () => {
disposeValidator();
clearConnectionValidators();
instance.dispose();
}, { once: true });
```
```ts title="Angular"
import { AfterViewInit, Component, OnDestroy, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import { clearConnectionValidators, registerConnectionValidator } from '@grafloria/renderer';
@Component({
standalone: true,
imports: [DiagramCanvasComponent],
template: `
`,
})
export class ConnectionValidationComponent implements AfterViewInit, OnDestroy {
canvas = viewChild.required(DiagramCanvasComponent);
nodes = [
{ id: 'a', position: { x: 120, y: 260 }, size: { width: 120, height: 70 }, label: 'A (out)', ports: [{ id: 'ao', side: 'right' as const, type: 'output' }] },
{ id: 'b', position: { x: 640, y: 140 }, size: { width: 120, height: 70 }, label: 'B (in)', ports: [{ id: 'bi', side: 'left' as const, type: 'input' }] },
{ id: 'c', position: { x: 640, y: 400 }, size: { width: 120, height: 70 }, label: 'C (out)', ports: [{ id: 'co', side: 'left' as const, type: 'output' }] },
];
edges = [];
private disposeValidator?: () => void;
ngAfterViewInit(): void {
clearConnectionValidators();
this.disposeValidator = registerConnectionValidator(({ sourcePort, targetPort }) => {
if (!sourcePort || !targetPort) return true;
return sourcePort.type === 'output' && targetPort.type === 'output'
? 'an output cannot feed another output'
: true;
});
}
ngOnDestroy(): void {
this.disposeValidator?.();
clearConnectionValidators();
}
}
```
```tsx title="Qwik"
import { component$, $, useVisibleTask$ } from '@builder.io/qwik';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik';
import { clearConnectionValidators, registerConnectionValidator } from '@grafloria/element';
const nodes = [
{ id: 'a', position: { x: 120, y: 260 }, size: { width: 120, height: 70 }, label: 'A (out)', ports: [{ id: 'ao', side: 'right' as const, type: 'output' as const }] },
{ id: 'b', position: { x: 640, y: 140 }, size: { width: 120, height: 70 }, label: 'B (in)', ports: [{ id: 'bi', side: 'left' as const, type: 'input' as const }] },
{ id: 'c', position: { x: 640, y: 400 }, size: { width: 120, height: 70 }, label: 'C (out)', ports: [{ id: 'co', side: 'left' as const, type: 'output' as const }] },
];
export default component$(() => {
useVisibleTask$(({ cleanup }) => {
clearConnectionValidators();
const disposeValidator = registerConnectionValidator(({ sourcePort, targetPort }) => {
if (!sourcePort || !targetPort) return true;
return sourcePort.type === 'output' && targetPort.type === 'output'
? 'an output cannot feed another output'
: true;
});
cleanup(() => { disposeValidator(); clearConnectionValidators(); });
});
return (
```
:::
Each binding mounts the same model and registers the same rule. During a drag, a rejected drop leaves the model unchanged; an allowed drop adds the link to the mounted diagram. Press Escape during a drag to cancel the attempt.
## Options that affect the interaction
| Option | Type | Default | What it does |
|---|---|---|---|
| `interaction.portVisibility` | `'hover' \| 'always'` | `'hover'` | Keeps ports visible during the example when set to `'always'`. |
| `ports[].type` | `'input' \| 'output' \| 'bi'` | — | Controls which direction a port accepts during wiring. |
## Pitfalls
- Validators are process-global. Dispose the returned function and call `clearConnectionValidators()` when the view unmounts; see [ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation) for the warning.
- Give the canvas host a real height, or the mounted diagram appears blank. See [style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram).
- Every registered validator must allow the candidate. Validators have veto power, not voting power.
## Live demo
Try the [connection-validation demo](https://grafloria.com/demos/ports/connection-validation.html). It rejects output-to-output and accepts output-to-input during real drags.
## Related
- [Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation)
- [Build a workflow editor](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/build-a-workflow-editor)
- [Edit and route edges](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/edit-and-route-edges)
# Edit and route edges
Use an edge specification for semantic intent, then let the mounted diagram route and edit the
geometry. This page shows obstacle avoidance, endpoint reconnection, and editable waypoints in
JavaScript, Angular, Qwik, React, and Vue.
## Choose the edge geometry
An [`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) needs only `source` and `target`.
Set `type` for the line's shape and `router` for the path it takes. `orthogonal` produces
right-angle segments; `manhattan` uses grid-based right-angle routing; `avoid` routes around nodes
and re-routes as they move; `elk` uses the ELK edge router. `connector` changes how the routed
segments are drawn.
In JavaScript, [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) mounts the spec and returns a live
[`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance). The following
mounted diagram puts a wall between A and B. The `avoid` edge bends around it rather
than crossing it. Replace `avoid` with `orthogonal`, `manhattan`, or `elk` when you want to choose a
different router.
:::code-group
```js title="JavaScript"
import { render } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '100vh';
const nodes = [
{ id: 'a', position: { x: 80, y: 305 }, size: { width: 120, height: 60 }, label: 'A' },
{ id: 'b', position: { x: 840, y: 305 }, size: { width: 120, height: 60 }, label: 'B' },
{ id: 'wall', position: { x: 430, y: 250 }, size: { width: 140, height: 170 }, label: 'obstacle' },
];
const edges = [{ id: 'e1', source: 'a', target: 'b', router: 'avoid', connector: 'rounded' }];
const instance = render({ nodes, edges }, host);
instance.fitView();
```
```ts title="Angular"
import { Component } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
@Component({
standalone: true,
imports: [DiagramCanvasComponent],
template: ``,
})
export class RoutedEdgesComponent {
nodes = [
{ id: 'a', position: { x: 80, y: 305 }, size: { width: 120, height: 60 }, label: 'A' },
{ id: 'b', position: { x: 840, y: 305 }, size: { width: 120, height: 60 }, label: 'B' },
{ id: 'wall', position: { x: 430, y: 250 }, size: { width: 140, height: 170 }, label: 'obstacle' },
];
edges = [{ id: 'e1', source: 'a', target: 'b', router: 'avoid', connector: 'rounded' }];
}
```
The same mounted instance is exposed by [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow) in the
Qwik binding; the React, Vue, and Angular bindings use the same engine and edge data.
```tsx title="Qwik"
import { component$ } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
const nodes = [
{ id: 'a', position: { x: 80, y: 305 }, size: { width: 120, height: 60 }, label: 'A' },
{ id: 'b', position: { x: 840, y: 305 }, size: { width: 120, height: 60 }, label: 'B' },
{ id: 'wall', position: { x: 430, y: 250 }, size: { width: 140, height: 170 }, label: 'obstacle' },
];
const edges = [{ id: 'e1', source: 'a', target: 'b', router: 'avoid' as const, connector: 'rounded' as const }];
export default component$(() => (
```
:::
The wire visibly detours around the wall. Move the wall through the corridor and the route follows
it; remove the wall and the clear route becomes a two-point line. See the [edge routing demo](https://grafloria.com/demos/edges/edge-routing.html).

## Reconnect an endpoint
Select an edge, then drag its endpoint handle onto another node's port. The mounted diagram changes
the link from A→B to A→C and emits the `reconnect` event. Pin handles when the endpoint must land on
a particular side.
```js
import { render } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '100vh';
const instance = render({
nodes: [
{ id: 'a', position: { x: 80, y: 260 }, size: { width: 120, height: 60 }, label: 'A' },
{ id: 'b', position: { x: 660, y: 110 }, size: { width: 120, height: 60 }, label: 'B' },
{ id: 'c', position: { x: 660, y: 430 }, size: { width: 120, height: 60 }, label: 'C' },
],
edges: [{ id: 'e1', source: 'a', target: 'b', sourceHandle: 'right', targetHandle: 'left', type: 'direct' }],
}, host);
const unsubscribe = instance.on('reconnect', ({ link }) => {
console.log(`edge now targets ${link.targetNodeId}`);
});
// Keep `unsubscribe` and call it from your host's unmount or teardown hook.
```
The selected edge displays endpoint handles; dropping the target handle on C rewires the existing
edge, rather than creating a second edge. The change is one undoable edit. See the [reconnect edge demo](https://grafloria.com/demos/edges/reconnect-edge.html).

## Add editable waypoints
Waypoint editing is opt-in. Enable it through the mounted diagram's interaction configuration,
select an edge, click its path to add an interior point, then drag that point. The endpoints remain
attached to their nodes, and each bend is one undoable edit.
```js
import { render } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '100vh';
const instance = render({
nodes: [
{ id: 'a', position: { x: 120, y: 260 }, size: { width: 120, height: 60 }, label: 'A' },
{ id: 'b', position: { x: 660, y: 260 }, size: { width: 120, height: 60 }, label: 'B' },
],
edges: [{ id: 'e1', source: 'a', target: 'b', type: 'direct' }],
}, host, { interaction: { enableWaypointEditing: true, showWaypointHandles: true } });
instance.renderNow();
```
The selected line gains a handle at the clicked position; dragging it bends the route while A and B
stay fixed. `points` contains the resulting interior coordinates, so an edited route can be saved
and restored as edge data. See the [editable edge demo](https://grafloria.com/demos/edges/editable-edge.html).

For a saved route, pass `points` in the edge spec. The points are interior world coordinates of
[`Point`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-types-interfaces-b-r#point) values; the
renderer supplies the endpoint geometry. Use `waypoints` when you want to declare the bends as the
edge's routing intent rather than restore an edited route.
## Options that matter
| Option | Type | Default | What it does |
|---|---|---|---|
| `type` | `'direct' \| 'smooth' \| 'orthogonal' \| 'bezier'` | — | Selects the line shape. |
| `router` | `'straight' \| 'orthogonal' \| 'manhattan' \| 'avoid' \| 'elk'` | — | Selects the path algorithm. |
| `connector` | `'straight' \| 'rounded' \| 'smooth' \| 'bezier'` | — | Selects the drawing treatment for the route. |
| `sourceHandle` / `targetHandle` | `string` | — | Pins an endpoint to a port, side, or positioned side such as `right@36`. |
| `points` | `Point[]` | — | Restores explicit interior waypoints. |
| `waypoints` | `Point[]` | — | Declares the bends the router must keep. |
| `interaction.enableWaypointEditing` | `boolean` | off | Enables adding and dragging waypoints from the mounted interaction layer. |
| `interaction.showWaypointHandles` | `boolean` | — | Shows waypoint handles while editing. |
## Pitfalls
- Give the host a resolved height such as `100vh`; a canvas without height appears blank. See [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram).
- Use the instance's `getEngine().undo()` for undo; `undo()` is not a `DiagramInstance` method. See [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo).
- A declarative `layout` prop does not re-run when node data changes. Call the engine layout method explicitly when your application changes data. See [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works).
## Live examples and related pages
- [Edge routing](https://grafloria.com/demos/edges/edge-routing.html) demonstrates obstacle avoidance and live re-routing.
- [Routing algorithms](https://grafloria.com/demos/edges/routing-algorithms.html) compares `orthogonal`, `manhattan`, and `elk` per edge.
- [Reconnect edge](https://grafloria.com/demos/edges/reconnect-edge.html) demonstrates endpoint replacement.
- [Editable edge](https://grafloria.com/demos/edges/editable-edge.html) demonstrates waypoint editing.
- [Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation) explains connection targets and validators.
- [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document) explains how links and points persist in the diagram document.
# Group nested diagrams
Use groups when nodes belong to a container rather than merely appearing inside a rectangle.
## Create membership and nesting
[`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core) mounts a spec and returns a [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance). Use its engine to create groups and its model to fit them.
```js
import { render } from '@grafloria/element';
const host = document.querySelector('#diagram');
if (!(host instanceof HTMLElement)) throw new Error('Missing #diagram');
host.style.height = '500px';
const instance = render({ nodes: [{ id: 'n1', position: { x: 100, y: 100 }, label: 'stage 1' }, { id: 'n2', position: { x: 260, y: 100 }, label: 'stage 2' }, { id: 'n3', position: { x: 180, y: 220 }, label: 'retry' }], edges: [{ source: 'n1', target: 'n2' }, { source: 'n1', target: 'n3' }] }, host);
const engine = instance.getEngine();
const diagram = instance.getModel();
void (async () => {
const pipeline = await engine.addGroup({ name: 'Pipeline' });
for (const id of ['n1', 'n2', 'n3']) await engine.addToGroup(pipeline.id, id);
const retryHandler = await engine.addGroup({ name: 'Retry handler' });
await engine.addToGroup(retryHandler.id, 'n3');
pipeline.addMember(retryHandler.id, diagram);
retryHandler.fitToContents(diagram); pipeline.fitToContents(diagram); instance.renderNow();
})();
```

The diagram renders nested frames around the members. Fit the inner group first, then the outer group. Give the host a real height; see [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram).
## Framework bindings
The same engine calls run from every binding. Use the binding's component and initialization callback to obtain the instance.
:::code-group
```ts title="Angular"
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
@Component({ standalone: true, imports: [DiagramCanvasComponent], template: '' })
export class Groups implements AfterViewInit {
canvas = viewChild.required(DiagramCanvasComponent);
nodes = [{ id: 'n1', position: { x: 100, y: 100 }, label: 'stage 1' }, { id: 'n2', position: { x: 260, y: 100 }, label: 'stage 2' }, { id: 'n3', position: { x: 180, y: 220 }, label: 'retry' }];
edges = [{ source: 'n1', target: 'n2' }, { source: 'n1', target: 'n3' }];
async ngAfterViewInit() { const e = this.canvas().activeEngine(); if (!e) return; const d = e.getDiagram(); if (!d) return; const g = await e.addGroup({ name: 'Pipeline' }); for (const id of ['n1', 'n2', 'n3']) await e.addToGroup(g.id, id); g.fitToContents(d); }
}
```
```tsx title="Qwik"
import { component$, $ } from '@builder.io/qwik';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik';
const nodes = [{ id: 'n1', position: { x: 100, y: 100 }, label: 'stage 1' }, { id: 'n2', position: { x: 260, y: 100 }, label: 'stage 2' }, { id: 'n3', position: { x: 180, y: 220 }, label: 'retry' }];
const edges = [{ source: 'n1', target: 'n2' }, { source: 'n1', target: 'n3' }];
export default component$(() =>
{ const e = i.getEngine(); const d = e.getDiagram(); if (!d) return; const g = await e.addGroup({ name: 'Pipeline' }); for (const id of ['n1', 'n2', 'n3']) await e.addToGroup(g.id, id); g.fitToContents(d); i.renderNow(); })} />
; }
```
:::
## Collapse and expand
Call `collapseGroup()` and `expandGroup()` on the engine. Collapse hides members and replaces boundary links with proxy links; expand restores the members and original links.
```ts
import { render } from '@grafloria/element';
import type { DiagramInstance } from '@grafloria/renderer';
async function collapseAndExpand(instance: DiagramInstance) {
const engine = instance.getEngine();
const service = await engine.addGroup({ name: 'Service' });
for (const id of ['n1', 'n2', 'n3']) await engine.addToGroup(service.id, id);
await engine.collapseGroup(service.id); instance.renderNow();
await engine.expandGroup(service.id); instance.renderNow();
}
const host = document.querySelector('#collapse-diagram');
if (!(host instanceof HTMLElement)) throw new Error('Missing #collapse-diagram');
host.style.height = '500px';
const instance = render({ nodes: [
{ id: 'n1', position: { x: 100, y: 100 }, label: 'one' },
{ id: 'n2', position: { x: 260, y: 100 }, label: 'two' },
{ id: 'n3', position: { x: 180, y: 220 }, label: 'three' },
] }, host);
void collapseAndExpand(instance);
```

See the [Sub-flow live demo](https://grafloria.com/demos/grouping/sub-flow.html) for nesting, fitting, and collective dragging, and the [collapse-and-expand demo](https://grafloria.com/demos/grouping/collapse-expand.html) for reversible proxy links.
## Options
| Option | Type | Default | What it does |
|---|---|---|---|
| `mode` | `GroupFitMode` | `exact` | Overrides the fit mode for one call. |
| `deepRecursive` | `boolean` | — | Fits descendants before the containing group. |
| `padding` | `GroupPadding` | — | Adds space around fitted members. |
| `fitMode` | `GroupFitMode` | `exact` | Controls whether fitting grows, shrinks, or replaces the frame. |
## Pitfalls
- Call `undo()` on `instance.getEngine()`, not on `DiagramInstance`. See [Commands, events and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo).
- A declarative `layout` prop does not re-run when node data changes; call the engine layout method explicitly. See [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works).
- If a group is decoration only, disable group dragging and membership-on-drop with interaction configuration.
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Commands, events and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo)
# Save and restore diagrams
Save the mounted model as a document, then mount that document again without rebuilding its graph by hand. The shared handle is [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance); [`DiagramSerializer`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization#diagramserializer) writes its model, [`fromDocument`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#fromdocument) prepares a saved document, and [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) mounts it.
## Save and restore with JavaScript
Give the host a resolved height. This example renders a connected graph, serializes its live model, deserializes the saved document, and reconciles its nodes back into the same mounted instance rather than creating a second host.
```js
import { DiagramSerializer, fromDocument, render } from '@grafloria/element';
const sourceHost = document.getElementById('source');
if (!sourceHost) throw new Error('diagram host is missing');
sourceHost.style.height = '240px';
const source = render({
nodes: [
{ id: 'start', position: { x: 80, y: 100 }, size: { width: 140, height: 56 }, label: 'Start' },
{ id: 'finish', position: { x: 340, y: 100 }, size: { width: 140, height: 56 }, label: 'Finish' },
],
edges: [{ id: 'path', source: 'start', target: 'finish', label: 'continues' }],
}, sourceHost);
const saved = JSON.stringify(new DiagramSerializer().serialize(source.getModel()));
const loaded = new DiagramSerializer().deserialize(JSON.parse(saved));
source.setNodes(loaded.getNodes().map((node) => ({
id: node.id,
position: { x: node.position.x, y: node.position.y },
size: { width: node.size.width, height: node.size.height },
label: node.getLabel(),
})));
source.renderNow();
```
After `renderNow()`, the mounted source canvas contains the two saved nodes and their labels again.
```html
```
`serialize()` returns a plain object. `JSON.stringify()` makes it suitable for storage. `fromDocument()` accepts that JSON string, the flat serializer object, or the portable envelope. `render()` returns the new live instance.
## Framework bindings
Every binding exposes the same live instance through its initialization callback. Serialize `getModel()` after the component mounts. The Angular binding also provides `snapshot()` and `loadSnapshot()` for saving and reconciling into the existing canvas.
:::code-group
```ts title="Angular"
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { SerializedDiagram } from '@grafloria/engine';
@Component({ standalone: true, imports: [DiagramCanvasComponent], template: '' })
export class SaveRestoreComponent implements AfterViewInit {
canvas = viewChild.required(DiagramCanvasComponent);
saved: SerializedDiagram | null = null;
nodes = [{ id: 'a', position: { x: 80, y: 100 }, label: 'A' }, { id: 'b', position: { x: 320, y: 100 }, label: 'B' }];
edges = [{ id: 'ab', source: 'a', target: 'b' }];
ngAfterViewInit(): void { this.saved = this.canvas().snapshot(); }
restore(): void { if (this.saved) this.canvas().loadSnapshot(this.saved); }
}
```
```tsx title="React"
import { useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/react';
import { DiagramSerializer } from '@grafloria/engine';
const nodes = [{ id: 'a', position: { x: 80, y: 100 }, label: 'A' }, { id: 'b', position: { x: 300, y: 100 }, label: 'B' }];
const edges = [{ id: 'ab', source: 'a', target: 'b' }];
import type { ReactElement } from 'react';
export default function SaveRestore(): ReactElement {
const api = useRef(null);
const save = (): void => { if (api.current) localStorage.setItem('diagram', JSON.stringify(new DiagramSerializer().serialize(api.current.getModel()))); };
return
; });
```
:::
The JavaScript, Qwik, React, and Vue examples save the model owned by the mounted component. Angular's `snapshot()` captures the document and `loadSnapshot()` reconciles nodes and edges into the same live model, keeping its renderer and listeners attached.
## Preserve metadata
The serialized model carries node and link metadata, group membership, geometry, and link waypoints. For new persistence, use the portable envelope; it carries generator identity, creation time, and an integrity checksum. `deserialize()` accepts both the envelope and the flat form.
```ts
import { DiagramSerializer } from '@grafloria/engine';
import { render } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('diagram host is missing');
host.style.height = '240px';
const instance = render({
nodes: [{ id: 'saved', position: { x: 80, y: 100 }, label: 'Saved' }],
edges: [],
}, host);
const serializer = new DiagramSerializer();
const saved = serializer.serialize(instance.getModel());
const model = serializer.deserialize(saved);
```
Use `fromDocument()` when the result must become a renderable spec. Use `deserialize()` when you need to inspect or transform the model before mounting.
## Pitfalls
- A custom renderer function is not data and does not serialize. Register or pass the renderer again when you mount the restored document.
- Do not put user-supplied values into a renderer's `innerHTML`; use `textContent` instead, so restoring metadata cannot create an XSS path.
- Give every diagram host a real height, or the restored graph has space in the model but no visible canvas.
## Live demo
Try the [save and restore demo](https://grafloria.com/demos/interaction/save-and-restore.html) and [view its source](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/demos/interaction/save-and-restore.html).
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Round-trip Mermaid text](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/round-trip-mermaid-text)
- [Add collaboration](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/add-collaboration)
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram)
# Round-trip Mermaid text
Use Mermaid text as an editable view of a live Grafloria diagram: export the current model, edit the visible Mermaid body, then load it back while retaining model data that Mermaid cannot express, including positions.
## When to use this
Use the instance methods after mounting a canvas. [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance) is the shared handle for the rendered model. `exportText()` returns Mermaid-compatible text, and `loadText()` parses that text and reconciles it into the same instance.
## Use the framework bindings
Each binding exposes the same instance operations after its component mounts. Keep the instance in the binding’s initialization callback or hook; do not recreate it in a render function.
### JavaScript
```js
import { render } from '@grafloria/element';
const stage = document.getElementById('stage');
const source = document.getElementById('source');
const instance = render({
nodes: [
{ id: 'start', label: 'Start', position: { x: 80, y: 60 }, size: { width: 140, height: 60 } },
{ id: 'work', label: 'Work', position: { x: 320, y: 60 }, size: { width: 140, height: 60 } },
{ id: 'done', label: 'Done', position: { x: 560, y: 60 }, size: { width: 140, height: 60 } },
],
edges: [
{ id: 'e1', source: 'start', target: 'work' },
{ id: 'e2', source: 'work', target: 'done' },
],
}, stage);
instance.renderNow();
source.value = instance.exportText();
document.getElementById('load').addEventListener('click', () => {
instance.loadText(source.value);
instance.renderNow();
});
```
```html
```
The canvas shows **Start → Work → Done**, and the textarea contains the exported text. Edit the textarea and choose **Load** to apply the text to the same mounted instance.
### Angular
```ts
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DiagramCanvasComponent } from '@grafloria/angular';
@Component({
standalone: true,
imports: [DiagramCanvasComponent, FormsModule],
template: `
;
}
```
The component renders **Start → Work → Done** and keeps the live instance in a ref. Editing the controlled textarea and selecting **Load** changes the mounted diagram.
### Vue
```vue
```
The mounted component shows **Start → Work → Done**. `v-model` supplies edited Mermaid text to `loadText()`; `exportText()` reads it back from the same instance.
## Inspect text before mounting
Use [`importDiagramText`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization) when you need to parse text before deciding how to mount it. It returns an `ImportTextResult`. The live canvas path remains `loadText()` because it reconciles the result into a rendered instance.
## See it running
Open the [Mermaid text demo](https://grafloria.com/demos/misc/mermaid-text.html) to edit Mermaid text and apply it to the canvas. Its [source](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/demos/misc/mermaid-text.html) follows the same flow.
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [The model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document)
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram)
# Export diagrams
Export the scene graph from a painted diagram as SVG, PNG, PDF, or a deterministic server-rendered SVG. Set the output `width` and `height` explicitly for headless output; browser exports use the live instance.
## When to use each entry point
Use a [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) when the diagram is mounted. Its `export()` method returns a promise: SVG is a raw SVG string, while PNG, JPEG, WebP, and PDF are data URLs. The [`ExportFormat`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-types-types#exportformat) values are `'png'`, `'svg'`, `'jpeg'`, `'webp'`, and `'pdf'`.
Use `exportSvgString()` when you need a synchronous, DOM-free SVG result. It returns an [`SvgExportResult`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-export-interfaces#svgexportresult), including `warnings`. Use `exportPdf()` for synchronous PDF bytes; it returns a [`PdfExportResult`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-export-interfaces#pdfexportresult). PDF paths remain paths and text remains selectable text.
Use [`renderStatic`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#renderstatic) when nothing is mounted. It returns a [`StaticRenderResult`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-core#staticrenderresult) containing `svg`, `css`, `html`, and `snapshot`, and does not require a DOM.
## Export a mounted diagram
Give the host a resolved height so the live diagram paints before you export it. The following sample creates download buttons, then downloads a PNG at 2× scale or a raw SVG file:
:::code-group
```js title="JavaScript"
import { render } from '@grafloria/element';
document.body.innerHTML = '';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
const instance = render({
nodes: [
{ id: 'a', label: 'Extract', position: { x: 40, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'b', label: 'Load', position: { x: 260, y: 60 }, size: { width: 150, height: 66 } },
],
edges: [{ id: 'e1', source: 'a', target: 'b' }],
}, host);
instance.renderNow();
function download(href, filename) {
const link = document.createElement('a');
link.href = href;
link.download = filename;
link.click();
}
document.getElementById('png')?.addEventListener('click', async () => {
download(await instance.export('png', { scale: 2 }), 'diagram.png');
});
document.getElementById('svg')?.addEventListener('click', async () => {
const svg = await instance.export('svg');
download('data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg), 'diagram.svg');
});
```
```ts title="Angular"
import { Component, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
@Component({
standalone: true,
imports: [DiagramCanvasComponent],
template: `
`,
})
export class ExportComponent {
canvas = viewChild.required(DiagramCanvasComponent);
nodes = [
{ id: 'a', label: 'Extract', position: { x: 40, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'b', label: 'Load', position: { x: 260, y: 60 }, size: { width: 150, height: 66 } },
];
edges = [{ id: 'e1', source: 'a', target: 'b' }];
private save(href: string, filename: string): void {
const link = document.createElement('a');
link.href = href;
link.download = filename;
link.click();
}
async downloadPng(): Promise {
this.save(await this.canvas().exportDiagram('png', { scale: 2 }), 'diagram.png');
}
async downloadSvg(): Promise {
const svg = await this.canvas().exportDiagram('svg');
this.save('data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg), 'diagram.svg');
}
}
```
```tsx title="Qwik"
import { component$, $, noSerialize, useSignal, type NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik';
const nodes = [
{ id: 'a', label: 'Extract', position: { x: 40, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'b', label: 'Load', position: { x: 260, y: 60 }, size: { width: 150, height: 66 } },
];
const edges = [{ id: 'e1', source: 'a', target: 'b' }];
export default component$(() => {
const instance = useSignal>();
const save = $((href: string, filename: string) => {
const link = document.createElement('a');
link.href = href;
link.download = filename;
link.click();
});
return
;
}
```
```vue title="Vue"
```
:::
The mounted result is the same diagram in every tab. PNG downloads as a raster data URL at 2× scale; SVG downloads as vector markup containing the node labels and edges. Pass [`ExportOptions`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-types-exportoptions#exportoptions) such as `scale`, `backgroundColor`, `viewport`, or `padding` as the second argument.

## Export PDF
`export('pdf')` returns a `data:application/pdf;base64,…` URL. Download it like the PNG above. The resulting PDF keeps paths as paths and text as selectable text. For bytes without a data URL, call `instance.exportPdf()` and read its `pdf` `Uint8Array`.
```js
import { render } from '@grafloria/element';
document.body.innerHTML = '';
const host = document.getElementById('pdf-diagram');
if (!host) throw new Error('Missing #pdf-diagram');
const instance = render({
nodes: [
{ id: 'a', label: 'Requirements', position: { x: 40, y: 60 }, size: { width: 170, height: 66 } },
{ id: 'b', label: 'Design', position: { x: 260, y: 60 }, size: { width: 170, height: 66 } },
{ id: 'c', label: 'Ship', position: { x: 480, y: 60 }, size: { width: 170, height: 66 } },
],
edges: [{ id: 'e1', source: 'a', target: 'b' }, { id: 'e2', source: 'b', target: 'c' }],
}, host);
instance.renderNow();
document.getElementById('pdf')?.addEventListener('click', async () => {
const link = document.createElement('a');
link.href = await instance.export('pdf');
link.download = 'diagram.pdf';
link.click();
});
```
## Render a deterministic SVG without mounting
Pass nodes, edges, and explicit dimensions to `renderStatic()`. `width` and `height` are CSS-pixel dimensions; `standalone: true` adds the SVG namespace so `svg` can be written as a file. The result is a styled artifact when you place `css` in a `');
document.body.innerHTML = '';
const preview = document.getElementById('preview');
if (!preview) throw new Error('Missing #preview');
preview.innerHTML = fileContents;
let hash = 0x811c9dc5;
for (let index = 0; index < fileContents.length; index += 1) {
hash ^= fileContents.charCodeAt(index);
hash = Math.imul(hash, 0x01000193);
}
const fingerprint = (hash >>> 0).toString(16);
const fingerprintElement = document.getElementById('fingerprint');
if (fingerprintElement) fingerprintElement.textContent = `artifact fingerprint: ${fingerprint}`;
```
Repeated calls with the same spec and dimensions produce byte-identical SVG and CSS. This path uses no DOM and does not mount an interactive diagram; custom and HTML-layer nodes are not server-rendered.

## Options that matter
| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `scale` | `number` | `1` | Scales raster output. |
| `quality` | `number` | `0.92` | Sets JPEG/WebP quality from 0 to 1. |
| `backgroundColor` | `string` | transparent | Sets the raster background. |
| `viewport` | `Rectangle` | content bounds | Selects the world-space rectangle to export. |
| `padding` | `number` | `20` | Adds world-unit margin around content when `viewport` is not explicit. |
| `width` | `number` | `800` | Sets the static render width in CSS pixels. |
| `height` | `number` | `600` | Sets the static render height in CSS pixels. |
| `fitView` | `boolean` | `false` | Frames static content instead of using `viewport` and `zoom`. |
## Pitfalls
- Export after the first paint. A mounted export requires a painted canvas; call `renderNow()` when you need to force that synchronous paint.
- `export('svg')` returns a string, not a data URL. Prefix it with `data:image/svg+xml;charset=utf-8,` and encode it before downloading.
- Synchronous SVG and PDF exports cannot wait for unfinished asynchronous custom-node painters; inspect their `warnings`. The asynchronous `export()` call waits for those painters.
- Static output is SVG only. It does not mount a live instance, and framework HTML-layer nodes are not included.
## Live demos
- [Download PNG and SVG](https://grafloria.com/demos/misc/download-image.html)
- [Download a vector PDF](https://grafloria.com/demos/misc/pdf-export.html)
- [Render a deterministic SVG without a DOM](https://grafloria.com/demos/misc/server-side-export.html)
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram)
- [The DiagramInstance](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/instance-and-bindings)
# Add canvas tools
Use a mounted [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) as the host, then register the tool that owns the gesture. Grafloria supplies freehand drawing, erasing, and rectangle creation; use [`registerTool`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-functions#registertool) when you need a host-specific interaction such as marquee selection.
## Mount a canvas and add a drawing tool
Give the host a resolved height. [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) returns the live instance, and the drawing tool writes a committed vector stroke into its model when the pointer is released.
```ts
import {
createDrawTool,
registerTool,
render,
} from '@grafloria/element';
const host = document.createElement('div');
document.body.append(host);
host.style.height = '480px';
const instance = render({ nodes: [{ id: 'start', position: { x: 80, y: 80 }, label: 'Start' }], edges: [] }, host);
registerTool(createDrawTool(instance, {
color: '#e11d48',
width: 3,
simplifyEpsilon: 0.8,
}));
// Keep the disposer returned by registerTool and call it when the feature is unloaded.
```
After a drag, the canvas shows a red SVG stroke. The model contains one simplified stroke for the gesture, so the gesture is one editable history operation rather than a screenshot.

## Choose the shipped whiteboard tools
The same mounted instance is the host for the eraser and rectangle tools. An eraser removes whole strokes that the pointer sweep crosses. A rectangle drag creates a real node, not ink, so the result participates in connection, resize, and layout behavior.
```ts
import {
createEraserTool,
createRectangleTool,
registerTool,
render,
} from '@grafloria/element';
const host = document.createElement('div');
document.body.append(host);
host.style.height = '480px';
const instance = render({ nodes: [{ id: 'start', position: { x: 80, y: 80 }, label: 'Start' }], edges: [] }, host);
registerTool(createEraserTool(instance, { radius: 10 }));
registerTool(createRectangleTool(instance, {
fill: '#dbeafe',
stroke: '#2563eb',
strokeWidth: 2,
label: 'Box',
}));
// Activate one point-agnostic mode at a time in your toolbar.
```
Do not leave competing mode tools active: draw, rectangle, and eraser can all claim an empty-canvas pointerdown. The registry chooses the claiming tool with the highest `priority`; ties fall back to registration order, which is not a contract. A tool disposer restores the previous tool with the same id.


## Add a custom interaction
Use [`registerTool`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-functions#registertool) for a gesture the built-in binder does not own. A [`CanvasTool`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-interfaces-a-t#canvastool) claims a pointerdown in `hitTest`; its pointer handlers then receive the rest of that gesture. Set an explicit priority whenever another tool can claim the same press.
This skeleton claims only an empty-canvas press and gives you world and screen coordinates for a host-owned overlay:
```ts
import type { CanvasTool } from '@grafloria/renderer';
import { registerTool } from '@grafloria/element';
import { render } from '@grafloria/element';
const host = document.createElement('div');
host.style.height = '480px';
document.body.append(host);
render({ nodes: [{ id: 'start', position: { x: 80, y: 80 }, label: 'Start' }], edges: [] }, host);
let start: { x: number; y: number } | undefined;
const marquee: CanvasTool = {
id: 'marquee',
priority: 1,
hitTest: (_event, hit) => hit.empty,
onPointerDown: (event) => {
start = { x: event.world.x, y: event.world.y };
},
onPointerMove: (event) => {
if (start) {
// Paint your overlay from start to event.screen here.
console.log(start, event.screen.x, event.screen.y);
}
},
onPointerUp: (event) => {
if (start) {
// Convert the world rectangle into the selection your application wants.
console.log(start.x, start.y, event.world.x, event.world.y);
}
start = undefined;
},
onCancel: () => {
start = undefined;
},
};
registerTool(marquee);
```
The custom tool itself does not draw the overlay or select nodes: those are host responsibilities. The live marquee example shows the complete version, including a dashed overlay and full-containment selection.

## Use the same setup in each framework
Register after the binding provides the mounted instance, and keep the canvas host sized.
:::code-group
```html title="JavaScript"
```
```tsx title="React"
import { useRef } from 'react';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/react';
import { createDrawTool, registerTool } from '@grafloria/element';
export function CanvasTools() {
const host = useRef(null);
const onInit = (instance: DiagramInstance) => {
if (host.current) registerTool(createDrawTool(instance, { color: '#e11d48', width: 3 }));
};
return
```
:::
The bindings mount the returned kit spec and preserve its class compartments and relationship markers.
## Editing and options
Set `editable: true` on either kit when the diagram itself is the editor. In an ER diagram, double-click a table header or column to rename it, use the add-column affordance, or delete a row. Each edit is undoable and field-level relationships remain attached to their columns. `rowSelection` controls whether clicking a row selects it; rows are selectable by default.
| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `entities` | `ErEntitySpec[]` | required | Declares ER table cards and their columns. |
| `relationships` | `ErRelationshipSpec[]` | — | Declares ER relationships; `TABLE.column` endpoints pin to rows. |
| `classes` | `UmlClassSpec[]` | required | Declares UML class cards, attributes, and methods. |
| `editable` | `boolean` | `false` | Enables in-canvas editing for the kit. |
| `rowSelection` | `boolean` | `true` | Enables column/member row selection. |
If you add a custom-node renderer around these diagrams, its initial render runs at mount, not whenever node data changes. Update the DOM that your renderer owns, or use the dashboard widget update and repaint handles when those are the surface you chose.
## See it running
- [Table / ER diagram](https://grafloria.com/demos/diagrams/table-er.html) shows typed columns, PK/FK badges, crow's-foot relationships, and row selection.

- [Class diagram (UML)](https://grafloria.com/demos/diagrams/class-uml.html) shows class compartments, inheritance, and aggregation.

For the editable ER surface, see [ERD editor](https://grafloria.com/demos/diagrams/erd-editor.html). For the complete UML relationship vocabulary, see [UML relationships](https://grafloria.com/demos/diagrams/uml-relationships.html).
## Related
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works) explains the shared model and engine.
- [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) explains the history behind kit edits.
- [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram) covers sizing and theming.
- [Export diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/export-diagrams) covers exporting the mounted instance.
# Build a dashboard
Use the dashboard kit when your board is data: declare views and widgets, mount
the board in a sized element, then use its live handle for layout changes and
persistence. The result is a responsive board with KPI and chart cards that the
user can rearrange.
## Declare the board
[`DashboardWidgetSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-dashboardwidgetspec)
is the data for one widget. Give it an `id`, a `kind`, a cell size, and the
payload consumed by the kit's renderer. A
[`DashboardViewSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-interfaces) groups
widgets into one view; supplying several views gives you tabs.
```ts
import type { DashboardViewSpec } from '@grafloria/element';
export const views: DashboardViewSpec[] = [{
id: 'overview',
name: 'Overview',
widgets: [
{
id: 'revenue', kind: 'kpi', span: 3, rows: 1,
data: { label: 'Revenue', value: '$6.81M', delta: 12.4 },
},
{
id: 'trend', kind: 'bar', span: 9, rows: 2,
title: 'Revenue trend',
data: {
bars: [{ label: 'Jan', value: 42 }, { label: 'Mar', value: 51 }, { label: 'May', value: 65 }],
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
},
},
],
}];
```
The shipped `kpi` and `line` widget painters render these cards. A widget with
`widgets` instead becomes a section with its own inner grid; use that shape for
nested boards rather than constructing grid nodes yourself.
## Mount it
Give the dashboard element a height. Without one, the board has no drawing
space. The following front doors produce the same board.
### JavaScript
The [`dashboard`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-functions) function
creates a [`DashboardSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-interfaces);
[`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core) mounts that spec and returns the
diagram instance.
```ts
import { dashboard, render } from '@grafloria/element';
import type { DashboardViewSpec } from '@grafloria/element';
const views: DashboardViewSpec[] = [{
id: 'overview', name: 'Overview', widgets: [
{ id: 'revenue', kind: 'kpi', span: 3, rows: 1,
data: { label: 'Revenue', value: '$6.81M', delta: 12.4 } },
{ id: 'trend', kind: 'bar', span: 9, rows: 2, title: 'Revenue trend',
data: { bars: [{ label: 'Jan', value: 42 }, { label: 'Mar', value: 51 }, { label: 'May', value: 65 }] } },
],
}];
const target = document.getElementById('dashboard') ?? document.body.appendChild(document.createElement('div'));
target.id = 'dashboard';
target.style.display = 'block';
target.style.height = '660px';
target.style.width = '1180px';
const spec = dashboard({ views, columns: 12, gap: 8, sizing: 'fit', responsive: { columnWidth: 96 } });
const instance = render(spec, target);
const handle = spec.handle;
handle.setLayout('grid');
localStorage.setItem('dashboard', JSON.stringify(handle.toJSON()));
window.addEventListener('unload', () => instance.dispose());
```
```html
```
`handle.toJSON()` returns the complete board as plain data, including the live
layout. Feed that object back to `dashboard()` when you load a saved board.
### Angular
[`GrafloriaDashboardComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-grafloriadashboardcomponent)
uses `[views]` for the board and emits its typed handle through `ready`.
```ts
import { Component } from '@angular/core';
import { GrafloriaDashboardComponent } from '@grafloria/angular';
import type { DashboardHandle, DashboardViewSpec } from '@grafloria/element';
@Component({
standalone: true,
imports: [GrafloriaDashboardComponent],
template: `
`,
})
export class DashboardComponent {
handle?: DashboardHandle;
dirty = false;
views: DashboardViewSpec[] = [{ id: 'overview', name: 'Overview', widgets: [
{ id: 'revenue', kind: 'kpi', span: 3, rows: 1, data: { label: 'Revenue', value: '$6.81M' } },
{ id: 'trend', kind: 'bar', span: 9, rows: 2, title: 'Revenue trend',
data: { bars: [{ label: 'Jan', value: 42 }, { label: 'Mar', value: 51 }, { label: 'May', value: 65 }] } },
] }];
changeLayout() { this.handle?.setLayout('split'); }
save() {
const snapshot = this.handle?.toJSON();
if (snapshot) localStorage.setItem('dashboard', JSON.stringify(snapshot));
this.dirty = false;
}
}
```
The `ready` output arrives after the first paint. `layoutChange` marks the
board dirty after a committed drag, resize, add, or remove; `save()` stores the
current arrangement rather than the original `views` array.
### Qwik
[`GrafloriaDashboard`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik) takes `views`, `layout`, and
`onReady$`. Keep the live handle non-serializable and call it from a Qwik event.
```tsx
import { component$, $, noSerialize, useSignal, type NoSerialize } from '@builder.io/qwik';
import { GrafloriaDashboard } from '@grafloria/qwik';
import type { DashboardHandle, DashboardViewSpec } from '@grafloria/element';
export default component$(() => {
const handle = useSignal>();
const views: DashboardViewSpec[] = [{ id: 'overview', widgets: [
{ id: 'revenue', kind: 'kpi', span: 3, rows: 1, data: { label: 'Revenue', value: '$6.81M' } },
{ id: 'trend', kind: 'bar', span: 9, rows: 2, data: { bars: [{ label: 'Jan', value: 42 }, { label: 'Mar', value: 51 }, { label: 'May', value: 65 }] } },
] }];
const save = $(() => {
const snapshot = handle.value?.toJSON();
if (snapshot) localStorage.setItem('dashboard', JSON.stringify(snapshot));
});
return <>
{
handle.value = noSerialize(value);
})} style={{ display: 'block', height: '660px' }} />
>;
});
```
### React
The React binding follows the same data-first props. Its `onReady` callback
provides the live handle used by the toolbar.
```tsx
import { useState } from 'react';
import { GrafloriaDashboard } from '@grafloria/react';
import type { DashboardHandle, DashboardViewSpec } from '@grafloria/element';
export default function Dashboard() {
const [handle, setHandle] = useState();
const views: DashboardViewSpec[] = [{ id: 'overview', widgets: [
{ id: 'revenue', kind: 'kpi', span: 3, rows: 1, data: { label: 'Revenue', value: '$6.81M' } },
{ id: 'trend', kind: 'bar', span: 9, rows: 2, data: { bars: [{ label: 'Jan', value: 42 }, { label: 'Mar', value: 51 }, { label: 'May', value: 65 }] } },
] }];
return <>
>;
}
```
### Vue
Vue exposes the same board through `v-model:active-view`; `@ready` captures the
handle while the component owns mounting and repainting.
```vue
```
## Change the live board
The [`DashboardHandle`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-dashboardhandle)
is the shared runtime handle. Use it for live layout changes. `addWidget(spec)`
creates and mounts a widget and
returns its handle, or `undefined` when a bounded board has no room. Use
`widget(id)` to call `pin(true)`, `resize()`, `moveTo()`, or `update()` on one
widget.
| Option | Type | Default | What it does |
|---|---|---:|---|
| `columns` | `number` | `12` | Sets the board column count. |
| `gap` | `number` | `8` | Sets widget gaps and board padding in pixels. |
| `sizing` | `'fit' \| 'grow'` | — | `fit` bounds the board; `grow` lets rows extend it. |
| `layout` | `'grid' \| 'split'` | — | Selects the cell grid or splitter layout. |
| `responsive` | `DashboardResponsiveOptions` | — | Derives the live column count from board width. |
| `static` | `boolean` | — | Turns pointer dragging, resizing, and handles off. |
Use the `layout` prop or input for the initial state and the handle for a live
toolbar switch. Do not mutate a saved snapshot while the board is mounted;
serialize the handle's current `toJSON()` result after the user's changes.
## See it running
- [Dashboard builder](https://grafloria.com/demos/dashboard/dashboard-builder.html)
shows tabbed views, palette additions, pinning, layout switching, and save/load.
- [Fluid board](https://grafloria.com/demos/dashboard/fluid-board.html) shows
fit versus grow sizing and grid versus split layout.
- [Grid options](https://grafloria.com/demos/dashboard/grid-options.html) shows
responsive columns, float, RTL, sections, and pinned widgets.
- [Nested containers](https://grafloria.com/demos/dashboard/nested-containers.html)
shows a widget containing its own board.
## Related
- [Dashboard options](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-dashboardoptions)
- [Dashboard widget spec](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-dashboardwidgetspec)
- [Dashboard handle](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-dashboard-kit-dashboardhandle)
# Add collaboration
Connect two mounted diagrams to the same room and watch edits, presence, comments, reconnects, and local undo converge.
## When to use this
Use the `collab` prop on [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) when each mounted diagram has a transport and an actor id. The canvas joins when it mounts and leaves when it unmounts. Local edits become CRDT operations; incoming operations merge per property, so a move and a rename on the same node can both survive.
`BroadcastChannelTransport` is the shipped no-server choice for two tabs in one browser. Use `WebSocketTransport` when your application supplies a server-backed channel. Grafloria supplies convergence, presence, comments, and the operation log; your application supplies rooms, authentication, and storage.
## Connect two diagrams
Use the same channel name for both transports and a different stable actor for each peer. Give each canvas a real height so both mounted diagrams render.
:::code-group
```js title="JavaScript"
import { render } from '@grafloria/element';
import { BroadcastChannelTransport, createSyncSession } from '@grafloria/engine';
document.body.innerHTML = '';
const nodes = [
{ id: 'ingest', label: 'Ingest', position: { x: 60, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'publish', label: 'Publish', position: { x: 320, y: 60 }, size: { width: 150, height: 66 } },
];
const edges = [{ id: 'e1', source: 'ingest', target: 'publish' }];
const room = 'diagram-' + Math.random().toString(36).slice(2);
const left = render({ nodes, edges }, '#left');
const right = render({ nodes: nodes.map((node) => ({ ...node, position: { ...node.position }, size: { ...node.size } })), edges: edges.map((edge) => ({ ...edge })) }, '#right');
createSyncSession(left.getModel(), new BroadcastChannelTransport({ name: room, actor: 'ana' }), { actor: 'ana' }).join();
createSyncSession(right.getModel(), new BroadcastChannelTransport({ name: room, actor: 'ben' }), { actor: 'ben' }).join();
left.getModel().getNode('ingest')?.setPosition(100, 180);
right.fitView();
```
```tsx title="React"
import { useMemo } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { BroadcastChannelTransport } from '@grafloria/engine';
const nodes = [
{ id: 'ingest', label: 'Ingest', position: { x: 60, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'publish', label: 'Publish', position: { x: 320, y: 60 }, size: { width: 150, height: 66 } },
];
const edges = [{ id: 'e1', source: 'ingest', target: 'publish' }];
export function CollaborativeDiagram() {
const collab = useMemo(() => {
const room = 'diagram-' + Math.random().toString(36).slice(2);
return {
ana: { transport: new BroadcastChannelTransport({ name: room, actor: 'ana' }), actor: 'ana', presence: { name: 'Ana' } },
ben: { transport: new BroadcastChannelTransport({ name: room, actor: 'ben' }), actor: 'ben', presence: { name: 'Ben' } },
};
}, []);
return
;
});
```
```ts title="Angular"
import { Component } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import { BroadcastChannelTransport } from '@grafloria/engine';
@Component({ standalone: true, imports: [DiagramCanvasComponent], template: `
` })
export class AppComponent {
nodesA = [
{ id: 'ingest', label: 'Ingest', position: { x: 60, y: 60 }, size: { width: 150, height: 66 } },
{ id: 'publish', label: 'Publish', position: { x: 320, y: 60 }, size: { width: 150, height: 66 } },
];
nodesB = this.nodesA.map((node) => ({ ...node, position: { ...node.position }, size: { ...node.size } }));
edges = [{ id: 'e1', source: 'ingest', target: 'publish' }];
private room = 'diagram-' + Math.random().toString(36).slice(2);
collabA = { transport: new BroadcastChannelTransport({ name: this.room, actor: 'ana' }), actor: 'ana', presence: { name: 'Ana' } };
collabB = { transport: new BroadcastChannelTransport({ name: this.room, actor: 'ben' }), actor: 'ben', presence: { name: 'Ben' } };
}
```
:::
Each pair renders the same connected diagram. Drag a node in either pane: the other pane follows and displays the other actor's presence. Camera changes remain local to each pane; document edits synchronize.
See the [live two-tabs demo](https://grafloria.com/demos/collab/two-tabs-live.html) and its [source](https://github.com/grafloria/grafloria/blob/ef2bcc55237d4d1f1643b6fea68bd996aa37a9e9/demos/collab/two-tabs-live.html).
## Add comments
Set `comments` to `true` to create the canvas's comment store. Read that store from the mounted instance and give it to the ready-made panel. This sample mounts the panel with an empty store, so it displays “Comments — No comments yet.”
For React, Vue, and Qwik, use the binding's [`GrafloriaCommentPanel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriacommentpanel); for Angular, use [`GrafloriaCommentPanelComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-classes#grafloriacommentpanelcomponent) as ``.
```tsx
import { useState } from 'react';
import { GrafloriaFlow, GrafloriaCommentPanel } from '@grafloria/react';
import type { CommentStore } from '@grafloria/engine';
export function Comments() {
const [store, setStore] = useState(null);
return
;
}
```
The Angular shape is:
```html
@if (canvas.getCommentStore(); as store) {
}
```
```ts
import { Component } from '@angular/core';
import { DiagramCanvasComponent, GrafloriaCommentPanelComponent } from '@grafloria/angular';
@Component({
standalone: true,
imports: [DiagramCanvasComponent, GrafloriaCommentPanelComponent],
template: `
@if (canvas.getCommentStore(); as store) {}
`,
styles: [':host { display: block; height: 400px; }'],
})
export class CommentsComponent {
nodes = [{ id: 'review', label: 'Review', position: { x: 80, y: 100 } }];
selectedThread: string | null = null;
}
```
Use the equivalent `GrafloriaFlow` and `GrafloriaCommentPanel` bindings in Vue and Qwik. In Qwik, mark the live store and transport with `noSerialize()`; they hold subscribers and channel state, not JSON data.
## Reconnect without losing edits
Use a transport that reports connection status. When it reconnects, the session runs anti-entropy and exchanges the operations each peer missed. A transport that never reports status cannot be caught up automatically.
With [`MemoryHub`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-sync-classes#memoryhub), you can test this without a server: disconnect both `MemoryTransport` ports, edit both mounted models, then reconnect and run the session's sync round. Both diagrams then contain both offline edits. See the [offline and reconnect demo](https://grafloria.com/demos/collab/offline-and-reconnect.html).
## Undo your own edit
Collaboration keeps local history separate from remote history. At the engine level, [`Replica`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-collab-replica#replica) captures local edits and applies remote operations without adding them to your undo stack. `undo()` therefore undoes your last edit, not the most recent edit made by another peer; `redo()` reapplies your last undone edit. Use `transact()` when several model mutations must become one undo step.
For a mounted diagram, obtain its model through [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) and keep the rendered instance as the shared handle. The rendered peers converge again when the undo operation crosses the transport.
## Choose the layer
- Use [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) when the framework owns the mounted canvas; use its Vue, Qwik, or Angular binding in those frameworks.
- Use [`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent) in Angular.
- Use [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render) when your application mounts diagrams directly.
- Use [`MemoryHub`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-sync-classes#memoryhub) for deterministic in-page or test peers.
## Pitfalls
- Give every peer a different actor id. The actor id participates in deterministic ordering.
- Create a transport and room once per mounted session. In React and Qwik, do not create them during every render; Qwik transports are live objects, so wrap them with `noSerialize()`.
- Collaboration does not synchronize viewport changes.
- A canvas with no resolved height appears blank; see [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram).
## Live examples
- [Two tabs, live](https://grafloria.com/demos/collab/two-tabs-live.html)
- [Offline and reconnect](https://grafloria.com/demos/collab/offline-and-reconnect.html)
- [Live cursors](https://grafloria.com/demos/collab/live-cursors.html)
- [Comments](https://grafloria.com/demos/collab/comments.html)
- [Conflict resolution](https://grafloria.com/demos/collab/conflict-resolution.html)
Related: [Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo), [Model and document](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/model-and-document), and [Save and restore diagrams](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/save-and-restore-diagrams).
# Style a diagram
Use this page when the diagram's appearance belongs to the host application: start with a built-in theme, add per-node or per-edge styling, and connect the canvas to the application's design tokens. The examples render a small workflow, so you can see the fill, stroke, and theme changes on a mounted canvas.
## Choose the styling layer
- Use `theme` for the canvas-wide palette and defaults. [`LIGHT_THEME`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes-constants#light_theme) and [`DARK_THEME`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes-constants#dark_theme) are shipped themes.
- Use `style.strokeWidth`, `style.fill`, and `style.stroke` for one node or edge.
- Use `style.styleClass` with `defineStyle()` for a reusable named style. Named styles follow the cascade `theme < type-default < named-class < element-inline < state`.
- Use a token bridge when the host already exposes CSS variables. A bridge makes the diagram read the host's shadcn, MUI, or Tailwind variables instead of maintaining a second palette.
The host element must have a resolved height. A canvas inside a container with no height appears blank; give it `100vh`, a flex size, or a sized grid cell.
## JavaScript
Install the element and engine packages:
```bash
npm install @grafloria/element @grafloria/engine @grafloria/renderer
```
Mount a real spec with [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render), then keep the returned [`DiagramInstance`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-diagraminstance#diagraminstance) for live changes. This sample starts dark, makes the middle node thicker, applies a named orange style to the first node, and connects the canvas to shadcn tokens.
```html
```
```js
import { render, DARK_THEME, shadcnBridge, defineStyle } from '@grafloria/element';
const host = document.getElementById('diagram');
if (!host) throw new Error('Missing #diagram');
host.style.height = '400px';
defineStyle('warning-step', { fill: '#fed7aa', stroke: '#c2410c', strokeWidth: 2 });
const nodes = [
{ id: 'start', position: { x: 40, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Start' }, style: { styleClass: 'warning-step' } },
{ id: 'review', position: { x: 280, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Review' }, style: { strokeWidth: 5 } },
{ id: 'done', position: { x: 520, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Done' } },
];
const edges = [
{ id: 'start-review', source: 'start', target: 'review' },
{ id: 'review-done', source: 'review', target: 'done', style: { strokeWidth: 3 } },
];
const instance = render({ nodes, edges }, host, { theme: DARK_THEME });
instance.setTokenBridge(shadcnBridge());
instance.renderNow();
```
The host now contains three visible nodes and two links. The first node uses the named orange style, the second node has a 5px border, and the second link has a 3px stroke. `setTokenBridge()` changes the instance's palette without changing the node data; `renderNow()` repaints synchronously.
## Use a built-in theme
Set the component's `theme` prop when the framework owns the diagram. The following snippets use the same nodes and edges in each framework; each host has a real height. The JavaScript example below shows a live theme swap through the instance.
The framework entry points are [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-react#grafloriaflow) for React, [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-vue#grafloriaflow) for Vue, [`GrafloriaFlow`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-qwik#grafloriaflow) for Qwik, and [`DiagramCanvasComponent`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-angular-components-diagramcanvascomponent#diagramcanvascomponent) for Angular.
:::code-group
```tsx title="React"
import { GrafloriaFlow, DARK_THEME } from '@grafloria/react';
import type { NodeSpec, EdgeSpec } from '@grafloria/react';
const nodes: NodeSpec[] = [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Order' } },
{ id: 'b', position: { x: 300, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Ship' } },
];
const edges: EdgeSpec[] = [{ id: 'e1', source: 'a', target: 'b' }];
export default function StyledFlow() {
return (
;
});
```
```js title="JavaScript"
import { render, LIGHT_THEME, DARK_THEME } from '@grafloria/element';
const host = document.getElementById('diagram') ?? document.body.appendChild(document.createElement('div'));
host.id = 'diagram';
host.style.height = '400px';
const instance = render({
nodes: [
{ id: 'a', position: { x: 60, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Order' } },
{ id: 'b', position: { x: 300, y: 80 }, size: { width: 170, height: 70 }, data: { label: 'Ship' } },
],
edges: [{ id: 'e1', source: 'a', target: 'b' }],
}, host, { theme: DARK_THEME });
let dark = true;
const toggle = document.getElementById('toggle');
if (!toggle) throw new Error('Missing #toggle');
toggle.addEventListener('click', () => {
dark = !dark;
instance.setTheme(dark ? DARK_THEME : LIGHT_THEME);
instance.renderNow();
});
```
:::
In Angular, `DiagramCanvasComponent` is the canvas element. In the other framework bindings, `GrafloriaFlow` is rendered as a component. The JavaScript example uses the instance's `setTheme()` method; retain the instance rather than recreating the canvas.
## Add named styles and a token bridge
Register a named style once, then name it from a node's `style.styleClass`. Namespace names in applications because the style registry is process-wide. An inline property outranks the named class, so this node is green even though its class declares orange:
```js
import { defineStyle } from '@grafloria/element';
defineStyle('review-step', { fill: '#fed7aa', stroke: '#c2410c', strokeWidth: 2 });
const node = {
id: 'review',
position: { x: 80, y: 80 },
size: { width: 180, height: 72 },
data: { label: 'Review' },
style: { styleClass: 'review-step', fill: '#22c55e' },
};
```
For a host that uses CSS variables, import one of the shipped bridges and pass it to the live instance:
```js
import { render, LIGHT_THEME, shadcnBridge, defineStyle } from '@grafloria/element';
const host = document.getElementById('diagram') ?? document.body.appendChild(document.createElement('div'));
host.id = 'diagram';
host.style.cssText = 'height:400px;width:800px;display:block';
defineStyle('review-step', { fill: '#fed7aa', stroke: '#c2410c', strokeWidth: 2 });
const node = {
id: 'review',
position: { x: 80, y: 80 },
size: { width: 180, height: 72 },
data: { label: 'Review' },
style: { styleClass: 'review-step', fill: '#22c55e' },
};
const instance = render({ nodes: [node], edges: [] }, host, { theme: LIGHT_THEME });
instance.setTokenBridge(shadcnBridge());
instance.renderNow();
```
`shadcnBridge()`, `muiBridge()`, and `tailwindBridge()` map the corresponding host vocabulary. The bridge is instance-scoped: two diagrams can use different themes on one page without one instance overwriting the other's CSS variables. To change the host palette, update the host's variables or class, then repaint the instance.
## Pitfalls
- A host without a resolved height produces a blank canvas. Size the host or its flex/grid parent before mounting.
- A named style does not beat an element-inline property. Put the property on the node when that node must win.
- Do not use a Mermaid-style text string as the `render()` spec. `render()` mounts a data object; text import is a separate API.
- Use `./create-custom-nodes.md` when you need a custom node; omit `custom: true` and the renderer uses a stock rectangle. Register its renderer before mount.
- Use `./build-er-and-uml-diagrams.md` for custom-node update behavior; custom renderers run at mount, so update DOM you own or repaint the dashboard widget.
## See also
- [The live dark-mode demo](https://grafloria.com/demos/styling/dark-mode.html)
- [The live CSS-variable demo](https://grafloria.com/demos/styling/css-variables.html)
- [The live named-style demo](https://grafloria.com/demos/styling/named-style-classes.html)
- [The live themes and tokens demo](https://grafloria.com/demos/styling/themes-and-tokens.html)
- [How Grafloria works](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/how-grafloria-works)
- [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram)
# Build a workflow editor
Use a diagram as the workflow document: nodes represent steps, typed ports constrain
connections, the engine supplies history, and node data records execution state. The result
is an editor that renders a connected workflow, rejects invalid links, can run the graph, and
can save and restore the document.
## When to use this
Use this pattern when users create or edit a directed process rather than view a fixed diagram.
The model remains the source of truth: keep the step configuration in `data`, keep connection
rules on ports, and update the live instance after execution changes.
The same engine drives every binding. The JavaScript example uses [`render`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-core#render);
## Define the workflow document
Create a shared module. The two nodes have explicit input and output ports. The output carries
`dataType: 'event'`, while the input accepts only `event`; a connection from the output to the
input is therefore legal, and a connection in the reverse direction is not. The live objects below are
[`NodeModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-nodemodel#nodemodel) and
[`PortModel`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-models-portmodel#portmodel); the renderer creates them from
these specs. Use [`NodeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance#nodespec) and
[`EdgeSpec`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance-edgespec#edgespec) for the plain data arrays.
```ts title="workflow.ts"
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
export const nodes: NodeSpec[] = [
{
id: 'trigger',
type: 'workflow-step',
position: { x: 80, y: 120 },
size: { width: 170, height: 72 },
data: { label: 'Receive commit', status: 'idle' },
ports: [
{ id: 'trigger-out', side: 'right', type: 'output', dataType: 'event' },
],
},
{
id: 'deploy',
type: 'workflow-step',
position: { x: 380, y: 120 },
size: { width: 170, height: 72 },
data: { label: 'Deploy staging', status: 'idle' },
ports: [
{ id: 'deploy-in', side: 'left', type: 'input', dataType: 'event' },
{ id: 'deploy-out', side: 'right', type: 'output', dataType: 'event' },
],
},
];
export const edges: EdgeSpec[] = [
{
id: 'trigger-to-deploy',
source: 'trigger',
sourceHandle: 'trigger-out',
target: 'deploy',
targetHandle: 'deploy-in',
type: 'orthogonal',
},
];
export function setExecutionState(
instance: import('@grafloria/renderer').DiagramInstance,
nodeId: string,
status: 'idle' | 'running' | 'success' | 'failed',
): void {
const node = instance.getModel().getNode(nodeId);
if (!node) return;
node.setData('status', status);
node.setSelected(status === 'running');
instance.render();
}
```
For persistence, use [`DiagramSerializer`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-serialization#diagramserializer)
in a browser-safe module:
```ts title="workflow-persistence.ts"
import { DiagramSerializer } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
export function saveDocument(instance: DiagramInstance): string {
return JSON.stringify(new DiagramSerializer().serialize(instance.getModel()));
}
export function restoreDocument(instance: DiagramInstance, text: string): void {
const document = JSON.parse(text) as ReturnType;
const model = new DiagramSerializer().deserialize(document);
instance.getEngine().setDiagram(model);
instance.renderNow();
}
```
Use the second module in the framework samples. It serializes the complete model, including ports
and links. Restoring replaces the engine's diagram and repaints the mounted canvas.
## Mount it in JavaScript
Give the host a resolved height. The canvas displays the two connected steps, and the buttons
change the live model, validate it, and round-trip it through JSON. The example uses the shipped
[`LIGHT_THEME`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes-constants#light_theme).
```ts title="main.ts"
import { render } from '@grafloria/element';
import { LIGHT_THEME } from '@grafloria/renderer';
import { nodes, edges, setExecutionState } from './workflow';
import { saveDocument, restoreDocument } from './workflow-persistence';
const host = document.getElementById('workflow')!;
host.style.height = '420px';
const instance = render({ nodes, edges }, host, {
theme: LIGHT_THEME,
interaction: { portVisibility: 'always' },
});
const engine = instance.getEngine();
document.getElementById('run')!.addEventListener('click', () => {
setExecutionState(instance, 'trigger', 'success');
setExecutionState(instance, 'deploy', 'running');
});
document.getElementById('validate')!.addEventListener('click', () => {
console.log(engine.validateDiagram({ validateTypes: true, validateConnections: true }));
});
document.getElementById('save')!.addEventListener('click', () => {
localStorage.setItem('workflow', saveDocument(instance));
});
document.getElementById('load')!.addEventListener('click', () => {
const text = localStorage.getItem('workflow');
if (text) restoreDocument(instance, text);
});
document.getElementById('undo')!.addEventListener('click', () => {
void engine.undo();
});
```
```html title="index.html"
```

Clicking **Run** changes the trigger to a success state and selects the deploy step as the running
step; the renderer repaints the model change. A custom node can read the stored `status` to draw
its own success or running badge. Dragging or connecting
nodes creates engine history entries, and **Undo** removes the latest user edit.
## Mount it in Angular, Qwik, React, and Vue
Each binding mounts a real component with the same nodes and edges. Store the instance in the
binding's mount callback; do not create it in render code. The host styles give the canvas height.
:::code-group
```ts title="Angular"
import { Component } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { RenderOptions } from '@grafloria/element';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges } from './workflow';
@Component({
standalone: true,
imports: [GrafloriaDiagramComponent],
template: '',
styles: ['grafloria-diagram { display: block; height: 420px; }'],
})
export class WorkflowComponent {
readonly spec = { nodes, edges };
readonly options: RenderOptions = { interaction: { portVisibility: 'always' } };
instance?: DiagramInstance;
ready(instance: DiagramInstance): void { this.instance = instance; }
}
```
```tsx title="React"
import { useRef, type ReactElement } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/react';
import { nodes, edges } from './workflow';
export function Workflow(): ReactElement {
const instance = useRef(null);
return { instance.current = value; }}
style={{ display: 'block', height: '420px' }} />;
}
```
```vue title="Vue"
```
```tsx title="Qwik"
import { component$, $, noSerialize, useSignal } from '@builder.io/qwik';
import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik';
import { nodes, edges } from './workflow';
export default component$(() => {
const instance = useSignal();
const ready = $((value: DiagramInstance) => { instance.value = noSerialize(value); });
return ;
});
```
:::
All five mounted canvases show the same connected workflow. Call `getEngine()` through the stored
instance for validation and undo, call `getModel()` to inspect or update step data, and call
`renderNow()` when a subsequent measurement must observe the change synchronously.
## Add validation and execution
Port direction, `dataType`, and connection limits provide structural validation while a user draws.
For a complete document check, call `validateDiagram()` on the [`DiagramEngine`](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-engine#diagramengine)
and display its returned
validation result. Your executor can walk from a trigger, set each node's `status` with
`setData()`, and call `render()` after each step. The renderer then shows the state your node
template reads from `data`.
Keep execution separate from editing: a run changes status data, while a drag or connection is a
command on the shared history. For a toolbar action that edits the document, use a shipped command
through the engine's command manager so the action participates in the same undo stack. See
[Commands, events, and undo](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/commands-events-and-undo) for the command boundary and
[Ports and validation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/ports-and-validation) for custom rules.
## Persistence and next steps
Store the string returned by `saveDocument()` in your database or browser storage. On load, call
`restoreDocument()` on a mounted instance. Re-register any custom renderer before mounting the
document; serialized data contains the model, not JavaScript renderer functions.
See the live [workflow automation builder](https://grafloria.com/demos/interaction/workflow-builder.html)
for insertion, editing, grouping, run state, and save/load in one editor.
The [n8n-style workflow builder](https://grafloria.com/demos/interaction/n8n-workflow.html) shows
item counts, branch execution, pause/step controls, and a per-node details view.
For a smaller execution-state example, open [Execute flow](https://grafloria.com/demos/interaction/execute-flow.html).
## Pitfalls
- A host without a resolved height renders a blank canvas. Give it a fixed height, a viewport height,
or a flex/grid size; see [Style a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/style-a-diagram).
- `undo()` belongs to the engine, not `DiagramInstance`; call `instance.getEngine().undo()`.
- Changing node data does not rerun a declarative layout. Call the engine layout method explicitly,
then repaint if you use the imperative layout path; see [Auto-layout a diagram](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/auto-layout-a-diagram).
- A custom node needs the custom-node flag and its renderer must be registered before mount; see
[Create custom nodes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/create-custom-nodes).
# @grafloria/react
React bindings for Grafloria Diagrams and Grafloria Dashboards — an MIT diagram and dashboard engine: routing, auto-layout, undo, collaboration and dashboard layouts, native in React.
## Install
```bash
npm install @grafloria/react @grafloria/engine @grafloria/renderer react react-dom @grafloria/element
```
It expects these alongside it:
- `@grafloria/engine` ^0.3.0
- `@grafloria/renderer` ^0.4.16
- `react` ^17.0.0 || ^18.0.0 || ^19.0.0
- `react-dom` ^17.0.0 || ^18.0.0 || ^19.0.0
- `@grafloria/element` ^0.4.3
## Functions
### `createGrafloriaStore`
```ts
function createGrafloriaStore(): GrafloriaStore
```
### `GrafloriaCommentPanel`
```ts
function GrafloriaCommentPanel(props: GrafloriaCommentPanelProps)
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `store` | `CommentStore` | | |
| `options?` | `CommentPanelOptions` | | |
| `onSelect?` | `(threadId: string) => void` | | |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
**Events**
- `onSelect`
### `GrafloriaDashboard`
```ts
function GrafloriaDashboard(props: GrafloriaDashboardProps)
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `views?` | `DashboardViewSpec[]` | | Multi-view (tabbed) board. Mutually exclusive with `widgets`. |
| `widgets?` | `DashboardWidgetSpec[]` | | Single-view shorthand. |
| `options?` | `Partial` | | Board options: columns, gap, sizing, rtl, responsive, binder… |
| `widgetTypes?` | `WidgetTypes` | | Maps a widget `kind` to the React component that renders it. |
| `activeView?` | `string` | | The visible view (the tab pattern). Omit for kit-managed. |
| `layout?` | `"split" \| "grid"` | | LIVE SWITCHES — the toolbar toggles as props. Each is applied at mount |
| `sizing?` | `"fit" \| "grow"` | | |
| `static?` | `boolean` | | Static board: the viewer's mode — no drag, no resize, no handles. |
| `onReady?` | `(handle: DashboardHandle) => void` | | The typed handle, once the board is live. |
| `onLayoutChange?` | `(change: { viewId: string; widgets: DashboardWidgetSpec[]; }) => void` | | Mirrors the kit's committed gestures (drag, resize, add, remove). |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
| `children?` | `ReactNode` | | |
**Events**
- `onReady` — The typed handle, once the board is live.
- `onLayoutChange` — Mirrors the kit's committed gestures (drag, resize, add, remove).
### `GrafloriaDiagram`
```ts
function GrafloriaDiagram(props: GrafloriaDiagramProps)
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `spec` | `RenderSpec` | | Any kit spec — `erDiagram(...)`, `umlDiagram(...)`, `dashboard(...)`, or DSL text. |
| `options?` | `RenderOptions` | | Options passed through to the underlying `createDiagram`. |
| `onReady?` | `(instance: DiagramInstance) => void` | | |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
**Events**
- `onReady`
### `GrafloriaFlow`
```ts
function GrafloriaFlow(props: GrafloriaFlowProps)
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes?` | `NodeSpec[]` | | Controlled nodes. Provide with `onNodesChange` (see `useNodesState`). |
| `edges?` | `EdgeSpec[]` | | Controlled edges. |
| `groups?` | `(GroupModel \| GroupSpec)[]` | | Controlled groups — zones around some nodes (a spec's `groups`, or the live |
| `defaultNodes?` | `NodeSpec[]` | | Uncontrolled nodes — the instance owns them from here on. |
| `defaultEdges?` | `EdgeSpec[]` | | |
| `defaultGroups?` | `(GroupModel \| GroupSpec)[]` | | |
| `onNodesChange?` | `(nodes: NodeModel[]) => void` | | |
| `onEdgesChange?` | `(edges: LinkModel[]) => void` | | |
| `onSelectionChange?` | `(change: { nodes: NodeModel[]; edges: LinkModel[]; }) => void` | | |
| `onConnect?` | `(change: { link: LinkModel; }) => void` | | |
| `onNodeClick?` | `(change: { node: NodeModel; world: { x: number; y: number; }; }) => void` | | |
| `onEdgeClick?` | `(change: { edge: LinkModel; world: { x: number; y: number; }; }) => void` | | |
| `onInit?` | `(instance: DiagramInstance) => void` | | |
| `nodeTypes?` | `NodeTypes` | | Custom node components, keyed by node `type`. |
| `theme?` | `Theme` | | |
| `fitView?` | `boolean` | | |
| `enablePan?` | `boolean` | | |
| `enableZoom?` | `boolean` | | |
| `zoomSensitivity?` | `number` | | |
| `dragThreshold?` | `number` | | |
| `readonly?` | `boolean` | | |
| `minZoom?` | `number` | | |
| `maxZoom?` | `number` | | |
| `ssr?` | `{ html: string; snapshot: HydrationSnapshot; }` | | The `renderToStaticSVG()` result. Renders server-side, hydrates client-side. |
| `layout?` | `string \| { name: string; options?: Record; }` | | Declarative auto-layout — any engine registry name ('elk', 'dagre', |
| `onLayoutDone?` | `(result: unknown) => void` | | Fires after each declarative layout completes. |
| `plugins?` | `boolean \| CanvasPluginOptions` | | Canvas plugins — `true` mounts minimap + zoom/fit controls + background |
| `collab?` | `GrafloriaCollabOptions` | | Real-time collaboration: hand in a transport (BroadcastChannelTransport, |
| `onCollabReady?` | `(session: SyncAdapter) => void` | | The live SyncAdapter, right after `join()`. |
| `comments?` | `boolean \| CommentStore` | | Anchored comment threads — `true` creates a store, or pass a shared |
| `commentsViewer?` | `string` | | Viewer id for a `comments: true`-created store. |
| `rendererConfig?` | `Record` | | Renderer config passthrough (parallelLinks, parallelSpacing, jump styles, …). |
| `interaction?` | `Record` | | Interaction config passthrough (portVisibility, enableHelperLines, …). |
| `tokenBridge?` | `unknown` | | Design-token bridge — adopt the app's shadcn / MUI / Tailwind CSS variables. |
| `highlighterConfig?` | `boolean \| Partial` | | The outline layer Angular's canvas draws: outlines around the hovered node, |
| `highlightConnected?` | `boolean \| HighlightConnectedOptions` | | Bring the selected nodes' lines forward and fade the rest: `true`, or |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
| `children?` | `ReactNode` | | Overlays (toolbars, panels). Rendered as siblings of the canvas. |
**Events**
- `onNodesChange`
- `onEdgesChange`
- `onSelectionChange`
- `onConnect`
- `onNodeClick`
- `onEdgeClick`
- `onInit`
- `onLayoutDone` — Fires after each declarative layout completes.
- `onCollabReady` — The live SyncAdapter, right after `join()`.
### `GrafloriaProvider`
Wrap anything that needs `useGrafloria()` outside of ``'s subtree.
```tsx
// useGrafloria() works here…
// …because the flow publishes its instance to the store
```
`` also creates its own store when there is no provider, so the
simple single-canvas case needs no wrapper at all.
```ts
function GrafloriaProvider({ children }: GrafloriaProviderProps)
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `children?` | `ReactNode` | | |
### `useEdgesState`
Controlled edge state. Mirrors {@link useNodesState}.
```ts
function useEdgesState(initial: EdgeSpec[] = []): EdgesState
```
### `useGrafloria`
The live `DiagramInstance`, or `null` until `` has mounted.
Works from anywhere inside an `` (a toolbar, a minimap, a
sidebar) and from inside ``'s own children.
```tsx
const grafloria = useGrafloria();
```
```ts
function useGrafloria(): DiagramInstance | null
```
### `useGrafloriaStore`
The nearest store, or null when there is no provider above us.
```ts
function useGrafloriaStore(): GrafloriaStore | null
```
### `useNodesState`
Controlled node state — the React Flow tuple everyone already knows:
```tsx
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
```
`onNodesChange` is what closes the loop: the user drags a node, the ENGINE
moves it, the instance emits `nodes:change`, `` calls this, and
React state catches up. Without it a controlled `` would snap the
node back on the next render — the classic controlled-component trap.
```ts
function useNodesState(initial: NodeSpec[] = []): NodesState
```
### `useOnSelectionChange`
Fire a callback whenever the selection changes.
```tsx
useOnSelectionChange(({ nodes }) => setInspected(nodes[0] ?? null));
```
The handler is held in a ref, so passing an inline arrow (the common case)
does NOT re-subscribe on every render.
```ts
function useOnSelectionChange(handler: (change: SelectionChange) => void): void
```
### `useSelection`
The current selection as state (for rendering an inspector panel).
```ts
function useSelection(): SelectionChange
```
### `useViewport`
The live camera (zoom + world rect) as state — for a minimap or a zoom badge.
```ts
function useViewport(): { zoom: number; x: number; y: number }
```
## Constants
### `GrafloriaContext`
```ts
const GrafloriaContext: any
```
## Interfaces
### `GrafloriaCommentPanelProps`
```ts
interface GrafloriaCommentPanelProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `store` | `CommentStore` | | |
| `options?` | `CommentPanelOptions` | | |
| `onSelect?` | `(threadId: string \| null) => void` | | |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
### `GrafloriaDashboardProps`
```ts
interface GrafloriaDashboardProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `views?` | `DashboardViewSpec[]` | | Multi-view (tabbed) board. Mutually exclusive with `widgets`. |
| `widgets?` | `DashboardWidgetSpec[]` | | Single-view shorthand. |
| `options?` | `Partial` | | Board options: columns, gap, sizing, rtl, responsive, binder… |
| `widgetTypes?` | `WidgetTypes` | | Maps a widget `kind` to the React component that renders it. |
| `activeView?` | `string` | | The visible view (the tab pattern). Omit for kit-managed. |
| `layout?` | `'grid' \| 'split'` | | LIVE SWITCHES — the toolbar toggles as props. Each is applied at mount (over `options`) and, when it changes afterwards, through the handle (`setLayout` / `setSizing` / `setStatic`) — no remount, like `activeView`. 'split' is the DevExpress splitter tree; 'grid' the cell grid. |
| `sizing?` | `'fit' \| 'grow'` | | |
| `static?` | `boolean` | | Static board: the viewer's mode — no drag, no resize, no handles. |
| `onReady?` | `(handle: DashboardHandle) => void` | | The typed handle, once the board is live. |
| `onLayoutChange?` | `(change: { viewId: string; widgets: DashboardWidgetSpec[] }) => void` | | Mirrors the kit's committed gestures (drag, resize, add, remove). |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
| `children?` | `ReactNode` | | |
### `GrafloriaDiagramProps`
```ts
interface GrafloriaDiagramProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `spec` | `RenderSpec` | | Any kit spec — `erDiagram(...)`, `umlDiagram(...)`, `dashboard(...)`, or DSL text. |
| `options?` | `RenderOptions` | | Options passed through to the underlying `createDiagram`. |
| `onReady?` | `(instance: DiagramInstance) => void` | | |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
### `GrafloriaFlowProps`
```ts
interface GrafloriaFlowProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes?` | `NodeSpec[]` | | Controlled nodes. Provide with `onNodesChange` (see `useNodesState`). |
| `edges?` | `EdgeSpec[]` | | Controlled edges. |
| `groups?` | `Array` | | Controlled groups — zones around some nodes (a spec's `groups`, or the live GroupModels of a loaded document). Reconciled like `nodes`. |
| `defaultNodes?` | `NodeSpec[]` | | Uncontrolled nodes — the instance owns them from here on. |
| `defaultEdges?` | `EdgeSpec[]` | | |
| `defaultGroups?` | `Array` | | |
| `onNodesChange?` | `(nodes: NodeModel[]) => void` | | |
| `onEdgesChange?` | `(edges: LinkModel[]) => void` | | |
| `onSelectionChange?` | `(change: { nodes: NodeModel[]; edges: LinkModel[] }) => void` | | |
| `onConnect?` | `(change: { link: LinkModel }) => void` | | |
| `onNodeClick?` | `(change: { node: NodeModel; world: { x: number; y: number } }) => void` | | |
| `onEdgeClick?` | `(change: { edge: LinkModel; world: { x: number; y: number } }) => void` | | |
| `onInit?` | `(instance: DiagramInstance) => void` | | |
| `nodeTypes?` | `NodeTypes` | | Custom node components, keyed by node `type`. |
| `theme?` | `Theme` | | |
| `fitView?` | `boolean` | | |
| `enablePan?` | `boolean` | | |
| `enableZoom?` | `boolean` | | |
| `zoomSensitivity?` | `number` | | |
| `dragThreshold?` | `number` | | |
| `readonly?` | `boolean` | | |
| `minZoom?` | `number` | | |
| `maxZoom?` | `number` | | |
| `ssr?` | `{ html: string; snapshot: HydrationSnapshot }` | | The `renderToStaticSVG()` result. Renders server-side, hydrates client-side. |
| `layout?` | `string \| { name: string; options?: Record }` | | Declarative auto-layout — any engine registry name ('elk', 'dagre', 'force', 'tree', 'grid', 'auto', …) or `{ name, options }`. Re-runs when the prop VALUE changes, never when node data changes. |
| `onLayoutDone?` | `(result: unknown) => void` | | Fires after each declarative layout completes. |
| `plugins?` | `boolean \| CanvasPluginOptions` | | Canvas plugins — `true` mounts minimap + zoom/fit controls + background grid with defaults; an object picks and configures them. |
| `collab?` | `GrafloriaCollabOptions` | | Real-time collaboration: hand in a transport (BroadcastChannelTransport, WebSocketTransport, MemoryTransport, …) and an actor id — the flow joins a CRDT sync session at mount and leaves on unmount. Fixed for the life of the instance. |
| `onCollabReady?` | `(session: SyncAdapter) => void` | | The live SyncAdapter, right after `join()`. |
| `comments?` | `boolean \| CommentStore` | | Anchored comment threads — `true` creates a store, or pass a shared `CommentStore`. Read it back with `useGrafloria()?.getCommentStore()`. |
| `commentsViewer?` | `string` | | Viewer id for a `comments: true`-created store. |
| `rendererConfig?` | `Record` | | Renderer config passthrough (parallelLinks, parallelSpacing, jump styles, …). |
| `interaction?` | `Record` | | Interaction config passthrough (portVisibility, enableHelperLines, …). |
| `tokenBridge?` | `unknown` | | Design-token bridge — adopt the app's shadcn / MUI / Tailwind CSS variables. |
| `highlighterConfig?` | `boolean \| Partial` | | The outline layer Angular's canvas draws: outlines around the hovered node, the selected node, nodes with a validation issue, and valid connection targets. `true` turns every kind on; an object turns kinds on or off one by one. Off when unset. Live: follows the prop by value. |
| `highlightConnected?` | `boolean \| HighlightConnectedOptions` | | Bring the selected nodes' lines forward and fade the rest: `true`, or options (depth, stroke, outgoing, dimOpacity). Off when unset. Live: follows the prop by value. |
| `className?` | `string` | | |
| `style?` | `CSSProperties` | | |
| `children?` | `ReactNode` | | Overlays (toolbars, panels). Rendered as siblings of the canvas. |
### `GrafloriaProviderProps`
```ts
interface GrafloriaProviderProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `children?` | `ReactNode` | | |
### `GrafloriaStore`
The provider + the store behind `useGrafloria()`.
React Flow's ergonomics come from exactly this shape: a ``
that lets a toolbar, a sidebar or a minimap — components that are SIBLINGS of
the canvas, not children of it — reach the live instance. We keep that shape,
but the thing being shared is our framework-agnostic `DiagramInstance`, so the
provider is a 40-line store and NOT a re-implementation of the diagram.
Why a hand-rolled store rather than `useSyncExternalStore`: that hook is React
18+, and this package supports React 17–19. Subscribe + `useState` costs one
extra render on attach and works everywhere.
```ts
interface GrafloriaStore
```
**Members**
- `get(): DiagramInstance | null` — The live instance, or null before `` has mounted.
- `set(instance: DiagramInstance | null): void` — Called by `` on mount/unmount.
- `subscribe(listener: (instance: DiagramInstance | null) => void): () => void` — Notified whenever the instance is attached or detached.
### `NodeProps`
Props a custom node component receives. Deliberately React-Flow-shaped.
```ts
interface NodeProps>
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | | |
| `data` | `TData` | | |
| `selected` | `boolean` | | |
| `node` | `NodeModel` | | The live engine model — the escape hatch. |
### `SelectionChange`
```ts
interface SelectionChange
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes` | `NodeModel[]` | | |
| `edges` | `LinkModel[]` | | |
### `WidgetProps`
Props a widget component receives — the `NodeProps` twin for boards.
```ts
interface WidgetProps>
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `widget` | `DashboardWidgetSpec` | | |
| `data` | `TData` | | |
## Types
### `EdgesState`
Also has every member of `Array`, listed on its own entry.
```ts
type EdgesState = [
EdgeSpec[],
Dispatch>,
(edges: LinkModel[]) => void,
];
```
### `NodesState`
Also has every member of `Array`, listed on its own entry.
What `useNodesState` hands back — React Flow's tuple, with our types.
```ts
type NodesState = [
NodeSpec[],
Dispatch>,
(nodes: NodeModel[]) => void,
];
```
### `NodeTypes`
`nodeTypes` maps a node's `type` to the component that renders it.
```ts
type NodeTypes = Record>>;
```
### `WidgetTypes`
```ts
type WidgetTypes = Record>;
```
## Also exported from here
These names are documented with the package that defines them, and can be imported from this one too.
- From [@grafloria/renderer](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-overview): `DARK_THEME`, `DiagramInstance`, `EdgeSpec`, `HydrationSnapshot`, `LIGHT_THEME`, `NodeSpec`, `PortSpec`, `renderToStaticSVG`, `StaticRenderOptions`, `StaticRenderResult`, `Theme`
# @grafloria/qwik
Qwik bindings for Grafloria Diagrams and Grafloria Dashboards — an MIT diagram and dashboard engine: routing, auto-layout, undo, collaboration and dashboard layouts, server-rendered and resumable in Qwik.
## Install
```bash
npm install @grafloria/qwik @grafloria/engine @grafloria/renderer @builder.io/qwik @grafloria/element
```
It expects these alongside it:
- `@grafloria/engine` ^0.3.0
- `@grafloria/renderer` ^0.4.18
- `@builder.io/qwik` ^1.5.0
- `@grafloria/element` ^0.4.3
## Functions
### `useGrafloria`
The live `DiagramInstance` signal. Falls back to a component-local signal
when there is no `` above, so the hook is always safe to
call — it simply never fills in without a provider or a sibling flow.
```ts
function useGrafloria(): GrafloriaStore
```
### `useOnSelectionChangeQrl`
Fire a QRL on every selection change; teardown is automatic.
The handler is a QRL rather than a plain function because Qwik has to be
able to serialize the subscription and load the handler lazily — that is
the whole point of the `$` suffix, and it is why this reads
`useOnSelectionChange$(...)` at the call site.
```ts
function useOnSelectionChangeQrl(handler: QRL<(change: SelectionChange) => void>): void
```
### `useSelection`
The current selection as reactive state (for an inspector panel).
```ts
function useSelection(): Signal
```
### `useViewport`
The live camera (zoom + world origin) as reactive state.
```ts
function useViewport(): Signal<{ zoom: number; x: number; y: number }>
```
## Constants
### `GRAFLORIA_STORE`
```ts
const GRAFLORIA_STORE: any
```
### `GrafloriaCommentPanel`
```ts
const GrafloriaCommentPanel: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `store` | `NoSerialize` | | The live comment store. Must be `noSerialize()`d. |
| `options?` | `CommentPanelOptions` | | |
| `onSelect$?` | `QRL<(threadId: string) => void>` | | |
| `class?` | `string` | | |
**Events**
- `onSelect$`
### `GrafloriaDashboard`
```ts
const GrafloriaDashboard: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `views?` | `DashboardViewSpec[]` | | |
| `widgets?` | `DashboardWidgetSpec[]` | | |
| `options?` | `Partial` | | |
| `activeView?` | `string` | | The visible view. |
| `layout?` | `"split" \| "grid"` | | LIVE SWITCHES — the toolbar toggles as props: applied at mount (over |
| `sizing?` | `"fit" \| "grow"` | | |
| `static?` | `boolean` | | Static board: the viewer's mode — no drag, no resize, no handles. |
| `widgetTypes?` | `WidgetTypes` | | Qwik components for widget kinds, keyed by `kind`. |
| `onReady$?` | `QRL<(handle: DashboardHandle) => void>` | | |
| `onLayoutChange$?` | `QRL<(change: { viewId: string; widgets: DashboardWidgetSpec[]; }) => void>` | | |
| `class?` | `string` | | |
| `style?` | `Record` | | |
**Events**
- `onReady$`
- `onLayoutChange$`
### `GrafloriaDiagram`
```ts
const GrafloriaDiagram: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `spec` | `RenderSpec` | | Any kit spec — erDiagram(...), umlDiagram(...), dashboard(...), or DSL text. |
| `options?` | `RenderOptions` | | |
| `onReady$?` | `QRL<(instance: DiagramInstance) => void>` | | Fires once the kit has rendered, with the live instance. |
| `class?` | `string` | | |
| `style?` | `Record` | | |
**Events**
- `onReady$` — Fires once the kit has rendered, with the live instance.
### `GrafloriaFlow`
```ts
const GrafloriaFlow: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes?` | `NodeSpec[]` | | |
| `edges?` | `EdgeSpec[]` | | |
| `groups?` | `(GroupModel \| GroupSpec)[]` | | Controlled groups — zones around some nodes (a spec's `groups`, or the live |
| `defaultNodes?` | `NodeSpec[]` | | |
| `defaultEdges?` | `EdgeSpec[]` | | |
| `defaultGroups?` | `(GroupModel \| GroupSpec)[]` | | |
| `onInit$?` | `QRL<(instance: DiagramInstance) => void>` | | |
| `onNodesChange$?` | `QRL<(nodes: NodeSpec[]) => void>` | | |
| `onEdgesChange$?` | `QRL<(edges: EdgeSpec[]) => void>` | | |
| `onSelectionChange$?` | `QRL<(change: SelectionChange) => void>` | | |
| `onConnect$?` | `QRL<(change: { link: LinkModel; }) => void>` | | |
| `onNodeClick$?` | `QRL<(change: { node: NodeModel; world: { x: number; y: number; }; }) => void>` | | |
| `onEdgeClick$?` | `QRL<(change: { edge: LinkModel; world: { x: number; y: number; }; }) => void>` | | |
| `onLayoutDone$?` | `QRL<(result: unknown) => void>` | | |
| `onCollabReady$?` | `QRL<(session: SyncAdapter) => void>` | | |
| `nodeTypes?` | `NodeTypes` | | Custom node components, keyed by node `type`. |
| `theme?` | `Theme` | | |
| `fitView?` | `boolean` | | |
| `enablePan?` | `boolean` | | |
| `enableZoom?` | `boolean` | | |
| `zoomSensitivity?` | `number` | | |
| `dragThreshold?` | `number` | | |
| `readonly?` | `boolean` | | |
| `minZoom?` | `number` | | |
| `maxZoom?` | `number` | | |
| `ssr?` | `{ html: string; snapshot: HydrationSnapshot; }` | | The `renderToStaticSVG()` result. Renders server-side; the visible task |
| `layout?` | `string \| GrafloriaLayoutRequest` | | Declarative auto-layout — any engine registry name ('elk', 'dagre', |
| `plugins?` | `boolean \| CanvasPluginOptions` | | Canvas plugins — `true` mounts minimap + zoom/fit controls + background |
| `collab?` | `NoSerialize` | | Real-time collaboration: a transport + actor id. The flow joins a CRDT |
| `comments?` | `any` | | Anchored comment threads — `true` creates a store, or pass a shared |
| `commentsViewer?` | `string` | | Viewer id for a `comments: true`-created store. |
| `rendererConfig?` | `Record` | | Renderer config passthrough (parallelLinks, parallelSpacing, jump styles, …). |
| `interaction?` | `Record` | | Interaction config passthrough (portVisibility, enableHelperLines, …). |
| `tokenBridge?` | `unknown` | | Design-token bridge — adopt the app's shadcn / MUI / Tailwind CSS variables. |
| `highlighterConfig?` | `boolean \| Partial` | | The outline layer: outlines around the hovered node, the selected node, |
| `highlightConnected?` | `boolean \| HighlightConnectedOptions` | | Bring the selected nodes' lines forward and fade the rest: `true`, or |
| `class?` | `string` | | |
| `style?` | `Record` | | |
**Events**
- `onInit$`
- `onNodesChange$`
- `onEdgesChange$`
- `onSelectionChange$`
- `onConnect$`
- `onNodeClick$`
- `onEdgeClick$`
- `onLayoutDone$`
- `onCollabReady$`
### `GrafloriaProvider`
Makes the nearest ``'s instance reachable by SIBLINGS —
toolbars, inspectors, minimaps — through the hooks below.
```ts
const GrafloriaProvider: any
```
### `useOnSelectionChange$`
```ts
const useOnSelectionChange$: any
```
## Interfaces
### `GrafloriaCollabOptions`
The uniform collab contract every Grafloria wrapper shares.
```ts
interface GrafloriaCollabOptions
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `transport` | `SyncTransport` | | The transport (BroadcastChannelTransport, WebSocketTransport, …). |
| `actor` | `string` | | |
| `presence?` | `boolean \| BindPresenceOptions` | | Live cursors + remote selection outlines. `true` for defaults. |
### `GrafloriaCommentPanelProps`
```ts
interface GrafloriaCommentPanelProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `store` | `NoSerialize` | | The live comment store. Must be `noSerialize()`d. |
| `options?` | `CommentPanelOptions` | | |
| `onSelect$?` | `QRL<(threadId: string \| null) => void>` | | |
| `class?` | `string` | | |
### `GrafloriaDashboardProps`
```ts
interface GrafloriaDashboardProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `views?` | `DashboardViewSpec[]` | | |
| `widgets?` | `DashboardWidgetSpec[]` | | |
| `options?` | `Partial` | | |
| `activeView?` | `string` | | The visible view. |
| `layout?` | `'grid' \| 'split'` | | LIVE SWITCHES — the toolbar toggles as props: applied at mount (over `options`) and, when they change, through the handle (`setLayout` / `setSizing` / `setStatic`), never by remounting. 'split' is the splitter tree; 'grid' the cell grid. |
| `sizing?` | `'fit' \| 'grow'` | | |
| `static?` | `boolean` | | Static board: the viewer's mode — no drag, no resize, no handles. |
| `widgetTypes?` | `WidgetTypes` | | Qwik components for widget kinds, keyed by `kind`. |
| `onReady$?` | `QRL<(handle: DashboardHandle) => void>` | | |
| `onLayoutChange$?` | `QRL< (change: { viewId: string; widgets: DashboardWidgetSpec[] }) => void >` | | |
| `class?` | `string` | | |
| `style?` | `Record` | | |
### `GrafloriaDiagramProps`
```ts
interface GrafloriaDiagramProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `spec` | `RenderSpec` | | Any kit spec — erDiagram(...), umlDiagram(...), dashboard(...), or DSL text. |
| `options?` | `RenderOptions` | | |
| `onReady$?` | `QRL<(instance: DiagramInstance) => void>` | | Fires once the kit has rendered, with the live instance. |
| `class?` | `string` | | |
| `style?` | `Record` | | |
### `GrafloriaFlowProps`
```ts
interface GrafloriaFlowProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes?` | `NodeSpec[]` | | |
| `edges?` | `EdgeSpec[]` | | |
| `groups?` | `Array` | | Controlled groups — zones around some nodes (a spec's `groups`, or the live GroupModels of a loaded document). Reconciled like `nodes`. |
| `defaultNodes?` | `NodeSpec[]` | | |
| `defaultEdges?` | `EdgeSpec[]` | | |
| `defaultGroups?` | `Array` | | |
| `onInit$?` | `QRL<(instance: DiagramInstance) => void>` | | |
| `onNodesChange$?` | `QRL<(nodes: NodeSpec[]) => void>` | | |
| `onEdgesChange$?` | `QRL<(edges: EdgeSpec[]) => void>` | | |
| `onSelectionChange$?` | `QRL<(change: SelectionChange) => void>` | | |
| `onConnect$?` | `QRL<(change: { link: LinkModel }) => void>` | | |
| `onNodeClick$?` | `QRL<(change: { node: NodeModel; world: { x: number; y: number } }) => void>` | | |
| `onEdgeClick$?` | `QRL<(change: { edge: LinkModel; world: { x: number; y: number } }) => void>` | | |
| `onLayoutDone$?` | `QRL<(result: unknown) => void>` | | |
| `onCollabReady$?` | `QRL<(session: SyncAdapter) => void>` | | |
| `nodeTypes?` | `NodeTypes` | | Custom node components, keyed by node `type`. |
| `theme?` | `Theme` | | |
| `fitView?` | `boolean` | | |
| `enablePan?` | `boolean` | | |
| `enableZoom?` | `boolean` | | |
| `zoomSensitivity?` | `number` | | |
| `dragThreshold?` | `number` | | |
| `readonly?` | `boolean` | | |
| `minZoom?` | `number` | | |
| `maxZoom?` | `number` | | |
| `ssr?` | `{ html: string; snapshot: HydrationSnapshot }` | | The `renderToStaticSVG()` result. Renders server-side; the visible task adopts the markup instead of rebuilding it, so there is no flash and no re-layout. Put `ssr.css` in your document head. |
| `layout?` | `string \| GrafloriaLayoutRequest` | | Declarative auto-layout — any engine registry name ('elk', 'dagre', 'force', 'tree', 'grid', 'auto', …) or `{ name, options }`. Re-runs when the prop VALUE changes, never when node data changes. |
| `plugins?` | `boolean \| CanvasPluginOptions` | | Canvas plugins — `true` mounts minimap + zoom/fit controls + background grid with defaults; an object picks and configures them. |
| `collab?` | `NoSerialize` | | Real-time collaboration: a transport + actor id. The flow joins a CRDT sync session on mount and leaves on unmount. Fixed for the life of the instance. `collab.transport` must be `noSerialize()`d. |
| `comments?` | `boolean \| NoSerialize` | | Anchored comment threads — `true` creates a store, or pass a shared `CommentStore` (which must be `noSerialize()`d). |
| `commentsViewer?` | `string` | | Viewer id for a `comments: true`-created store. |
| `rendererConfig?` | `Record` | | Renderer config passthrough (parallelLinks, parallelSpacing, jump styles, …). |
| `interaction?` | `Record` | | Interaction config passthrough (portVisibility, enableHelperLines, …). |
| `tokenBridge?` | `unknown` | | Design-token bridge — adopt the app's shadcn / MUI / Tailwind CSS variables. |
| `highlighterConfig?` | `boolean \| Partial` | | The outline layer: outlines around the hovered node, the selected node, nodes with a validation issue, and valid connection targets. `true` turns every kind on; an object turns kinds on or off one by one. Off when unset. Follows the prop by VALUE. |
| `highlightConnected?` | `boolean \| HighlightConnectedOptions` | | Bring the selected nodes' lines forward and fade the rest: `true`, or options (depth, stroke, outgoing, dimOpacity). Off when unset. Follows the prop by VALUE. |
| `class?` | `string` | | |
| `style?` | `Record` | | |
### `GrafloriaLayoutRequest`
```ts
interface GrafloriaLayoutRequest
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | | |
| `options?` | `Record` | | |
### `NodeProps`
Props a custom node component receives.
```ts
interface NodeProps>
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | | |
| `data` | `TData` | | |
| `selected` | `boolean` | | |
| `node` | `NodeModel` | | The live engine model — the escape hatch. |
### `SelectionChange`
```ts
interface SelectionChange
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes` | `NodeModel[]` | | |
| `edges` | `LinkModel[]` | | |
### `WidgetProps`
Props a custom widget component receives.
```ts
interface WidgetProps>
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `widget` | `DashboardWidgetSpec` | | |
| `data` | `TData` | | |
## Types
### `GrafloriaStore`
The live instance, or `undefined` until a `` mounts. Always
`noSerialize`d — see the note at the top of this file.
```ts
type GrafloriaStore = Signal | undefined>;
```
### `NodeTypes`
`nodeTypes` maps a node's `type` to the Qwik component that renders it.
Declaring a type here IS the opt-in: specs whose `type` has an entry are
flagged `custom` automatically, the same rule the Vue and Angular wrappers
use. An explicit `custom` on the spec always wins.
```ts
type NodeTypes = Record>>;
```
### `WidgetTypes`
```ts
type WidgetTypes = Record>>;
```
## Also exported from here
These names are documented with the package that defines them, and can be imported from this one too.
- From [@grafloria/renderer](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-overview): `DARK_THEME`, `DiagramInstance`, `EdgeSpec`, `GroupSpec`, `HighlightConnectedOptions`, `HydrationSnapshot`, `LIGHT_THEME`, `NodeSpec`, `renderToStaticSVG`, `StaticRenderOptions`, `StaticRenderResult`, `Theme`
# @grafloria/vue
Vue 3 bindings for Grafloria Diagrams and Grafloria Dashboards — an MIT diagram and dashboard engine: routing, auto-layout, undo, collaboration and dashboard layouts, native in Vue.
## Install
```bash
npm install @grafloria/vue @grafloria/engine @grafloria/renderer vue @grafloria/element
```
It expects these alongside it:
- `@grafloria/engine` ^0.3.0
- `@grafloria/renderer` ^0.4.16
- `vue` ^3.4.0
- `@grafloria/element` ^0.4.3
## Functions
### `useGrafloria`
The live `DiagramInstance` ref, `null` until a `` mounts.
```ts
function useGrafloria(): ShallowRef
```
### `useOnSelectionChange`
Fire a callback on every selection change; teardown is automatic.
```ts
function useOnSelectionChange(handler: (change: SelectionChange) => void): void
```
### `useSelection`
The current selection as reactive state (for an inspector panel).
```ts
function useSelection(): Ref
```
### `useViewport`
The live camera (zoom + world rect) as reactive state.
```ts
function useViewport(): Ref<{ zoom: number; x: number; y: number }>
```
## Constants
### `GRAFLORIA_STORE`
```ts
const GRAFLORIA_STORE: InjectionKey>
```
### `GrafloriaCommentPanel`
```ts
const GrafloriaCommentPanel: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `store` | `CommentStore` | | |
| `options?` | `CommentPanelOptions>, default: () =` | | |
**Events**
- `select`
### `GrafloriaDashboard`
```ts
const GrafloriaDashboard: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `views?` | `DashboardViewSpec[]` | | |
| `widgets?` | `DashboardWidgetSpec[]` | | |
| `options?` | `Partial>, default: () =` | | |
| `activeView?` | `String` | | The visible view — `v-model:active-view`. |
| `layout?` | `'grid' \| 'split'` | | LIVE SWITCHES — the toolbar toggles as props: applied at mount (over |
| `sizing?` | `'fit' \| 'grow'` | | |
| `static?` | `Boolean` | | Static board: the viewer's mode — no drag, no resize, no handles. |
**Events**
- `update:activeView`
- `ready`
- `layoutChange`
### `GrafloriaDiagram`
```ts
const GrafloriaDiagram: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `spec` | `RenderSpec` | | Any kit spec — erDiagram(...), umlDiagram(...), dashboard(...), or DSL text. |
| `options?` | `RenderOptions>, default: () =` | | |
**Events**
- `ready`
### `GrafloriaFlow`
```ts
const GrafloriaFlow: any
```
**Props**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes?` | `NodeSpec[]` | | Controlled nodes — `v-model:nodes`. |
| `edges?` | `EdgeSpec[]` | | Controlled edges — `v-model:edges`. |
| `groups?` | `Array` | | Controlled groups — zones around some nodes (a spec's `groups`, or the live |
| `defaultNodes?` | `NodeSpec[]` | | Uncontrolled initial data. |
| `defaultEdges?` | `EdgeSpec[]` | | |
| `defaultGroups?` | `Array` | | |
| `theme?` | `Theme` | | |
| `layout?` | `string \| GrafloriaLayoutRequest` | | Declarative auto-layout — any engine registry name ('elk', 'dagre', |
| `plugins?` | `boolean \| CanvasPluginOptions` | | Canvas plugins — `true` mounts minimap + zoom/fit controls + background |
| `collab?` | `GrafloriaCollabOptions` | | Real-time collaboration: a transport + actor id — the flow joins a CRDT |
| `comments?` | `boolean \| object` | | Anchored comment threads — `true` creates a store; or pass a shared one. |
| `commentsViewer?` | `String` | | |
| `fitView?` | `Boolean` | | |
| `enablePan?` | `Boolean` | | |
| `enableZoom?` | `Boolean` | | |
| `readonly?` | `Boolean` | | |
| `minZoom?` | `Number` | | |
| `maxZoom?` | `Number` | | |
| `zoomSensitivity?` | `Number` | | |
| `rendererConfig?` | `Record` | | Renderer config passthrough (parallelLinks, parallelSpacing, jump styles, …). |
| `interaction?` | `Record` | | Interaction config passthrough (portVisibility, enableHelperLines, …). |
| `tokenBridge?` | `unknown` | | Design-token bridge — adopt the app's shadcn / MUI / Tailwind CSS variables. |
| `highlighterConfig?` | `boolean \| Partial` | | The outline layer Angular's canvas draws: outlines around the hovered node, |
| `highlightConnected?` | `boolean \| HighlightConnectedOptions` | | Bring the selected nodes' lines forward and fade the rest: `true`, or |
**Events**
- `update:nodes`
- `update:edges`
- `init`
- `selectionChange`
- `connect`
- `nodeClick`
- `edgeClick`
- `layoutDone`
- `collabReady`
### `GrafloriaProvider`
Makes the nearest ``'s instance reachable by SIBLINGS —
toolbars, inspectors, minimaps — through the composables below.
```ts
const GrafloriaProvider: any
```
## Interfaces
### `GrafloriaCollabOptions`
The uniform collab contract every Grafloria wrapper shares.
```ts
interface GrafloriaCollabOptions
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `transport` | `SyncTransport` | | |
| `actor` | `string` | | |
| `presence?` | `boolean \| BindPresenceOptions` | | Live cursors + remote selection outlines. `true` for defaults. |
### `GrafloriaLayoutRequest`
```ts
interface GrafloriaLayoutRequest
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | | |
| `options?` | `Record` | | |
### `NodeSlotProps`
Context handed to `#node-` slots.
```ts
interface NodeSlotProps
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `node` | `NodeModel` | | |
| `data` | `Record` | | |
| `engine` | `DiagramEngine` | | |
### `SelectionChange`
```ts
interface SelectionChange
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes` | `NodeModel[]` | | |
| `edges` | `LinkModel[]` | | |
## Also exported from here
These names are documented with the package that defines them, and can be imported from this one too.
- From [@grafloria/renderer](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-overview): `DARK_THEME`, `DiagramInstance`, `EdgeSpec`, `LIGHT_THEME`, `NodeSpec`, `Theme`
# @grafloria/canvas-ng
Angular canvas integration for the Grafloria diagram engine
## Install
```bash
npm install @grafloria/canvas-ng @angular/common @angular/core
```
It expects these alongside it:
- `@angular/common` ^18.1.0
- `@angular/core` ^18.1.0
## Classes
### `CanvasNgCanvasNgComponent`
```ts
@Component({
selector: 'lib-canvas-ng-canvas-ng',
imports: [CommonModule],
templateUrl: './canvas-ng-canvas-ng.component.html',
styleUrl: './canvas-ng-canvas-ng.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CanvasNgCanvasNgComponent
```
Use it as `` in a template.
# @grafloria/dashboard
Grafloria Dashboards is an MIT JavaScript dashboard layout library: draggable, resizable widgets on a grid or a splitter layout, with undo, nesting and persistence built in, for Angular, React, Vue or plain JavaScript.
## Install
```bash
npm install @grafloria/dashboard @grafloria/element @grafloria/engine @grafloria/renderer
```
It expects these alongside it:
- `@grafloria/element` ^0.4.9
- `@grafloria/engine` ^0.3.0
- `@grafloria/renderer` ^0.4.0
## Also exported from here
These names are documented with the package that defines them, and can be imported from this one too.
- From [@grafloria/element](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-element-overview): `bindDashboardGrid`, `BUILT_IN_WIDGET_KINDS`, `dashboard`, `DashboardGridHandle`, `DashboardGridOptions`, `DashboardHandle`, `DashboardOptions`, `DashboardSnapshot`, `DashboardSpec`, `DashboardViewSpec`, `DashboardWidgetSpec`, `defaultWidgetRenderer` and 7 more
# @grafloria/renderer
SVG renderer for the Grafloria diagram engine — interaction, theming, accessibility, and SVG/PNG/PDF vector export
## Install
```bash
npm install @grafloria/renderer @grafloria/engine
```
It expects these alongside it:
- `@grafloria/engine` ^0.3.18
## What it exports
- [Core](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-core): 17 exports, including `cancelFrame`, `CanvasRect`, `getDocument`, `hasDocument`
- [A11y](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-a11y): 51 exports, including `Adjacency`, `analyseTopology`, `boundsOfPoints`, `buildAdjacency`
- [Canvas](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-canvas): 79 exports, including `ALWAYS_SAFE_MODE`, `applyMatrix`, `arcToCubics`, `BackendMode`
- [Comments](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-comments): 9 exports, including `CommentOverlayController`, `CommentOverlayOptions`, `CommentPanelOptions`, `CommentPanelView`
- [Export](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-export): 106 exports, including `Artifact`, `AssetFetcher`, `AVG_CHAR_WIDTH_EM`, `base64ToBytes`
- [Ext](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext): 115 exports, including `activeRegistryScope`, `AnchorContext`, `AnchorFn`, `AnchorResult`
- [Ext — Components](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-ext-components): 15 exports, including `attachCanvasPlugins`, `BACKGROUND_LAYER_CLASS`, `BackgroundHandle`, `BackgroundOptions`
- [Instance](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-instance): 49 exports, including `applyEdges`, `applyEdgeSpec`, `applyGroups`, `applyNodes`
- [Interaction](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-interaction): 85 exports, including `AddWaypointResult`, `AlignmentGuide`, `angleAt`, `Announcement`
- [Lazy](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-lazy): 13 exports, including `DeferredQuery`, `EntityKind`, `FreezeQuery`, `HostCullMode`
- [Perf](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-perf): 8 exports, including `EMPTY_SNAPSHOT`, `formatSnapshot`, `GovernorOptions`, `GovernorState`
- [Presence](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-presence): 12 exports, including `actorColor`, `actorInitials`, `bindPresence`, `BindPresenceOptions`
- [Presentation](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-presentation): 11 exports, including `FollowOptions`, `followPresenter`, `InMemoryViewportChannel`, `isDocumentLocked`
- [Services](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-services): 25 exports, including `AnimationConfig`, `AnimationEventData`, `AnimationLifecycleEvent`, `AnimationLifecycleManager`
- [Svg](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-svg): 198 exports, including `applySpread`, `ArrowRenderer`, `assignSpreadLanes`, `autoSizeDiagram`
- [Themes](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-themes): 83 exports, including `assertThemeContrast`, `auditThemeContrast`, `BASE_STYLE_RULES`, `BRIDGEABLE_TOKENS`
- [Types](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-types): 50 exports, including `BooleanPropertyDefinition`, `BoundingBox`, `CanvasRendererConfig`, `ColorPalette`
- [Utils](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-utils): 37 exports, including `AnimationColorSchemes`, `AnimationDescriptor`, `AnimationPresets`, `AnimationPriority`
- [Vnode](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-renderer-vnode): 17 exports, including `camelToKebab`, `ContainerIdGenerator`, `createDomElement`, `createForeignObject`
## Also exported from here
These names are documented with the package that defines them, and can be imported from this one too.
- From [@grafloria/engine](https://grafloria.atloria.app/p/grafloria-h7YM7amryF/developer/grafloria-engine-overview): `NodeModel`, `PortLayoutArgs`, `PortLayoutSpec`, `PortModel`
# Core
Import these from `@grafloria/renderer`.
## Functions
### `cancelFrame`
Cancel a handle from {@link requestFrame}, whichever mechanism produced it.
```ts
function cancelFrame(handle: number): void
```
### `getDocument`
The ambient `Document`, or `undefined` on the server. Never throws.
```ts
function getDocument(): Document | undefined
```
### `hasDocument`
True when a real DOM `document` is reachable (browser, jsdom, happy-dom).
```ts
function hasDocument(): boolean
```
### `isBrowser`
True in a browser-like environment: a `window` AND a `document`.
```ts
function isBrowser(): boolean
```
### `now`
Monotonic-ish clock that also works where `performance` is absent.
```ts
function now(): number
```
### `renderToStaticSVG`
```ts
function renderToStaticSVG(options: StaticRenderOptions = {}): StaticRenderResult
```
### `requestFrame`
`requestAnimationFrame`, or a `setTimeout(…, 16)` shim where it is missing
(Node, older jsdom). Returns an opaque handle usable with {@link cancelFrame}.
```ts
function requestFrame(callback: (time: number) => void): number
```
## Classes
### `ViewportController`
ViewportController — the framework-agnostic camera.
This is the piece every framework wrapper otherwise re-implements (and gets
subtly wrong): screen↔world conversion, zoom clamping, pan accumulation, and
the `viewBox` convention that the SVG renderer and the hit-tester MUST agree
on. Owning it here means a React/Vue/web-component host inherits pixel-exact
hit-testing for free.
Like {@link InteractionController } it answers **"what is the camera now?"** and
never **"who should re-render?"** — hosts subscribe via {@link onChange} and
translate that into their own render trigger (`markForCheck`, `setState`, …). It has zero framework imports, zero engine imports, and no DOM dependency:
callers hand it a plain {@link CanvasRect}, not an element.
## The coordinate contract
`viewport.x/y` are WORLD coordinates. `viewport.width/height` are the canvas's
**CSS-pixel** size — NOT a world-space span. The world span actually shown is
derived by dividing by `zoom`, which is exactly what {@link getViewBox} does:
```text
center = (viewport.x + w/2, viewport.y + h/2) // zoom is centre-preserving
viewBox.w/h = (w / zoom, h / zoom) // higher zoom ⇒ less world visible
viewBox.x/y = center − viewBox.w/h / 2
```
This is the identical formula `SVGRenderer.render()` applies to the viewport
it is handed (`libs/renderer/src/svg/svg-renderer.ts`, "Apply zoom to viewBox"),
and the one {@link clientToWorld} inverts. Because both sides derive from the
same {@link getViewBox}, screen→world round-trips exactly at any zoom — see
the round-trip tests in `viewport-controller.spec.ts`.
⚠️ Feed {@link getRenderViewport} — not a pre-scaled rectangle — to
`IRenderer.render(viewport, zoom)`. Dividing width/height by `zoom` *before*
calling `render()` makes the renderer divide by `zoom` a second time, applying
zoom quadratically and desynchronising the picture from the hit-tester at any
zoom ≠ 1. (`DiagramCanvasComponent.calculateActualViewport()` currently does
exactly that; the fix belongs to the zoom card and is why this convention now
lives in one place.)
```ts
class ViewportController
```
**Methods**
- `constructor(options: ViewportControllerOptions = {})`
- `getViewport(): Rectangle`
- `getZoom(): number`
- `getState(): ViewportState`
- `setViewport(viewport: Rectangle): void` — Replace the camera rectangle wholesale.
- `setCanvasSize(width: number, height: number): void` — Track the canvas element's pixel size. Call on mount and on resize: the
width/height of the camera rect must stay equal to the canvas's CSS-pixel
size for {@link clientToWorld} to be the true inverse of the rendered
`viewBox` (see the coordinate contract).
- `syncCanvasSize(rect: CanvasRect): void` — Convenience form of {@link setCanvasSize} taking a `getBoundingClientRect()`.
- `clampZoom(zoom: number): number` — Clamp to `[minZoom, maxZoom]`. Non-finite input falls back to the current zoom.
- `setZoom(zoom: number): number` — Set zoom (centre-preserving), clamped. Returns the zoom actually applied.
- `zoomBy(delta: number): number` — Additive zoom step, clamped — the convention the Angular canvas's wheel
handler uses (`zoom + delta`, not `zoom * factor`). Returns the applied zoom.
- `zoomByWheel(deltaY: number): number` — Apply one wheel notch. Mirrors `DiagramCanvasComponent.onWheel`: scrolling
DOWN (`deltaY > 0`) zooms OUT by `zoomSensitivity`, scrolling up zooms in.
- `zoomAtPoint(zoom: number, clientX: number, clientY: number, rect: CanvasRect): number` — Cursor-anchored zoom: change zoom while keeping the world point currently
under `(clientX, clientY)` pinned to that same screen pixel. This is the
standard "zoom towards the pointer" behaviour; the plain {@link setZoom} /
{@link zoomByWheel} pair is centre-anchored instead.
Returns the zoom actually applied (clamped).
- `pan(dx: number, dy: number): void` — Translate the camera by a WORLD-space delta.
- `panByScreenDelta(dxPx: number, dyPx: number): void` — Translate the camera by a SCREEN-space (pixel) drag delta, converting to
world units by dividing by zoom.
Sign convention matches the canvas's middle-drag handler: pass
`(lastClientX - clientX, lastClientY - clientY)`, i.e. dragging the pointer
RIGHT moves the camera LEFT, so the content appears to follow the cursor.
- `getViewBox(): Rectangle` — The world-space rectangle actually visible — centre-preserving zoom applied
to the camera rect. Identical to the `viewBox` `SVGRenderer` emits, and the
basis of {@link clientToWorld}.
- `getViewBoxString(): string` — The `viewBox` attribute string: `"x y width height"`.
- `getRenderViewport(): Rectangle` — The rectangle to hand to `IRenderer.render(viewport, zoom)` alongside
{@link getZoom}. The renderer applies the zoom itself, so this is the raw
camera rect — do NOT pre-divide it by zoom (see the class docs).
- `getHtmlLayerTransform(): string` — CSS transform that keeps an HTML overlay layer registered with the SVG
layer in the hybrid renderer: `translate(...) scale(zoom)`.
MUST be driven off the same {@link getViewBox} the SVG viewBox and
{@link worldToClient} use — NOT the raw `viewport.x/y`. Since the camera
rect's width/height became CANVAS PIXELS (see setCanvasSize), the visible
world box is the pixel rect expanded around its centre by 1/zoom; the SVG
renderer applies exactly that expansion (svg-renderer.ts `viewBoxX =
centerX - width/zoom/2`). Using the raw `viewport.x` here omitted the
`width*(1-zoom)/2` centring term, so the HTML custom-node layer drifted
from the SVG at any zoom != 1 — invisible until a custom-node dashboard was
framed with fitToBounds. Routing through getViewBox() makes a host at world
W land at the identical pixel worldToClient(W) reports. Identical at zoom 1.
- `clientToWorld(clientX: number, clientY: number, rect: CanvasRect): ViewportPoint` — Convert a client/screen point (e.g. `event.clientX/Y`) into world space. Exact inverse of {@link worldToClient} at any zoom.
- `worldToClient(worldX: number, worldY: number, rect: CanvasRect): ViewportPoint` — Convert a world point into client/screen coordinates — for positioning
overlays, toolbars and tooltips over the canvas. Exact inverse of
{@link clientToWorld}.
- `fitToBounds(bounds: Rectangle, padding = 40, options?: { maxZoom?: number }): number` — Frame `bounds` (a world-space content rectangle): pick the largest clamped
zoom at which it fits inside the canvas with `padding` CSS pixels of margin
on every side, and centre it. A zero-area canvas or bounds is a no-op.
Returns the zoom actually applied.
- `onChange(listener: ViewportChangeListener): Unsubscribe` — Subscribe to camera changes. Returns an unsubscribe function.
- `dispose(): void` — Drop all subscribers.
## Interfaces
### `CanvasRect`
The subset of `DOMRect` the camera actually needs. Any `getBoundingClientRect()`
result satisfies it; tests can pass a plain object. Keeping it structural is
what lets this class run in Node with no DOM.
```ts
interface CanvasRect
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `left` | `number` | | |
| `top` | `number` | | |
| `width` | `number` | | |
| `height` | `number` | | |
### `HydrationSnapshot`
Everything the client needs to reproduce this render exactly.
```ts
interface HydrationSnapshot
```
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `instanceId` | `string` | | |
| `width` | `number` | | |
| `height` | `number` | | |
| `zoom` | `number` | | |
| `viewport` | `{ x: number; y: number }` | | |
### `StaticRenderOptions`
The deterministic SERVER path.
`renderToStaticSVG()` runs the real `DiagramEngine` + the real `SVGRenderer`
in Node, with no DOM anywhere, and returns:
- `html` — the exact markup `createDiagram()` would have mounted,
- `svg` — just the `