Vanilla Diagram Toolbar Technical Docs

<vn-diagram-toolbar diagram="<id>"> (VanillaDiagramToolbarElement) is a diagram's command bar, a component of its own beside vanilla-diagram. Its bar is written in markup, as the grid toolbar's is: each item is an element that draws its own button, and a host chooses the standard commands, adds commands of its own and gives each button a style. It reaches the diagram through <vn-diagram>'s public API only, as the grid and Gantt toolbars reach theirs. Getting Started is a step-by-step guide with live examples.

<vn-diagram-toolbar diagram="flow">                <vn-diagram id="flow">
  <vn-diagram-toolbar-status>                        public API only:
  <vn-diagram-toolbar-command command="save"    -->  isInitialized(), canUndo(),
       label="Save" variant="primary">               getSelectedIds(), deleteSelection(),
  <vn-diagram-toolbar-separator>                     setSwatch(), getNodeCount(),
  <vn-diagram-toolbar-command command="undo">        transaction(), updateConnector(), ...
  <vn-diagram-toolbar-swatches>
  <vn-diagram-toolbar-connector-type>
  <vn-diagram-toolbar-arrows>

The elements

Tag Class Role
<vn-diagram-toolbar> VanillaDiagramToolbarElement The bar: role="toolbar", the link, the state, the commands, the labels, the status text
<vn-diagram-toolbar-command> VanillaDiagramToolbarCommandElement One command button, standard or custom
<vn-diagram-toolbar-status> VanillaDiagramToolbarStatusElement The host's status text (role="status")
<vn-diagram-toolbar-separator> VanillaDiagramToolbarSeparatorElement A vertical rule (role="separator")
<vn-diagram-toolbar-swatches> VanillaDiagramToolbarSwatchesElement The colour menu's button
<vn-diagram-toolbar-connector-type> VanillaDiagramToolbarConnectorTypeElement The connector type menu's button
<vn-diagram-toolbar-arrows> VanillaDiagramToolbarArrowsElement The arrows menu's button

All seven are light-DOM elements in one file, src/vanilla-diagram-toolbar/vanilla-diagram-toolbar.js. The items are defined before the toolbar, so a toolbar that draws its default bar on upgrade gets upgraded items.

The default bar

A toolbar with no item children when it connects appends the items of the default bar, each marked data-vn-default:

status undo redo | zoomIn zoomOut zoomToFit | delete | bringToFront sendToBack | swatches connectorType arrows | exportSvg exportPng

A MutationObserver on the toolbar's own subtree removes the default items as soon as a host item is added, so a framework that renders the children after connecting gets only its own. An item added or removed redraws the bar; the items' own buttons and text don't count.

Items and their context

The toolbar computes its state on every change it follows and sets each item's toolbarContext to { state, diagram, toolbar }; the item redraws in contextChanged(). An item reads its toolbar's last context when it connects, and an item outside a toolbar draws its button disabled.

<vn-diagram-toolbar-command> draws one <button> with the attributes of <vn-grid-toolbar-command>:

Attribute
command A standard name or the host's own
arg JSON, parsed on each click; the commandArg property overrides it
label, label-key Text beside the icon; label-key reads the toolbar's messages; else the element's own text
title-key The tooltip; a standard command defaults to its toolbar.<item> label
icon, icon-position A built-in or registered icon (a standard command defaults to its own), or an inline <svg> child; left (default) or right of the label
variant primary, secondary, ghost (default) or danger; an unknown value is ghost
disabled-when, show-when, hide-when A state field, ! to negate

A button without a label is icon-only, with aria-label from its title, else its command name. A standard button carries data-item (its item name, zoom-in) and every button data-command.

<vn-diagram-toolbar-swatches> draws the colour menu's button: a colour box in the colour every selected node has (the theme's own, struck through, for none or a mixed selection) and a caret. Its variant works as a command's.

<vn-diagram-toolbar-connector-type> and <vn-diagram-toolbar-arrows> draw the connector menus' buttons the same way: the icon of the type, or of the arrows, every selected connector has, else mixed (a dashed line: no connector selected, or connectors that differ), and a caret (The menus).

<vn-diagram-toolbar-status> shows the text of setStatusMessage(text, severity): severity info, success or error, and only error tints it (--vn-diagram-error-color); '' or null clears it. The toolbar keeps the text, so a status item added later shows it; getStatusMessage() returns { text, severity }.

State

state is frozen, recomputed from public methods only:

Field From
linked a linked, initialized diagram
readOnly readOnly
canUndo, canRedo canUndo(), canRedo() (false while read-only)
canZoomIn, canZoomOut getViewport().zoom against getZoomLimits(), read once per link, within 1e-6
hasNodes getNodeCount() > 0
hasSelection, selectedCount getSelectedIds()
hasSelectedNode a selected id for which getNode() returns a node
hasSelectedConnector a selected id for which getConnector() returns a connector
busy isBusy(): a load or a layout() runs, until its drawing in view is final, or an export runs (the toolbar's own included)

While unlinked every field is false and the count 0. The toolbar recomputes it on the diagram's vn-diagram-history-changed, -selection-changed, -changed, -loaded, -save-failed and -busy-changed, and on its read-only attribute. busy follows the diagram at once, as its overlay does. On vn-diagram-viewport-changed (once per pan or zoom frame, from the write pass) it recomputes only canZoomIn and canZoomOut, and pushes the state to the items but the menus, whose values a pan or zoom doesn't change.

Enabled rules.

Command Enabled
undo, redo canUndo, canRedo, not busy
zoomIn, zoomOut canZoomIn, canZoomOut, not busy (the canvas takes no zoom then either)
zoomToFit linked, not busy
delete a selection, not read-only, not busy
bringToFront, sendToBack, swatch a selected node, not read-only, not busy
connectorType, arrows a selected connector, not read-only, not busy
exportSvg, exportPng hasNodes, not busy (an export would catch a drawing replaced a moment later)
layout hasNodes, not read-only, not busy (a second click can't restart a run)
any other (custom) linked

On a standard command's button disabled-when can only add to the rule: it can't enable undo with nothing to undo. On a custom one it replaces the rule, as on <vn-grid-toolbar-command>, and read-only disables nothing by itself (disabled-when="readOnly" does). show-when and hide-when set the item's hidden. A disabled button is aria-disabled="true", not disabled, so the arrow keys still reach it; a click on it does nothing.

Commands

dispatchCommand(command, arg) returns false while unlinked, for a standard command that is disabled, or when a listener cancels; else it fires vn-diagram-toolbar-command (VanillaDiagramToolbarEvents.COMMAND) on the toolbar, cancelable, bubbling and composed, with { command, arg, diagram, toolbar, state, source } (arg null when not given; source the item whose button was pressed, null from script), then runs the handler registerCommand(name, fn) stored, else the standard action, else nothing, and returns true. A handler is called as fn(diagram, arg, toolbar); one that throws is logged and the toolbar keeps working. registerCommand() with a standard name replaces its action; the enabled rule stays the standard one.

Command Item name, icon and label Standard action
undo, redo undo, redo undo(), redo()
zoomIn, zoomOut zoom-in, zoom-out zoomBy(1.25), zoomBy(1 / 1.25)
zoomToFit zoom-to-fit zoomToFit()
delete delete deleteSelection(): vn-diagram-removing first
bringToFront, sendToBack bring-to-front, send-to-back bringToFront(), sendToBack()
swatch (arg: a slot, or null) the colour menu setSwatch(arg): one undo step
connectorType (arg: straight, bezier or elbow) the connector type menu (connector-type) updateConnector(id, { type }) on each selected connector whose type differs, in one transaction() labelled command.connectorType: one undo step. An edited route is cleared, as by any type change
arrows (arg: none, end, start or both) the arrows menu (arrows) updateConnector(id, { arrows }) likewise, labelled command.arrows
exportSvg, exportPng export-svg, export-png Awaits toSVG() or toPNG(), then downloads diagram.svg or diagram.png through a temporary <a download>; a rejection logs a warning. The export's busy job turns both buttons off while it runs
layout layout (Tidy up) layout() with its defaults (layered, down), then zoomToFit() when it resolves true (16-auto-layout). Not in the default bar

The changes these make report source api in vn-diagram-changed (undo and redo keep undo and redo). An invalid connectorType or arrows arg changes nothing, as a bad slot does for swatch; a value every selected connector already has records nothing. Nodes in the selection are left alone, and neither command touches the diagram's connector-type: the type a user draws next stays the palette's, with an end arrow. A host that wants the exported file itself cancels the command and awaits toSVG() or toPNG(), both promises (11-clipboard-and-export).

Icons are SVG path data in a 16 x 16 box, stroked with currentColor, the last of several paths filled. VanillaDiagramToolbarElement.registerIcon(name, paths) adds or replaces one and redraws every toolbar; an inline <svg> child of a command keeps its own paint.

The menus

The three menu items share one internal base class: a click, Enter, Space or the down arrow on the button opens a role="menu" of one menuitemradio per value, each a picture and a label; the value every selected item has is checked, and a mixed selection checks none. Finding that value stops at the first item that differs, and a selection of more than 1,000 items reads as mixed without reading each one. A pick dispatches the item's command with the value.

Menu Values Picture Current value
Colours (swatch) each slot of VanillaDiagramElement.SUPPORTED_SWATCHES, then "No colour" a colour box (a span with data-swatch, coloured by the diagram's base stylesheet) the selected nodes' common swatch
Connector type (connectorType) Straight, Curved, Elbow the connector-straight, -bezier, -elbow icon the selected connectors' common type
Arrows (arrows) No arrows, Arrow at end, Arrow at start, Arrows at both ends the arrows-none, -end, -start, -both icon the selected connectors' common arrows, read as the renderer draws them: start is arrows.start === true, end is arrows.end !== false

The arrows command writes the shortest arrows field for the value: { end: false } for none, no field for end (as a drawn connector has), { start: true, end: false } for start, { start: true } for both. The icons are built in and registerIcon() replaces any of them; they aren't mirrored under dir="rtl", since "end" is the connector's to end, not a direction.

Labels and events

The toolbar owns its labels, as the grid toolbar does: an English bundle, messages (a copy), and setMessages(map), which merges strings over it and redraws the labels. The keys are toolbarLabel ('Diagram tools'), toolbar.<item> for each standard item, swatchesLabel ('Colours'), swatch.col1 to swatch.col10 and swatch.none, connectorTypeLabel ('Connector type'), connectorType.straight, .bezier and .elbow ('Straight', 'Curved', 'Elbow'), arrowsLabel ('Arrows'), arrows.none, .end, .start and .both, command.connectorType and command.arrows (the connector menus' undo steps: 'Change connector type', 'Change arrows'), and any key a host adds for label-key and title-key. There is no locale attribute: the grid toolbar's only formats numbers and lists, and this toolbar shows neither.

VanillaDiagramToolbarEvents (frozen, on window) holds the one event name, COMMAND: 'vn-diagram-toolbar-command'.

diagram="<id>" is resolved with getElementById(), or the diagram property takes an element; the property reads the linked element, or null. The toolbar links when the target is a <vn-diagram> whose public isInitialized() returns true; an element not upgraded yet has no isInitialized and doesn't link. A MutationObserver on the document (child lists and id attributes) re-checks on every change while the toolbar is connected: initializeDiagram() adds the canvas markup and destroy() removes it, so the toolbar links and unlinks with them. A second observer watches the linked diagram's read-only and theme attributes.

Stylesheets and theme

The toolbar injects its base stylesheet, vanilla-diagram-toolbar.css, from its own script's folder, once per page. Colours come from the diagram's theme files (09-themes), which put .vn-diagram-toolbar in their token selector and frame it: the palette's tokens, and five of the toolbar's own, --vn-diagram-toolbar-primary-bg, -primary-color, -danger-bg, -danger-color and -border.

The theme is the toolbar's own theme attribute, else the linked diagram's theme, else default. The toolbar loads that theme file through the diagram's public VanillaDiagramElement.getThemeHref(name), once <vn-diagram> is defined, with its own refcounted <link> per URL; when it follows the diagram, its link and the diagram's name the same URL, which the browser serves from its cache.

Variants. ghost is the tile background with no border; secondary adds the --vn-diagram-toolbar-border outline; primary and danger fill with their tokens and darken on hover (brightness(0.94)). A labelled button is wider (--labelled); --icon-right reverses the row. In forced colours every button is ButtonFace and ButtonText, primary and danger with a 2px border, focus Highlight, the status text CanvasText and the menu Canvas, its checked item Highlight.

Keys

The buttons are one tab stop: the left and right arrows move between the visible buttons (swapped under dir="rtl"), Home and End go to the first and the last. A hidden item leaves the ring; the menus' items are outside it. An item that connects hands the tab stop out again.

Loading and the dist bundle

Performance

Not on a hot path. One state per diagram event, which reads getNodeCount() (the model's size, where getNodes() would copy every node) and getNode() and getConnector() for the selection only; the colour box reads the selected nodes once more, and each connector menu the selected connectors, each stopping at the first difference and not at all above 1,000 selected items. A pan or zoom frame recomputes only the two zoom fields: after Ctrl+A on 100,000 nodes it would otherwise copy every node each frame (diagram-performance.spec.js pans the sample at 100,000 with everything selected). The document observer's callback is one getElementById() and one isInitialized() per DOM change batch.

TypeScript declarations

src/vanilla-diagram-toolbar/vanilla-diagram-toolbar.d.ts is hand-authored. It imports VanillaDiagramElement from the diagram's declarations and declares the seven classes, VanillaDiagramToolbarEvents, the state, the command detail, the handler, the messages, the variants, the standard command names and the connector commands' arguments (VanillaDiagramToolbarConnectorType, VanillaDiagramToolbarArrows), and maps the seven tags and the event in HTMLElementTagNameMap and HTMLElementEventMap. tests/types/vanilla-diagram-toolbar.dts-typecheck.ts compiles against it, and tests/node/dts-conformance.test.js checks each class's accessors and methods and the event registry against the runtime, both directions.