Rendering and Viewport Implementation in Vanilla-Diagram
One coordinate transform
World units are CSS px at zoom 1. A node's x, y is its top-left corner
before rotation; width, height its box; rotation turns it (degrees,
clockwise on screen) about its centre. The world has no bounds.
The viewport { x, y, zoom } is the world point at the canvas's top-left
corner and the scale: screen = (world - viewport) * zoom.
VanillaDiagramGeometry.toWorld() and toScreen() are the only conversions;
a pointer handler subtracts the canvas's client rectangle first. The geometry
module also turns a node's own frame into the world (localToWorld(),
worldToLocal()), places ports (a port's side turns with the node, rounded
to the nearest of the four directions), gives a rotated node's bounding box,
and resizes in a node's own frame (04-pointer-and-touch).
Layers
<svg class="vn-diagram-svg">
<defs> two arrowhead markers per diagram (normal, selected)
<g class="vn-diagram-world"> style="transform: matrix(zoom, 0, 0, zoom, tx, ty)"
<g class="vn-diagram-grid"> one <rect> filled with a dot <pattern>, under everything
<g class="vn-diagram-frames"> one <g> per container node, depth-first (a container under the
containers inside it), siblings by z; as a node's <g>, plus a
border hit path and a label-band hit rect
<g class="vn-diagram-connectors"> one <g> per connector: a 12px transparent hit path, the visible path,
and a <foreignObject> label box when it has a label
<g class="vn-diagram-nodes"> one <g> per node, in z order, data-swatch="<slot>" when it has one:
transform="translate(x y) rotate(r w/2 h/2)"
the shape (a <path>, or the render callback's element)
a <foreignObject> on the text box holding an HTML <div>
<g class="vn-diagram-preview"> the connect preview, the palette's drop outline
<g class="vn-diagram-adorners"> screen space: snap guides, selection outlines, the joining outline,
the focus ring, ports, route handles and tangents, resize handles,
the rotation handle, connector end handles, the rubber band
- Connectors are drawn under the nodes and above the container frames: a
plain elbow crossing a shape passes behind it, and while
avoid-shapesis on an elbow routes around the shapes (12-routing-around-shapes). A lane's fill never hides the connectors between its children (13-containers). - A node's own colours are custom properties set on its
<g>(--vn-diagram-node-fill, ...), so they win over the theme by inheritance; presentation attributes would lose to the theme's class rules. A node'sswatchis thedata-swatchattribute on the same<g>, which the base stylesheet maps to the slot's tokens; the inlinestylestill wins (09-themes). - The browser hit-tests the painted shape: a click in the corner of a diamond's box misses the diamond. The rubber band and the arrow keys use the boxes.
- Text is HTML in a
<foreignObject>covering the symbol's text box: CSS wraps it, centres it and clips what overflows; the<div>takes no pointer events.white-space: pre-wrapkeeps a\nas a line. An emptytextnode shows thetextPlaceholdermessage. The text editor takes the<div>'s place while it is open, and a connector's label has a<foreignObject>of its own at the route's midpoint (10-text-editing). - The adorners live in screen space, so handles and ports keep their size at any zoom; they are pooled and redrawn from the model each pass that needs them. That includes the snap guides of a move or resize (04-pointer-and-touch) and the route handles of each selected elbow or bezier (05-ports-and-connectors).
- The rotation handle shows with the resize handles (one selected node,
nothing else selected, not read-only), but not on a container: a 16px disc
24 screen px beyond the middle of the node's top edge, in its own frame, on
a thin stem from that edge, with a clockwise circular arrow on it (an arc
and its head,
vn-diagram-rotate-iconand-icon-tip); it turns with the node and paints with the resize handles' tokens, the arrow in the selection colour. Its hit area is the disc, 16px across, 24px under(pointer: coarse).
The grid
grid-size (world px, 0 off) draws dots with an SVG <pattern> (spacing the
grid size, offset half a cell so a dot sits on each multiple, a dot of 1
screen px) on one <rect> in the vn-diagram-grid group, first in the world
layer. The rect covers three views' width and height around the view and is
rewritten with each viewport write, so the grid is O(1) per pan or zoom step.
Below 8 screen px between dots the grid hides: it would be noise. The grid
takes no pointer events, and the export leaves it out. Its dots paint with
--vn-diagram-grid-color.
What is in the DOM
Only what meets the drawn rect (the view grown by a quarter of its size
on each side; below zoom 0.4 by one 256 px bucket), plus the items a gesture
previews and the text editor's item: a host's code or CSS can't expect one
.vn-diagram-node per node. A diagram that fits the view after its load's
zoom to fit draws every item. Items entering the rect are drawn under a
per-frame budget, nearest the view's centre first, in records that leaving
items gave to a free list
(14-large-diagrams). Every node and
connector group is aria-hidden, with no role or aria-label, but the
text editor's (15-screen-readers).
The far view. Below zoom 0.4 a drawn item's text box and connector label
are display="none" and not written, ports show on the hovered node only,
and the hit bands are 40 world px strokes rather than non-scaling ones. The
shapes, connectors, arrowheads, the selection and the adorners stay; the
export and the text editor show the text at any zoom.
The write pass
A change marks ids dirty (_markNode(), _markConnector(), _markEffect();
a node's connectors with it); a selection change marks only the ids that
joined or left it. One requestAnimationFrame pass (_renderNow()) reads
the view once, works the drawn rect out again when the view left it, syncs
the dirty nodes (their index entries, then drawn, queued or released), keeps
the obstacle index of the routed elbows on the nodes as drawn, syncs the
dirty connectors, draws the entering items under the budget and releases the
leaving ones, puts entering node groups in z order (a binary search of the
drawn order; the frames layer in its depth-first order), writes the
viewport, redraws the overlays and adorners, and fires the viewport event.
Every attribute is written only when its value changed, as the Gantt's link
layer does. A node's shape is rebuilt only when its symbol, size, or (for a
render callback) text or data changed. A change of more than 2,000 items is
synced over several passes. A ResizeObserver on the canvas schedules a
pass when it resizes.
A gesture's preview (_preview: a move offset, a resized box or a rotation) is applied
by _effectiveNode() when drawing, so the model is untouched until the
gesture commits.
Pan and zoom
- Wheel zooms about the pointer, with or without Ctrl or Cmd, by
exp(-deltaY * 0.002), at most 1.25 (the keys' step) in or out per event: Windows' "one screen at a time" setting sends page-mode deltas, about 4x a notch uncapped. Line and page delta modes are converted to px.deltaXis ignored, so no wheel pans: a horizontal-only event (a tilt wheel, Shift + wheel where the browser moves the delta to x, a sideways swipe) does nothing. A trackpad's two-finger scroll zooms too; a trackpad pinch arrives as Ctrl + wheel in Chromium and Firefox. Safari'sgesturestartandgesturechangezoom by the gesture's scale. While the diagram is busy, the canvas swallows both and zooms nothing (01-web-component ยง The busy state). - Mouse: a middle- or right-button drag pans, from anywhere on the canvas; the canvas cancels the browser's context menu. Touch: one finger on the empty canvas pans, two pinch-zoom and pan together (04-pointer-and-touch).
- Keys: arrows pan 40 screen px with nothing selected;
+,-,0,1(06-keyboard-and-focus). - API:
setViewport()(zoom clamped),zoomBy(factor, at)about a canvas point (default the centre),zoomToFit(padding = 24)(no-op when empty),scrollToNode(id)(centres it, keeps the zoom).
Zoom stays within minZoom and maxZoom (0.1 and 4 by default), which
getZoomLimits() returns; zooming about a point keeps the world point under
it. vn-diagram-viewport-changed
fires from the write pass, so at most once per frame. An API call marks the
viewport as set by the host: a load then keeps it instead of zooming to fit.
Why a CSS transform. The world group's transform is the CSS transform
property, not the transform attribute (an SVG element's transform origin is
0 0, so the matrix means the same). Chromium lays the whole SVG subtree out
again when the attribute changes, about 20ms at 1,000 nodes, and not for the
property, about 5ms. For the same reason nothing is written on the <svg>
per zoom step: a custom property there restyles every descendant. The
matrix takes the zoom unrounded, the very value the screen-space adorners
use: a scale rounded to 0.001 moved a shape away from its outline, handles
and ports by its world coordinate times the rounding, a few px at 10,000
world px from the origin. Only the offsets round, to 0.001 screen px.