Skip to content
D
Documentation

Customize rendering contracts

how-to
11 min readUpdated

Use custom rendering when a node needs application markup, or an edge needs a visual that the stock styles cannot express. The engine owns the box and its connections; your renderer paints the inside. Start with the binding's HTML host, then use VNodes when you need to extend SVG or share geometry with a canvas renderer.

These examples start in the project left by your quick start: JavaScript, React, Vue, Angular, or Qwik. Keep the starter's entry file, stylesheet imports and framework configuration. Add the modules below and render the example component from your existing app; the JavaScript tab runs in your existing entry module.

The host examples use the packages installed by those quick starts. The following command installs all bindings used on this page along with the element, engine and renderer packages in devDependencies, matching the Qwik starter:

bash
npm install -D @grafloria/element @grafloria/engine @grafloria/renderer @grafloria/react @grafloria/vue @grafloria/angular @grafloria/qwik

Fill custom node hosts

The result is two HTML cards, Build and Deploy, connected by an edge. Each card fills an engine-positioned host; its position and size remain model data. See the HTML nodes demo for the same task running.

  1. Add the shared data module. NodeSpec describes the cards and EdgeSpec connects them.
ts
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = [
  { id: 'build', type: 'card', custom: true,
    position: { x: 60, y: 80 }, size: { width: 220, height: 110 },
    data: { title: 'Build', owner: 'CI', status: 'passing' } },
  { id: 'deploy', type: 'card', custom: true,
    position: { x: 390, y: 80 }, size: { width: 220, height: 110 },
    data: { title: 'Deploy', owner: 'CD', status: 'ready' } },
];
export const edges: EdgeSpec[] = [
  { id: 'pipeline', source: 'build', target: 'deploy' },
];
  1. Mount through your binding. For Angular, put the shared module at src/rendering-data.ts and the component below at src/app/rendering-example.ts. For Qwik, put the component at src/rendering-example.tsx and import it from your route. The other components can be imported by your existing app component.

The JavaScript path uses registerNodeType with a NodeTypeRenderer, then render returns the live DiagramInstance.

React's GrafloriaFlow passes NodeProps to your component. Vue's GrafloriaFlow uses a named slot. Angular's DiagramCanvasComponent discovers GrafloriaNodeDefDirective templates. Qwik's GrafloriaFlow accepts Qwik components with NodeProps.

ts
import { registerNodeType, render } from '@grafloria/element';
import type { NodeTypeRenderer } from '@grafloria/element';
import { nodes, edges } from './rendering-data';

const card: NodeTypeRenderer = (node, host) => {
  const body = document.createElement('div');
  body.className = 'rendering-card';
  const title = document.createElement('strong');
  title.textContent = String(node.getData('title') ?? '');
  const owner = document.createElement('p');
  owner.textContent = `owner: ${String(node.getData('owner') ?? '')}`;
  const status = document.createElement('span');
  status.textContent = String(node.getData('status') ?? '');
  body.append(title, owner, status);
  host.append(body);
};
registerNodeType('card', card);
const host = document.createElement('div');
host.style.height = '400px';
document.body.append(host);
const diagram = render({ nodes, edges }, host);
const close = document.createElement('button');
close.textContent = 'Close diagram';
close.onclick = () => {
  diagram.dispose();
  host.remove();
  close.remove();
};
document.body.append(close);

The JavaScript host displays the node data and a Close diagram button.

Build and Deploy show their owners and statuses, with an arrow between them and a Close diagram button below.

The React component displays the same connected node content.

Build and Deploy show owner CI and owner CD, with passing and ready statuses and an arrow between them.

In React and JavaScript, registration alone does not select the HTML path: supply custom: true and a matching renderer or component. Register JavaScript renderers before mounting; existing empty hosts are not back-filled. Vue's wildcard #node slot also needs explicit custom: true. A named Vue slot, an Angular node definition and a Qwik node type can opt their matching types into the HTML layer; the shared specs make the intent explicit in every binding.

For content that changes with connected data, continue with Compute connected data.

Fill hosts with element templates

For a static page, put a template inside <grafloria-flow>. Each node receives a clone; data-field="id" reads the node id, other fields read its data, and missing values become empty text. A registered renderer takes precedence over a matching template.

In the JavaScript quick-start project, add this markup and import @grafloria/element from your existing entry module. This renders one Build card without a renderer function.

html
<grafloria-flow style="display:block;height:400px"
  nodes='[{"id":"build","type":"template-card","custom":true,"position":{"x":60,"y":80},"size":{"width":220,"height":110},"data":{"title":"Build"}}]'>
  <template data-node-type="template-card">
    <div class="rendering-card">
      <strong data-field="title"></strong>
      <p data-field="id"></p>
    </div>
  </template>
</grafloria-flow>

Host registered Angular components

Use ComponentRendererService when your adapter instantiates registered Angular components inside a node template. Register the type before the template mounts, call renderComponent() with the template's view container, and call destroyComponent() when that host disappears. The service rejects duplicate component registrations; a component-scoped provider keeps this example's registry and instances local.

Add this file in the Angular quick-start project. Render RegisteredRenderingExample from your existing app. It reuses src/rendering-data.ts and the card stylesheet below. You get the same Build and Deploy cards, now instantiated by the service rather than written directly in the node template.

ts
import { Component, Directive, Input, ViewContainerRef, inject } from '@angular/core';
import type { OnDestroy, OnInit } from '@angular/core';
import {
  ComponentRendererService, DiagramCanvasComponent, GrafloriaNodeDefDirective,
} from '@grafloria/angular';
import { nodes, edges } from '../rendering-data';

@Component({
  selector: 'app-registered-card',
  template: `<div class="rendering-card">
    <strong>{{ title }}</strong><p>owner: {{ owner }}</p><span>{{ status }}</span>
  </div>`,
})
class RegisteredCard {
  @Input() title = '';
  @Input() owner = '';
  @Input() status = '';
}

@Directive({ selector: 'ng-container[registeredCard]' })
export class RegisteredCardHost implements OnInit, OnDestroy {
  @Input({ required: true }) registeredCard = '';
  @Input({ required: true }) cardData: Record<string, unknown> = {};
  private readonly renderer = inject(ComponentRendererService);
  private readonly container = inject(ViewContainerRef);

  ngOnInit(): void {
    this.renderer.renderComponent(
      { id: this.registeredCard, type: 'registered-card' }, this.container,
      { inputs: {
        title: String(this.cardData['title'] ?? ''),
        owner: String(this.cardData['owner'] ?? ''),
        status: String(this.cardData['status'] ?? ''),
      } },
    );
  }

  ngOnDestroy(): void {
    this.renderer.destroyComponent(this.registeredCard);
  }
}

@Component({
  selector: 'app-registered-rendering-example',
  imports: [DiagramCanvasComponent, GrafloriaNodeDefDirective, RegisteredCardHost],
  providers: [ComponentRendererService],
  template: `
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      style="display:block;height:400px">
      <ng-template grafloriaNode="card" let-node let-data="data">
        <ng-container [registeredCard]="node.id" [cardData]="data" />
      </ng-template>
    </grafloria-diagram-canvas>
  `,
})
export class RegisteredRenderingExample {
  nodes = nodes;
  edges = edges;

  constructor() {
    inject(ComponentRendererService).registerComponent('registered-card', RegisteredCard);
  }
}

This adapter seeds component inputs at mount. For subsequent live-data changes, use updateComponent() rather than creating another instance; Compute connected data covers subscribing to those changes.

Register a property editor and a contextual toolbar

PropertyEditorRegistryService maps editor names to Angular component classes. registerEditor() replaces an existing registration. Use an existing editor name such as select to substitute a domain-specific editor in a typed PropertyDefinition. This example limits status choices to passing and ready.

The adapter below retrieves the registered component and mounts it with Angular's NgComponentOutlet. It passes the editor's value and property inputs, and an application callback that commits the value through SetNodeDataCommand. The editor retains its readonly = false default. The editor also exposes valueChange and validationError outputs for hosts that subscribe to that contract; ValidationError describes a validation failure.

AutoToolbarDirective attaches a toolbar when a node is selected. NodeToolbarService creates, positions and hides its component instances. Bind the directive to the same engine and camera as the canvas. The sample's ToolbarAction reads the selected card's title into the message below the canvas without changing the document.

  1. Add the following file to the Angular quick-start project and render RenderingToolsExample from your existing app.
  2. Change Build status to ready. The card's badge changes through an undoable data command. Select a card to display its Inspect toolbar action.
ts
import { NgComponentOutlet } from '@angular/common';
import { Component, Input, inject, output, signal } from '@angular/core';
import {
  AutoToolbarDirective, DiagramCanvasComponent, GrafloriaNodeDefDirective,
  NodeToolbarService, PropertyEditorRegistryService,
} from '@grafloria/angular';
import type { ToolbarAction } from '@grafloria/angular';
import { DiagramEngine, SetNodeDataCommand } from '@grafloria/engine';
import type { EdgeSpec, NodeSpec, PropertyDefinition, ValidationError } from '@grafloria/renderer';
import { nodes, edges } from '../rendering-data';

@Component({
  selector: 'app-status-editor',
  template: `
    <label>{{ property.label }}
      <select [value]="value" [disabled]="readonly" (change)="change($event)">
        <option value="passing">passing</option>
        <option value="ready">ready</option>
      </select>
    </label>
  `,
})
class StatusEditor {
  @Input() value = 'passing';
  @Input({ required: true }) property!: PropertyDefinition;
  @Input() readonly = false;
  @Input({ required: true }) commit!: (value: string) => void;
  readonly valueChange = output<string>();
  readonly validationError = output<ValidationError | null>();

  change(event: Event): void {
    if (!(event.target instanceof HTMLSelectElement)) return;
    const value = event.target.value;
    this.validationError.emit(null);
    this.valueChange.emit(value);
    this.commit(value);
  }
}

@Component({
  selector: 'app-rendering-tools-example',
  imports: [NgComponentOutlet, DiagramCanvasComponent,
    GrafloriaNodeDefDirective, AutoToolbarDirective],
  providers: [PropertyEditorRegistryService, NodeToolbarService],
  template: `
    <div grafloriaAutoToolbar [engine]="engine"
      [viewport]="viewport()" [zoom]="zoom()" [toolbarActions]="actions"
      style="position:relative;height:400px">
      <grafloria-diagram-canvas [engine]="engine"
        [(nodes)]="nodes" [(edges)]="edges"
        [(viewport)]="viewport" [(zoom)]="zoom"
        (ready)="mounted.set(true)" style="display:block;height:100%">
        <ng-template grafloriaNode="card" let-data="data">
          <div class="rendering-card">
            <strong>{{ data['title'] }}</strong>
            <p>owner: {{ data['owner'] }}</p><span>{{ data['status'] }}</span>
          </div>
        </ng-template>
      </grafloria-diagram-canvas>
    </div>
    @if (mounted()) {
      <ng-container *ngComponentOutlet="editor; inputs: editorInputs" />
    }
    <p aria-live="polite">{{ message() }}</p>
  `,
})
export class RenderingToolsExample {
  readonly engine = new DiagramEngine();
  nodes: NodeSpec[] = nodes;
  edges: EdgeSpec[] = edges;
  readonly viewport = signal({ x: 0, y: 0, width: 800, height: 400 });
  readonly zoom = signal(1);
  readonly mounted = signal(false);
  readonly message = signal('Select a card to inspect it');
  readonly property: PropertyDefinition = {
    key: 'status', label: 'Build status', editor: 'select',
    validation: { enum: ['passing', 'ready'] },
  };
  private readonly registry = inject(PropertyEditorRegistryService);
  readonly editor;
  readonly commit = (value: string): void => {
    void this.engine.commandManager.execute(
      new SetNodeDataCommand('build', { status: value }),
    );
  };
  get editorInputs() {
    const build = this.nodes.find((node) => node.id === 'build');
    return {
      value: String(build?.data?.['status'] ?? ''),
      property: this.property, commit: this.commit,
    };
  }
  readonly actions: ToolbarAction[] = [{
    id: 'inspect', label: 'Inspect',
    onClick: (node) => this.message.set(String(node.getData('title') ?? node.id)),
  }];

  constructor() {
    this.registry.registerEditor('select', StatusEditor);
    this.editor = this.registry.getEditor(this.property.editor);
  }
}

The editor's two options are passing and ready; it commits one field on Build. The component-scoped registry contains the shipped editors for other names, and its select registration applies only within this example. For a full property inspector and event-driven Undo/Redo controls, continue with Angular: state and tooling.

Styling

  1. Add these rules to the global stylesheet already imported by your quick start. In Angular, use src/styles.css, not the containing component's encapsulated stylesheet.
  2. Run the host example above. The cards have a white background, rounded blue borders and green status badges.
css
.rendering-card {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 12px;
  border: 2px solid #94a5f0;
  border-radius: 12px;
  background: #fff;
  color: #232a3d;
  font: 14px/1.4 system-ui, sans-serif;
  text-align: start;
}
.rendering-card p { margin: 6px 0; font-size: 12px; }
.rendering-card span {
  padding: 2px 8px;
  border-radius: 999px;
  background: #ecfdf5;
  color: #047857;
}

The JavaScript element uses light DOM, so your stylesheet applies to its content. Style the child card, not the host's left, top, width or height: the engine writes the host geometry. Use textContent for user-supplied values rather than interpolating them into innerHTML.

To change the diagram's palette rather than its card markup, use Theme a diagram. For stock silhouettes with per-node fill and stroke, see the Custom nodes demo.

Draw custom edges and labels with VNodes

Use registerLinkTemplate when changing stroke options is not enough. A LinkTemplate receives the routed points, pathData, resolved styles, LOD tier and selection state. Return a VNode, an array of VNodes, or null. Keep the path from the context rather than drawing a fixed line.

The browser example below mounts a two-rail pipe between Source and Sink. It also registers a LabelTemplate through registerLabelTemplate for a separate edge from Source to Status. That edge's ready badge uses the resolved world-space label anchor. A link template replaces the entire link visual, including arrows and labels; use a label template on an ordinary edge when you want the renderer to position its label. Compare the Custom edges demo.

ts
import { render } from '@grafloria/element';
import {
  registerLinkTemplate, registerLabelTemplate,
} from '@grafloria/renderer';
import type { LabelTemplate, LinkTemplate } from '@grafloria/renderer';

function mountPipe(host: HTMLElement): () => void {
  const pipe: LinkTemplate = (ctx) => {
    const stroke = ctx.selected ? '#2563eb' : '#0ea5e9';
    return [
      { type: 'path', props: { d: ctx.pathData, fill: 'none', stroke,
        strokeWidth: 10, opacity: 0.35, className: 'pipe-casing' } },
      { type: 'path', props: { d: ctx.pathData, fill: 'none', stroke,
        strokeWidth: 2.5, className: 'pipe-core' } },
    ];
  };
  const badge: LabelTemplate = (ctx) => ({
    type: 'g', props: { transform: `translate(${ctx.anchor.x},${ctx.anchor.y})` },
    children: [
      { type: 'rect', props: { x: -38, y: -14, width: 76, height: 28,
        rx: 8, ry: 8, fill: '#ecfdf5', stroke: '#059669', strokeWidth: 1.5 } },
      { type: 'text', props: { x: -26, y: 5, textAnchor: 'start',
        fontSize: 14, fill: '#047857', textContent: ctx.label.text } },
    ],
  });
  registerLinkTemplate('pipe', pipe);
  registerLabelTemplate('status-badge', badge);
  host.style.height = '400px';
  const diagram = render({
    nodes: [
      { id: 'source', position: { x: 60, y: 80 }, label: 'Source' },
      { id: 'sink', position: { x: 420, y: 220 }, label: 'Sink' },
      { id: 'status', position: { x: 60, y: 280 }, label: 'Status' },
    ],
    edges: [{ id: 'pipe', source: 'source', target: 'sink',
      type: 'smooth', style: { template: 'pipe' } },
      { id: 'status-edge', source: 'source', target: 'status', label: 'ready' }],
  }, host);
  const link = diagram.getModel().getLinks().find((edge) => edge.id === 'status-edge');
  if (link) {
    link.setLabels([{ id: 'status', text: 'ready', position: 0.5,
      offset: { x: 0, y: 0 }, template: 'status-badge' }]);
  }
  return () => diagram.dispose();
}

const host = document.createElement('div');
document.body.append(host);
const unmount = mountPipe(host);
const close = document.createElement('button');
close.textContent = 'Close pipe diagram';
close.onclick = () => {
  unmount();
  host.remove();
  close.remove();
};
document.body.append(close);

This browser entry module mounts its own host and disposes the diagram when you close it. Import ./edge-rendering from your existing JavaScript entry to run it. The model stores template names, not closures, so register those names wherever you reopen the diagram.

Embed HTML in an SVG subtree

HTML-layer hosts and SVG foreignObject are different contracts. The former gives your binding a positioned HTML element. The latter puts HTML inside an SVG tree. Use createForeignObject for the latter; its ForeignObjectOptions supplies the box and children.

This browser example fills a custom node with an SVG frame containing an HTML badge. ContainerIdGenerator supplies a stable id for this mount. isForeignObject checks the VNode type, and getContainerId reads its container id. VNodePatcher creates the subtree; append the result to make it visible.

ts
import { registerNodeType, render } from '@grafloria/element';
import {
  ContainerIdGenerator, createForeignObject, getContainerId,
  isForeignObject, VNodePatcher,
} from '@grafloria/renderer';
import type { VNode } from '@grafloria/renderer';

function mountForeignCard(host: HTMLElement): () => void {
  const patcher = new VNodePatcher();
  registerNodeType('svg-card', (node, element) => {
    const containerId = ContainerIdGenerator.generate(node.id);
    const foreign = createForeignObject({
      nodeId: node.id, x: 10, y: 10, width: 200, height: 90,
      containerId, key: `content-${node.id}`,
      children: [{ type: 'div', props: {
        xmlns: 'http://www.w3.org/1999/xhtml',
        className: 'rendering-card',
        style: { backgroundColor: '#ecfdf5' },
        textContent: 'HTML inside SVG',
      } }],
    });
    const id = getContainerId(foreign);
    if (!isForeignObject(foreign) || !id ||
        !ContainerIdGenerator.isContainerId(id) ||
        ContainerIdGenerator.getNodeId(id) !== node.id) {
      throw new Error('Invalid foreignObject identity');
    }
    const tree: VNode = {
      type: 'svg', props: { width: 220, height: 110 },
      children: [foreign],
    };
    element.append(patcher.createElement(tree));
  });
  host.style.height = '400px';
  const diagram = render({ nodes: [{
    id: 'html-svg', type: 'svg-card', custom: true,
    position: { x: 60, y: 80 }, size: { width: 220, height: 110 },
  }] }, host);
  return () => diagram.dispose();
}

const host = document.createElement('div');
document.body.append(host);
const unmount = mountForeignCard(host);
const close = document.createElement('button');
close.textContent = 'Close foreignObject diagram';
close.onclick = () => {
  unmount();
  host.remove();
  close.remove();
};
document.body.append(close);

Import ./foreign-object-rendering from your JavaScript entry to run this browser entry module.

createForeignObject() generates an id when you omit containerId and supplies an XHTML div when you omit children. Supplying children replaces that default wrapper. Keep the id and key stable while updating one mounted subtree.

ContainerIdGenerator.reset() resets the process-wide counter. Use it only in an isolated test with no surviving containers, not while diagrams are mounted:

ts
import { ContainerIdGenerator } from '@grafloria/renderer';

ContainerIdGenerator.reset();
const id = ContainerIdGenerator.generate('test-node');
if (id !== 'fo-test-node-1') throw new Error('Unexpected initial counter');

SVG_NS is the default namespace for createElement(). Children of a foreignObject use XHTML. For repeated updates, use the instance's patcher.reconcile(); the exported reconcile uses a default patcher to mount or patch a VNode into a container.

Adapt HTML template results to a host

Use HtmlTemplateRenderer when integrating the engine's HtmlConfig contract into a host you own. It returns a result, not mounted DOM: template mode returns html, bindings and event handlers; component mode returns componentRef for your framework adapter.

The example below mounts a trusted static template on a real node. It attaches the returned DOM event handlers so clicks reach the same DiagramEngine's event bus. Template substitutions are HTML strings: keep this path for trusted markup and trusted values. Use the text-writing host or element template above for user input.

ts
import { DiagramEngine, HtmlTemplateRenderer } from '@grafloria/engine';
import type { HtmlConfig } from '@grafloria/engine';
import { render } from '@grafloria/element';

function mountTemplate(host: HTMLElement): () => void {
  const engine = new DiagramEngine();
  engine.registerNodeType({ type: 'template-card', label: 'Template card' });
  const renderer = new HtmlTemplateRenderer(engine.eventBus);
  const config: HtmlConfig = {
    mode: 'template',
    template: '<strong>{{data.title}}</strong><p>{{owner}}</p><button>Inspect</button>',
    bindings: { owner: 'data.owner' },
    className: ['rendering-card', 'template-content'],
    style: { backgroundColor: '#eff6ff', padding: '12px' },
    events: { click: 'card:inspect' },
  };
  const componentConfig: HtmlConfig = {
    mode: 'component', component: 'StatusCard', className: 'component-content',
  };
  host.style.height = '400px';
  const diagram = render({ nodes: [
    { id: 'template', type: 'template-card', custom: true,
      position: { x: 60, y: 80 }, size: { width: 220, height: 110 },
      data: { title: 'Build', owner: 'CI' } },
    { id: 'component', custom: true,
      position: { x: 390, y: 80 }, size: { width: 220, height: 110 } },
  ] }, host, {
    engine,
    renderCustomNode(node, element) {
      const result = renderer.render(node.id === 'template' ? config : componentConfig, node);
      if (result.mode === 'template' && result.html) {
        const template = document.createElement('template');
        template.innerHTML = result.html;
        element.append(template.content.cloneNode(true));
        for (const [name, handler] of Object.entries(result.eventHandlers)) {
          element.addEventListener(name, handler);
        }
      } else {
        // Replace this text with your framework's component mount in an adapter.
        element.textContent = `Component reference: ${result.componentRef ?? ''}`;
      }
    },
    removeCustomNode(nodeId) {
      const node = engine.getDiagram()?.getNode(nodeId);
      if (node) renderer.disposeNode(node.uuid);
    },
  });
  return () => {
    diagram.dispose();
    renderer.dispose();
  };
}

const host = document.createElement('div');
document.body.append(host);
const unmount = mountTemplate(host);
const close = document.createElement('button');
close.textContent = 'Close template diagram';
close.onclick = () => {
  unmount();
  host.remove();
  close.remove();
};
document.body.append(close);

Import ./template-rendering from your JavaScript entry to run this browser entry module.

The first card shows Build, CI and an Inspect button. The second shows the component reference StatusCard; component mode does not instantiate that reference itself. engine.registerNodeType() registers a model type definition, whereas the element's renderer registry fills hosts.

LemonadeJSRenderer is the shipped DOM-producing renderer for LemonadeJS two-way bindings and reactive templates. Its render() returns an element in template mode; mount that element in your host. Its disposeNode() and dispose() release renderer resources. Do not treat HtmlTemplateRenderer's string substitution as a reactive framework mount.

OptionTypeDefaultWhat it does
mode'template' | 'component'Inferred from template, then componentSelects string rendering or component-reference pass-through.
templatestringUnsetSupplies template markup; required for template mode.
componentstringUnsetSupplies the reference; required for component mode.
bindingsRecord<string, string>UnsetMaps variables to paths on the node; data, nodeId and nodeUuid are also bound.
eventsRecord<string, string>UnsetMaps DOM event names to engine event names; attach the returned handlers.
classNamestring | string[]UnsetApplies one or more classes to the wrapper.
styleDeclaration mapUnsetApplies inline styles to the wrapper.
zIndexnumberUnsetAdds the wrapper's z-index.
pointerEventsbooleantruefalse makes the wrapper pass through pointer events.

Share SVG geometry with canvas consumers

VNodes are the common rendering contract: the DOM patcher creates SVG elements, while the canvas painter converts geometry, styles and transforms into drawing commands. Canvas does not paint live HTML inside foreignObject; an HTML overlay is required for that content. Prefer SVG geometry for custom visuals that need both consumers.

SVGRenderer can build a VNode tree from a live engine. Go below render() here only to inspect that tree or implement another consumer. This browser example mounts the interactive diagram and a separate SVG preview from the same model. Closing it disposes both renderers.

ts
import { render } from '@grafloria/element';
import { SVGRenderer, VNodePatcher, hashString, parseInlineStyle } from '@grafloria/renderer';

function mountPreview(host: HTMLElement, preview: HTMLElement): () => void {
  host.style.height = '400px';
  const diagram = render({ nodes: [
    { id: 'source', position: { x: 40, y: 60 }, label: 'Source' },
    { id: 'sink', position: { x: 300, y: 160 }, label: 'Sink' },
  ], edges: [
    { id: 'first', source: 'source', target: 'sink' },
    { id: 'second', source: 'source', target: 'sink' },
  ] }, host, {
    renderer: { parallelSpacing: 24 },
  });
  const renderer = new SVGRenderer(diagram.getEngine());
  const tree = renderer.render({ x: 0, y: 0, width: 600, height: 400 }, 1);
  tree.props.width = 600;
  tree.props.height = 400;
  const patcher = new VNodePatcher();
  preview.append(patcher.createElement(tree));
  const declarations = parseInlineStyle({ backgroundColor: '#eff6ff' });
  for (const [name, value] of Object.entries(declarations)) {
    preview.style.setProperty(name, value);
  }
  preview.dataset['sceneHash'] = hashString(JSON.stringify(tree));
  return () => {
    renderer.dispose();
    diagram.dispose();
    preview.replaceChildren();
  };
}

const interactiveHost = document.createElement('div');
const previewHost = document.createElement('div');
document.body.append(interactiveHost, previewHost);
const unmountPreview = mountPreview(interactiveHost, previewHost);
const closePreview = document.createElement('button');
closePreview.textContent = 'Close preview';
closePreview.onclick = () => {
  unmountPreview();
  interactiveHost.remove();
  previewHost.remove();
  closePreview.remove();
};
document.body.append(closePreview);

hashString provides a stable FNV-1a hash for cache keys. parseInlineStyle accepts a CSS string or object and returns string-valued declarations; object keys become kebab-case. It is not the DSL style parser.

For a custom canvas consumer, IDENTITY is the initial matrix. translation, rotation and scaling build matrices; multiply composes them, applying its second argument first. rotation() takes degrees and can rotate about a supplied center.

VNode properties that matter

VNodeProps carries geometry and presentation; these optional properties have no value until supplied by your template or consumer.

PropertiesTypeEffect
x, y, width, heightnumberPositions and sizes boxes.
rx, rynumberRounds rectangle corners.
cx, cy, rnumberDefines a circle's center and radius.
x1, y1, x2, y2numberDefines a line's endpoints.
dstringSupplies SVG path data.
fill, stroke, strokeDasharraystringSupplies colors and dash patterns.
strokeWidth, opacitynumberSupplies stroke width and opacity.
transformstringTransforms the subtree.
textContent, fontFamilystringSupplies text and its font family.
fontSizenumberSupplies font size in pixels.
textAnchor'start' | 'middle' | 'end'Aligns text at the start, center or end of its anchor.
classNamestringAdds space-separated CSS classes.
styleDeclaration map or CSS stringSupplies inline styles.
containerIdstringIdentifies a foreignObject container.
xmlnsstringOverrides the element namespace.
requiredExtensionsstringSupplies the SVG required-extensions attribute.

Choose the extension boundary

  • InteractionController handles world-space hover detection, connection dragging, endpoint reconnection and edge-editing logic; the host owns coordinate conversion and painting. SelectionToolsController supplies selection-handle geometry and commands for resizing, rotation and contextual tools without rendering them.
  • HighlighterController computes hover, selection, validation and connection-target decoration geometry independently of node visuals. InPlaceTextEditor holds the label-editing session, its world-space bounds and the undoable commit command; your host supplies the text widget.
  • VNodeRendererService wraps VNodePatcher for Angular: it reconciles VNode trees into DOM containers while reusing existing elements. Use it when implementing an Angular rendering consumer rather than duplicating the SVG diff algorithm.
  • NodeComponent, returned by defineNodeComponent, defines render, optional onUpdate and onDestroy, and optional autoSize. Its renderer returns a VNode or owns the supplied element. Auto-sizing is off by default; sizeThreshold defaults to 1 pixel. Use a lifecycle-aware component adapter when you need updates and teardown, rather than a mount-only element renderer.
  • getShape resolves geometry with a rectangle fallback. getInnerRect returns the local label box, using a padded box when the shape has no override. See Define shapes and styles for authoring that geometry.
  • PortLayoutStrategy returns node-local coordinates from the box, side, rank and count. Register it with registerPortLayout. portWorldPosition converts a port's placement into the world position used by hit-testing and endpoints. Continue with Arrange ports and connect.
  • TextKit decorates an imported model before it reaches the canvas and optionally finalizes against the live instance. registerTextKit selects that decoration by diagram type; the last registration wins. The element package already registers its ER and UML looks. Continue with Import Mermaid and draw.io.

At the instance factory boundary, CreateDiagramOptions's renderer passes SVG renderer configuration, not a renderer instance. instanceId controls the CSS scope; leave it to hydration unless you need an explicit scope. hydrate adopts the snapshot's existing DOM. cullCustomNodes is off by default; enabling it limits hosts near the viewport and defaults to detaching and reattaching them without remounting. See Instance and lifecycle for adoption and cleanup, and Navigate accessible canvases for culling and LOD policies.

Mount a rendering module in the browser

The browser entry modules above create their hosts and mount when imported. Add this import to your existing JavaScript entry to display the SVG preview below the interactive diagram. Keep the starter's stylesheet import. To run another example instead, replace ./svg-preview with ./edge-rendering, ./foreign-object-rendering or ./template-rendering.

ts
import './style.css';
import './svg-preview';

Was this page helpful?