Use stencils when your editor needs reusable shape masters, a searchable palette, and properties that follow the selected shape. The example below opens with an approval shape selected, its editable fields on the right, and notation masters on the left. Palette placement and property edits share the diagram's command history.
Start in the project from your JavaScript, React, Vue, Angular, or Qwik quick start. Keep its entry point, configuration, stylesheet imports, and mounting wrapper. Add the files below; render the new component from your existing app or Qwik route.
The quick starts install the packages used here. If your project lacks them, add them with the command matching its package convention:
bash# JavaScript
npm install @grafloria/element @grafloria/engine @grafloria/renderer
# React
npm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer
# Vue
npm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer
# Angular
npm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer
# Qwik starter: these packages belong in devDependencies
npm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer
1. Define a reusable master
An engine NodeTemplate describes the structure, defaults, and schema of a shape. A Stencil groups masters into a named palette section. Keep the master id stable: the stamped node records that id, and the properties panel uses it to find the schema.
Add this shared module at src/approval.ts in any of the five projects. It follows the Template Builder's separation of meta, structure, dataSchema, and defaultData. The approval master adds text, numeric, boolean, and enumerated fields rather than a custom form implementation.
tsimport type { NodeTemplate, Stencil } from '@grafloria/engine';
export const approval: NodeTemplate = {
id: 'team-approval',
version: '1.0.0',
meta: {
name: 'Approval',
category: 'workflow',
description: 'An approval with an owner and spending limit',
tags: ['approval', 'review', 'team'],
},
structure: {
type: 'team-approval',
size: { width: 180, height: 100 },
shape: { type: 'rect', cornerRadius: 12, fill: '#eef2ff', stroke: '#4f46e5' },
},
defaultData: { label: 'Approval', owner: 'Finance', limit: 500, required: true, status: 'pending' },
dataSchema: {
type: 'object',
properties: {
owner: { type: 'string', title: 'Owner' },
limit: { type: 'number', title: 'Spending limit' },
required: { type: 'boolean', title: 'Approval required' },
status: { type: 'string', title: 'Status', enum: ['pending', 'approved', 'rejected'] },
},
},
};
export const teamStencil: Stencil = {
id: 'team',
name: 'Team',
description: 'Approval shapes for this editor',
masters: [approval],
};
structure supplies the node's type, numeric dimensions, geometry, and optional ports or children. defaultData seeds values; data supplied to the factory overrides those defaults. meta.tags makes the master discoverable in the palette. For a first preview, keep the structure small; the Template Builder documentation recommends shallow HTML and few ports when developing richer templates.
2. Register masters and connect the palette to the properties panel
Use the mounted DiagramInstance, not a second engine. Its engine owns the TemplateRegistry; its model owns the stamped nodes.
registerStencils makes the masters available for stamping. listStencils supplies the shipped Flowchart, BPMN, UML, and ERD sections. NodeFactory creates the initial diagram content. Then bindStencilPalette handles search and placement, while bindShapeDataPanel follows selection and commits field edits through commands.
Add this module alongside approval.ts. It seeds two real shapes before binding the panel, so the first view already contains editable content. Its returned function removes the palette and panel when your app removes the editor; the framework binding owns the canvas lifecycle.
tsimport { bindShapeDataPanel, bindStencilPalette } from '@grafloria/element';
import { listStencils, NodeFactory, registerStencils } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
import { approval, teamStencil } from './approval';
export function connectEditor(
api: DiagramInstance,
rail: HTMLElement,
panelHost: HTMLElement,
canvas: HTMLElement,
): () => void {
const registry = api.getEngine().templateRegistry;
const stencils = [teamStencil, ...listStencils()];
registerStencils(registry, stencils);
const model = api.getModel();
const factory = new NodeFactory(registry, model);
const review = factory.createFromTemplate(approval.id, { owner: 'Finance' }, { x: 80, y: 100 });
factory.createFromTemplate('flowchart-decision', { label: 'Approved?' }, { x: 340, y: 100 });
model.selectNode(review);
const palette = bindStencilPalette(api, { palette: rail, canvas }, { stencils });
const panel = bindShapeDataPanel(api, panelHost);
const stopPanelUpdates = model.on('node:changed', () => {
if (model.getSelectedNodes().length) panel.refresh();
});
return () => {
stopPanelUpdates();
panel.destroy();
palette.destroy();
};
}
The factory's position is the shape's top-left corner. Palette placement instead centers the master on the drop point. palette.place(masterId, worldPoint) provides the same undoable placement without a drag and resolves to a node id, or null when the master is absent. palette.setSearch(query) filters the list like its search input.
Mount the editor in your framework
Use the following framework-specific file with the two shared modules. Each mounts its own binding, receives the live instance through that binding's ready callback, and tears down the attached controls on unmount. The React, Vue, and Qwik examples use uncontrolled defaultNodes: the instance owns subsequent palette additions.
Add palette and property-panel hosts beside the canvas and pass them with the live instance to connectEditor(); see Group and collapse objects for the shared mounting APIs and typed specs.
ts// src/main.ts: retain the starter's stylesheet import above these additions.
import { render } from '@grafloria/element';
import type { NodeSpec } from '@grafloria/renderer';
import { connectEditor } from './stencils';
const host = document.getElementById('app');
if (!host) throw new Error('Missing #app');
const editor = document.createElement('section');
editor.style.cssText = 'display:grid;grid-template-columns:200px minmax(0,1fr) 240px;height:500px';
const rail = document.createElement('aside');
const canvas = document.createElement('div');
canvas.style.cssText = 'min-width:0;position:relative';
const panel = document.createElement('aside');
editor.append(rail, canvas, panel);
host.append(editor);
const nodes: NodeSpec[] = [
{ id: 'instructions', label: 'Drag a master here', position: { x: 80, y: 280 } },
];
const api = render({ nodes }, canvas);
const disconnect = connectEditor(api, rail, panel, canvas);
const close = document.createElement('button');
close.textContent = 'Close editor';
close.onclick = () => {
disconnect();
api.dispose();
editor.remove();
close.remove();
};
host.append(close);
tsx// src/StencilEditor.tsx
import { useEffect, useRef, useState } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance, NodeSpec } from '@grafloria/renderer';
import { connectEditor } from './stencils';
const nodes: NodeSpec[] = [
{ id: 'instructions', label: 'Drag a master here', position: { x: 80, y: 280 } },
];
export function StencilEditor() {
const rail = useRef<HTMLElement>(null);
const panel = useRef<HTMLElement>(null);
const [instance, setInstance] = useState<DiagramInstance | null>(null);
useEffect(() => {
if (!instance || !rail.current || !panel.current) return;
return connectEditor(instance, rail.current, panel.current, instance.container);
}, [instance]);
return (
<section style={{ display: 'grid', gridTemplateColumns: '200px minmax(0,1fr) 240px', height: 500 }}>
<aside ref={rail} />
<GrafloriaFlow defaultNodes={nodes} onInit={setInstance} style={{ minWidth: 0, height: '100%' }} />
<aside ref={panel} />
</section>
);
}
vue<!-- src/components/StencilEditor.vue --> <script setup lang="ts"> import { onBeforeUnmount, ref } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import type { DiagramInstance, NodeSpec } from '@grafloria/renderer'; import { connectEditor } from '../stencils'; const rail = ref<HTMLElement | null>(null); const panel = ref<HTMLElement | null>(null); const nodes: NodeSpec[] = [ { id: 'instructions', label: 'Drag a master here', position: { x: 80, y: 280 } }, ]; const disconnect = ref<(() => void) | null>(null); function onInit(api: DiagramInstance): void { if (!rail.value || !panel.value) return; disconnect.value = connectEditor(api, rail.value, panel.value, api.container); } onBeforeUnmount(() => disconnect.value?.()); </script> <template> <section style="display:grid;grid-template-columns:200px minmax(0,1fr) 240px;height:500px"> <aside ref="rail" /> <GrafloriaFlow :default-nodes="nodes" @init="onInit" style="min-width:0;height:100%" /> <aside ref="panel" /> </section> </template>
ts// src/app/stencil-editor.component.ts
import { Component, ElementRef, inject, viewChild, DestroyRef } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { RenderSpec } from '@grafloria/element';
import type { DiagramInstance, NodeSpec } from '@grafloria/renderer';
import { connectEditor } from '../stencils';
@Component({
selector: 'app-stencil-editor',
imports: [GrafloriaDiagramComponent],
template: `
<section style="display:grid;grid-template-columns:200px minmax(0,1fr) 240px;height:500px">
<aside #rail></aside>
<grafloria-diagram [spec]="spec" (ready)="onReady($event)" style="min-width:0;height:100%" />
<aside #panel></aside>
</section>
`,
})
export class StencilEditorComponent {
private readonly rail = viewChild.required<ElementRef<HTMLElement>>('rail');
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
private readonly destroyRef = inject(DestroyRef);
private disconnect: (() => void) | undefined;
readonly nodes: NodeSpec[] = [
{ id: 'instructions', label: 'Drag a master here', position: { x: 80, y: 280 } },
];
readonly spec: RenderSpec = { nodes: this.nodes };
constructor() {
this.destroyRef.onDestroy(() => this.disconnect?.());
}
onReady(api: DiagramInstance): void {
this.disconnect?.();
this.disconnect = connectEditor(api, this.rail().nativeElement, this.panel().nativeElement, api.container);
}
}
tsx// src/StencilEditor.tsx
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { DiagramInstance, NodeSpec } from '@grafloria/renderer';
import { connectEditor } from './stencils';
export default component$(() => {
const rail = useSignal<HTMLElement>();
const panel = useSignal<HTMLElement>();
const instance = useSignal<NoSerialize<DiagramInstance>>();
const nodes: NodeSpec[] = [
{ id: 'instructions', label: 'Drag a master here', position: { x: 80, y: 280 } },
];
useVisibleTask$(({ track, cleanup }) => {
const api = track(() => instance.value);
const railHost = track(() => rail.value);
const panelHost = track(() => panel.value);
if (!api || !railHost || !panelHost) return;
cleanup(connectEditor(api, railHost, panelHost, api.container));
});
return (
<section style="display:grid;grid-template-columns:200px minmax(0,1fr) 240px;height:500px">
<aside ref={rail} />
<GrafloriaFlow defaultNodes={nodes} style={{ minWidth: '0', height: '100%' }}
onInit$={(api: DiagramInstance) => { instance.value = noSerialize(api); }} />
<aside ref={panel} />
</section>
);
});
Import the Qwik component from src/StencilEditor.tsx into your existing route and render it there. The instance is created by the binding in the browser, stored with noSerialize(), and consumed by useVisibleTask$; it is not server-serialized.
The selected Approval shape sits beside the Approved? diamond, with the searchable Team and notation palette on the left and Shape data controls on the right. The JavaScript editor also provides a Close editor button.
Drag Approval from the Team section to add another instance. Search for decision to narrow the palette; matching sections open during a search. Select either existing shape to see its properties. Change Owner and leave the field, or press Enter, to commit one edit; use Ctrl+Z or ⌘Z with the canvas active to undo it. Clearing selection returns the panel to its empty message.
Compare this surface with the live Stencil palette and Shape data panel. The Visio-style editor combines both controls with the editor's other authoring actions.
3. Browse the template library and register a subset
The curated TemplateLibrary is a discovery catalog, separate from the mounted engine's registry. CommonTemplates, WorkflowTemplates, and DataVizTemplates expose its ready-made masters. getTemplatesByCategory groups the catalog; getAllTemplates returns it as an array.
Use registerTemplateLibrary for the shipped catalog, registerTemplatesByCategory for one category, or registerTemplatesById for selected ids. The latter returns registered, notFound, and total; inspect notFound rather than assuming every requested id exists. getUnregisteredTemplates returns the shipped ids still missing from your engine registry.
Add this module to expose a curated library section on the same mounted editor. It uses the authors' direct template imports and grouped exports, then places a real card master in the diagram. In this SVG palette, these masters show their silhouettes and labels; use Build a dashboard for rendered metric/chart widgets and Edit database diagrams for entity tables.
tsimport { bindStencilPalette } from '@grafloria/element';
import {
Activity, BadgeLabel, BarChart, ButtonNode, CardNode, CommonTemplates,
DataTable, DataVizTemplates, DecisionNode, EndEvent, Gateway, Gauge, IconNode,
InputField, MetricCard, PieChart, ProgressBar, StartEvent, StatCounter,
Subprocess, TemplateLibrary, WorkflowTemplates, getTemplatesByCategory,
getUnregisteredTemplates, registerTemplateLibrary, registerTemplatesByCategory,
registerTemplatesById,
} from '@grafloria/engine';
import type { NodeTemplate, Stencil, TemplateRegistry } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
function registerLibrary(registry: TemplateRegistry, mode: 'all' | 'workflow' | 'selected'): void {
if (mode === 'workflow') {
registerTemplatesByCategory(registry, 'workflow');
} else if (mode === 'selected') {
const result = registerTemplatesById(registry, ['card-node', 'metric-card']);
if (result.notFound.length) throw new Error(`Missing: ${result.notFound.join(', ')}`);
} else {
registerTemplateLibrary(registry);
}
}
export function connectLibrary(api: DiagramInstance, rail: HTMLElement): () => void {
const registry = api.getEngine().templateRegistry;
registerLibrary(registry, 'all');
const available: NodeTemplate[] = [
CommonTemplates.UserAvatar, CardNode, ButtonNode, InputField, BadgeLabel, IconNode,
WorkflowTemplates.ProcessStep, DecisionNode, StartEvent, EndEvent, Subprocess, Gateway, Activity,
DataVizTemplates.MetricCard, MetricCard, Gauge, BarChart, DataTable, PieChart, StatCounter, ProgressBar,
];
const masters = [...new Map(available.map(master => [master.id, master])).values()]
.filter(master => registry.has(master.id));
const section: Stencil = {
id: 'library', name: 'Template library', description: 'Curated template silhouettes', masters,
};
const palette = bindStencilPalette(api, { palette: rail, canvas: api.container }, { stencils: [section] });
const card = TemplateLibrary.get('card-node');
if (card && registry.get(card.id)) void palette.place(card.id, { x: 450, y: 330 });
console.log('Catalog categories', getTemplatesByCategory());
console.log('Unregistered shipped IDs', getUnregisteredTemplates(registry));
return () => palette.destroy();
}
To run this section, import connectLibrary into src/stencils.ts. In connectEditor(), replace the palette declaration with const palette = { destroy: connectLibrary(api, rail) };, retaining its existing teardown call. Remove the now-unused bindStencilPalette import. The initial approval shapes and property panel stay in place; the rail now contains the curated library. Change the registerLibrary() mode to 'workflow' or 'selected' to restrict which masters appear.
The individual masters are CardNode, ButtonNode, InputField, BadgeLabel, IconNode, DecisionNode, StartEvent, EndEvent, Subprocess, Gateway, Activity, MetricCard, Gauge, BarChart, DataTable, PieChart, StatCounter, and ProgressBar. UserAvatar and ProcessStep also have individual exports; the sample accesses them through their groups.
Category choices
TemplateCategory accepts all five values below. A palette's stencil grouping need not match a master's category.
| Value | Catalog grouping |
|---|---|
'common' | Avatars, cards, buttons, inputs, badges, icons |
'workflow' | Processes, decisions, events, subprocesses, gateways, activities |
'data-viz' | Metrics, gauges, charts, tables, counters, progress bars |
'diagram' | Diagram templates registered under this category |
'erd' | Entity-relationship templates and rendering variants |
4. Register a custom template for discovery
registerCustomTemplate adds your master to the discovery catalog. Register it explicitly in the mounted engine too, so the factory and panel can resolve it. Add this module, then call it from src/stencils.ts before constructing the factory:
tsimport { registerCustomTemplate, TemplateLibrary } from '@grafloria/engine';
import type { TemplateRegistry } from '@grafloria/engine';
import { approval } from './approval';
export function registerApproval(registry: TemplateRegistry): void {
registerCustomTemplate(approval, 'workflow', ['approval', 'team']);
const master = TemplateLibrary.get(approval.id);
if (!master) throw new Error('Approval is missing from the catalog');
registry.register(master);
}
Import registerApproval from ./custom-registration and call registerApproval(registry) inside connectEditor(). registry.get(id) returns the registered engine master or undefined; catalog registration alone does not supply it to the mounted diagram.
Generated templates and notation families
registerGeneratedTemplates bulk-registers the generated BPMN, Flowchart, UML, and ERD masters without defining palette sections. Use registerStencils() when you also need those sections. getStencil looks up a built-in section by id and returns undefined for an absent id.
Type definitions and drawing geometry are separate registrations. registerBPMNTypes, registerFlowchartTypes, registerUMLTypes, and registerERDTypes take the engine's typeRegistry and register domain type definitions. They do not register masters into templateRegistry. registerNotationShapes registers notation outlines; importing the renderer already invokes it, so the mounted sample needs no additional call.
Render a data-driven property preview
The renderer's NodeTemplate is a different contract: a function, or a definition with render, that returns HTML, ports, and size for current node data. Use nodeTemplates when changing a property needs to repaint the inside of a card. This browser entry file mounts the approval master with a DOM-based Owner preview and the same schema-driven panel; it does not interpolate user text into HTML.
tsimport { render, bindShapeDataPanel } from '@grafloria/element';
import { NodeFactory } from '@grafloria/engine';
import type { NodeTemplate } from '@grafloria/renderer';
import { approval } from './approval';
const ownerPreview: NodeTemplate = data => {
const content = document.createElement('div');
content.style.cssText = 'padding:16px;background:#eef2ff;border:2px solid #4f46e5;box-sizing:border-box;height:100%';
content.textContent = `Owner: ${String(data['owner'] ?? '')}`;
return { html: content, size: { width: 180, height: 100 } };
};
const host = document.getElementById('app');
if (!host) throw new Error('Missing #app');
const frame = document.createElement('section');
frame.style.cssText = 'display:grid;grid-template-columns:minmax(0,1fr) 240px;height:400px';
const canvas = document.createElement('div');
canvas.style.cssText = 'position:relative;min-width:0';
const panelHost = document.createElement('aside');
frame.append(canvas, panelHost);
host.append(frame);
const api = render({ nodes: [] }, canvas, { nodeTemplates: { 'team-approval': ownerPreview } });
api.getEngine().templateRegistry.register(approval);
const factory = new NodeFactory(api.getEngine().templateRegistry, api.getModel());
const node = factory.createFromTemplate(approval.id, { owner: 'Finance' }, { x: 80, y: 100 });
api.getModel().selectNode(node);
const panel = bindShapeDataPanel(api, panelHost);
const close = document.createElement('button');
close.textContent = 'Close preview';
close.onclick = () => {
panel.destroy();
api.dispose();
frame.remove();
close.remove();
};
host.append(close);
Run this as a separate browser entry instead of mounting the first editor. The card reads Owner: Finance initially. Edit Owner in the panel and commit the field: the rendered card follows the node data. A renderer template may also return stable port specs and a size; the engine derives those during the data edit's undo step. See Customize rendering contracts for framework-native content.
Options and boundaries
| Option | Type | Default | What it does |
|---|---|---|---|
StencilPaletteOptions.stencils | Stencil[] | Built-in stencils | Chooses the rail's sections; register their masters in the engine separately. |
StencilPaletteOptions.search | boolean | true | Shows the search input; search matches name, id, or tags. |
StencilPaletteOptions.collapsed | string[] | All sections except the first | Sets initially closed sections; searches open matching sections. |
StencilPaletteOptions.data | Master-to-data callback | Not supplied | Adds data to each placed master. |
StencilPaletteOptions.onPlace | Placement callback | Not supplied | Receives the master, node id, and top-left world coordinates after placement. |
ShapeDataPanelOptions.title | string | 'Shape data' | Changes the panel heading. |
ShapeDataPanelOptions.emptyText | string | 'Select a shape to edit its data.' | Changes the empty-selection message. |
ShapeDataPanelOptions.onEdit | Edit callback | Not supplied | Receives node id, key, and value for schema-field edits. |
The schema panel maps enums to selects, booleans to checkboxes, numbers and integers to numeric inputs, and other fields to text inputs. It is not a complete JSON Schema validator: do not treat required, nested object schemas, or numeric bounds as application validation. Enum controls commit string values. An empty numeric input commits null.
The panel subscribes to selection:change. The stencil editor also subscribes to the model's node:changed event and calls the panel's refresh() while nodes are selected, keeping position, size, and data fields current after dragging, resizing, undo, or edits from another control. It unsubscribes when the editor closes or unmounts. No refresh is needed for initial binding or selection changes. onEdit is a notification for panel schema edits, not a subscription to every diagram mutation. For other inspector UI that tracks edits, use the instance's change events as described in Edit nodes from your UI.
Use the factory for initial content: it writes directly to the model, outside history. Use palette placement for user additions: it commits the created subtree as one batch command. Keep masters registered while their nodes need schema fields. For rich HTML rendering beyond this preview, follow Customize rendering contracts; for saving the resulting document, follow Save and restore documents.
Was this page helpful?