# 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 canvas shows the Ingest and Publish boxes connected by one edge.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/d91de328beb165a2057c016d2af6de7d.png) 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. ![The canvas shows Archive added to the right of Publish with a second edge.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/65677bd94ceb34e23b57de8248eb1355.png) 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. ![The custom-element canvas shows Extract and Load as connected boxes.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/f38a972307e28cb462728d84295efeec.png) ## 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 browser result of the mounted React flow.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/b0c9167e4e826f3330f14d04febd43ca.png) 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" ``` ![Two connected custom job cards appear in the sized canvas with the canvas tools visible.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/9d715c7a5940f5147d08eee9fe3e8eaf.png) 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 Qwik flow displays the Start and Finish boxes connected by an edge.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/ec9e48d8d2bc2c832b15457a85b8ba0e.png) 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}
); } export default function DiagramPage() { const [instance, setInstance] = useState(null); return (

{instance ? 'Diagram ready' : 'Starting diagram'}

); } ``` 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 ``` ![The Vue canvas shows the Start and Finish nodes with Undo and Redo buttons below it.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/7f9723e9d5b02c338d676a0cae4a2833.png) `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$(() => (
instance.getEngine().layout('dagre', { nodeSpacing: 40, rankSpacing: 90 }).then(() => { instance.renderNow(); instance.fitView(50); }))} />
)); ``` ```tsx title="React" import { GrafloriaFlow } from '@grafloria/react'; import type { DiagramInstance, EdgeSpec, NodeSpec } from '@grafloria/react'; 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 function AutoLayout() { const onInit = async (instance: DiagramInstance): Promise => { await instance.getEngine().layout('dagre', { nodeSpacing: 40, rankSpacing: 90 }); instance.renderNow(); instance.fitView(50); }; return
; } ``` ```vue title="Vue" ``` ::: ![The JavaScript canvas shows the four pipeline nodes separated and fitted within the container.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/8bb0dc98340c89772ca543a25a072bfc.png) ![The Angular canvas shows the four pipeline nodes separated and fitted within the container.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/1fa09e1e3c66ba7e35a68392f244916f.png) ![The Qwik canvas shows the four pipeline nodes separated and fitted within the container.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/8bb0dc98340c89772ca543a25a072bfc.png) ![The React canvas shows the four pipeline nodes separated and fitted within the container.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/8bb0dc98340c89772ca543a25a072bfc.png) ![The Vue canvas shows the four pipeline nodes separated and fitted within the container.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/8bb0dc98340c89772ca543a25a072bfc.png) 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. ![The pipeline nodes are spread across the canvas and the selected layout result is visible.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/c23f1a8b87e7f610fefe3cda0d4d916e.png) 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
{id === 'build' ? 'Build' : 'Deploy'}
node: {id}
; } const nodes = [ { id: 'build', type: 'card', custom: true, position: { x: 80, y: 100 }, size: { width: 220, height: 100 } }, { id: 'deploy', type: 'card', custom: true, position: { x: 400, y: 100 }, size: { width: 220, height: 100 } }, ]; const edges = [{ id: 'build-to-deploy', source: 'build', target: 'deploy' }]; export function CustomNodes() { return
; } ``` ```vue title="Vue" ``` ```ts title="Angular" import { Component } from '@angular/core'; import { DiagramCanvasComponent, GrafloriaNodeDefDirective } from '@grafloria/angular'; @Component({ standalone: true, imports: [DiagramCanvasComponent, GrafloriaNodeDefDirective], template: `
{{ data['title'] }}
application card
` }) export class CustomNodesComponent { nodes = [ { id: 'build', type: 'card', position: { x: 80, y: 100 }, size: { width: 220, height: 100 }, data: { title: 'Build' } }, { id: 'deploy', type: 'card', position: { x: 400, y: 100 }, size: { width: 220, height: 100 }, data: { title: 'Deploy' } }, ]; edges = [{ id: 'build-to-deploy', source: 'build', target: 'deploy' }]; } ``` ```tsx title="Qwik" import { component$ } from '@builder.io/qwik'; import { GrafloriaFlow, type NodeProps, type NodeTypes } from '@grafloria/qwik'; const Card = component$(({ id, selected }: NodeProps) => (
{id === 'build' ? 'Build' : 'Deploy'}
node: {id}
)); const nodeTypes: NodeTypes = { card: Card }; const nodes = [ { id: 'build', type: 'card', position: { x: 80, y: 100 }, size: { width: 220, height: 100 } }, { id: 'deploy', type: 'card', position: { x: 400, y: 100 }, size: { width: 220, height: 100 } }, ]; const edges = [{ id: 'build-to-deploy', source: 'build', target: 'deploy' }]; export default component$(() =>
); ``` ::: ![The custom card and its connected edge rendered inside the sized diagram host.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/5c0e5d12f019b51f9dd54e5848dd1041.png) 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 (
{ instance.renderNow(); })} />
); }); ``` ```tsx title="React" import { useEffect } from 'react'; import { GrafloriaFlow, type DiagramInstance } from '@grafloria/react'; 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 function ConnectionValidation() { useEffect(() => { 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; }); return () => { disposeValidator(); clearConnectionValidators(); }; }, []); const onInit = (instance: DiagramInstance): void => { instance.renderNow(); }; return
; } ``` ```vue title="Vue" ``` ::: 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$(() => (
)); ``` ```tsx title="React" import { GrafloriaFlow } from '@grafloria/react'; 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 function RoutedEdges() { return
; } ``` ```vue title="Vue" ``` ::: 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). ![A right-angle wire bends around the labelled obstacle between A and B.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/b8fd1e509c84ce1a45108ddaeff99ebf.png) ## 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). ![A selected wire runs from A to C with its endpoint handle on C.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/94174021318dd870cd6649a9c600d476.png) ## 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). ![A selected edge has a waypoint handle below its straight path between A and B.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/b7bdbbd08c201944b4538111f3aba91e.png) 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 mounted diagram shows the nodes inside the fitted group frame.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/d51203a9e3a8505f443d3635b85eed00.png) 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(); })} />
); ``` ```vue title="Vue" ``` ```tsx title="React" import { GrafloriaFlow } from '@grafloria/react'; import type { DiagramInstance } from '@grafloria/react'; 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 function Groups() { const onInit = (i: DiagramInstance) => { void (async () => { 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(); })(); }; return
; } ``` ::: ## 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); ``` ![The mounted diagram shows the service group after the collapse-and-expand sequence completes.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/df7dfb7ff1c5c2a7345d8bc7a67b2398.png) 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
{ api.current = instance; }} />
; } ``` ```vue title="Vue" ``` ```tsx title="Qwik" import { component$, $, noSerialize, useSignal, type NoSerialize } from '@builder.io/qwik'; import { GrafloriaFlow, type DiagramInstance } from '@grafloria/qwik'; 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' }]; export default component$(() => { const api = useSignal>(); const save = $(() => { if (api.value) localStorage.setItem('diagram', JSON.stringify(new DiagramSerializer().serialize(api.value.getModel()))); }); return
{ api.value = noSerialize(instance); })} />
; }); ``` ::: 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: `
`, }) export class MermaidTextComponent implements AfterViewInit { canvas = viewChild.required(DiagramCanvasComponent); text = ''; nodes = [ { id: 'start', position: { x: 80, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Start' } }, { id: 'work', position: { x: 320, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Work' } }, { id: 'done', position: { x: 560, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Done' } }, ]; edges = [{ id: 'e1', source: 'start', target: 'work' }, { id: 'e2', source: 'work', target: 'done' }]; exportText(): void { this.text = this.canvas().exportText(); } loadText(): void { this.canvas().loadText(this.text); } ngAfterViewInit(): void { this.exportText(); } } ``` The canvas renders **Start → Work → Done**. **Export** fills the textarea; edit it and choose **Load** to reconcile the edit into the mounted canvas. ### Qwik ```tsx import { component$, $, noSerialize, useSignal, type NoSerialize } from '@builder.io/qwik'; import { GrafloriaFlow, type DiagramInstance, type NodeSpec, type EdgeSpec } from '@grafloria/qwik'; const nodes: NodeSpec[] = [ { id: 'start', position: { x: 80, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Start' } }, { id: 'work', position: { x: 320, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Work' } }, { id: 'done', position: { x: 560, y: 60 }, size: { width: 140, height: 60 }, data: { label: 'Done' } }, ]; const edges: EdgeSpec[] = [{ id: 'e1', source: 'start', target: 'work' }, { id: 'e2', source: 'work', target: 'done' }]; export default component$(() => { const instance = useSignal>(); const text = useSignal(''); return
{ instance.value = noSerialize(api); text.value = api.exportText(); })} />