Skip to content

Graph layout and routing ​

The core computes where nodes go and how edges run, without Vue: a deterministic layered layout (layoutLayeredGraph) in four directions with crossing reduction, tree, radial, circular, grid, concentric, force and swimlane layouts, named ports, orthogonal routes around obstacles, edge label placement, incremental placement that keeps the nodes already on display, and quantity flows (Sankey diagrams). NetworkGraph calls the same functions; call them yourself to lay out on a server or in a Worker, to feed the layout prop, or to draw your own renderer.

Minimal example ​

ts
import { layoutRadialGraph, type GraphLayoutFunction } from '@eightkk/vue-weave/core'

const nodes = [{ id: 'hub', label: 'Hub' }, { id: 'a', label: 'A' }, { id: 'b', label: 'B' }]
const edges = [{ id: 'ha', from: 'hub', to: 'a' }, { id: 'hb', from: 'hub', to: 'b' }]

// On a server or in a Worker: a plain result with boxes, paths and bounds
const layout = layoutRadialGraph(nodes, edges, { roots: ['hub'] })

// In NetworkGraph: the same function through the `layout` prop
const radial: GraphLayoutFunction = (shownNodes, shownEdges) => layoutRadialGraph(shownNodes, shownEdges, { roots: ['hub'] })
// <NetworkGraph :nodes="nodes" :edges="edges" :layout="radial" />

Examples: Linked views and the example index. Guide: Graph integration, including ELK.js. Types: GraphLayout, layoutLayeredGraph, routeGraphEdges. The overview table of every core export is on Core entry point.

Graph routing ​

graphPortAnchor(box, port) returns a GraphPoint on the named side of a GraphBox. Coordinates are world-coordinate pixels. port.offset defaults to 0.5 and measures down a vertical side or across a horizontal side. Supply finite box geometry and a port offset in [0, 1]; the helper does not validate them. A port.side other than left, right, top or bottom throws an Error naming the port.

graphEdgeEndpoint(layout, nodes, edge, end, direction) returns { x, y, side }. nodes is a node-ID-keyed map, end is from or to, and direction is a GraphLayoutDirection. Named ports take precedence. Otherwise, when edge has an id with a path in layout.paths, the result is the drawn first or last point of that path, and side is the box side closest to it. This matches the rendered edge after saved positions reverse two nodes and for custom layouts that choose their own sides. Without a path, LR uses right/left and TB uses bottom/top for source/target endpoints. Validate nodes and edges with indexGraph and supply matching layout boxes before calling this helper; an endpoint without a layout box throws an Error naming the edge and the node, and a named port whose side is not left, right, top or bottom throws an Error naming the node and the port. routeGraphPorts throws the same errors.

graphPathEndpoints(path) returns { start, end }: the first moveto point and the current point after the last segment (the subpath start after Z), or undefined for a path without coordinates. It throws like graphPathBounds for malformed path data.

NetworkGraph applies applyGraphPositions, then applyGraphSizes, then routeGraphPorts and finally routeGraphEdges for its edgeStyle. applyGraphPositions overlays finite, nonnegative coordinates, expands the layout bounds when needed and reroutes incident edges while preserving other paths. Position entries for unknown node IDs are ignored, but their coordinates are still validated (RangeError), and an incident edge whose other end has no layout box throws an Error naming the edge and the node. routeGraphPorts then replaces paths and label positions for edges with named ports, leaving unnamed-edge routes intact; with the routingPolicy prop 'preserve' both routing steps run with policy: 'preserve' and keep the layout's valid paths, also for edges with named ports. These operations do not mutate the supplied layout and may return it unchanged when there is nothing to update.

Layout defaults and option checks ​

Every built-in layout uses the same defaults for the options it shares: nodes 144 × 58, columnGap 50, rowGap 24 and padding 20.

LayoutOptions typeShared defaultsOther spacing defaults
layoutLayeredGraphGraphLayeredLayoutOptions (extends GraphLayoutOptions)all—
layoutTreeGraphGraphTreeLayoutOptions (extends GraphLayoutOptions)all—
layoutSwimlaneGraphGraphSwimlaneLayoutOptions (extends GraphLayoutOptions)alllaneGap 0, lanePadding 12, minLaneSize 0, headerSize 120 (LR, RL) or 32 (TB, BT)
layoutGraphIncrementallyGraphIncrementalLayoutOptions (extends GraphLayoutOptions)allmaxDisplacement 0
layoutGridGraphGraphGridLayoutOptionsnodes, columnGap, rowGap, padding—
layoutRadialGraphGraphRadialLayoutOptionsnodes, paddingringGap 40
layoutCircularGraphGraphCircularLayoutOptionsnodes, paddingnodeGap 40 (between neighbours on the circle)
layoutConcentricGraphGraphConcentricLayoutOptionsnodes, paddingringGap 40
layoutForceGraphGraphForceLayoutOptionsnodes, paddingnodeGap 16 (kept by the overlap passes), linkDistance 180
layoutFlowGraphGraphFlowOptionspaddingnodeThickness 24, nodeGap 16 (across the flow), rankGap 120, referenceGap 12

The tree, swimlane and incremental options extend GraphLayoutOptions and add their own fields, so one GraphLayoutOptions object can be spread into any of them.

Every layout checks its numeric options the same way and throws a RangeError whose message names the option, the rule it broke and the value it got: <option> must be <rule> (got <value>).

RuleOptionsExample message
a finite number > 0nodeWidth, nodeHeight; radius (circular), levelWidth (concentric), nodeThickness, minNodeSize, pixelsPerUnit and fitExtent (flow)nodeWidth must be a finite number > 0 (got 0)
a finite number ≥ 0columnGap, rowGap, padding, ringGap, nodeGap, laneGap, lanePadding, minLaneSize, headerSize, maxDisplacement, linkDistance, repulsion, rankGap, minBandWidth, referenceGapcolumnGap must be a finite number ≥ 0 (got -1)
a finite numberstartAngle (circular, concentric)startAngle must be a finite number (got NaN)
an integer ≥ 1crossingSweeps, columns (grid), iterations (force)crossingSweeps must be an integer ≥ 1 (got 0)
a finite number in [0, 1]gravity (force)gravity must be a finite number in [0, 1] (got 2)
a safe integerseed (force)seed must be a safe integer (got 0.5)

The same check and message are used by these numeric options of other graph functions: cornerRadius (≥ 0) and parallelSpacing (> 0) of routeGraphEdges and graphPolylinePath, clearance and bendPenalty (≥ 0) of obstacle avoidance, threshold (≥ 0) of graphAlignmentGuides, grid (> 0) of snapGraphPoint, tolerance (> 0) and maxIterations (integer ≥ 1) of graphPageRank, resolution (> 0) of detectGraphCommunities, minSize (integer ≥ 1) of graphCommunityGroups, and neighborhood of filterGraph, which must be an integer ≥ 0 (neighborhood must be an integer ≥ 0 (got -1)).

A value that is not a number is reported as such, for example (got "5") or (got null). Options are checked in a fixed order (node sizes first), and only the first invalid one is reported. Node data such as positions and per-node sizes keeps its own messages, which name the node.

Same-rank edges (inside a cycle) and self-loops of the layered, tree and swimlane layouts leave the flow-end side of the box and turn min(24, max(6, columnGap / 2)) units past it.

Layout directions, crossing reduction and extra layouts ​

GraphLayoutOptions.direction also accepts RL and BT. They mirror the LR and TB layouts (ranks grow right-to-left or bottom-to-top) and keep paths, edge labels and bounds consistent. graphEdgeEndpoint, routeGraphPorts and applyGraphPositions accept the same GraphLayoutDirection type; unnamed endpoints leave and enter on the mirrored sides.

layoutLayeredGraph accepts GraphLayeredLayoutOptions, which adds opt-in crossing reduction:

OptionMeaning
crossingReductionnone (default, input order, output unchanged), barycenter or median. Alternating down/up sweeps reorder each rank by the mean or median position of neighbouring nodes. Ties keep input order and the best ordering seen, never worse than the input, is kept. Deterministic and iterative.
crossingSweepsPositive integer sweep limit. Default 8.

countGraphCrossings(layout, edges, direction = LR) counts crossings between edges that join adjacent ranks, measured on box centres. Long edges (rank jump above one), same-rank edges and self-loops use dedicated routes and are not counted. An unknown direction and a box without finite x, y, width, height and rank throw a RangeError; an edge end without a box in the layout throws an Error.

layoutTreeGraph(nodes, edges, options) and layoutRadialGraph(nodes, edges, options) return a GraphLayout, so they can be used as the NetworkGraph layout prop, for example (n, e) => layoutTreeGraph(n, e, { direction: 'TB' }). Both build a breadth-first spanning forest. Roots are options.roots (unknown IDs throw an Error), then nodes without incoming edges, then any node left over inside a cycle. Edges that are not tree edges (cross, back, same-depth and self-loops) are still routed. Cycles, disconnected nodes and self-loops do not throw. Invalid numbers throw RangeError. Traversals are iterative.

  • GraphTreeLayoutOptions extends GraphLayoutOptions (direction LR, TB, RL or BT, nodeWidth, nodeHeight, columnGap between depths, rowGap between leaves, padding) with roots. Leaves are spaced evenly and each parent is centred over its children. Box rank is the tree depth.
  • GraphRadialLayoutOptions: nodeWidth, nodeHeight, ringGap (default 40), padding and roots. Nodes sit on concentric rings by depth; one root is placed at the centre, several roots share the first ring. Subtrees receive angular wedges proportional to their leaf counts and ring radii are widened so boxes do not overlap. Edges are straight segments clipped to the box borders.

layoutCircularGraph(nodes, edges, options), layoutGridGraph(nodes, edges, options) and layoutConcentricGraph(nodes, edges, options) are three more built-in GraphLayout producers for the layout prop, for example (n, e) => layoutGridGraph(n, e, { columns: 4 }). Edges are straight lines between box borders (so in a grid they can pass over other boxes) and self-loops are small curves on the right side of the node. Cycles, disconnected nodes, parallel edges and self-loops do not throw; duplicate node IDs and edges that reference unknown nodes throw an Error, invalid numbers throw RangeError. All three are deterministic, never mutate their input, are iterative, and take O(n + e) (concentric adds a sort of the distinct levels).

  • layoutCircularGraph places all nodes on one circle in input order (or in sort order, a stable sort of a copy). The default radius is the smallest one that keeps nodeGap (default 40) between neighbouring boxes, so it grows linearly with the node count. An explicit radius throws a RangeError when it is not finite and positive or too small for the node count. startAngle is in radians, default -Math.PI / 2 (top), and clockwise defaults to true.
  • layoutGridGraph fills rows of columns nodes in input order. columns must be a positive integer (default Math.ceil(Math.sqrt(n))). rank is the row index.
  • layoutConcentricGraph puts nodes on rings by level(node, degree), where degree counts incident edges without self-loops and is the default level. Higher levels sit closer to the centre and rank is the ring index, 0 being the innermost. levelWidth groups levels into one ring when floor(level / levelWidth) is equal; without it each distinct level has its own ring. level must return finite numbers (RangeError otherwise). Every ring is large enough for its nodes and rings are at least one node diagonal plus ringGap (default 40) apart, so boxes never overlap. Nodes keep input order within a ring.
  • GraphCircularLayoutOptions: nodeWidth, nodeHeight, nodeGap, padding, radius, startAngle, clockwise, sort.
  • GraphGridLayoutOptions: nodeWidth, nodeHeight, columnGap (default 50), rowGap (default 24), padding, columns.
  • GraphConcentricLayoutOptions: nodeWidth, nodeHeight, ringGap, padding, level, levelWidth, startAngle.
  • Both functions are generic over the node type, so sort and level receive your own nodes (for example NetworkNode<MyData>) without casts.

layoutSwimlaneGraph(nodes, edges, options) lays a process out in swimlanes: one band per lane in the caller's order, the flow running along the bands. It returns a GraphSwimlaneLayout, a GraphLayout (for the NetworkGraph layout prop) plus lanes, one GraphSwimlane per lane in the given order: the band { x, y, width, height } across the whole flow (header included), its header rectangle at the flow start of the band, id, label, index and nodeIds (by rank, then by position inside the lane). Pass lanes to the NetworkGraph lanes prop and to renderGraphSvg; see Swimlanes.

  • Ranks (position along the flow) are those of layoutLayeredGraph: the condensation of the strongly connected components, so cycles and self-loops terminate and every node of a cycle shares one rank; same-rank edges and self-loops turn on the right side of the box (in LR). Traversals are iterative, so a 12,000-node chain lays out.
  • Across the flow every node lies inside its own lane's band, clear of the header. Several nodes of one lane in one rank are stacked (rowGap apart) and centred, and the band grows to fit the largest stack. A lane without nodes still gets a band one node thick, so a step added to it later keeps the other lanes in order. The lane order itself never changes, and adding a node or an edge keeps every lane's position relative to the others.
  • crossingReduction: 'barycenter' (the default) reorders the nodes of one lane in one rank by alternating barycenter sweeps and keeps the best order found by adjacent-rank crossings; 'none' keeps input order. Nodes never leave their lane. The output is deterministic.
  • Edges are cubic curves from the source box's flow-end side to the target's flow-start side, labels at their middle (in the gap between ranks, never in a header). Edges that skip ranks are not routed around the boxes between; use edgeStyle: 'orthogonal' with avoidNodes for that.
OptionMeaning
lanesRequired. Lane IDs or { id, label } (GraphSwimlaneSpec) in display order; the label defaults to the ID. An ID that is not a non-empty string throws Error('Invalid swimlane ID: <value>') and a repeated one Error('Duplicate swimlane ID: <id>').
laneOfRequired. (node) => laneId (it receives your node type) or a ReadonlyMap of node ID to lane ID. A node without a lane (undefined, null or an empty string) throws Error('Graph node has no swimlane: <id>'); an unknown lane throws Error('Unknown swimlane in graph node <id>: <lane>'). There is no implicit "unassigned" lane: add one to lanes and map such nodes to it if you want them drawn.
directionLR (default) and RL give horizontal lanes stacked top to bottom; TB and BT give vertical lanes stacked left to right. The header sits at the flow start: left (LR), right (RL), top (TB) or bottom (BT).
nodeWidth, nodeHeightBox size, default 144 × 58; positive.
columnGapDistance between ranks along the flow. Default 50.
rowGapDistance between stacked nodes of one lane in one rank. Default 24.
laneGapFree space between neighbouring bands. Default 0.
lanePaddingSpace between a band's edges (and its header) and its nodes. Default 12.
minLaneSizeSmallest band thickness across the flow. Default 0, so a band is at least one node plus twice lanePadding.
headerSizeThickness of the header along the flow. Default 120 for LR and RL, 32 for TB and BT; 0 draws no header.
paddingMargin around the bands. Default 20.
crossingReduction, crossingSweepsbarycenter (default) or none; positive integer sweep limit, default 8.
pools, poolHeaderSize, poolGapOpt-in pools (BPMN participants) around consecutive lanes, the thickness of their title band (default 32) and the space between pools (default 24); see BPMN and flowchart shapes, markers and pools.

GraphSwimlaneLayoutOptions extends GraphLayoutOptions. Sizes that are not finite or are negative (and node sizes of 0) throw RangeError (see Layout defaults and option checks), as do an unknown direction or crossing method; the graph errors of indexGraph (duplicate IDs, unknown endpoints) throw Error.

graphSwimlaneAt(lanes, target) returns the lane (of any GraphSwimlaneBand list) whose band contains a point, or the centre of a rectangle such as a node box, or undefined in a gap or outside every band. Bands are half-open, so a point on the far edge of one band belongs to the next. A non-finite point throws RangeError.

layoutForceGraph(nodes, edges, options) is a deterministic force-directed GraphLayout producer for the same layout prop, for example (n, e) => layoutForceGraph(n, e, { seed: 1 }). Linked nodes are pulled toward linkDistance, every pair of nodes repels through an iterative Barnes–Hut quadtree, and a weak gravity pulls each group toward its centre while the simulation cools over iterations steps. Grid-based passes then push overlapping boxes apart until every pair keeps nodeGap of free space, spreading free nodes slightly when a region stays crowded. The same input and options always give the same output: start positions come from a seeded mulberry32 generator, never Math.random. About 2,000 nodes with the default 300 iterations take roughly half a second in Node. The work grows with the node count and iterations (3,750 nodes take about a second) and runs synchronously, so for large graphs compute it once in a worker or on the server and pass the result through positions, or lower iterations.

OptionMeaning
nodeWidth, nodeHeight, paddingBox size (144 × 58) and outer margin (20).
iterationsPositive integer simulation steps. Default 300.
linkDistancePreferred distance between the centres of linked nodes. Default 180.
repulsionNonnegative many-body repulsion strength. Default 600.
gravityPull toward the group centre in [0, 1]. Default 0.05.
nodeGapMinimum free space between boxes after the overlap passes. Default 16.
seedInteger seed for the initial placement. Default 1.
initialPositionsReadonlyMap<string, GraphPoint> of start positions as box top-left corners, for example the boxes of a previous layout. A node without one starts near an already placed neighbour, otherwise at a seeded point. Unknown IDs are ignored.
fixedReadonlySet<string> of pinned node IDs. They keep their initial position (or their seeded start without one). Unknown IDs are ignored.

Connected components (ignoring edge direction) are laid out separately and packed in rows, so disconnected parts never overlap. Without pinned nodes the drawing is translated so its bounding box starts at padding. Components that contain a pinned node are simulated together in the caller's coordinate frame and the other components are packed to their right; pinned boxes are reported at exactly their given coordinates unless some node or route would start above or left of padding, in which case the whole drawing is shifted by the same amount. Overlaps between two pinned boxes are not resolved. Box rank is the breadth-first depth, ignoring edge direction, from the first node of its component in input order. Edges are straight segments clipped to the box borders with labels at their midpoints. Parallel edges between one pair (in either direction) bend to alternate sides as quadratic curves with the label at the curve midpoint, and self-loops are drawn as growing loops on the right side. An empty graph returns 2 × padding (at least 1) for both dimensions. Unknown endpoints and duplicate IDs throw Error through indexGraph; invalid numbers, a non-integer seed and non-finite initial positions throw RangeError. All traversals are iterative and the arguments are never mutated.

Related exported types: GraphCrossingReduction, GraphForceLayoutOptions, GraphSwimlaneLayoutOptions.

Incremental placement ​

layoutGraphIncrementally(nodes, edges, positions: ReadonlyMap<string, GraphKnownPosition>, options?: GraphIncrementalLayoutOptions): GraphIncrementalLayout places the nodes that have no position yet around the ones that do, for a graph that grows (a page of a graph expansion, a new node) without moving what the user is looking at. GraphKnownPosition is a box top-left corner, optionally with width, height and rank, so the boxes of an earlier layout can be passed as they are. The result is a complete GraphLayout for the layout prop (or its boxes for positions) plus placedIds (the new nodes in placement order), movedIds (positioned nodes the relaxed mode pushed aside) and fallbackIds (see allowNegative).

  • Every node in positions keeps its box exactly: displacement 0. Positions of IDs that are not nodes are ignored, so a map can be reused after nodes are removed.
  • A new node goes on the flow side of its placed neighbours: after its placed predecessors (at the largest end along the flow, plus columnGap), or, when none is placed, before its placed successors. Across the flow it takes the free place nearest to the middle of those neighbours, below before above (right before left for TB and BT), keeping columnGap along and rowGap across the flow from every box, so several new nodes of one neighbour stack around it in input order. Its rank is one more than its predecessors' (one less than its successors').
  • New nodes are placed breadth-first from the positioned ones, so a chain of new nodes is placed in dependency order, each one after the one before. Self-loops are ignored for placement and cycles are allowed: a node with placed predecessors and successors goes after the predecessors.
  • Components without any positioned node are laid out together with layoutLayeredGraph (with the largest node size) and placed after every other box across the flow: below them for LR and RL, to their right for TB and BT, starting at the smallest coordinate along the flow, rowGap away. With no positions at all they start at padding.
  • Edges get the curve drawn for a moved node between their boxes; with previousLayout, an edge whose two end boxes are unchanged keeps its path, label anchor and route metadata.
  • Free places are found with a bucket grid of the boxes (jumping past the boxes in the way, at most 256 jumps each way before using the place past every box), so the cost grows with the number of nodes and edges: a 12,000-node chain appended to 3,000 boxes takes well under a second in Node. Deterministic for the same input; all traversals are iterative; the inputs are not modified.
OptionMeaning
directionGraphLayoutDirection / 'LR'. RL and BT place successors to the left and above. GraphIncrementalLayoutOptions extends GraphLayoutOptions, which holds direction, nodeWidth, nodeHeight, columnGap, rowGap and padding.
nodeWidth, nodeHeight144 × 58: the size of a node without its own.
sizesReadonlyMap<string, GraphNodeSize> of node sizes; a size in the node's position wins.
columnGap, rowGap50 and 24: free space along and across the flow.
padding20: added to the right and bottom of the layout size, and the origin of a graph without positions.
fixedIdsIterable<string> of pinned nodes. Each must be a node with a position. They never move, whatever the other options.
maxDisplacement0. Relaxed mode: a positioned node that is not fixed may be pushed across the flow by at most this many units when it blocks the place a new node wants. Only the boxes in that place are pushed, each away from it, and only when they then keep their gaps to every other box; otherwise nothing moves and the new node searches as usual.
allowNegativefalse: new boxes keep nonnegative coordinates, as the positions prop requires and the camera fit expects. A new node whose flow side would leave that area (a predecessor of a node at the left edge in LR) is placed beside its nearest neighbour in that neighbour's rank, across the flow, and listed in fallbackIds. true always uses the flow side, also at negative coordinates.
previousLayoutAn earlier layout (boxes, paths, edgeLabels, optional routes) whose paths are kept for edges between unchanged boxes.

Throws Error for the graph errors of indexGraph and for a fixed ID that is not a node (Unknown node in fixedIds: <id>) or has no position, and RangeError for an unknown direction, a non-finite position, a size that is not finite and positive, and gaps, padding or maxDisplacement that are not finite and nonnegative. For a force layout that keeps chosen nodes, layoutForceGraph takes initialPositions and fixed; it moves the other nodes.

graphLayoutChangeMetrics(before: ReadonlyMap<string, GraphPoint>, after: { boxes, paths? }, options?: { edges? }): GraphLayoutChangeMetrics measures one layout change, as a diagnostic for tests and evaluation, not a benchmark or quality score: compared (IDs of before with a box in after), maxDisplacement and totalDisplacement (distances between top-left corners), movedIds, overlaps (pairs of boxes of after whose interiors overlap) and edgeBoxIntersections (pairs of an edge of options.edges and a box other than its ends that its path in after.paths passes through; curves are sampled, so this count is approximate for curves). Boxes go into a bucket grid. Throws RangeError for non-finite coordinates.

Related exported types: GraphLayoutChangeOptions.

Quantity flow projection ​

layoutFlowGraph(nodes, edges, options) projects quantities on edges into a Sankey-style GraphFlowLayout: node boxes in ranks along the flow and one band per edge whose thickness is quantity × scale, on one scale for the whole picture, so a lot of 100 that splits into 60 and 40 gives bands in exact 60:40 proportion in every rank. Every item carries the original node or edge ID. It runs without a DOM, is deterministic, never mutates its input, and its traversals are iterative (a 12,000-node chain lays out). The result is a GraphLayout (boxes, centre-line paths for the bands, empty edgeLabels, width, height) for the NetworkGraph layout prop and renderGraphSvg, plus:

  • unit (the displayed unit), scale (pixels per unit) and direction.
  • nodes: one GraphFlowNode per node in input order, with id, box, rank, order (position in its rank), inflow, outflow, difference (outflow − inflow), value (max(inflow, outflow)), referenceInflow and referenceOutflow.
  • bands: one GraphFlowBand per edge in the displayed unit, in input order, with edgeId, from, to, quantity, unit, thickness (exactly quantity × scale), width (the drawn stroke width: thickness, at least minBandWidth), reference, selfLoop, sourceSide and targetSide, sourceOffset and targetOffset (where the band starts along that side, from its top end for left and right sides and its left end for top and bottom sides; it covers [offset, offset + thickness]), path and label (for example Cut → Inspect: 60 pcs).
  • excluded: one GraphFlowExcludedEdge (edgeId, from, to, unit, quantity) per edge in another unit.

graphFlowBands(flow) returns the edgeBands map (width, reference, label by edge ID) for NetworkGraph and renderGraphSvg; see Quantity bands.

Layout. Ranks and the order inside a rank come from layoutLayeredGraph with barycenter crossing reduction over the forward edges (crossingSweeps sweeps). Each box is nodeThickness long along the flow and value × scale across it, at least minNodeSize; the ranks are centred on the fullest one. Bands leave a node on its downstream side and enter on its upstream side, stacked from the top (LR, RL) or left (TB, BT) end of the side and sorted by the position of their other end, then by input order, so a split does not cross itself. A band that skips ranks is a single curve and may pass over the nodes of the ranks between.

Totals are reported, never balanced. Where inflow and outflow differ, the box is as large as the larger stack, the shorter stack leaves the rest empty, and difference says by how much (negative: less leaves than arrives). The library gives the difference no meaning: scrap, stock, yield, rounding or a missing edge are the caller's interpretation. Sources have difference = outflow and sinks −inflow.

Units are never mixed. unit is required: a string for every edge, or an accessor per edge together with displayUnit (an accessor without displayUnit throws Error). Only edges whose unit is displayUnit are drawn, ranked and summed; every other edge is returned in excluded and added to nothing, so a node total never combines units. Switch displayUnit to view another unit.

Zero and invalid quantities. Every quantity, also of an excluded edge, must be a finite number of at least 0, else RangeError naming the edge. A quantity of 0 keeps its band with thickness 0, drawn as a minBandWidth hairline (default 1), so it stays visible and selectable; minBandWidth: 0 draws nothing. A missing or empty unit throws Error, as do unknown endpoints and duplicate or empty IDs (from indexGraph).

Cycles. A Sankey layout needs a DAG. An iterative depth-first search in node and edge input order marks every edge that closes a cycle (a rework loop) and every self-loop as a reference band (reference: true; selfLoop for the latter). Cycles never stop the layout from terminating, and no edge is dropped. Reference bands are stacked below the forward bands at both ends and routed back through lanes of their own beside the ranks (below for LR and RL, to the right for TB and BT), nested so that loops do not cross each other; the renderers draw them dashed and more transparent. They are counted in referenceInflow and referenceOutflow, not in inflow, outflow, difference or value; the box of a node with reference bands is max(inflow + referenceInflow, outflow + referenceOutflow) × scale across, so the reference stacks fit on it. Loops are not unrolled by period: to show rework as forward flow over time, give each period its own node copies (for example inspect@w1 and inspect@w2) before the projection and map their IDs back yourself.

OptionMeaning
quantityRequired. (edge) => number, receiving your edge type.
unitRequired. A unit string, or (edge) => string together with displayUnit.
displayUnitThe unit to draw and sum. Required with a unit accessor; defaults to a string unit.
directionLR (default), RL, TB or BT; RL and BT mirror LR and TB.
nodeThicknessBox size along the flow. Default 24; positive.
nodeGapGap between the nodes of one rank across the flow. Default 16.
rankGapGap between ranks, where the bands run. Default 120.
paddingMargin. Default 20; widened along the flow when reference loops at the first or last rank need room.
scale{ pixelsPerUnit } (fixed, positive) or { fitExtent } (default { fitExtent: 360 }): the largest scale at which every rank's boxes and gaps fit into that cross-flow extent. Boxes raised to minNodeSize can exceed it slightly; without any flow the scale is 0. An explicit fitExtent too small for a rank's gaps throws RangeError. When scale is left out, the extent of a rank grows past 360 to its gaps plus minNodeSize per node when it needs more, so a wide rank (for example 30 leaves) still lays out.
minNodeSizeSmallest box size across the flow. Default 2; positive.
minBandWidthSmallest drawn band width. Default 1.
referenceGapGap between the picture and the reference lanes, and between two lanes. Default 12.
crossingSweepsPositive integer number of barycenter sweeps. Default 4.
nodeLabel(node) => string for band labels. Default: the node's label when it is a string, else its ID.
formatQuantity(quantity, unit) => string for band labels. Default `${quantity} ${unit}`.

Sizes that are not finite or are negative (and a node thickness, minimum node size, pixels per unit or fit extent of 0), an unknown direction or scale and a sweep count that is not a positive integer throw RangeError, in the format of Layout defaults and option checks.

Related exported types: GraphFlowOptions, GraphFlowScale.

Viewport helpers ​

The helpers behind cullOffscreen are exported for custom renderers and workers. Rectangles are GraphRect values (x, y, width, height) in chart coordinates.

ExportPurpose
graphViewportRect(camera, size, overscan = 0)World rectangle a GraphViewport camera shows for a screen size, grown by overscan screen pixels. Throws RangeError for a nonpositive scale or negative size
graphRectsIntersect(a, b)Whether the interiors of two rectangles overlap: on both axes each starts strictly before the other ends, compared exactly without a tolerance. Rectangles that only touch along an edge or at a corner do not intersect. A zero-width or zero-height rectangle (a segment or point) intersects a rectangle whose interior it passes through, not one whose border it lies on, and never another zero-size rectangle at the same place
graphPathBounds(path)Bounding rectangle of an SVG path string, or undefined without coordinates. Bézier curves use their control points, including the reflected control point of S and T; arcs are bounded exactly after SVG radius correction and rotation. Numbers may use e/E exponents. Throws for malformed data (including data that does not begin with a moveto, M or m) or unsupported commands
graphPathEndpoints(path)First moveto point and final current point of an SVG path string, or undefined without coordinates
graphLayoutBounds(layout, labelReach = 80)GraphBounds with one rectangle per node and per edge, edge labels included
cullGraphElements(bounds, view, keep?)GraphVisibleIds of the nodes and edges whose bounds intersect or touch view (touching counts here, unlike graphRectsIntersect, because the bounds leave out the stroke width), plus any IDs in keep (GraphCullKeep)
graphCameraAt(point, size, scale)Camera that centers a world point at a scale; focusNode uses the same rule
graphPointInPolygon(point, polygon)Whether a point is inside a polygon of vertices in order (closed implicitly), by the even-odd rule; a point on the outline counts as inside, and a polygon with fewer than three vertices contains nothing. Throws RangeError for a non-finite coordinate
graphNodesInPolygon(boxes, polygon)IDs of the boxes (for example layout.boxes) whose centre is inside the polygon, in map order; the lasso of selectionMode uses it. Throws RangeError for non-finite polygon points or box geometry

Asynchronous layouts and preserved routes ​

Core (@eightkk/vue-weave/core):

  • graphLayoutInputKey(input: GraphLayoutKeyInput): string identifies a layout input: scope, direction, settings (JSON text), revision, and in order the nodes (ID, label, detail, shape, ports), edges (ID, ends, ports, label, waypoints), groups, collapsed group IDs, and any positions, sizes, fixedIds and addedIds given to the engine (the last two only when present, so keys of inputs without them are unchanged). Node and edge data is not read; change revision when it matters. Throws RangeError for an unknown scope or direction or settings that are not JSON-serializable.
  • buildGraphLayoutRequests(input: GraphLayoutRequestInput<N, E, G>, requestId: string): GraphLayoutRequests<N, E, G> makes the requests NetworkGraph's layout calls correspond to: one shown request (ID requestId + ':shown') and, while a known group is collapsed, an expanded request (requestId + ':expanded') for the full input plus the collapse result. Unknown collapsed IDs are dropped and proxy details use labels.collapsedNode / labels.collapsedNodes, as in NetworkGraph.
  • Incremental layout fields (optional, additive): GraphLayoutRequestInput.fixedIds (pinned nodes, kept where positions puts them) and addedIds (nodes new since the last layout), both ReadonlySet<string>, are copied to every request and to AsyncGraphFrame when nonempty, so an adapter can forward them to an engine with incremental options (see Use ELK.js for layout). Requests and frames without them have no such fields. IDs that are not nodes of a request, such as members of a collapsed group in the shown request, are passed as they are. In JSON messages they are arrays of IDs; parseGraphLayoutMessage requires Sets.
  • validateGraphLayoutResponse(request, response): GraphLayout checks that a response echoes requestId, inputKey and scope; every node needs a finite positive box; a shown layout also needs finite positive dimensions, a path for every edge and route metadata (when given) with finite points and the edge's ports.
  • completeGraphLayout(layout, nodes, edges, options?: { direction? }): { layout, temporaryEdgeIds, unresolvedEdgeIds } adds temporary built-in routes for edges without a path whose end boxes exist.
  • isGraphRouteValid(layout, nodes: ReadonlyMap<string, IdentifiedNode>, edge): boolean tells whether the preserve policy keeps an edge's path.
  • graphLayoutToJson(layout), graphLayoutFromJson(value), graphLayoutMessageToJson(message), graphLayoutMessageFromJson(value) and parseGraphLayoutMessage(value) convert and check layout Worker messages (request, cancel, success, failure; each with requestId and inputKey) for JSON and structured-clone transport.
  • routeGraphPorts(layout, nodes, edges, direction, options?: GraphPortRouteOptions) and routeGraphEdges(layout, edges, nodes, options) accept policy?: GraphRoutingPolicy ('builtin' default, or 'preserve').
  • GraphLayout has an optional routes?: Map<string, GraphLayoutRoute>: start, end, fromPort, toPort, fromSide, toSide and bend points of each routed edge.
  • Types: GraphLayoutScope, GraphLayoutRequestInput, GraphLayoutRequest, GraphLayoutResponse, GraphLayoutRequests, GraphLayoutKeyInput, GraphLayoutCompletionOptions, GraphLayoutCompletion, GraphLayoutRoute, GraphRoutingPolicy, GraphPortRouteOptions, GraphLayoutWorkerMessage (and its four members), GraphLayoutJson, GraphLayoutRequestJson, GraphLayoutWorkerJsonMessage.

Vue (@eightkk/vue-weave):

  • useAsyncGraphLayout(options: UseAsyncGraphLayoutOptions<N, E, G>): AsyncGraphLayout<N, E, G> with input, adapter(request, signal), optional initialLayout, gesture, provisional (default true) and cacheSize (default 32: the number of computed layouts, by scope and input key, kept in least recently used order for reuse by later inputs; 0 keeps none). The layouts and failures of the desired frame are held with the frame, apart from that cache, so a frame completes with any cacheSize, and a failed request is not repeated until the input changes. It returns desired and display frames, a layout function of stable identity, pending, deferred, error, gestureListeners, gesturing, cancel() and dispose(). display.source is 'initial', 'layout' (every layout of the frame came from the adapter) or 'provisional' (the previous boxes with temporary routes for temporaryEdgeIds, shown while the adapter computes a frame whose nodes all have boxes already). A failure sets error and keeps the display: the last adapter frame, or, with provisional, the provisional frame of the failed input, which is consistent (every node and edge has geometry) and says by its source that its new routes are temporary. Set provisional: false to keep showing only adapter frames. Finished frames wait (deferred) while a gesture is in flight: bind gestureListeners (AsyncGraphGestureListeners: onGestureStart(gesture: GraphGesture) and onGestureEnd(gesture: GraphGestureEnd), frozen, of stable identity) to NetworkGraph with v-bind="graph.gestureListeners" or spread them into h(NetworkGraph, props); the composable counts started gestures that have not ended, ignoring an end without a start. The gesture option (a boolean ref or getter) still holds frames for gestures the application tracks itself; gesturing is true while either holds them. A frame that finished during the gesture is shown when it ends, unless the input changed in the meantime.
  • graphLayoutWorkerAdapter(port: GraphLayoutWorkerPort, options?: { transport?: 'clone' | 'json' }) makes an adapter that talks to a Worker the caller created. A response is matched by requestId and inputKey; one with those but another scope, or a malformed message for the request, rejects it. If posting the request throws, the request rejects with that error. Whichever way a request ends (response, failure, abort or a failed post), its message listener and its abort listener are removed; a cancel message that cannot be posted is ignored.
  • Types: AsyncGraphLayoutAdapter, AsyncGraphFrame, AsyncGraphDisplayFrame, AsyncGraphLayoutError, UseAsyncGraphLayoutOptions, AsyncGraphLayout, AsyncGraphGestureListeners, GraphLayoutWorkerPort, GraphLayoutWorkerAdapterOptions.

Related exported types: GraphLayoutRequestMessage, GraphLayoutCancelMessage, GraphLayoutSuccessMessage, GraphLayoutFailureMessage.

Released under the MIT License.