Use the custom element when your integration speaks HTML and DOM events. Use render when your application needs the live instance immediately, kit specs or the full options surface. Both doors use the same headless model and return access to the same DiagramInstance.
This page starts from the Vite vanilla TypeScript project in the JavaScript quick start, including its stylesheet changes. The quick start already installs the packages used here; in an existing project, install them together:
bashnpm install @grafloria/element @grafloria/engine @grafloria/renderer
The examples below are alternative versions of src/main.ts. Keep the starter's index.html, configuration and stylesheet import.
Choose the input surface
| Surface | Input | Live handle | Cleanup |
|---|---|---|---|
<grafloria-flow> attributes | JSON arrays for data; strings for options | el.diagram | Disconnecting the element disposes the diagram |
| Element properties | Real node and edge spec arrays | el.diagram | Same element lifecycle |
render(spec, target, options) | Spec object or its JSON string, including kit specs | Return value | Call dispose() when your view closes |
Importing @grafloria/element registers <grafloria-flow>. GrafloriaFlowElement gives you a runtime check and typed access to its nodes, edges, diagram and fitView() members. Options such as theme are attributes, not JavaScript property setters.
Mount attributes and update properties
- Use JSON attributes for a small initial graph. Put a
<template data-node-type="card">inside the element to paint custom content. Itsdata-fielddescendants receive text from node data;data-field="id"receives the node id. - Pass typed arrays to
el.nodesandel.edgeswhen application code changes the graph. The example adds a third card and a second connection without serializing the new data. - Listen on the parent for bubbling DOM events. Use the event payload types from
DiagramEventHandler; the payload contains live models, not the input specs.
The typed arrays below use NodeSpec and EdgeSpec.
tsimport './style.css';
import { GrafloriaFlowElement } from '@grafloria/element';
import type { DiagramEventHandler, EdgeSpec, NodeSpec } from '@grafloria/renderer';
const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = `
<h1>Element integration</h1>
<button id="add">Load three steps</button>
<button id="frame">Frame content</button>
<button id="measure">Measure SVG</button>
<button id="close">Close view</button>
<p id="status">Waiting for the diagram</p>
<grafloria-flow style="height:400px;width:100%" theme="dark"
highlight-connected="trace"
nodes='[
{"id":"a","type":"card","custom":true,"position":{"x":60,"y":80},"size":{"width":180,"height":80},"data":{"title":"Ingest"}},
{"id":"b","type":"card","custom":true,"position":{"x":340,"y":80},"size":{"width":180,"height":80},"data":{"title":"Publish"}}
]'
edges='[{"id":"ab","source":"a","target":"b"}]'>
<template data-node-type="card">
<div style="height:100%;box-sizing:border-box;padding:20px;border:1px solid #94a3b8;border-radius:8px;background:#1e293b;color:white">
<strong data-field="title"></strong>
</div>
</template>
</grafloria-flow>
`;
const el = app.querySelector('grafloria-flow');
if (!(el instanceof GrafloriaFlowElement)) throw new Error('Missing flow element');
const status = app.querySelector<HTMLParagraphElement>('#status');
if (!status) throw new Error('Missing status');
const listeners = new AbortController();
app.addEventListener('grafloria-ready', () => {
const diagram = el.diagram;
if (!diagram) return;
const model = diagram.getModel();
const engine = diagram.getEngine();
status.textContent = `${model.getNodes().length} nodes; engine attached: ${engine.getDiagram() === model}`;
}, { signal: listeners.signal });
app.addEventListener('grafloria-nodes-change', (event) => {
const payload = (event as CustomEvent<Parameters<DiagramEventHandler<'nodes:change'>>[0]>).detail;
console.info('Current live nodes', payload.nodes);
}, { signal: listeners.signal });
app.addEventListener('grafloria-connect', (event) => {
const payload = (event as CustomEvent<Parameters<DiagramEventHandler<'connect'>>[0]>).detail;
console.info('Connected link', payload.link);
}, { signal: listeners.signal });
app.addEventListener('grafloria-selection-change', (event) => {
const payload = (event as CustomEvent<Parameters<DiagramEventHandler<'selection:change'>>[0]>).detail;
status.textContent = `${payload.nodes.length} nodes and ${payload.edges.length} edges selected`;
}, { signal: listeners.signal });
app.querySelector<HTMLButtonElement>('#add')!.addEventListener('click', () => {
const nodes: NodeSpec[] = [
{ id: 'a', type: 'card', custom: true, position: { x: 60, y: 80 },
size: { width: 180, height: 80 }, data: { title: 'Ingest' } },
{ id: 'b', type: 'card', custom: true, position: { x: 340, y: 80 },
size: { width: 180, height: 80 }, data: { title: 'Publish' } },
{ id: 'c', type: 'card', custom: true, position: { x: 340, y: 230 },
size: { width: 180, height: 80 }, data: { title: 'Archive' } },
];
const edges: EdgeSpec[] = [
{ id: 'ab', source: 'a', target: 'b' },
{ id: 'bc', source: 'b', target: 'c' },
];
el.nodes = nodes;
el.edges = edges;
}, { signal: listeners.signal });
app.querySelector<HTMLButtonElement>('#frame')!.addEventListener('click', () => {
el.fitView(40);
}, { signal: listeners.signal });
app.querySelector<HTMLButtonElement>('#measure')!.addEventListener('click', () => {
// Flush a queued paint because this handler measures the DOM immediately.
el.diagram?.renderNow();
const svg = el.querySelector('svg');
if (svg) status.textContent = `SVG width: ${svg.getBoundingClientRect().width.toFixed(0)}px`;
}, { signal: listeners.signal });
app.querySelector<HTMLButtonElement>('#close')!.addEventListener('click', () => {
listeners.abort();
el.remove();
status.textContent = 'View closed';
});
On first load, you see Ingest and Publish as HTML cards joined by an edge. Load three steps adds Archive below Publish. Frame content changes the camera to include the content; it is an explicit user action, not a required repaint after updating data. The selection text follows library events rather than button handlers.
These property writes load or reconcile data; they do not create undoable application edits. For inspector edits, use commands from your UI. For in-place changes to custom card data, see Compute connected data.
Configure the element
Set mount-time attributes before inserting the element into the document. Live attributes take effect when their value changes after mount.
| Option | Type | Default | What it does |
|---|---|---|---|
nodes, edges | JSON arrays, or spec-array properties | Empty arrays | Live: reconcile data into the instance |
theme | "light" or "dark" | "light" | Live: swap the theme; unrecognized strings fall back to light |
fit-view | Presence boolean | Absent | Fit on mount; adding it later frames content |
readonly | Presence boolean | Absent | Mount-time: prevent mutating gestures while retaining navigation |
zoom | Numeric string | 1 | Live: set the camera zoom, clamped to its range |
min-zoom | Numeric string | 0.1 | Mount-time: lower zoom clamp |
max-zoom | Numeric string | 3 | Mount-time: upper zoom clamp |
pan | Opt-out string | Enabled | Mount-time: only the literal "false" disables panning |
wheel-zoom | Opt-out string | Enabled | Mount-time: only the literal "false" disables wheel zoom |
highlight-connected | Presence, string or numeric string | Off | Live: bring selected nodes' connected lines forward |
For highlight-connected, absence or "false" turns highlighting off; presence with an empty value turns it on. "trace" follows every path in and out. A finite number at least 1 sets the traversal depth. Other values turn highlighting on. The parser trims and lowercases this value.
Presence booleans do not interpret "false": readonly="false" still enables read-only mode, and fit-view="false" still requests fitting. For live read-only changes, use el.diagram?.setReadonly(value) rather than changing the mount-time attribute. For wheel navigation, hold Ctrl or ⌘ to zoom; an unmodified wheel pans.
Malformed JSON attributes log a warning and fall back to an empty array. For incremental reconciliation and replacement imports, see Edit nodes from your UI. For host sizing, see Nest containers and lanes.
Subscribe to DOM events
All eight forwarded events bubble and are composed, so a listener on a parent or document receives them across shadow boundaries. Filter by the originating element when a parent contains multiple diagrams.
| Event | event.detail |
|---|---|
grafloria-ready | { diagram } |
grafloria-nodes-change | { nodes }, live node models |
grafloria-edges-change | { edges }, live link models |
grafloria-selection-change | { nodes, edges } |
grafloria-connect | { link } |
grafloria-node-click | { node, world: { x, y } } |
grafloria-edge-click | { edge, world: { x, y } } |
grafloria-viewport-change | { viewport, zoom } |
The first example listens before the queued ready event runs. diagram is null before mounting and after disconnecting. Removing the element disposes its diagram and removes the generated canvas; reconnecting mounts a fresh instance. Remove your own parent listeners too, as the example's close handler does.
For instance-only events such as reconnect and node:doubleclick, subscribe through el.diagram.on(); see Instance and lifecycle.
Rename the element tag
Register a subclass under your application's tag name, then mount it with the same attributes and properties. This entry file draws a node inside <acme-flow>:
tsimport './style.css';
import { GrafloriaFlowElement } from '@grafloria/element';
if (!customElements.get('acme-flow')) {
customElements.define('acme-flow', class extends GrafloriaFlowElement {});
}
const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = `
<acme-flow style="height:400px;width:100%"
nodes='[{"id":"a","position":{"x":80,"y":80},"data":{"label":"Acme step"}}]'>
</acme-flow>
`;
defineGrafloriaFlow registers the default tag when the package imports. It returns without registering when customElements is unavailable, and returns if the requested tag already exists. Grafloria exposes it as define; use the subclass registration above for an additional browser tag.
Mount with render and own custom-content teardown
Use render() for per-instance custom rendering and explicit disposal. Its RenderOptions type accepts the renderer's options except nodes and edges; those belong in the spec. Here, the shipped DARK_THEME supplies the theme, and the hook pair installs and releases each card's button listener.
tsimport './style.css';
import { render } from '@grafloria/element';
import { DARK_THEME } from '@grafloria/renderer';
import type { EdgeSpec, NodeSpec, RenderOptions } from '@grafloria/element';
const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = `
<h1>Render integration</h1>
<button id="close">Close view</button>
<p id="status">Choose a card</p>
<div id="canvas" style="height:400px;width:100%"></div>
`;
const status = app.querySelector<HTMLParagraphElement>('#status');
if (!status) throw new Error('Missing status');
const nodes: NodeSpec[] = [
{ id: 'a', type: 'action', custom: true, position: { x: 60, y: 80 },
size: { width: 180, height: 80 }, data: { title: 'Ingest' } },
{ id: 'b', type: 'action', custom: true, position: { x: 340, y: 80 },
size: { width: 180, height: 80 }, data: { title: 'Publish' } },
];
const edges: EdgeSpec[] = [{ id: 'ab', source: 'a', target: 'b' }];
const cleanups = new Map<string, () => void>();
const options: RenderOptions = {
theme: DARK_THEME,
fitView: true,
renderCustomNode(node, host) {
const button = document.createElement('button');
button.textContent = String(node.data['title']);
button.style.cssText = 'width:100%;height:100%;box-sizing:border-box';
const choose = () => { status.textContent = `Chosen: ${node.id}`; };
button.addEventListener('click', choose);
cleanups.set(node.id, () => button.removeEventListener('click', choose));
host.append(button);
},
removeCustomNode(nodeId) {
cleanups.get(nodeId)?.();
cleanups.delete(nodeId);
},
};
const diagram = render({ nodes, edges }, '#canvas', options);
const unsubscribe = diagram.on('node:doubleclick', ({ node }) => {
status.textContent = `Double-clicked: ${node.id}`;
});
app.querySelector<HTMLButtonElement>('#close')!.addEventListener('click', () => {
unsubscribe();
diagram.dispose();
status.textContent = 'View closed';
}, { once: true });
You see two connected HTML buttons, framed on a dark canvas. Each button writes its node id into the status text. Close view releases the subscription and disposes the mounted diagram.
The engine positions and sizes each HTML host; your renderer paints its inside. An explicit renderCustomNode option takes precedence over a spec's painter, which takes precedence over the global node-type registry. The element instead checks the registry before its nested templates. For registration and template contracts, see Customize rendering contracts.
Return a promise from renderCustomNode when painting is asynchronous, so export() can wait for that content. Use removeCustomNode to release resources when a node host is removed, including during view disposal.
The target argument accepts an HTMLElement or CSS selector. An unmatched selector throws. The spec accepts an object or its JSON string, not Mermaid text; use Import Mermaid and draw.io for text input. Kit specs mount through the same call and their finalization runs automatically; see Build a dashboard for a complete kit example.
Live demo and related guides
Try the live Mermaid viewer to see a JavaScript-mounted instance receiving updated input, then follow Import Mermaid and draw.io for that loading task.
- Instance and lifecycle covers instance subscriptions and view ownership.
- Customize rendering contracts covers registered painters and data-driven templates.
- Theme a diagram covers system color mode and host design tokens beyond the element's two theme strings.
Was this page helpful?