Large Diagrams Implementation in Vanilla-Diagram

The model holds the whole diagram, at any size: loading by region was left out, since a model of 100,000 nodes and 100,000 connectors loads in well under a second. What a large diagram can't afford is the DOM: at 100,000 nodes the browser's layout of the SVG cost 8s at load and 67ms per drag frame, whatever was in view. So only what meets the drawn rect is in the DOM, every per-node scan goes through a spatial index, and the long jobs run in slices.

The spatial index

VanillaDiagramSpatialIndex (features/spatial-index.feature.js, pure) is a uniform grid of 256 world px buckets: set(id, box) and remove(id) cost the buckets of one box, query(rect) those of the rect (or every item, when the rect spans more buckets than there are items), query(rect, { sorted: true }) returns the items in id order, and bounds() is kept as boxes grow it, worked out again after one on its edge leaves. The diagram keeps three:

Index Holds Kept
The router's obstacles Each non-container node's bounds, padded by the stub (12-routing-around-shapes) As the node is drawn, preview included
Nodes (_nodeIndex) Every node's bounds (a rotated node by its bounding box), containers included Each committed box change; a preview doesn't move it
Connectors (_connIndex) Each connector's route box, grown by its label box (200 x 80 about the midpoint); until it routes, the box of its route drawn without searching Each route kept or drawn

What reads them, instead of walking the model:

Reader Query
Culling The strips the drawn rect gains and loses
The rubber band The band; the nodes it holds, in drawing order
_guideIndex() The view
_findPortTarget() The pointer's world point grown by the 16 screen px snap distance
_nodesShowingPorts() The view
_containerAt() The point; the containers among the hits, the last by a cached frame rank (rebuilt after an add, a removal, or a change of a container)
A committed move's swept boxes The connector index: only its hits can hold a kept route that meets a swept box

The selection keeps a Set beside its ordered list: membership, setSelectedIds()'s dedupe and the selected state of a drawn item read it. Ctrl+A (_selectAll()) takes the nodes in arrival order, the topmost last (the focus node, as in drawing order): O(n), no sort. The arrow keys' nearest node and zoomToFit() stay O(n): once per key or call.

Culling

The drawn rect is the view grown by a quarter of its width and height on each side; in the far view (below zoom 0.4), by one bucket, rounded out to the buckets. The write pass reads the view once, before writing anything, and works the rect out again when the view leaves it, when the far threshold is crossed, or when it is 2.5 times the area the view needs (zooming in: a smaller drawn set costs less layout at each scale step). A ResizeObserver on the canvas schedules a pass when it resizes.

What is drawn: the nodes and connectors whose box meets the drawn rect (a connector crossing the view between two nodes out of it is drawn), plus the records a gesture or a nudge burst previews (a dragged node stays drawn past the margin) and the item under the text editor. Hit-testing, ports and handles act only on what is drawn.

Entering and leaving. A recompute queries only the strips the new rect gains (their items not drawn are queued to enter) and the strips it loses (their drawn items are queued to leave): O(items in the strips). Each pass draws the entering items, nearest the view's centre first by rings one bucket wide, up to its draw budget, then releases leaving ones with what is left (at least 64, or 1ms). The budget is 4ms while the view moves (2.5ms in the far view, where each item costs more layout) and 8ms in a pass where neither the viewport nor a gesture moved (the view at rest catches up). A zoom-out or a fast pan in the far view fills in over the next frames.

Records. An item leaving gives its record to a free list of its kind (node, container, connector), its cached keys cleared; one entering takes a record from it, else a new one, and _drawNode() / _drawConnector() rewrite it as they always did, writing an attribute only when it changed (a record's own shape <path> is kept and given the new outline). A load and destroy() drop the free lists. The model, history, selection, saves and events don't change: culling is a view concern.

Drawing order. The nodes layer keeps its records sorted by (z, arrival); a record entering or changing z is placed by a binary search and one DOM move, not by sorting the drawn set again. The frames layer, a few containers, is sorted by the cached frame rank when it changes.

Marks. A geometry mark (an add, a removal, a change of box, symbol, parent or z) of an undrawn item updates its index entries only. A selection mark is a drawing mark: only the ids that joined or left the selection are marked, and an undrawn one needs nothing. The adorners walk the smaller of the selection and the drawn set; above 1,000 selected nodes in view the outlines give way to the selection colour on the selected shapes' strokes (a class on the canvas), since each outline is rewritten every pan frame.

Bulk changes. A change of more than 2,000 items (a layout, its undo) marks every route to compute again at once, instead of sweeping them node by node, and syncs its items over several passes, 8ms each: the edited node at once, the drawn nodes, the others, then, once every node has its new box, the connectors (the drawn ones first), so each routes once.

Consumers of the elements. The export draws the items it exports that aren't drawn, at full detail, a slice at a time, and releases a slice's items before the slice ends, so between slices only the drawn rect is drawn (11-clipboard-and-export). The text editor's item is drawn wherever it is, at full detail.

The drawing's hold. An export of many items holds the drawing (_holdDrawing()): while a hold lasts there is no drawn rect, so the write pass enters nothing and releases the drawn items through the leave queue at its budget, but the text editor's; an API change updates the indexes only; the adorners hide; _drawnComplete() is false. The last release queues what is still drawn for a rewrite at the zoom's detail and the next pass works the drawn rect out again; until a pass has, the drawing still counts as incomplete. A load's swap drops every hold (11-clipboard-and-export).

The far view

Below zoom 0.4 (about 5 px glyphs) a drawn item's text box and connector label are display="none" and not written; ports show on the hovered node only; the hit bands (connectors' and containers') are 40 world px strokes (4 to 16 screen px) rather than non-scaling ones, which Chromium lays out again at every zoom step. Shapes, fills, swatches, connector paths, arrowheads, the selection and the adorners stay. Crossing the threshold rewrites the drawn items that stay in the drawn rect, those in view first, 2ms of them a pass. The item under the text editor keeps its text box (a hidden <textarea> can't take focus). It hides elements and adds no paint, so every theme and forced colours draw it alike.

The load

After the fetch, loadDiagramAsync():

  1. Builds a new model with model.loadChunked() (the same code as load(), a generator that yields every 512 items; it awaits the page's turn after 8ms and stops when the load is superseded), then its three indexes in 8ms slices (_buildIndexes(), each connector by the route it is drawn with before searching). The current model stays drawn meanwhile; the diagram is busy, so a user edit is refused, and an API edit made then is replaced by the loaded data, as during the fetch.
  2. Swaps it in (_replaceModel()): cancels a gesture, clears the selection and the history, aborts the save queue, drops the drawn items; nothing walks every node.
  3. Zooms to fit unless the host set the viewport, then draws the drawn rect, one pass per frame (VanillaDiagram.nextFrame(): the next animation frame, or 100ms in a hidden page), still busy: the busy overlay, shown since the load began, stays.
  4. Ends its busy job (the overlay hides), fires vn-diagram-loaded and resolves: an awaiting caller finds the drawn rect drawn.
  5. Starts the route pass.

The yield (VanillaDiagram.yieldToPage()) is a MessageChannel task, as the grid's main-thread-yield.js (not loaded: the diagram needs no other component), setTimeout(0) where there is none; back-to-back MessageChannel tasks can keep the browser from drawing for up to 100ms, so after 32ms without a frame it waits for the next one.

The route pass

The elbows not drawn route in the background, in 8ms slices: the connectors waiting for a route are sorted into buckets by distance from the view's centre (doubling outward), routed nearest first, and each re-indexed by its route's box; one that now meets the drawn rect is queued to enter. A drawn connector routes when drawn, as before. The pass waits for the load's first draw, pauses while a gesture previews or a bulk change syncs, picks up the routes a committed change marked, and stops on a load and destroy(). With avoid-shapes="false" there is none. Until a connector routes, a detour outside its plain box may be missed by culling: the pass converges after the load.

Budgets and measurements

diagram-performance.spec.js (in PERF_SPECS), headless Chromium at 1280 x 720, 100,000 nodes and 100,000 connectors (rows of 316, one elbow per neighbour). A frame is one write pass and a forced layout, as the 1,000-node tests measure it; the 95th percentile of each kind on its own, twice:

Zoom 1 Zoom 0.1
Pan step (40 screen px) about 2.5ms about 13 to 15ms
Zoom-in step (1.1) about 1.5ms about 14 to 15ms
Zoom-out step about 11 to 13ms about 12ms
One-node drag frame about 1ms about 4ms
The view complete after the last step under 100ms about 150 to 450ms

The perf spec measures script and layout, not paint; at zoom 0.1 the browser's paint of the 8,000 drawn items adds about 12ms per frame in headless Chromium.