Web Component Implementation in Vanilla-Diagram
<vn-diagram> (VanillaDiagramElement) owns the attributes, the
stylesheets, the data manager and the load. initializeDiagram() builds the
canvas and a VanillaDiagram core, which owns the model, the history, the
selection, the viewport and the save queue; the element's public methods
delegate to it.
Attributes and properties
| Attribute | Property | Read when |
|---|---|---|
theme |
theme (default default) |
At connect and on change: swaps the theme stylesheet |
theme-css-path |
themeCssPath |
Likewise; overrides theme |
read-only |
readOnly |
On every gesture and key. Turning it on commits an open text edit and a nudge burst, cancels a gesture and leaves connect mode; canUndo() and canRedo() read false while it is on, so vn-diagram-history-changed fires when it toggles |
connector-type |
connectorType (default elbow) |
When a user draws a connector, and as addConnector()'s default type. An invalid value reads as elbow |
port-visibility |
portVisibility (default hover) |
On the next adorner pass |
grid-size |
gridSize (default 0, off) |
On the next write pass: the grid's spacing in world px, which moves, resizes, nudges and drops snap to (04-pointer-and-touch). Zero, a negative or an invalid value reads as 0 |
snap-guides |
snapToGuides (default true; "false" turns it off) |
At each move or resize start |
free-ends |
freeEnds (default false) |
When a user connect or reconnect is released on the empty canvas (05-ports-and-connectors); the data and the API take free ends either way |
avoid-shapes |
avoidShapes (default true; "false" turns it off) |
Whenever an elbow is routed: on, an elbow without edited points routes around the nodes in its way, its own end nodes included; a change redraws every elbow (12-routing-around-shapes) |
The properties reflect their attributes at any time, before
initializeDiagram() too.
Lifecycle
connectedCallback()adds thevn-diagramclass (the theme files' scope) and acquires the base and theme stylesheets.ready()resolves oncewindow.VanillaDiagramReadyand the element's stylesheets have loaded.initializeDiagram(options)builds the markup below, constructs the core with the options (minZoom,maxZoom,historyLimit,locale,messages,logger), labels the canvas from the messages and adds thevn-diagram--readyclass. A second call is a no-op with a warning.getZoomLimits()then returns{ min, max }as the core clamped them; before it, the defaults{ min: 0.1, max: 4 }.disconnectedCallback()waits a microtask: a move in the DOM disconnects and reconnects in one task and keeps everything. Leaving the DOM commits a nudge burst, cancels a gesture and releases the theme link.destroy()aborts a load, destroys the core (its listeners, the save queue), drops the data manager, removes the markup and thevn-diagram--readyclass: the element is back in the return-type contract.
Markup
<vn-diagram class="vn-diagram vn-diagram--ready">
<div class="vn-diagram-root"> absolutely fills the element
<svg class="vn-diagram-svg" tabindex="0" role="application" aria-label="Diagram"
aria-describedby="vn-diagram-hint-1">
<defs> the arrowhead markers
<g class="vn-diagram-world"> the viewport transform
<g class="vn-diagram-grid"> the grid: one rect filled with a dot pattern
<g class="vn-diagram-frames"> containers, under the connectors
<g class="vn-diagram-connectors">
<g class="vn-diagram-nodes">
<g class="vn-diagram-preview"> connect preview, drop outline
<g class="vn-diagram-adorners"> screen space (aria-hidden, as the preview)
<div class="vn-diagram-announcer" role="status"> the live region (visually hidden)
<div class="vn-diagram-keyboard-hint" id="vn-diagram-hint-1"> keyboardHint (visually hidden)
<div class="vn-diagram-outline"><ul aria-label="Diagram: outline"> the outline (visually hidden)
<div class="vn-diagram-message" role="status" hidden> the busy overlay or the load error
<div class="vn-diagram-message-box">
<span class="vn-diagram-message-spinner" aria-hidden="true"> while busy only
<span class="vn-diagram-message-label">
The element is a block with a 240px minimum height; the host sizes it. The layers are described in 03-rendering-and-viewport; the announcer, the hint and the outline in 15-screen-readers.
The load
loadDiagramAsync() follows the Gantt's loadTasksAsync():
- Rejects without a manager or before
initializeDiagram(). - Commits a nudge burst and cancels a gesture, aborts the previous load, and takes a generation number: a later call supersedes this one, which then resolves without drawing.
- Fires
vn-diagram-loadingand clears an earlier load error. The load is busy from its start (The busy state): the canvas refuses every user input, and the busy overlay saysloadingover the previous drawing. - Waits for the pending saves (
saveQueue.whenSaved()), so it reads what was stored. - Fetches both lists in parallel with one
AbortController. - Builds a new model (validation, 02-model-and-commands) and its spatial indexes in 8ms slices; the current model stays drawn meanwhile. A user edit is refused while the load runs; an API edit made then is replaced by the loaded data, as during the fetch.
- Swaps it in: clears the selection and the history, aborts the save
queue, zooms to fit unless the host set a viewport since
initializeDiagram(), draws what meets the drawn rect one pass per frame (still busy), ends its busy job and firesvn-diagram-loadedwith the counts:nodeCount,connectorCount, and inskippedthe unknown symbols, duplicate ids, dangling connectors and invalid parents (13-containers). It resolves with the drawn rect drawn; the elbows out of view then route in the background (14-large-diagrams).
A superseded or aborted load, or destroy(), stops it between slices.
A fetch that rejects (not an abort) shows loadError, keeps the previous
model, fires vn-diagram-error and rejects. reloadDataManager() calls the
manager's reset(), then loads. setAutoReloadOnConfigChange(true) reloads,
coalesced to one per task, when the manager fires onConfigChanged.
The busy state
The core keeps the running jobs, each with a reason: 'loading' (a load,
reloadDataManager() included), 'layout'
(16-auto-layout) and 'export'
(toSVG() and toPNG(),
11-clipboard-and-export).
isBusy() is true while any runs, and the reason is the newest one's.
The export's job begins when
toSVG()ortoPNG()is called and ends when it settles; one that fits in one slice ends in the task that began it, so its overlay is never painted, though the events still fire. An export of many items holds the drawing: under the overlay the drawing and its adorners empty, and it settles once they are drawn again, so an applied layout's wait that it joined ends with it (11-clipboard-and-export). It starts at once while a load or a layout runs, and doesn't end an applied layout's wait for its drawing, as a newer load or layout does. Begun while a load's job runs, it leaves an open text edit to the load's swap, as the load does. The element leaving the page ends it with a rejection, at its next slice.The load's job begins before the previous load is aborted, so
busynever reads false between two loads. It ends when the drawn rect is complete, when the fetch fails (beforeloadErrorshows), and when the load stops._abortLoad()(a newer load,setDataManager(),destroy()) ends it at once, so a manager that ignores the abort signal can't hold busy. It leaves an open text edit to the swap, which closes it without committing, as a load always did (a failed load keeps it open).What busy refuses: every user input, as if the canvas were disabled: no pointer, touch or key gesture starts (selecting, the rubber band, panning and pinching included), hovering shows no ports, a wheel or a Safari pinch is swallowed (the page neither scrolls nor zooms under the overlay), no key acts (Ctrl+Z, Ctrl+Y and the zoom keys included; Tab still leaves), the defaults the idle, read-only canvas prevents stay prevented (Escape, the arrows, the z-order, undo, redo, duplicate and select-all keys, the zoom and walk keys, and a middle press: Escape doesn't close a dialog around it, Ctrl/Cmd+A doesn't select the page's text, Ctrl/Cmd+D doesn't bookmark it, N doesn't open Firefox's quick find, a middle press doesn't autoscroll; every other key keeps the browser's default), the page's copy, cut and paste do nothing (a copy or cut with a selection prevents the browser's own too, and writes nothing), and the text editor doesn't open (
_inputRefused()at each input handler, and_editsRefused(source)beside each user-input read-only check: an'api'source passes). The palette's tiles and drops and its connector kinds are off (07-symbols-and-palette), and so are the toolbar's zoom buttons (Diagram Toolbar). Every API call works (a zoom, a selection, an edit), andcanUndo(),canRedo(), the history events and the adorners don't change (an export that holds the drawing hides the adorners, and draws such a call's change when the drawing comes back). A job beginning stops user input as turningread-onlyon does (the editor commits, except for a load, which leaves it; a nudge burst commits; a gesture is cancelled; connect mode ends), and the hovered node's ports hide. Leaving the DOM ends an applied layout's wait for its drawing. Read-only and busy are independent.Reporting:
vn-diagram-busy-changed({ busy, reason }) fires whenbusyor the reason changes, never afterdestroy(); the element has the classvn-diagram--busymeanwhile: the state hook (nodes lose themovecursor).destroy()drops the jobs silently.The overlay (
.vn-diagram-message) shows when a job begins, before anything is drawn, so a drawing in progress shows only under its scrim: a spinner, the label (loading,arrangingorexporting, set as text) and a box over a scrim (--vn-diagram-busy-scrim,--vn-diagram-busy-bg, 09-themes). A job over before the next frame is never painted. It hides when the last job ends, stays up while the element leaves the DOM and comes back, and takes no pointer events: the canvas under it refuses them. The label follows the reason. The spinner stands still underprefers-reduced-motion: reduce. The load error (kinderror) is text only: a job ending never hides it, and an overlay that covers it gives it back when it hides; a load clears it.
Stylesheets
The base stylesheet (vanilla-diagram.css) is one <link> per page. Each
theme URL is one <link> with a refcount, shared by every diagram and
palette that uses it (_VnDiagramThemeLink): the same machinery as the
Gantt's, copied rather than shared, so the diagram needs no other component.
The URLs resolve against the folder the element's script was loaded from.
VanillaDiagramElement.getThemeHref(name) returns the URL a theme name
resolves to (registered, built in, else the default's); the palette and
<vn-diagram-toolbar> load their theme file through it.
The authoring API
The element forwards each to the core, with source api, and keeps the
return-type contract before initializeDiagram()
(00-index):
| Method | |
|---|---|
editText(id) |
Opens the text editor (10-text-editing) |
copy(), cut(), paste(), duplicate() |
The clipboard (11-clipboard-and-export) |
bringToFront(ids?), sendToBack(ids?) |
The drawing order (02-model-and-commands) |
toSVG(options?), toPNG(options?) |
The export, a promise of an SVG string or a PNG Blob, built in slices under the 'export' job (11-clipboard-and-export) |
getZoomLimits() |
The zoom limits, for a host's own zoom buttons and the toolbar |
isInitialized() |
True between initializeDiagram() and destroy(): what <vn-diagram-toolbar> waits for |
isBusy() |
True while a load or a layout() runs, until what it changed is drawn in view, and while an export runs, until the drawing is back for one that held it (The busy state); false before initializeDiagram() and after destroy() |
getNodeCount() |
The number of nodes, without copying them (getNodes() copies each); 0 before initializeDiagram() |
deleteSelection() |
Deletes the selection as the Delete key does: the cancelable vn-diagram-removing first, then one remove. How many items it removed; 0 while read-only, with nothing selected or when cancelled |
layout(options?) |
Arranges every node, as layers or as a tree, in a direction; one undo step. A promise of whether a node moved (16-auto-layout) |
setSwatch(slot, ids?) |
Gives the nodes ids (default the selected ones) colour slot slot (null clears it), as one undo step labelled by command.swatch. An API mutation, so it works in read-only mode. False for a slot name that isn't one (^[a-z][a-z0-9-]*$), or when no node changes |
<vn-diagram-toolbar>, a component of its own
(Diagram Toolbar), reads the
diagram through these public methods only.
VanillaDiagramElement.SUPPORTED_SWATCHES names the ten built-in colour
slots, col1 to col10 (09-themes).
setDataManager() also closes an open text edit without committing it.
The palette's hook
_paletteAdd(symbolName, extra) adds a symbol at the centre of the view,
with extra (the palette's swatch for it); while the view's centre hasn't
moved, each add lands 16px right and below the previous one.
07-symbols-and-palette
describes the palette. The palette links to a diagram through a helper,
_VnDiagramLink (exposed as VanillaDiagramElement._Link), described there;
<vn-diagram-toolbar> has a link of its own on the public API.