Auto-Layout Implementation in Vanilla-Diagram

layout({ kind, direction, spacing }) arranges every node of the diagram, as layers or as a tree, gives each connector of a moved node the ports that face each other at the new places, and applies the result as one command. A shape hanging off the side of a step (a note, a data store) stays beside it. A second layout() with the same options moves nothing.

layout(options?: {
    kind?: 'layered' | 'tree';                      // default 'layered'
    direction?: 'down' | 'right' | 'up' | 'left';   // default 'down'
    spacing?: { node?: number; layer?: number };    // world px, default 40 and 80
}): Promise<boolean>;

Two spacings, since a flowchart needs more room between layers than within one; a spacing that isn't a positive finite number takes its default. Directions are absolute: a right-to-left page doesn't flip them. A promise, since a large layout computes in slices (a worker could take it later without an API change).

The step

  1. Resolves false, with no warning, for an empty diagram, before initializeDiagram() and after destroy(); with a warning, for an unknown kind or direction.
  2. Begins its busy job (isBusy(), 01-web-component ยง The busy state), which stops user input first (an open text edit commits), so that can't make it stale; user edits are refused from here on. Commits a nudge burst, then reads a snapshot: each node's bounds (a rotated node by its bounding box), container flag, label band (its share of the height and its cap) and minimum size, its parent, the connectors whose both ends are on nodes with the side, as drawn, of the port at each end (fromSide, toSide; none for a port its symbol doesn't have), and the model's changeCount (grown by every mutation and load).
  3. Computes the positions with VanillaDiagramLayout.steps(), yielding in 8ms slices; then, in slices too, the ports of each connector with a moved end (Ports after a layout); and always yields once more after that.
  4. Resolves false when the change count moved, a load ran, another layout() started, or the diagram was destroyed meanwhile: nothing is applied.
  5. Cancels a gesture in progress and applies the positions as one batch labelled command.layout (Arrange {count} shapes, the shapes it moved), executed once through _execute(), as setSwatch() and the rotation keys do: an update of x and y per moved node (and width, height per resized container), and the connector updates below (their new ports, free ends and cleared routes). One undo step, one vn-diagram-changed (source api), one change set; the undo restores the ports too. Resolves true, or false when nothing moved.

Busy until drawn. A run that resolves false ends its busy job then. After an apply, the job outlives the promise: it ends at the first animation frame where the drawn rect is complete (_drawnComplete(): the bulk sync has given every drawn node and connector its place), so a zoomToFit() made when the promise resolves, as Tidy up's, is drawn first, and nothing in view moves after busy ends. A newer load or layout, or destroy(), ends that wait at once; an export doesn't, and its job joins the layout's. A user edit during the run is refused, so it can't make the run give up; an API mutation still does. At 100,000 shapes busy lasts about 2.5s past the resolve (about 5s in all).

It works in read-only mode, as every API mutation. The apply is one task, accepted for a user-requested arrangement of the whole diagram. When every connector's ports change (a chain drawn left to right, laid out down), it builds and executes an update per node and per connector: at 10,000 nodes about 60ms (the largest frame gap about 110 to 130ms), at 100,000 about 650 to 700ms (half of it executing the batch and storing the change set). The view then syncs the change in slices (14-large-diagrams, bulk changes). In process-flowchart-js at 100,000 shapes in 1,000 lanes, the positions compute in about 0.8s in Chromium and 1.3s in Firefox, and layout() resolves in 2.5 to 3.5s; at 10,000 shapes, in 0.33 to 0.45s.

The layered layout

Pure and deterministic (features/layout.feature.js, ties by z, then id):

  1. Components. Each connected component is laid out on its own; they go side by side across the flow, 2 x spacing.node apart, in the order of their leading edge across the flow today (the smallest x for down and up, y for right and left; ties by their first node's z); the nodes with no connector last, in one row, in their order across the flow today. So separate flows keep the order they were drawn in, and a second run reads the order the first one placed.
  2. Cycles. A depth-first search from the nodes in z order reverses its back edges (the Gantt's cycle rule as a pattern, not its code).
  3. Layers. The longest path from the sources: every edge points to a later layer.
  4. Long edges cross the layers between their ends through dummy points of no size.
  5. Order in a layer. The search's order first, then four sweeps (down, up, down, up) by the median of the neighbours' positions, ties kept.
  6. Coordinates. Each layer's boxes left to right spacing.node apart, then four passes pulling each box toward the median of its neighbours' centres without breaking the order or the gaps (pooled adjacent violators: the nearest positions the order and gaps allow). The layers stack spacing.layer apart, each as tall as its tallest box, the boxes centred in it.
  7. Direction. Computed for down, the boxes' axes swapped for right and left, mirrored for up and left.

Cost: O((n + d) x 4 + m log n) for d dummy points; a 20,000-node graph with long edges lays out in well under a second in Node.

The tree layout

The roots are the nodes with no incoming connector, in z order (a cycle with no root starts at its first node); a breadth-first search from them takes each node's first parent, and the other connectors place nothing. Each subtree is as wide as the larger of its root and its children side by side spacing.node apart, the root centred over them, the levels spacing.layer apart. O(n + m). The same components, satellites, directions and grid as the layered layout.

Containers, free ends, edited routes

Ports after a layout

A connector keeps the ports it was drawn with until a layout: then each connector with both ends on nodes and a moved end gets the ports that face each other at the new boxes. VanillaDiagramLayout.facingSides(a, b, direction) reads how the two bounding boxes lie along the flow (y for down and up, x for right and left, mirrored for up and left):

The target The sides
After the source (forward, a long connector too) The flow's exit and entry: bottom and top for down, top and bottom for up, right and left for right, left and right for left
Before the source (a cycle's back edge) One side across the flow at both ends, a loop on the side: right for down and up, bottom for right and left
Overlapping it along the flow (a satellite, a tree's cross edge) The facing sides across the flow, by the centres
Holding it, or held by it (a container and its descendant), or itself None: the ports are kept

VanillaDiagramLayout.portsAfter() then picks each end's port among its symbol's ports placed at the node's new box, sides turned by its rotation (portPoint()): the current port when it is already on the wanted side, so an author's choice among several ports on one side survives; else the one on that side nearest the other node's centre. With no port on that side, a forward connector takes the nearest port on the flow axis, then the nearest of any side; the others the nearest of any side. A symbol with no ports keeps its port. The flow axis first keeps a second run from finding a side port on a one-connector shape's neighbour and taking it for a satellite.

The choice runs between steps() and the stale check, in 8ms slices, and portsAfter() is in a fast-path chunk: the apply only adds an update of from and to per changed connector. A connector with a free end keeps its port, and a connector with no moved end is left alone. The change is an API mutation like the rest of the batch: vn-diagram-connecting doesn't fire, and a host whose ports carry a meaning (an input and an output) sees them chosen again.

Satellites

A shape hanging off the side of a step of the flow is placed beside that step, not in a layer of its own. At each level (inside out, as above), a node S is a satellite of O when:

Before the components are found, each owner's satellites leave the graph and the owner's box is widened on both sides by the larger of its two sides' extents (each satellite's size across the flow plus spacing.node), so the owner stays centred and the flow through it straight; its size along the flow becomes the largest of it and its satellites. After the kind's layout, each satellite goes on its port's side, spacing.node from the owner and from each other, outward in z order, centred on the owner along the flow, in the owner's layer; then the direction and the grid apply to it as to any box.

On the order sample laid out down, the note, Inventory, Purchase order, Invoice and Orders are satellites; End is not (Cancel order's flow enters by its left port, along no flow of down), nor Order complete and Shipping email (they hang off a bottom port). The rules read ports against the direction layout() is given, not the one the diagram was drawn in: a diagram drawn top down and laid out right gets the ends of its flow as satellites. After that run, the ports fit the new direction.

A second run

A second layout() with the same options on an unchanged diagram moves nothing and resolves false. Nothing it reads changes: the order inside a component doesn't depend on the positions; a satellite's connector gets the facing sides across the flow, so it is still a satellite on the same side; a one-connector shape that isn't one lands in another layer than its neighbour, so its connector gets flow sides (or a port on the flow axis); and the flows and unconnected nodes sit in the order they were placed in. One case can change: an owner whose only connectors along the flow are cycle back edges, which the side loop puts across the flow.

The grid and the anchor

The laid-out diagram keeps the top-left of the old one. With a grid (grid-size), the spacings round up to a multiple of it, every box's corner snaps to it, and the boxes are pushed in layer order (each layer at least spacing.layer past the one before, each box at least spacing.node past its neighbour), so no gap shrinks; a container's children start on the grid inside it.

Tidy up

<vn-diagram-toolbar>'s standard command layout (label key toolbar.layout, Tidy up; icon layout) runs layout() with the defaults, then zoomToFit() when it resolves true. It is enabled while linked, not read-only, not busy and with nodes, so a second click can't restart a run; the busy overlay says arranging until the fitted drawing is final. It isn't in the default bar (Diagram Toolbar). process-flowchart-js and plant-automation-js put it after the status line.