# Customize rendering contracts

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start), or [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start). 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](https://grafloria.com/demos/nodes/html-nodes.html) for the same task running.

1. Add the shared data module. [`NodeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) describes the cards and [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec) connects them.

```ts title="src/rendering-data.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' },
];
```

2. 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core) with a [`NodeTypeRenderer`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#nodetyperenderer), then [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render) returns the live [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance).

React's [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriaflow) passes [`NodeProps`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#nodeprops) to your component. Vue's [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriaflow) uses a named slot. Angular's [`DiagramCanvasComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-diagramcanvascomponent) discovers [`GrafloriaNodeDefDirective`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-core#graflorianodedefdirective) templates. Qwik's [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriaflow) accepts Qwik components with [`NodeProps`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#nodeprops).

:::code-group
```ts title="JavaScript"
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);
```
```tsx title="React"
// src/RenderingExample.tsx
import { GrafloriaFlow } from '@grafloria/react';
import type { NodeProps } from '@grafloria/react';
import { nodes, edges } from './rendering-data';

function Card({ data }: NodeProps) {
  return <div className="rendering-card">
    <strong>{String(data['title'] ?? '')}</strong>
    <p>owner: {String(data['owner'] ?? '')}</p>
    <span>{String(data['status'] ?? '')}</span>
  </div>;
}
const nodeTypes = { card: Card };

export default function RenderingExample() {
  return <div style={{ height: 400 }}>
    <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} nodeTypes={nodeTypes} />
  </div>;
}
```
```vue title="Vue"
<!-- src/RenderingExample.vue -->
<script setup lang="ts">
import { GrafloriaFlow } from '@grafloria/vue';
import { nodes, edges } from './rendering-data';
</script>

<template>
  <div style="height:400px">
    <GrafloriaFlow :default-nodes="nodes" :default-edges="edges">
      <template #node-card="{ data }">
        <div class="rendering-card">
          <strong>{{ data['title'] }}</strong>
          <p>owner: {{ data['owner'] }}</p>
          <span>{{ data['status'] }}</span>
        </div>
      </template>
    </GrafloriaFlow>
  </div>
</template>
```
```ts title="Angular"
// src/app/rendering-example.ts
import { Component } from '@angular/core';
import { DiagramCanvasComponent, GrafloriaNodeDefDirective } from '@grafloria/angular';
import { nodes, edges } from '../rendering-data';

@Component({
  selector: 'app-rendering-example',
  imports: [DiagramCanvasComponent, GrafloriaNodeDefDirective],
  template: `
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      style="display:block;height:400px">
      <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>
  `,
})
export class RenderingExample {
  nodes = nodes;
  edges = edges;
}
```
```tsx title="Qwik"
// src/rendering-example.tsx
import { component$ } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { NodeProps } from '@grafloria/qwik';
import { nodes, edges } from './rendering-data';

const Card = component$((props: NodeProps) => (
  <div class="rendering-card">
    <strong>{String(props.data['title'] ?? '')}</strong>
    <p>owner: {String(props.data['owner'] ?? '')}</p>
    <span>{String(props.data['status'] ?? '')}</span>
  </div>
));

export default component$(() => (
  <div style={{ height: '400px' }}>
    <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
      nodeTypes={{ card: Card }} />
  </div>
));
```
:::

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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 title="index.html — add inside body"
<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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-services-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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start). 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 title="src/app/registered-rendering-example.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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/compute-connected-data) covers subscribing to those changes.

### Register a property editor and a contextual toolbar

[`PropertyEditorRegistryService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-services#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-types-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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-r-u#setnodedatacommand). The editor retains its `readonly = false` default. The editor also exposes `valueChange` and `validationError` outputs for hosts that subscribe to that contract; [`ValidationError`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-types-interfaces-s-v#validationerror) describes a validation failure.

[`AutoToolbarDirective`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-classes#autotoolbardirective) attaches a toolbar when a node is selected. [`NodeToolbarService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-classes#nodetoolbarservice) creates, positions and hides its component instances. Bind the directive to the same engine and camera as the canvas. The sample's [`ToolbarAction`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-interfaces#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 title="src/app/rendering-tools-example.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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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 title="global stylesheet — append"
.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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/theme-diagram). For stock silhouettes with per-node fill and stroke, see the [Custom nodes demo](https://grafloria.com/demos/nodes/custom-nodes.html).

## Draw custom edges and labels with VNodes

Use [`registerLinkTemplate`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-p-w#registerlinktemplate) when changing stroke options is not enough. A [`LinkTemplate`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-types#linktemplate) receives the routed points, `pathData`, resolved styles, LOD tier and selection state. Return a [`VNode`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-types-interfaces-s-v#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-types#labeltemplate) through [`registerLabelTemplate`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-p-w#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](https://grafloria.com/demos/edges/custom-edges.html).

```ts title="src/edge-rendering.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#createforeignobject) for the latter; its [`ForeignObjectOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#foreignobjectoptions) supplies the box and children.

This browser example fills a custom node with an SVG frame containing an HTML badge. [`ContainerIdGenerator`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#containeridgenerator) supplies a stable id for this mount. [`isForeignObject`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#isforeignobject) checks the VNode type, and [`getContainerId`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#getcontainerid) reads its container id. [`VNodePatcher`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#vnodepatcher) creates the subtree; append the result to make it visible.

```ts title="src/foreign-object-rendering.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 title="isolated container-id test"
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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#svgns) is the default namespace for `createElement()`. Children of a `foreignObject` use XHTML. For repeated updates, use the instance's `patcher.reconcile()`; the exported [`reconcile`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-vnode#reconcile) uses a default patcher to mount or patch a VNode into a container.

## Adapt HTML template results to a host

Use [`HtmlTemplateRenderer`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-core-classes#htmltemplaterenderer) when integrating the engine's [`HtmlConfig`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-templates#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine)'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 title="src/template-rendering.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-core-classes#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.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `mode` | `'template' \| 'component'` | Inferred from `template`, then `component` | Selects string rendering or component-reference pass-through. |
| `template` | `string` | Unset | Supplies template markup; required for template mode. |
| `component` | `string` | Unset | Supplies the reference; required for component mode. |
| `bindings` | `Record<string, string>` | Unset | Maps variables to paths on the node; `data`, `nodeId` and `nodeUuid` are also bound. |
| `events` | `Record<string, string>` | Unset | Maps DOM event names to engine event names; attach the returned handlers. |
| `className` | `string \| string[]` | Unset | Applies one or more classes to the wrapper. |
| `style` | Declaration map | Unset | Applies inline styles to the wrapper. |
| `zIndex` | `number` | Unset | Adds the wrapper's z-index. |
| `pointerEvents` | `boolean` | `true` | `false` 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-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 title="src/svg-preview.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-a-p#hashstring) provides a stable FNV-1a hash for cache keys. [`parseInlineStyle`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-functions#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-constants#identity) is the initial matrix. [`translation`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-functions#translation), [`rotation`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-functions#rotation) and [`scaling`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-functions#scaling) build matrices; [`multiply`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-canvas-functions#multiply) composes them, applying its second argument first. `rotation()` takes degrees and can rotate about a supplied center.

### VNode properties that matter

[`VNodeProps`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-types-vnodeprops) carries geometry and presentation; these optional properties have no value until supplied by your template or consumer.

| Properties | Type | Effect |
| --- | --- | --- |
| `x`, `y`, `width`, `height` | `number` | Positions and sizes boxes. |
| `rx`, `ry` | `number` | Rounds rectangle corners. |
| `cx`, `cy`, `r` | `number` | Defines a circle's center and radius. |
| `x1`, `y1`, `x2`, `y2` | `number` | Defines a line's endpoints. |
| `d` | `string` | Supplies SVG path data. |
| `fill`, `stroke`, `strokeDasharray` | `string` | Supplies colors and dash patterns. |
| `strokeWidth`, `opacity` | `number` | Supplies stroke width and opacity. |
| `transform` | `string` | Transforms the subtree. |
| `textContent`, `fontFamily` | `string` | Supplies text and its font family. |
| `fontSize` | `number` | Supplies font size in pixels. |
| `textAnchor` | `'start' \| 'middle' \| 'end'` | Aligns text at the start, center or end of its anchor. |
| `className` | `string` | Adds space-separated CSS classes. |
| `style` | Declaration map or CSS string | Supplies inline styles. |
| `containerId` | `string` | Identifies a foreignObject container. |
| `xmlns` | `string` | Overrides the element namespace. |
| `requiredExtensions` | `string` | Supplies the SVG required-extensions attribute. |

## Choose the extension boundary

- [`InteractionController`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-interactioncontroller) handles world-space hover detection, connection dragging, endpoint reconnection and edge-editing logic; the host owns coordinate conversion and painting. [`SelectionToolsController`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-selectiontoolscontroller) supplies selection-handle geometry and commands for resizing, rotation and contextual tools without rendering them.
- [`HighlighterController`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#highlightercontroller) computes hover, selection, validation and connection-target decoration geometry independently of node visuals. [`InPlaceTextEditor`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-classes#inplacetexteditor) holds the label-editing session, its world-space bounds and the undoable commit command; your host supplies the text widget.
- [`VNodeRendererService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-services#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-interfaces-a-t#nodecomponent), returned by [`defineNodeComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-a-p#getshape) resolves geometry with a rectangle fallback. [`getInnerRect`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-a-p#getinnerrect) returns the local label box, using a padded box when the shape has no override. See [Define shapes and styles](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/shapes-markers-and-styles) for authoring that geometry.
- [`PortLayoutStrategy`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-types#portlayoutstrategy) returns node-local coordinates from the box, side, rank and count. Register it with [`registerPortLayout`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-p-w#registerportlayout). [`portWorldPosition`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-svg-functions-p-w#portworldposition) converts a port's placement into the world position used by hit-testing and endpoints. Continue with [Arrange ports and connect](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/ports-and-connection-gestures).
- [`TextKit`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#textkit) decorates an imported model before it reaches the canvas and optionally finalizes against the live instance. [`registerTextKit`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-functions#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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/import-diagram-text).

At the instance factory boundary, [`CreateDiagramOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/instance-and-lifecycle) for adoption and cleanup, and [Navigate accessible canvases](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/navigate-large-diagrams) 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 title="src/main.ts — add to existing entry"
import './style.css';
import './svg-preview';
```

## Related

- [Compute connected data](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/compute-connected-data) — update custom content from live model changes.
- [Define shapes and styles](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/shapes-markers-and-styles) — extend body geometry, markers and named styles.
- [Export images and vector PDF](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/export-diagram) — capture the diagram and its custom content.
