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

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():

  1. Rejects without a manager or before initializeDiagram().
  2. 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.
  3. Fires vn-diagram-loading and 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 says loading over the previous drawing.
  4. Waits for the pending saves (saveQueue.whenSaved()), so it reads what was stored.
  5. Fetches both lists in parallel with one AbortController.
  6. 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.
  7. 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 fires vn-diagram-loaded with the counts: nodeCount, connectorCount, and in skipped the 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.

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.