Vanilla Diagram Technical Docs
Implementation-focused documentation for <vn-diagram>, an SVG canvas of
nodes (shapes) and connectors that the user edits by pointer, touch and
keyboard; and <vn-diagram-palette>, a palette of symbols and connector kinds
linked to a diagram by id. The two elements ship in one bundle and need no
other component. Its command bar, <vn-diagram-toolbar>, is a component of
its own, vanilla-diagram-toolbar
(Diagram Toolbar), which links a
diagram by id and reads it through its public API.
<vn-diagram-palette diagram="flow"> <vn-diagram id="flow">
+-----------------+ +----------------------------------+
| Basic shapes | | +-------+ /\ |
| [ ] ( ) <> /\ T | drag or click --> | | Start o-------->o o---+ |
| Flowchart | | +-------+ \/ | |
| [~] /_/ (=) | | v |
| Connectors | | ( End ) |
| -- ~~ -| | | |
+-----------------+ +----------------------------------+
symbol sets, then o a port, ---> a connector
the connector kinds
Every change is a command: applied to the model, recorded in the undo
history, announced by vn-diagram-changed, and queued as a change set for
the data manager. A drag previews without touching the model and commits one
command on release.
See also the component README for the
public API, the process-flowchart-js sample,
and the plant-automation-js sample, whose
three symbol sets draw every symbol with a render callback.
Documents
Listed in reading order.
- Getting Started: a step-by-step guide with live examples.
- Web Component: attributes,
lifecycle,
ready(), the canvas markup, the load and its events, the stylesheet links. - Model and Commands: nodes and
connectors, validation,
z, the commands, undo and redo, transactions, change sets. - Rendering and Viewport:
the SVG layers, the write pass, text in a
<foreignObject>, the coordinate transform, pan and zoom. - Pointer and Touch: selection, the rubber band, move and resize with their preview, pinch, auto-pan.
- Ports and Connectors: ports, connecting and reconnecting, the three routes, arrowheads.
- Keyboard and Focus: the keys, the nudge burst, connect mode.
- Symbols and Palette: the
symbol registry, the
basicset, render callbacks, the palette's link, tiles and drag. - Data Manager: the contract, the static manager, the load, saves in order and reverts on failure.
- Themes: the base and theme stylesheets, the tokens, the colour slots, forced colours.
- Text Editing: the in-place editor on node text and connector labels, its keys, commit and close rules.
- Clipboard and Export: copy,
cut, paste and duplicate, the format and the clipboard events;
toSVG(),toPNG()and its SVG-text fallback. - Routing Around Shapes:
elbows around the nodes in their way, their own end nodes included, the
fast path, the search, what re-routes,
the gesture budget,
avoid-shapes. - Containers:
parent, the container flag and thegroupsymbol, the frames layer, selection, moving with descendants, joining on release, resizing, removing. - Large Diagrams: the spatial indexes, culling to the drawn rect, the draw budget and the free lists, the far view, the chunked load, the background route pass, the measurements at 100,000 nodes.
- Screen Readers: the canvas as an application, the announcer, walking connections with N, P and J, the outline.
- Auto-Layout:
layout(), the layered and the tree layouts, containers inside out, Tidy up.
The toolbar, <vn-diagram-toolbar>, has its own docs:
Diagram Toolbar and its
getting-started guide.
Module map
| File | Global | Role |
|---|---|---|
vanilla-diagram-events.js |
VanillaDiagramEvents |
Frozen event-name registry |
features/geometry.feature.js |
VanillaDiagramGeometry |
Pure: the viewport transform, rotated frames, port points, boxes, resizing, the nearest node in a direction, SVG path data flattened to polylines |
features/symbols.feature.js |
VanillaDiagramSymbols |
The symbol and set registry, the basic set |
features/model.feature.js |
VanillaDiagramModel |
Nodes, connectors, the node-to-connector index, validation, change sets, toJSON() |
features/commands.feature.js |
VanillaDiagramCommands |
The commands (apply, revert) and the undo / redo history |
features/save-queue.feature.js |
VanillaDiagramSaveQueue |
Pure: saves in order, what a failure reverts |
features/routing.feature.js |
VanillaDiagramRouting |
Pure: straight, bezier and elbow paths between two ends, edited routes, free-end sides, the label midpoint |
features/spatial-index.feature.js |
VanillaDiagramSpatialIndex |
Pure: a uniform grid of 256 px buckets over world boxes (the router's obstacles, the node and connector indexes) |
features/orthogonal-router.feature.js |
VanillaDiagramOrthogonalRouter |
Pure: the obstacle index (on the spatial index), elbows routed around the padded node boxes |
features/snapping.feature.js |
VanillaDiagramSnapping |
Pure: snapping to the grid and to guides, the guide index |
features/layout.feature.js |
VanillaDiagramLayout |
Pure: the layered and the tree layouts, containers inside out, satellites beside their owners, in slices; the facing sides and ports after a layout |
vanilla-diagram.js |
VanillaDiagram |
The core class (model operations, history, selection, saves, rotation by keys, the load's swap and indexes, the route pass, layout()), the yield, the locale registry, the logger, the dev auto-loader |
features/rendering.feature.js |
(VanillaDiagram.prototype) |
The SVG layers, culling to the drawn rect, the records and their free lists, adorners, the write pass, the far view, the route cache and what re-routes |
features/groups.feature.js |
(VanillaDiagram.prototype) |
Containers: the frames' order, the container under a point, joining on release, the resize clamp |
features/viewport.feature.js |
(VanillaDiagram.prototype) |
Pan and zoom: wheel zoom, gesture events, the viewport API, fit, the viewport event |
features/interaction.feature.js |
(VanillaDiagram.prototype) |
Pointer and touch gestures, auto-pan, the palette's drop |
features/keyboard.feature.js |
(VanillaDiagram.prototype) |
Focus, keys, the nudge burst, connect mode |
features/text-editing.feature.js |
(VanillaDiagram.prototype) |
The in-place text editor |
features/clipboard.feature.js |
VanillaDiagramClipboard, (VanillaDiagram.prototype) |
The clipboard format and paste (pure), the clipboard events and API |
features/export.feature.js |
(VanillaDiagram.prototype) |
toSVG(), toPNG() and the SVG-text fallback both use |
features/accessibility.feature.js |
(VanillaDiagram.prototype) |
The announcer, the descriptions, walking connections (N, P, J), the outline |
data-managers/diagram-data-manager.js |
VanillaDiagramDataManager |
The data source contract (base class) |
data-managers/static-diagram-data-manager.js |
VanillaDiagramStaticDataManager |
Nodes and connectors in memory, as copies |
vanilla-diagram-element.js |
VanillaDiagramElement |
<vn-diagram>: attributes, stylesheets, the load, the public API, the symbol and theme statics; the palette's link helper |
vanilla-diagram-palette.js |
VanillaDiagramPaletteElement |
<vn-diagram-palette>: set groups, tiles, the drag source, the swatch map |
vanilla-diagram.css, themes/vn-diagram-*.css |
Structure; paint per theme | |
vanilla-diagram.d.ts |
Hand-authored declarations |
The pure modules attach to window in the browser and to globalThis in
Node, and export themselves for require(), so tests/node/ loads them
without a DOM. Each JavaScript file carries a Depends on: header, which
build.js's checkModuleLoadOrder() checks against the bundle order, and
every bundled file goes through checkNoDirectConsoleCalls().
Loading and bundling
Development. A page loads one script:
<script src="../../src/vanilla-diagram/vanilla-diagram.js"></script>
vanilla-diagram.js injects the component's other files as
<script async=false> tags, as the Gantt's entry script does (parallel
download, in-order execution), the two elements last, and exposes
window.VanillaDiagramReady, which resolves once they have run.
window.VanillaDiagramSkipAutoload = true, or data-skip-autoload on the
script tag, turns the auto-loader off; VanillaDiagramReady then resolves at
once. A host module that extends a diagram class (a custom data manager)
defines it after VanillaDiagramReady, since a module script can run before
the injected files have.
Production. npm run build writes
dist/vanilla-components/latest/vanilla-diagram/ with
vanilla-diagram.bundle.js, vanilla-diagram.css, themes/ and
vanilla-diagram.d.ts. The bundle concatenates DIAGRAM_BUNDLE_PARTS (in
build.js) behind a header that sets VanillaDiagramSkipAutoload. The HTML
rewrite (rewriteHtmlForDiagramBundle()) renames the vanilla-diagram.js tag
to vanilla-diagram.bundle.js, after rewriteHtmlComponentPathsToShared()
pointed it at the shared folder, and rewriteHtmlComponentScriptVersions()
stamps it with the ?v= token.
Obfuscation. npm run build:obfuscate processes each part on its own
profile. DIAGRAM_BUNDLE_FAST_PATH keeps on the fast profile the parts that
run per node or per frame: geometry, routing, the spatial index, the
orthogonal router, snapping, the layout, the model, rendering, the groups
(the joining target per drag frame) and the static manager. Interaction,
keyboard, the save queue, text editing, the clipboard, the export and the
accessibility layer stay heavy: they run per input event or per command.
No other component. The diagram brings its own logger fallback (the
grid's VanillaGridLogger.normalizeLogger() when the grid is on the page,
else a console bridge) and its own requestAnimationFrame write pass, and
loads in any order relative to the other components.
Top-level names. Every bundle's top-level class and const share the
page's global lexical scope, so every diagram global and top-level name is
VanillaDiagram*, VN_DIAGRAM_* or _vnDiagram* (_VnDiagramThemeLink for
the shared stylesheet helper). tests/node/gantt-bundle-coexistence.test.js
evaluates the diagram's sources alone and after the other five bundles in one
vm context, and fails on any redeclaration.
Return-type contract
Before initializeDiagram() the element draws nothing (it has no markup) and
its methods are safe no-ops: the getters return null or [], toJSON() an
empty version 1 document, getViewport() { x: 0, y: 0, zoom: 1 }; the
mutations return null, false or 0; undo(), redo(), canUndo(),
canRedo() and scrollToNode() return false; the viewport calls and
transaction() do nothing; hasPendingSaves() is false and whenSaved()
resolves. editText(), copy(), cut(), duplicate(), bringToFront(),
sendToBack(), setSwatch(), isInitialized() and isBusy() return false,
deleteSelection() and getNodeCount() 0, paste() resolves false,
toSVG() resolves with an empty <svg>, toPNG() rejects, layout() resolves
false, and getZoomLimits() returns the defaults, { min: 0.1, max: 4 }. A palette, or a
<vn-diagram-toolbar>, draws its buttons disabled until a diagram is
linked. The attribute properties reflect at any time, and
setDataManager() may come first. loadDiagramAsync() and
reloadDataManager() reject without a manager, and loadDiagramAsync() also
before initializeDiagram(). A second initializeDiagram() is a no-op with a
warning; after destroy() the element is back in this state.
Performance
Only the nodes and connectors that meet the drawn rect (the view and a quarter of it around) are in the DOM, and every per-node scan goes through a spatial index: 14-large-diagrams holds the design and the measurements at 100,000 nodes and 100,000 connectors (pan, zoom and drag frames within 16ms at zoom 1 and 0.1, the load in slices, select all, the rubber band, port targets, guides and the joining container within their budgets). A layered layout of 10,000 nodes resolves within 2s (16-auto-layout).
At 1,000 nodes and 1,000 connectors, diagram-performance.spec.js (in
PERF_SPECS) measures the median frame of a one-node drag, of a guided
one-node drag (a 16px grid and the guides of every node in view) and of a
zoom step against a 16ms budget; they measure about 1ms, under 1ms and 2ms in
Chromium. With the elbows routed around shapes it also measures the load's
routing pass against 50ms (about 9ms), and a routed drag frame and a
container drag frame (20 children) against 16ms (about 1ms and 2ms).
- A drag frame is O(k + c): the moved nodes and their connectors, found through the node-to-connector index. No attribute is written unchanged. The moved nodes' elbows route until 4ms of routing in the frame; a committed change finds the kept routes it sweeps through the connector index (12-routing-around-shapes).
- Guides collect the lines of the nodes in view once at drag start, through
the node index, and sort them; each frame looks the moved box's six lines
up by binary search, O(log n). The grid is one
<rect>filled with a pattern: O(1) per viewport write. An edited elbow re-joins at most two segments per end. - A zoom step writes one CSS
transformon the world group and redraws the adorners, O(drawn selection); when the view leaves the drawn rect, the strips it gains and loses are queried. Thetransformattribute would cost about 20ms: Chromium lays the whole SVG subtree out again when it changes, and not for the CSS property. Nothing is set on an ancestor of the world group per step: a custom property there restyles every descendant. - A load is O(n + m), in 8ms slices after the fetch; the rubber band queries the node index, O(nodes in the band).
TypeScript declarations
src/vanilla-diagram/vanilla-diagram.d.ts is hand-authored, names every type
with the full VanillaDiagram* prefix, and imports nothing.
tests/types/vanilla-diagram.dts-typecheck.ts compiles against it, and
tests/node/dts-conformance.test.js checks the declared element, palette,
data-manager and event names against the runtime, both directions, and that
the declarations no longer name the toolbar, whose own are in
vanilla-diagram-toolbar.d.ts.