Vanilla Diagram

A diagram editor web component: <vn-diagram>, an SVG canvas of nodes (shapes) and connectors; <vn-diagram-palette diagram="<id>">, a palette of symbols and connector kinds linked to it by id. The two elements ship in one bundle. Its command bar, <vn-diagram-toolbar diagram="<id>">, is a component of its own: vanilla-diagram-toolbar. The user drags shapes from the palette, moves and resizes them on a grid and along guides, connects them by their ports, edits their text in place, colours them, copies and pastes, deletes, undoes and redoes, pans and zooms, by mouse, pen, touch or keyboard, and exports a picture. Every change is a command: undoable, announced by an event, and stored through the data manager as it happens.

It needs no other component and loads in any order relative to them.

The design docs are in docs/vanilla-diagram/; the process-flowchart-js sample shows an order-handling flowchart with a custom symbol set, and the plant-automation-js sample a plant's control layout drawn with three symbol sets of its own.

Features

Installation

Development (the entry script auto-loads the component's other files):

<script src="vanilla-diagram/vanilla-diagram.js"></script>

Production (npm run build writes dist/vanilla-components/latest/):

<script src="vanilla-diagram/vanilla-diagram.bundle.js"></script>

The stylesheets (vanilla-diagram.css, themes/vn-diagram-*.css) are injected by the elements, relative to their script. vanilla-diagram.d.ts ships next to the bundle.

Usage

New to the diagram? Getting started builds one step by step, with a live example at each step.

<vn-diagram-toolbar diagram="flow"></vn-diagram-toolbar>
<vn-diagram-palette diagram="flow" sets="basic flowchart" swatches="rectangle:col1 diamond:col2"></vn-diagram-palette>
<vn-diagram id="flow" theme="default" grid-size="16" style="height: 600px"></vn-diagram>
<script src="vanilla-diagram/vanilla-diagram.js"></script>
<!-- The toolbar's own script (vanilla-diagram-toolbar), in any order with the diagram's. -->
<script src="vanilla-diagram-toolbar/vanilla-diagram-toolbar.js"></script>
<script type="module">
  await window.VanillaDiagramReady;
  VanillaDiagramElement.registerSymbolSet('flowchart', [documentSymbol, databaseSymbol]);
  const diagram = document.getElementById('flow');
  await diagram.ready();
  diagram.initializeDiagram();
  diagram.setDataManager(new VanillaDiagramStaticDataManager(savedDocument));
  await diagram.loadDiagramAsync();
  diagram.addEventListener('vn-diagram-changed', (e) => console.log(e.detail.command.label));
</script>

A node is a box in world px, drawn by a symbol; a connector joins two ports, or a port and a free point:

{ id: 'a', symbol: 'diamond', x: 0, y: 0, width: 100, height: 80, text: 'Valid?',
  rotation: 0, z: 3, swatch: 'col2', style: { fill: '#fde68a' }, parent: 'lane1', data: { anything: 'the host keeps' } }
{ id: 'c1', type: 'elbow', from: { node: 'a', port: 'right' }, to: { node: 'b', port: 'left' },
  arrows: { start: false, end: true }, label: 'yes', points: [{ x: 160, y: 40 }, { x: 160, y: 120 }] }
{ id: 'c2', type: 'straight', from: { node: 'a', port: 'bottom' }, to: { x: 50, y: 200 } }

swatch names a colour slot (style wins over it); points is an edited route (an elbow's bend points, or a bezier's two control-point offsets from their ends); parent names the container the node belongs to (a node whose symbol has container: true), its x and y still in world px. A load drops a parent that names no node, a node that isn't a container, the node itself, or one in a cycle (counted in the loaded event's invalidParents).

toJSON() returns { version: 1, nodes, connectors }, nodes in z order; VanillaDiagramStaticDataManager accepts it.

Attributes

<vn-diagram> attribute Property Default
theme theme default default, default-dark, material, material-dark, fiori, fiori-dark, carbon, carbon-dark, glow, glow-dark, fluent, fluent-dark, apple, apple-dark, or a registered theme
theme-css-path themeCssPath A stylesheet URL; overrides theme
read-only readOnly off Selecting, panning and zooming only
connector-type connectorType elbow The kind a user draws next: straight, bezier, elbow
port-visibility portVisibility hover hover: the hovered node's ports; always: every node's
grid-size gridSize 0 (off) The grid's spacing in world px: dots on the canvas, and moves, resizes, nudges and drops snap to it
snap-guides snapToGuides true Moves and resizes snap to the other shapes' edges and centres, with guide lines; "false" turns it off
free-ends freeEnds off A connector end released on the empty canvas stays there; the data and the API take free ends either way
avoid-shapes avoidShapes true An elbow without edited points routes around the nodes in its way, its own end nodes included (containers aside); "false" keeps the plain elbow, which passes behind them
<vn-diagram-palette> attribute Property Default
diagram diagram A <vn-diagram>'s id; the property takes the element or an id and reads the linked element, null while unlinked
sets sets basic Space-separated set names, one group each, in order
connectors connectors true "false" hides the connector kinds
theme theme default The palette's own theme
swatches swatches Space-separated symbol:slot pairs: a listed shape's tile shows its slot and its adds take it. The property is a map, a new one each read; null or {} removes the attribute

<vn-diagram-toolbar>'s attributes, items, commands and styles are in its README.

Options (initializeDiagram(options))

Option Default
minZoom, maxZoom 0.1, 4 The zoom limits
historyLimit 100 Undo steps kept; 0 keeps none
locale the page's lang, then the browser's Picks the message bundle
messages Overrides of single messages
logger console false or null silences the diagram

Methods

Method
ready() Resolves once the scripts and stylesheets are loaded
initializeDiagram(options?) Builds the canvas, empty. A second call is a no-op with a warning
destroy() Removes the canvas, drops the manager and the pending saves
setDataManager(dm), getDataManager() Setting one aborts a load, the save in flight and the queue; the model keeps its changes
setAutoReloadOnConfigChange(enabled) Reload when the manager fires onConfigChanged
loadDiagramAsync() Waits for pending saves, fetches, builds and validates the new model in slices, swaps it in, clears the selection and the history, and zooms to fit unless the host set a viewport since initializeDiagram(); resolves once what is in view is drawn. Last call wins
reloadDataManager() reset(), then loadDiagramAsync()
hasPendingSaves(), whenSaved() The save queue
toJSON() A deep copy of the model
getNode(id), getNodes(), getConnector(id), getConnectors(), getConnectorsOf(nodeId) Copies
addNode(node) The new id; null for an unknown symbol or an id in use. Undoable, as every mutation
updateNode(id, patch), updateConnector(id, patch) False for an unknown id or an invalid patch. updateNode(id, { parent }) refuses a node that can't hold it (not a container, the node itself, a descendant); parent: null makes it top-level
addConnector(connector) The new id; null when an end doesn't resolve or both ends are the same port. type defaults to connectorType
removeItems(ids) Removes nodes and connectors, a removed container's descendants, and the removed nodes' connectors; returns how many
deleteSelection() Deletes the selection (a container with what it holds) as the Delete key does: vn-diagram-removing first, then one undo step. Returns how many items it removed; 0 while read-only, with nothing selected or when cancelled
setSwatch(slot, ids?) Gives the nodes ids (default the selected ones) colour slot slot, null to clear it, as one undo step. False for a bad slot name or when no node changes
getNodeCount() The number of nodes, without copying them
isInitialized() True between initializeDiagram() and destroy()
isBusy() True from the start of a load or a layout() until what it changed is drawn in its final place in view (for layout(), after its promise resolves), and while toSVG() or toPNG() runs (one of 1,000 or more items empties the canvas under the overlay and runs until it is drawn again). Meanwhile the canvas refuses every user input, as if disabled: no pointer, touch or key gesture (selecting, the rubber band, panning and zooming included), no wheel zoom, no clipboard key, no text editor, and the palette's tiles and connector kinds are off; every API call still works. The element has the class vn-diagram--busy meanwhile
transaction(label, fn) The calls fn makes become one undo step and one change set; a throw reverts them and rethrows, a nested call joins the outer one, and undo()/redo() return false while fn runs
getSelectedIds(), setSelectedIds(ids), clearSelection()
undo(), redo(), canUndo(), canRedo(), clearHistory() False when there is nothing to do, or read-only
getViewport(), setViewport({ x, y, zoom }), zoomBy(factor, at?), zoomToFit(padding = 24), scrollToNode(id) { x, y } is the world point at the canvas's top-left corner
getZoomLimits() { min, max } from minZoom and maxZoom
editText(id) Opens the text editor on a node or a connector. False when read-only, unknown, or cancelled
copy(), cut(), duplicate() The selected nodes, a selected container's descendants, and the connectors whose ends are all among them. False when nothing is selected. cut() fires vn-diagram-removing first
paste() A promise: the page's clipboard, else the system one where the browser allows reading it (it may prompt). New ids, 16px from the previous paste
bringToFront(ids?), sendToBack(ids?) Default the selected nodes; one undo step. False when the order doesn't change
toSVG({ ids, padding, background }?) A promise of a standalone SVG string, the container frames first, the routes as drawn, a listed container with its descendants: no adorners, theme values written in, each text as HTML with an SVG <text> fallback for viewers that draw no HTML (GIMP). padding 24, background the canvas's (null: transparent). Its width and height are the box's, scaled down to at most 32,767 px a side (GIMP's librsvg opens nothing larger); the viewBox keeps the whole drawing. Built in slices under the 'export' busy job (the overlay shows for an export longer than one slice), after an open text edit is committed (not while a load runs). Like layout(), it ends a gesture the user has in progress (a drag goes back). It rejects when the diagram is destroyed, another diagram is loaded or the element leaves the page meanwhile
toPNG({ ids, padding, background, scale }?) A promise of a PNG Blob, at scale (default devicePixelRatio), or at the largest scale under it the browser gives a canvas for (the PNG's size tells which); built as toSVG() is
layout({ kind, direction, spacing }?) Arranges every node: kind 'layered' (default) or 'tree', direction 'down' (default), 'right', 'up' or 'left', spacing { node, layer } (40 and 80 world px). Containers inside out, the ports of moved connectors chosen again to face each other, a shape with one connector on the side of a step beside it, edited routes of moved ends cleared, free ends moved with their node, the grid kept; one undo step, one change set; a second call moves nothing. A promise of whether a node moved: false for an empty diagram, an unknown kind or direction, or when a change, a load or another layout() came first. Works in read-only mode

Before initializeDiagram() the element draws nothing and every method is a safe no-op: getters return null or [] (getNodeCount() 0, isInitialized() and isBusy() false), mutations null, false or 0, toJSON() an empty document, getViewport() { x: 0, y: 0, zoom: 1 }, getZoomLimits() { min: 0.1, max: 4 }, paste() and layout() resolve false, toSVG() resolves with an empty <svg>. loadDiagramAsync() and toPNG() reject then, and loadDiagramAsync() whenever no manager is set.

API mutations work in read-only mode: the host is the caller. They fire vn-diagram-changed but no cancelable event. deleteSelection() is the exception by design: it deletes as the Delete key does.

Statics

VanillaDiagramElement.SUPPORTED_THEMES, getSupportedThemes(), registerTheme(name, cssPath) Themes, page-wide
VanillaDiagramElement.getThemeHref(name) The stylesheet URL a theme name resolves to: registered, built in, else the default's
VanillaDiagramElement.SUPPORTED_SWATCHES The colour slots, col1 to col10
VanillaDiagramElement.registerSymbol(symbol) False, registering nothing, for an invalid symbol or a taken name
VanillaDiagramElement.registerSymbolSet(name, symbols, { label }) Definitions are registered with the set; names must be registered. Registering a name again replaces the set, except basic
VanillaDiagramElement.getSymbol(name), getSymbolSets() The registry
VanillaDiagram.registerLocale(name, messages), getLocaleMessages(name), defaultLocale Messages

Symbols

{
  name: 'document',                     // unique on the page
  label: 'Document',                    // default: the symbol.<name> message, else the name
  defaultSize: { width: 120, height: 70 },
  minSize: { width: 16, height: 16 },   // the default
  lockAspect: false,                    // true: resizing keeps the ratio
  path: (w, h) => 'M0 0H' + w + '...',  // or render: (w, h, node) => svgElement
  ports: [{ id: 'top', x: 0.5, y: 0, side: 'top' }, ...],   // default: the four side midpoints
  textBox: { x: 0, y: 0, width: 1, height: 0.8 },           // fractions of the box; maxHeight (px) caps the height
  container: false,                     // true: other nodes may name it as their parent
}

A container draws under the connectors and is picked by its border and its text box (its label band); a click inside it reaches the shapes it holds, or the canvas. Moving it moves its descendants; at a move's release, a node joins the container under its centre, or leaves its own; a palette drop and a paste join the same way. Its resize stops at its children, and removing it removes them.

A render callback is called when the node is drawn and when its size, text or data changes; an exception is logged and the node drawn as a rectangle. Either form may paint with the theme's tokens (fill: var(--vn-diagram-node-fill)). A node whose symbol isn't registered yet is drawn as a rectangle and redrawn once it is.

Data managers

Class
VanillaDiagramDataManager Base class: fetchNodes({ signal }), fetchConnectors({ signal }), saveChanges(changeSet, { signal }) (read-only: rejects), reset(), destroy(), onConfigChanged
VanillaDiagramStaticDataManager In memory, as copies: setNodes(), setConnectors(), getNodes(), getConnectors(); saveChanges() applies adds, updates and removals, and rejects whole on an unknown id. A version above 1 throws unsupported-version

A change set is one command's changes: { nodes: { added, updated, removed }, connectors: { added, updated, removed } }, updated holding whole items after the change, removed their ids.

Events

Named in window.VanillaDiagramEvents; all fire on <vn-diagram>, bubble and are composed. The toolbar's command event is in its own component's registry, VanillaDiagramToolbarEvents.

Event Detail
vn-diagram-loading {}
vn-diagram-loaded { nodeCount, connectorCount, skipped: { unknownSymbols, duplicateIds, danglingConnectors, invalidParents } }
vn-diagram-error { error }, when a load fails; the previous model stays
vn-diagram-busy-changed { busy, reason }, when isBusy() or the reason ('loading', 'layout', 'export', the newest job; null when not busy) changes, around every export too; never after destroy()
vn-diagram-changed { command: { kind, label, ids }, source }, after a command is executed, undone or redone. source: pointer, keyboard, palette, api (a toolbar command too), undo, redo
vn-diagram-saved { command, source }, when the manager has stored a change
vn-diagram-save-failed { error, code: 'manager-rejected', reverted }; reverted lists the reverted changes, newest first
vn-diagram-history-changed { canUndo, canRedo }
vn-diagram-selection-changed { selectedIds }
vn-diagram-node-adding { node, source }; cancelable, before the user adds a node. The host may set node.id, node.text, node.data, node.swatch, node.style; node.parent names the container it is dropped in
vn-diagram-connecting { connector, from, to, type, reconnect }; cancelable, before the user connects or reconnects. For a new connector the host may set connector.id, connector.data
vn-diagram-removing { ids }; cancelable, before the user deletes; ids lists a selected container's descendants too
vn-diagram-node-dblclick { node }
vn-diagram-connector-dblclick { connector }
vn-diagram-viewport-changed { x, y, zoom }, at most once per frame
vn-diagram-text-editing { target, id, source }; cancelable, before the text editor opens (target: node or connector)
vn-diagram-pasting { nodes, connectors, source }; cancelable, before a paste or a duplicate adds its items, new ids assigned. The host may change text, data, swatch

Keyboard

With focus on the canvas (one tab stop):

Key Nothing selected A selection
Arrows Pan 40px Select the nearest node in that direction (from the anchor while a walked connector is selected)
Shift + arrows Pan 40px Move the selection (a container with what it holds) 10px, or to the next grid line with a grid (Shift + Alt: 1px, unsnapped), one undo step per burst
Ctrl/Cmd + Shift + arrows Resize the one selected node by 10px
Delete, Backspace Remove
Ctrl/Cmd + Z; Ctrl/Cmd + Shift + Z, Ctrl + Y Undo; redo Undo; redo
Ctrl/Cmd + A Select every node Select every node
Enter, F2 Edit the focus node's text, else the selected connector's label
Ctrl/Cmd + C, X, V, D Paste (V) Copy, cut, paste, duplicate
Ctrl/Cmd + Shift + ], [ Bring to front, send to back
+, -, 0, 1 Zoom in, out, to fit, to 100% The same
C Connect mode: arrows pick the target, Enter connects
R, Shift + R Turn the selected nodes 15 degrees clockwise, counter-clockwise (a container doesn't turn)
N, P Select the focus node's next or previous connector, clockwise from 12 o'clock; the node becomes the anchor
J Select the walked connector's other end
Escape Cancel a gesture or connect mode, else back from a walked connector to its anchor, else clear the selection

A screen reader hears each keyboard selection, connection and change through a live region; the canvas is role="application" (its shapes aria-hidden), described by the keys, and a hidden outline after it lists the nodes and their connections for browse mode.

In the text editor: Enter commits, Shift + Enter adds a line, Escape cancels, Tab commits; no key reaches the diagram.

The palette is one tab stop too: arrows move between the tiles, Home and End go to the first and the last, Enter or Space adds the symbol. The toolbar's keys are in its README.

Theming

theme="default-dark" loads themes/vn-diagram-default-dark.css, which styles the diagram, the palette and <vn-diagram-toolbar> (whose own variant tokens are listed in its README). Every colour, width and the node font come from custom properties the theme sets on .vn-diagram, .vn-diagram-palette and .vn-diagram-toolbar: --vn-diagram-bg, --vn-diagram-node-fill, --vn-diagram-node-stroke, --vn-diagram-node-stroke-width, --vn-diagram-node-text-color, --vn-diagram-node-font, --vn-diagram-connector-color, --vn-diagram-connector-width, --vn-diagram-port-fill, --vn-diagram-port-stroke, --vn-diagram-port-active-fill, --vn-diagram-selection-color, --vn-diagram-handle-fill, --vn-diagram-rubber-band-bg, --vn-diagram-focus-ring, --vn-diagram-message-color (the error text, and the busy overlay's label and spinner), --vn-diagram-busy-scrim and --vn-diagram-busy-bg (the busy overlay's scrim and box), --vn-diagram-palette-bg, --vn-diagram-palette-heading-color, --vn-diagram-palette-tile-bg, --vn-diagram-palette-tile-hover-bg, --vn-diagram-palette-tile-pressed-bg, --vn-diagram-grid-color, --vn-diagram-guide-color, --vn-diagram-error-color (the toolbar's error status), --vn-diagram-group-fill and --vn-diagram-group-stroke (a container's frame, in place of the node fill and stroke), and per colour slot --vn-diagram-swatch-<slot>-fill, --vn-diagram-swatch-<slot>-stroke and --vn-diagram-swatch-<slot>-text for col1 to col10. The toolbar paints with the palette's tokens and its own. A node's style sets the node properties on its own group, so it wins over the theme and over its swatch.

Colour slots. swatch: 'col3' on a node (or a palette's swatches map, or the toolbar's colour menu) puts data-swatch="col3" on its group, and the base stylesheet maps it to the slot's tokens. Each theme colours the ten slots its own way (the Material, Fiori, Carbon, Fluent and Apple themes from their design system's own colour palette), so a theme switch can change a shape's hue. A host adds a swatch of its own with one rule: [data-swatch="brand-red"] { --vn-diagram-node-fill: #c00; }; a name nothing styles draws in the theme's colours.

The built-in themes are the grid's seven families, each light and dark: default (the purple accent, rounded corners), material (Google Blue, 8px corners, Roboto), fiori (SAP Quartz, Fiori Blue, square corners, the 72 font), carbon (neutral shapes, IBM Blue selection and ports, square corners, IBM Plex Sans), glow (neutral shapes, the indigo accent, 12px corners, Inter), fluent (Fluent 2, communication blue, 4px corners, Segoe UI) and apple (system colours, systemBlue, 10px corners, SF Pro), and the -dark twin of each. Like the grid's, they name the design system's font first in --vn-diagram-node-font and load no font file: load it on the page to get it, otherwise the text falls back to the next family in the list (Helvetica, Arial or the system font). Set the same theme on the palette, which picks its own. A custom theme is a stylesheet that defines the tokens above on the same selectors, registered with VanillaDiagramElement.registerTheme(name, cssPath); process-flowchart-js registers a Ledger theme of its own that way. Themes are page-global, as the grid's and the Gantt's are. Under forced-colors: active shapes, container frames, connectors, selection, ports, handles and focus take system colours, and swatches and node styles drop.

Messages

English is built in; VanillaDiagram.registerLocale(name, messages) adds a language. Keys: diagramLabel, paletteLabel, connectorsLabel, loading, arranging (the busy overlay's label during layout()), exporting (during toSVG() and toPNG()), loadError, textPlaceholder, nodeLabel ({symbol}, {text}), symbolSet.<name>, symbol.<name>, connectorType.<kind>, command.<kind> ({count}) for each command kind, and command.editText, command.paste, command.duplicate, command.route, command.bringToFront, command.sendToBack, command.swatch, command.rotate, command.layout; textEditorLabel; and for screen readers nodeConnections, connectorDescription, connectorDescriptionLabelled, freeEnd, announceConnection, announceMoved, announceConnected, announceUndone, announceRedone, announceSaveFailed, announceConnectMode, announceTarget, announceDiagram, keyboardHint, outlineLabel, outlineTooLarge, outlineTo, outlineFrom. The toolbar's labels are its own (setMessages(), in its README).

File structure

vanilla-diagram/
  vanilla-diagram.js               core class (the load's swap, the route pass, layout()), locale registry, logger, dev auto-loader
  vanilla-diagram-events.js        VanillaDiagramEvents
  vanilla-diagram-element.js       <vn-diagram>
  vanilla-diagram-palette.js       <vn-diagram-palette>
  features/
    geometry.feature.js            viewport transform, rotated frames, ports, resizing
    symbols.feature.js             symbol and set registry, the basic set
    model.feature.js               nodes, connectors, the index, validation, change sets
    commands.feature.js            commands, undo and redo history
    save-queue.feature.js          saves in order, reverts on failure
    routing.feature.js             straight, bezier and elbow paths, edited routes, free ends
    spatial-index.feature.js       a uniform grid of buckets over world boxes
    orthogonal-router.feature.js   the obstacle index, elbows routed around shapes
    snapping.feature.js            grid and guide snapping
    layout.feature.js              the layered and the tree layouts
    rendering.feature.js           SVG layers, culling, write pass, adorners, the route cache
    groups.feature.js              containers: frame order, joining, the resize clamp
    viewport.feature.js            pan, zoom, wheel zoom, fit
    interaction.feature.js         pointer and touch gestures, the rotation handle
    keyboard.feature.js            keys, nudges, rotation, connect mode
    text-editing.feature.js        the in-place text editor
    clipboard.feature.js           copy, cut, paste, duplicate
    export.feature.js              toSVG(), toPNG()
    accessibility.feature.js       the announcer, walking connections, the outline
  data-managers/
    diagram-data-manager.js        VanillaDiagramDataManager
    static-diagram-data-manager.js VanillaDiagramStaticDataManager
  vanilla-diagram.css              structure
  themes/                          vn-diagram-<name>.css, vn-diagram-<name>-dark.css for
                                   default, material, fiori, carbon, glow, fluent, apple
  vanilla-diagram.d.ts             hand-authored TypeScript declarations

Changelog

Version 1.3.0

Version 1.2.0

Version 1.1.0

Version 1.0.0