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
- The
basicset: rectangle, rounded rectangle, ellipse, circle, diamond, triangle, text and group (a container), each with four ports. - Custom symbols and sets, declarative (an SVG path of the node's size) or drawn by a callback, registered page-wide and shown by the palette as groups.
- Connectors between two ports: straight, bezier or elbow, with
arrowheads and an optional label; drawn by a drag from a port, or a click on
one port and then another; reconnected by dragging a selected connector's
end. An elbow's segments and a bezier's control points can be dragged; with
free-ends, an end can rest on the empty canvas. - Elbows route around shapes (
avoid-shapes, on by default): an elbow finds a path around the nodes in its way, its own end nodes included, when one exists, keeps the plain elbow when nothing is in its way, and routes again when a node moves across it or away from it. - Select, move, resize: click, Ctrl/Cmd-click, Shift-click, a rubber band; a drag previews without touching the model and commits one command; eight resize handles in the node's own frame, rotated nodes included.
- Rotate a node by its rotation handle (Shift: 15 degree steps) or by
Rand Shift +R. - Containers: nodes of a container symbol (the
basicset'sgroup, a host's lane) hold other nodes through theirparent; they draw under the connectors, nest, move and are removed with what they hold, and a node dropped in one joins it. - Snapping to a grid (
grid-size) and to guides along the other shapes, on move, resize, nudge and drop; Alt turns it off for a drag. - Zoom by wheel, trackpad pinch and keys; pan by a right- or
middle-button drag (the canvas has no browser context menu), one finger,
two-finger pinch and keys;
zoomToFit(). - Undo and redo of every change, gestures and API calls alike, by keys and
by API;
transaction()groups calls into one step. - A data manager: two fetches and one atomic
saveChanges()per command, in order, optimistic; a rejected save reverts that change and every later one and restores the history.VanillaDiagramStaticDataManagerbuilt in. - Cancelable events before a user adds, connects, removes, edits text or pastes.
- Wrapped text in nodes, HTML in a
<foreignObject>, edited in place (double-click, Enter, F2), with newlines. - Copy, cut, paste, duplicate by keys and API, within a diagram, between diagrams on a page and between pages.
- Bring to front, send to back.
- Ten colour slots,
col1tocol10, that each theme colours its own way; a palette gives each of its shapes one. - Export as SVG (
toSVG()) and PNG (toPNG()). - A toolbar,
<vn-diagram-toolbar>, in its own component (vanilla-diagram-toolbar): written in markup, standard and custom commands, four button styles. It reads the diagram through the public methods below. - The keyboard: one tab stop, arrow-key selection, nudges, keyboard
resize, rotation, connect mode, walking a node's connectors (
N,P,J); every drag has a non-drag alternative. - Large diagrams: 100,000 nodes and 100,000 connectors pan, zoom and drag
within 16ms a frame. Only what meets the view (and a margin) is in the
DOM, so a host's code or CSS can't expect one
.vn-diagram-nodeper node; below zoom 0.4 text, labels and ports hide; the load builds the model in slices. - Screen readers: the canvas is an application whose shapes are out of the accessibility tree; a live region says what the keys and the changes did, and a hidden outline lists the nodes and their connections (up to 10,000) for browse mode.
- Auto-layout:
layout()arranges the diagram as layers or as a tree, in four directions, containers inside out, as one undo step; moved connectors get the ports that face each other, and a shape hanging off the side of a step stays beside it; the toolbar's Tidy up. - A busy state: while a load or a layout runs, and until its drawing in
view is final, and while an export runs,
isBusy()is true, the canvas refuses every user input (selecting, panning and zooming too; the API still works) and a spinner overlay with a label covers the canvas;vn-diagram-busy-changedand thevn-diagram--busyclass follow it. - Fourteen themes, the grid's seven families light and dark (
default,material,fiori,carbon,glow,fluent,apple, each with its-darktwin), custom themes, and forced colours.
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
- Added (
vanilla-diagram) - ten built-in themes, so the diagram now ships the grid's seven families light and dark:material,fiori,glow,fluentandapple, each with its-darktwin, besidedefaultandcarbon(VanillaDiagramElement.SUPPORTED_THEMES, thethemeattribute). Each names its design system's font first in--vn-diagram-node-fontand loads no font file; the Material, Fiori, Carbon, Fluent and Apple themes colour the ten swatch slots from their design system's palette. - Added (
vanilla-diagram) -textBox.maxHeighton a symbol (VanillaDiagramSymbol): a cap, in px, on the text box's height, so a label band along the top of a tall container stays a band. The built-ingroupcaps its band at 30 px (15% of its height up to 30 px);layout()keeps the capped band clear, so a long column of children no longer leaves a large empty band. - Changed (
vanilla-diagram) - withavoid-shapes, an elbow now routes around the nodes in its way, its own end nodes included: a stub that would end inside its own node's padded box (a port inside the node's box, or a port of a rotated node) runs on to the padded edge before the route bends, and a neighbour closer than two stubs stays an obstacle with its padding cut toward the stub end, so the route passes it but never through it. When no route is found that way, the router tries once more by a looser rule before falling back to the plain elbow. - Fixed (
vanilla-diagram) - facing ports closer than two stubs (32 px) no longer loop back: the stubs meet on one line across the gap (halfway, or leaving the target its 10 px arrowhead), so the elbow crosses straight or with one jog (VanillaDiagramRouting.facingTargetStub()). A 16 px stub with another shape straight ahead closer than 32 px ends halfway to it. - Fixed (
vanilla-diagram) - an edited elbow route (points) no longer turns back at an end when a node moves or rotates: a stored end point slides along its segment to the moved stub, a join that would still turn back is the plain elbow into the stored end segment, a stored end point on its port is skipped, and a single stored point (an L) falls back to the plain elbow while its route would turn back. The storedpointsstay as they are. - Maintenance -
process-flowchart-jsandplant-automation-jsoffer the fourteen themes;process-flowchart-jsregisters a Ledger theme of its own (registerTheme(),themes/vn-diagram-ledger.cssandthemes/app-ledger.css) and caps its lanes' label band at 40 px; the connect, reconnect and connect-mode previews pass each end's node to the router;docs/vanilla-diagram/updated (themes, routing around shapes, ports and connectors, containers, symbols, auto-layout); diagram node and Playwright tests extended (routing, orthogonal router, layout, symbols, rotation, groups, render, plant-automation smoke).
Version 1.2.0
- Changed (
vanilla-diagram) - breaking fortoSVG()callers:toSVG()now returns aPromise<string>(beforeinitializeDiagram()it resolves with the empty<svg>).toSVG()andtoPNG()build in slices that yield to the page, so a large export no longer freezes it; with 1,000 or more items they hold the drawing (the canvas empties under the overlay) and draw it again before they settle. They commit an open text edit, end a gesture in progress, and reject when the diagram is destroyed, another diagram is loaded or the element leaves the page meanwhile. - Added (
vanilla-diagram) - an'export'busy reason (VanillaDiagramBusyReason,vn-diagram-busy-changed):isBusy()is true whiletoSVG()ortoPNG()runs, with the newexportingmessage (Exporting...) on the overlay. - Changed (
vanilla-diagram) -toSVG()'s rootwidthandheightare scaled down to at most 32,767 px a side (GIMP's librsvg opens nothing larger), theviewBoxkeeps the whole drawing;toPNG()draws at the largest scale underscalethe browser gives a canvas for, instead of failing. - Changed (
vanilla-diagram) - while busy, the canvas refuses every user input, as if disabled: selecting, the rubber band, panning, wheel and pinch zoom and every key included (Tab still leaves); the palette's connector kinds are off too. A copy or cut refused while busy (or a cut while read-only) no longer lets the browser's own copy run in its place. The busy overlay now shows as soon as a job begins (no half-second delay), over a more opaque scrim (--vn-diagram-busy-scrimin the four themes). - Added (
vanilla-diagram) - a reconnect drag previews the connector in flight: dashed, with its own type, arrows and edited route, from its fixed end to the target port or the pointer, the connector itself hidden meanwhile. - Fixed (
vanilla-diagram) - a change, undo, redo or reverted save that removes what a drag acts on (a reconnect's or a route's connector, a connect's source, a resized or rotated node, every moved node) now ends that drag; a connect drag snapped to a removed port looks for its target again, and connect mode ends with its source or drops a removed target. Connect mode and a connect or reconnect drag no longer run at once. - Maintenance -
process-flowchart-jsreplaces its Reload command with Reset (restores the initial plan) and fits up to 10,000 shapes in view (minZoom0.02);docs/vanilla-diagram/updated; diagram Playwright specs extended (busy, connect, export, large, performance).
Version 1.1.0
- Added (
vanilla-diagram) - a busy state:isBusy()is true from the start ofloadDiagramAsync()(andreloadDataManager()) orlayout()until what it changed is drawn in its final place in view (forlayout(), after its promise resolves). Thevn-diagram-busy-changedevent ({ busy, reason }, reason'loading'or'layout', theVanillaDiagramBusyChangedDetailtype) and thevn-diagram--busyclass follow it. After half a second a spinner overlay with a label covers the canvas: theloadingmessage, or the newarrangingmessage (Arranging shapes...) duringlayout(), styled by the new--vn-diagram-busy-scrimand--vn-diagram-busy-bgtokens in every theme. - Changed (
vanilla-diagram) - while busy, user edits (pointer, keyboard, clipboard, the text editor, the palette) are refused as in read-only mode, Ctrl+Z and Ctrl+Y included, and the palette dims at once; every API call still works. A text editor already open when a load begins stays open, so a load still closes it without committing. - Fixed (
vanilla-diagram) -layout()over many containers: each connector is now placed at its level in one pass, so the cost grows with the connectors times the nesting depth instead of the containers times the connectors. At 100,000 shapes in 1,000 lanes,layout()resolves in 2.5 to 3.5s. - Maintenance -
process-flowchart-jsdrops its own "Reloading..." status for the busy overlay;docs/vanilla-diagram/updated; repository testing:npm run test:affected(scripts/run-affected.js, only the Playwright specs a branch's changes reach) andscripts/run-with-progress.js(desktop progress notifications for a test run) added.
Version 1.0.0
- Added (
vanilla-diagram) - first release: the<vn-diagram>custom element, an SVG canvas of nodes and connectors, and<vn-diagram-palette diagram="<id>">, a palette of symbols and connector kinds linked to it by id, in onevanilla-diagram.bundle.jswith hand-authoredvanilla-diagram.d.tsand four themes (default,default-dark,carbon,carbon-dark). Needs no other component. - Added (
vanilla-diagram) - shapes and symbols: thebasicset (withgroup, a container), custom symbols and sets registered page-wide, declarative or drawn by a callback (VanillaDiagramElement.registerSymbolSet()), and ten colour slots (col1tocol10). - Added (
vanilla-diagram) - connectors (straight, bezier, elbow) with arrowheads, labels, editable routes,free-endsand elbows routed around shapes (avoid-shapes); selection, move, resize, rotation, containers, snapping to a grid (grid-size) and to guides; text edited in place; copy, cut, paste and duplicate; z-order; SVG and PNG export (toSVG(),toPNG()). - Added (
vanilla-diagram) - undo and redo of every change,transaction(), a data manager that stores each change as it happens and reverts a rejected save (VanillaDiagramStaticDataManagerbuilt in), and cancelable events before a user adds, connects, removes, edits or pastes. - Added (
vanilla-diagram) -layout(): layered and tree layouts in four directions, containers inside out, one undo step. - Added (
vanilla-diagram) - the keyboard (one tab stop, arrow-key selection, nudges, resize, rotation, connect mode), screen-reader announcements and outline, forced-colours support, and large diagrams (100,000 nodes and connectors drawn only where in view). - Maintenance -
docs/vanilla-diagram/added;build.jsbundles and ships the component;process-flowchart-jsandplant-automation-jssamples and the getting-started pages added; iterative tuning and fixing of snapping, selection box, connectors, export, toolbar and samples.