Birch UI v0.1
Pricing

Node templatesDiagram

Define custom node types with their own size, ports and shape, render them as SVG or as HTML in the HTML layer, and make them export cleanly.

Open .md

Built-in shapes cover classic flowcharts. For anything richer, such as an org chart with photos, a network map with status lights or a workflow step with an assignee, register a node type with a render function.

Register a node type#

nodeTypes maps a type name to a NodeTypeDefinition. Nodes use it through type:

TypeScript
import { createDiagram, type DiagramNode } from '@birchui/diagram';

interface Employee {
  title: string;
  department: string;
}

const diagram = createDiagram<Employee>(container, {
  nodeTypes: {
    person: {
      label: 'employee',
      defaultSize: { width: 220, height: 64 },
      ports: [
        { id: 'top', side: 'top' },
        { id: 'bottom', side: 'bottom' },
      ],
      render(node, ctx) {
        const card = ctx.document.createElement('div');
        card.className = ctx.isSelected ? 'person-card person-card--selected' : 'person-card';
        const name = ctx.document.createElement('strong');
        name.textContent = node.label ?? '';
        const title = ctx.document.createElement('span');
        title.textContent = `${node.data?.title}, ${node.data?.department}`;
        card.append(name, title);
        return card;
      },
    },
  },
  defaultNodeType: 'person',
  nodes: [
    { id: 'e1', x: 0, y: 0, label: 'Maria Lopez', data: { title: 'Chief Executive Officer', department: 'Executive' } },
    { id: 'e2', x: 0, y: 0, label: 'Daniel Okafor', data: { title: 'VP Engineering', department: 'Engineering' } },
    { id: 'e3', x: 0, y: 0, label: 'Hannah Schmidt', data: { title: 'VP Operations', department: 'Operations' } },
  ],
  edges: [
    { id: 'e1-e2', source: { node: 'e1', port: 'bottom' }, target: { node: 'e2', port: 'top' } },
    { id: 'e1-e3', source: { node: 'e1', port: 'bottom' }, target: { node: 'e3', port: 'top' } },
  ],
});

await diagram.layout({ type: 'tree', direction: 'TB' });
CSS
.person-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
  padding: 8px 12px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  background: #ffffff;
  font: 13px/1.3 system-ui, sans-serif;
}

.person-card--selected {
  border-color: #2563eb;
  box-shadow: 0 0 0 2px rgb(37 99 235 / 0.25);
}
Field Description
render(node, ctx) Returns an SVGElement or an HTMLElement for the node's content. Optional: without it the type draws its shape.
defaultSize { width, height } for nodes of this type that have no size of their own. Defaults to 160 × 64.
ports Default ports for nodes of this type. Defaults to one in the middle of each side. A node's own ports replace them.
shape 'rect', 'ellipse' or 'diamond'. Used where the diagram needs geometry: straight edges end at this outline, and it is drawn when render is missing, throws or cannot be exported. Defaults to 'rect'.
isContainer true makes nodes of this type groups that can hold children.
resizable false hides resize handles for this type. A node's own resizable wins.
label The type's name for people, such as 'employee'. It is part of each node's accessible name and of the list view.

A node whose type is unknown is drawn with the default type, with one warning per unknown name. defaultNodeType (default 'rounded') may also name one of your own types.

The render context#

render receives the node and a context:

Field Description
width, height The node's current size. Fill this box.
isSelected Whether the node is selected, so you can style it.
isExport true when the call comes from toSVG() or toPNG().
document The document to create elements with. Use it instead of the global document so templates work in iframes and tests.

The template runs again whenever the node changes (position, size, label, data or style), when its selection state changes, and when you replace nodeTypes with update(). Keep it fast and free of side effects; build the element from node and ctx alone.

If render throws, the error is logged and the node falls back to its shape, so one broken template never takes the diagram down.

SVG templates#

Return an SVG element when the node is mostly shapes and text. It is placed in the node's group in the SVG scene, so it shares z-order with built-in nodes and exports exactly as drawn.

TypeScript
const SVG_NS = 'http://www.w3.org/2000/svg';

const statusColors = { healthy: '#16a34a', degraded: '#d97706', down: '#dc2626' } as const;

createDiagram<{ status: keyof typeof statusColors; ip: string }>(container, {
  nodeTypes: {
    server: {
      label: 'server',
      shape: 'rect',
      defaultSize: { width: 180, height: 56 },
      render(node, { width, height, document }) {
        const g = document.createElementNS(SVG_NS, 'g');
        const box = document.createElementNS(SVG_NS, 'rect');
        box.setAttribute('width', String(width));
        box.setAttribute('height', String(height));
        box.setAttribute('rx', '6');
        box.setAttribute('class', 'server-box');
        const light = document.createElementNS(SVG_NS, 'circle');
        light.setAttribute('cx', '18');
        light.setAttribute('cy', String(height / 2));
        light.setAttribute('r', '6');
        light.setAttribute('fill', statusColors[node.data?.status ?? 'healthy']);
        const name = document.createElementNS(SVG_NS, 'text');
        name.setAttribute('x', '34');
        name.setAttribute('y', String(height / 2 - 4));
        name.textContent = node.label ?? '';
        const ip = document.createElementNS(SVG_NS, 'text');
        ip.setAttribute('x', '34');
        ip.setAttribute('y', String(height / 2 + 12));
        ip.setAttribute('class', 'server-ip');
        ip.textContent = node.data?.ip ?? '';
        g.append(box, light, name, ip);
        return g;
      },
    },
  },
});

Update the status from your monitoring feed with updateNode(id, { data: { ...node.data, status: 'down' } }); the template re-renders that one node.

HTML templates and the HTML layer#

Return an HTML element for content that benefits from normal CSS layout: cards, avatars, badges, progress bars, even small forms. HTML content is drawn in an absolutely positioned HTML layer above the SVG scene. The layer has the same translate(x, y) scale(zoom) transform as the scene, so the two stay aligned while users pan and zoom.

The diagram uses this layer rather than SVG foreignObject because HTML inside foreignObject renders inconsistently across browsers (most visibly in Safari with zoomed content), because a separate layer keeps normal focus, text selection and inputs, and because plain elements are cheaper to mount and unmount while scrolling.

What to know:

  • Z-order: HTML content always sits above SVG nodes. Edges sit under all nodes either way.
  • Wrapper: each HTML node is wrapped in a div.lq-diagram-html-node with data-node-id, sized to the node. While selected it has lq-diagram-html-node--selected.
  • Interactive content: pointer events on input, textarea, select, button, links and contenteditable elements inside a template go to those elements and do not start a drag, and keys typed into them do not trigger diagram shortcuts.
  • Ports are drawn on top of HTML nodes and appear on hover and while connecting.

A task card with a checkbox:

TypeScript
const diagram = createDiagram<{ assignee: string; isDone: boolean }>(container, {
  nodeTypes: {
    task: {
      label: 'task',
      defaultSize: { width: 240, height: 72 },
      render(node, ctx) {
        const card = ctx.document.createElement('label');
        card.className = 'task-card';
        const done = ctx.document.createElement('input');
        done.type = 'checkbox';
        done.checked = node.data?.isDone ?? false;
        done.addEventListener('change', () => {
          diagram.updateNode(node.id, { data: { ...node.data!, isDone: done.checked } });
        });
        const text = ctx.document.createElement('span');
        text.textContent = `${node.label} (${node.data?.assignee})`;
        card.append(done, text);
        return card;
      },
    },
  },
});

Templates and export#

toSVG() and toPNG() call render again with isExport: true:

  • SVG content is written into the export as it is.
  • HTML content is written into SVG exports as foreignObject, unless you pass includeHtml: false.
  • PNG exports never include HTML, because drawing foreignObject onto a canvas would taint it. HTML nodes fall back to their shape with the node's label.

For exports that look the same as the screen, return SVG when ctx.isExport is true:

TypeScript
createDiagram<Employee>(container, {
  nodeTypes: {
    person: {
      defaultSize: { width: 220, height: 64 },
      render: (node, ctx) => (ctx.isExport ? personSvg(node, ctx) : personCard(node, ctx)),
    },
  },
});

Next steps#

↑ ↓ to move, Enter to open, Esc to close