Model and Commands Implementation in Vanilla-Diagram

The model

VanillaDiagramModel.create(symbols) holds the nodes and connectors as its own copies (symbols is the symbol registry, which childrenOf() reads; the diagram passes VanillaDiagramSymbols): what goes in is copied, and the public getters copy what comes out, so no host object is ever shared with it. Ids are strings (a number is converted). A node is { id, symbol, x, y, width, height, rotation?, z, text?, style?, swatch?, parent?, data? }; a connector { id, type, from, to, arrows?, label?, points?, data? }.

The document stays version 1: a phase 1 build drops a connector with a free end on load and ignores points, label, swatch and parent.

Validation on load (load()):

Case What happens Counted as
A node whose symbol isn't registered Kept, drawn as a rectangle, redrawn once the symbol is registered unknownSymbols
A second node or connector with an id already seen Left out; the first copy wins duplicateIds
A connector whose node is missing, whose node's known symbol lacks the port, or whose two ends are the same port Left out danglingConnectors
A node without an id or a symbol name Left out, with a warning (not in the event)
A swatch that isn't a valid name Dropped from the node, with one warning; a valid name outside the ten slots is kept (a host's own) (not in the event)
A free end without finite x and y The connector is left out danglingConnectors
points that aren't finite pairs, or don't fit the type Dropped from the connector (not in the event)
A parent naming no node, a node whose known symbol isn't a container, or the node itself; every node in a parent cycle Dropped: the node loads top-level (a parent whose symbol isn't registered is kept) invalidParents
A label that isn't a string Converted to one

A port on a node whose symbol is unknown is accepted: the symbol may arrive later. The counts go to vn-diagram-loaded and one warning names the first id of each kind. loadChunked() is load() in slices, the same code (a generator yielding every 512 items): after 8ms it awaits the caller's pause() and resolves null once stopped() is true; the element's load builds a new model with it (14-large-diagrams).

Commands

Every change goes through a command, which holds what it needs both to apply itself and to revert:

Kind Holds Made by
add the nodes and connectors added addNode(), a palette add
remove what it removed, z included; a removed container's descendants and every removed node's connectors with it removeItems(), Delete
move the node ids (a moved container's descendants among them) and the offset a drag, a nudge burst; with parent updates in a batch when a moved node joins or leaves a container
resize the id, the box before and after a handle drag, the resize keys
connect the connector addConnector(), a user connect
reconnect the id, the ends before and after an end-handle drag
update the target (node or connector), the id, the fields before and after updateNode(), updateConnector(), a text edit (command.editText), a route edit (command.route), the rotation handle (command.rotate)
batch an ordered list of commands, reverted in reverse transaction(); bring to front and send to back (z updates); setSwatch() (command.swatch); R and Shift + R (rotation updates, command.rotate); layout() (x, y, a container's size, free ends and cleared points, command.layout)

apply() and revert() return an effect: per kind, id to added, updated or removed, merged across a batch (added then removed is nothing, removed then added is updated). The model turns an effect into the change set the data manager stores. A command's info is the frozen { kind, label, ids } the events carry; the label comes from the command.<kind> message.

Executing, undoing, redoing

_execute(cmd, source) applies the command, then _commit():

  1. records it in the history (for an undo or a redo, moves it between the stacks),
  2. marks what the effect touched for the next draw and drops removed ids from the selection,
  3. fires vn-diagram-changed with { command, source },
  4. with a data manager, queues { change, cmd, changeSet, stacks }, the stacks being a copy of both history stacks from just before the change (08-data-manager),
  5. fires vn-diagram-history-changed when canUndo() or canRedo() changed.

undo() reverts the top of the undo stack with source undo; redo() applies the top of the redo stack with source redo. Both, and canUndo() and canRedo(), return false while the diagram is read-only. A gesture commits one command on release; the preview before it changes nothing (04-pointer-and-touch).

The history keeps historyLimit commands (100 by default), trimming the oldest; 0 keeps none (saves still run). A new command clears the redo stack. clearHistory() empties both stacks and the stack copies in the save queue. A load clears the history.

transaction(label, fn). The commands the calls in fn make are applied at once (so fn reads its own changes) and collected; at the end they become one batch: one undo step, one vn-diagram-changed, one change set. If fn throws, the collected commands are reverted and the error rethrown: nothing is recorded, announced or saved. A nested call runs inside the outer transaction. An fn that changes nothing records nothing, and undo() and redo() return false while fn runs. Without a label, the step takes the command.batch message.

The API mutations

addNode() needs a registered symbol; it assigns an id when none is given (crypto.randomUUID(), else a counter with a random suffix), fills the size from the symbol's default and clamps it to its minimum. updateNode() and updateConnector() validate the patch (numbers finite, sizes positive, a known symbol, a valid swatch name, ends that resolve and differ, a label string, points that fit the type, a parent that can hold the node: a container, not the node itself nor one of its descendants) and return false without a command when it is invalid; a patch that changes nothing returns true without one. A container that holds nodes keeps a container symbol. A null text, style, swatch, arrows, label, points or parent removes the field. addNode() drops a parent that can't hold the node. removeItems(ids) removes a removed container's descendants too. A new type clears points unless the patch sets them.

Drawing order. bringToFront(ids) gives the nodes (default the selected ones) z values above every other node, keeping their relative order; sendToBack(ids) below. One batch of update commands, labelled command.bringToFront or command.sendToBack: one undo step, one change set. Nodes already in place in that order change nothing, and the call returns false (model.zOrderPatches()). Connectors stay under the nodes.

Paste adds its items as one add, labelled command.paste (or command.duplicate) (11-clipboard-and-export).

Sources. A change's source is pointer, keyboard, palette, api, undo or redo. A <vn-diagram-toolbar> command calls the public methods, so its changes report api. API mutations work in read-only mode, fire vn-diagram-changed with source api, and fire no cancelable event: the host is the caller. deleteSelection() is the exception by design: it deletes as the Delete key does, so it fires the cancelable vn-diagram-removing first (its ids list a selected container's descendants too) and refuses while read-only.

Layout. layout(options) arranges every node and applies the result as one batch labelled command.layout, executed once: one undo step, one change set, source api; it resolves false when the model changed while it computed (16-auto-layout).

A swatch on nodes. setSwatch(slot, ids?) gives the nodes ids (default the selected ones; connectors and unknown ids are skipped) the slot, or clears it with null, as one batch labelled command.swatch. It returns false for a name that isn't a slot name or when no node changes. getNodeCount() reads the model's size without copying a node.

The removal method is removeItems(ids), not remove(): a <vn-diagram> is an element, and Element.remove() keeps its DOM meaning (it detaches the diagram from the page).

Before anything else reaches the model, a pending nudge burst is committed (06-keyboard-and-focus).