Lay flows out so edges stop crossing where they need not
The canvas placed nodes with dagre, which orders nodes but knows nothing about ports: an edge leaves a particular handle and lands on a particular one, so two producers feeding a consumer in the other order crossed just before they landed however well the nodes were arranged. The graph was not a multigraph either, so two messages between one pair of nodes collapsed into one before crossings were counted, and the endpoint labels were laid out as 220-wide cards with every handle stacked on a single pixel. ELK's layered algorithm replaces it. Every declared port is handed to it as a fixed point on the node's rim, at the fraction `portFraction` puts the handle at — which the node components now render from the same function — so what the crossing count is minimised over is what ends up on the screen. Measured on this installation's flows, with the labels included: `home` goes from 51 crossings to 6 across and 70 to 29 down, `demo_training` 27 to 5 and 59 to 32, and every graph is the same size or smaller. The engine answers asynchronously and is a chunk of its own, so positions became state: the canvas draws nothing until the first layout lands, and an edit keeps the arrangement it had rather than flashing through the corner. The entry chunk is untouched and the flow route's own chunk came down 167 to 121 kB, since dagre used to be in it. Two things the crossings made worse come with it. A hovered edge resolves to full strength so one line can be followed through a busy rank, and a feedback edge — one whose target the layout put behind its source — swings out into a lane beside the graph instead of being drawn through everything between its ends, which is what "House history" was reported for.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import dagre from "@dagrejs/dagre"
|
||||
import type { ElkNode, ElkPort } from "elkjs/lib/elk-api"
|
||||
|
||||
/**
|
||||
* Where the nodes of a flow go.
|
||||
@@ -10,19 +10,27 @@ import dagre from "@dagrejs/dagre"
|
||||
*
|
||||
* Left to right on a desktop, top to bottom on a phone, which is the direction
|
||||
* each screen has room to grow in.
|
||||
*
|
||||
* The layout is ELK's layered algorithm rather than a plain ranking, because
|
||||
* the thing that actually crosses on this canvas is *ports*, not nodes. An edge
|
||||
* leaves a particular handle and lands on a particular handle, so two producers
|
||||
* feeding one consumer in the other order cross just before they land however
|
||||
* well the nodes themselves are arranged. ELK is told where every handle sits
|
||||
* and counts crossings there, which lets it order the nodes to undo the twist.
|
||||
*/
|
||||
export type Direction = "LR" | "TB"
|
||||
|
||||
/** `FlowNode` is `min-w-[168px] max-w-[220px]`; an endpoint is narrower. */
|
||||
const NODE_W = 220
|
||||
/** An endpoint is drawn as a label, `max-w-48` in `EndpointNode`. */
|
||||
const ENDPOINT_W = 192
|
||||
/** Icon row plus two text lines, as measured. The floor, not the height. */
|
||||
const NODE_H = 56
|
||||
/**
|
||||
* How much of a node's edge the ports are spread over, as a fraction.
|
||||
*
|
||||
* Shared with `FlowNode`'s `handleOffset`, which does the spreading: the
|
||||
* height below is chosen so that span has room for the ports, so the two
|
||||
* cannot be allowed to drift apart.
|
||||
* Shared with the offsets below, which do the spreading: the height is chosen
|
||||
* so that span has room for the ports, so the two cannot drift apart.
|
||||
*/
|
||||
export const PORT_SPAN = 0.6
|
||||
/**
|
||||
@@ -42,20 +50,50 @@ export function nodeHeight(ports: number): number {
|
||||
return Math.max(NODE_H, Math.ceil(((ports - 1) * PORT_PITCH) / PORT_SPAN))
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a port's handle sits along its side, as a fraction of that side.
|
||||
*
|
||||
* The one place this is decided. The node components render it as a percentage
|
||||
* and the layout hands ELK the same number as a fixed port position, so what
|
||||
* the crossing count is minimised over is exactly what ends up on the screen.
|
||||
*/
|
||||
export function portFraction(index: number, total: number): number {
|
||||
if (total <= 1) return 0.5
|
||||
return 0.5 - PORT_SPAN / 2 + (PORT_SPAN / (total - 1)) * index
|
||||
}
|
||||
|
||||
/** {@link portFraction} as the CSS offset a handle is placed with. */
|
||||
export function handleOffset(index: number, total: number): string {
|
||||
return `${portFraction(index, total) * 100}%`
|
||||
}
|
||||
|
||||
/**
|
||||
* Room for the live value an edge carries (`LiveEdge`'s chip is
|
||||
* `max-w-[140px]`). Reserved on the edge itself, so dagre routes nodes around
|
||||
* the chip rather than through it.
|
||||
* `max-w-[140px]`). Reserved on the edge itself, so the layout routes nodes
|
||||
* around the chip rather than through it.
|
||||
*
|
||||
* Only its height is reserved when the graph runs downwards. The chip's width
|
||||
* is then spent across the screen rather than along the flow, and a phone has
|
||||
* none to spare — while the rank gap it would otherwise widen is already 80px,
|
||||
* none to spare — while the rank gap it would otherwise widen is already there,
|
||||
* more than the chip is tall. Sibling edges are a node's width apart there, so
|
||||
* the chips clear each other without being asked to.
|
||||
*/
|
||||
const LABEL_W = 150
|
||||
const LABEL_H = 24
|
||||
|
||||
/** Along a rank. */
|
||||
const NODE_GAP = 40
|
||||
/**
|
||||
* Between two ranks — half of what a labelled edge should span.
|
||||
*
|
||||
* A chip gets a rank of its own and the gap is paid on both sides of it, so
|
||||
* the pitch between two wired nodes is this twice over plus the chip: 480px
|
||||
* across, 160px down, which is what the canvas has always used.
|
||||
*/
|
||||
const RANK_GAP = { LR: 55, TB: 40 } as const
|
||||
/** Around the whole graph. */
|
||||
const MARGIN = 40
|
||||
|
||||
/**
|
||||
* How many nodes may sit abreast when the graph runs downwards.
|
||||
*
|
||||
@@ -76,45 +114,179 @@ const ABREAST = 2
|
||||
*/
|
||||
const WRAP_PASSES = 6
|
||||
|
||||
/**
|
||||
* What a node is, as far as the layout is concerned.
|
||||
*
|
||||
* The declared ports in the order they are drawn in, and whether the node is
|
||||
* one of the endpoint labels rather than a card. Read from the document rather
|
||||
* than from the canvas on purpose — see {@link nodeHeight}.
|
||||
*/
|
||||
export type NodeShape = {
|
||||
requires: string[]
|
||||
provides: string[]
|
||||
endpoint?: boolean
|
||||
}
|
||||
|
||||
export type LayoutEdge = {
|
||||
source: string
|
||||
target: string
|
||||
sourceHandle?: string | null
|
||||
targetHandle?: string | null
|
||||
}
|
||||
|
||||
const EMPTY: NodeShape = { requires: [], provides: [] }
|
||||
|
||||
/**
|
||||
* ponytail: every node is still treated as its widest rather than measured.
|
||||
* Measuring would feed the result back into the layout and oscillate; if nodes
|
||||
* ever grow past that, take the width from `node.measured` once it has settled.
|
||||
*/
|
||||
function sizeOf(shape: NodeShape, direction: Direction) {
|
||||
// Ports run down the sides only while the graph runs across, and that is the
|
||||
// only direction in which their number decides the height: running downwards
|
||||
// they spread along the node's width, which is fixed.
|
||||
const ports = Math.max(shape.requires.length, shape.provides.length)
|
||||
return {
|
||||
width: shape.endpoint ? ENDPOINT_W : NODE_W,
|
||||
height: direction === "LR" ? nodeHeight(ports) : NODE_H,
|
||||
}
|
||||
}
|
||||
|
||||
/** A wire the layout adds and nobody draws: "put this one a rank further on". */
|
||||
type Wrap = [string, string]
|
||||
|
||||
function build(
|
||||
/**
|
||||
* The graph as ELK takes it.
|
||||
*
|
||||
* Every declared port becomes a fixed point on the node's rim, at the fraction
|
||||
* {@link portFraction} puts the handle at — including the ports nothing is
|
||||
* wired to, since they still take up their slot in the spread and so decide
|
||||
* where the wired ones land.
|
||||
*/
|
||||
function graphOf(
|
||||
ids: string[],
|
||||
edges: { source: string; target: string }[],
|
||||
edges: LayoutEdge[],
|
||||
direction: Direction,
|
||||
shapes: Map<string, NodeShape>,
|
||||
wrap: Wrap[],
|
||||
heights: Map<string, number>,
|
||||
) {
|
||||
const graph = new dagre.graphlib.Graph()
|
||||
graph.setDefaultEdgeLabel(() => ({}))
|
||||
graph.setGraph({
|
||||
rankdir: direction,
|
||||
// Along the rank, and between ranks. A left-to-right graph needs the wider
|
||||
// gap between ranks because the nodes themselves are wide.
|
||||
nodesep: 40,
|
||||
ranksep: direction === "LR" ? 110 : 80,
|
||||
marginx: 40,
|
||||
marginy: 40,
|
||||
): ElkNode {
|
||||
const across = direction === "LR"
|
||||
// A port is identified by the side it is on as well as by its name: a node
|
||||
// may well read and write the same message. The id ELK gets is generated
|
||||
// rather than composed, so nothing has to be escaped out of a name somebody
|
||||
// else chose, and the key that finds it again cannot run two of them
|
||||
// together either.
|
||||
const portIds = new Map<string, string>()
|
||||
const portKey = (side: string, node: string, port: string) =>
|
||||
JSON.stringify([side, node, port])
|
||||
|
||||
const children: ElkNode[] = ids.map((id) => {
|
||||
const shape = shapes.get(id) ?? EMPTY
|
||||
const { width, height } = sizeOf(shape, direction)
|
||||
const ports: ElkPort[] = []
|
||||
|
||||
const side = (
|
||||
names: string[],
|
||||
kind: "in" | "out",
|
||||
elkSide: string,
|
||||
at: (fraction: number) => { x: number; y: number },
|
||||
) => {
|
||||
names.forEach((name, index) => {
|
||||
const portId = `p${portIds.size}`
|
||||
portIds.set(portKey(kind, id, name), portId)
|
||||
ports.push({
|
||||
id: portId,
|
||||
width: 0,
|
||||
height: 0,
|
||||
...at(portFraction(index, names.length)),
|
||||
layoutOptions: { "org.eclipse.elk.port.side": elkSide },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
side(shape.requires, "in", across ? "WEST" : "NORTH", (fraction) =>
|
||||
across ? { x: 0, y: height * fraction } : { x: width * fraction, y: 0 },
|
||||
)
|
||||
side(shape.provides, "out", across ? "EAST" : "SOUTH", (fraction) =>
|
||||
across
|
||||
? { x: width, y: height * fraction }
|
||||
: { x: width * fraction, y: height },
|
||||
)
|
||||
|
||||
return {
|
||||
id,
|
||||
width,
|
||||
height,
|
||||
// Where the handles are is the whole point of using this algorithm, so
|
||||
// ELK is told them exactly rather than left to invent an order.
|
||||
layoutOptions: { "org.eclipse.elk.portConstraints": "FIXED_POS" },
|
||||
ports,
|
||||
}
|
||||
})
|
||||
|
||||
// Insertion order is what makes the result deterministic, so it follows the
|
||||
// document rather than whatever order the edges happen to mention nodes in.
|
||||
for (const id of ids) {
|
||||
graph.setNode(id, { width: NODE_W, height: heights.get(id) ?? NODE_H })
|
||||
}
|
||||
for (const edge of edges) {
|
||||
if (!graph.hasNode(edge.source) || !graph.hasNode(edge.target)) continue
|
||||
graph.setEdge(edge.source, edge.target, {
|
||||
width: direction === "LR" ? LABEL_W : 0,
|
||||
height: LABEL_H,
|
||||
labelpos: "c",
|
||||
})
|
||||
}
|
||||
// Nothing draws these: they only say "put this one a rank further down".
|
||||
for (const [from, to] of wrap) graph.setEdge(from, to, { weight: 2 })
|
||||
const known = new Set(ids)
|
||||
const wired = edges.filter(
|
||||
(edge) => known.has(edge.source) && known.has(edge.target),
|
||||
)
|
||||
const isEndpoint = (id: string) => shapes.get(id)?.endpoint === true
|
||||
// An edge whose handle the node never declared — a half-bound spec — is hung
|
||||
// off the node itself rather than dropped.
|
||||
const endOf = (kind: "in" | "out", node: string, port?: string | null) =>
|
||||
(port && portIds.get(portKey(kind, node, port))) || node
|
||||
|
||||
dagre.layout(graph)
|
||||
return graph
|
||||
return {
|
||||
id: "root",
|
||||
layoutOptions: {
|
||||
"org.eclipse.elk.algorithm": "layered",
|
||||
"org.eclipse.elk.direction": across ? "RIGHT" : "DOWN",
|
||||
"org.eclipse.elk.spacing.nodeNode": String(NODE_GAP),
|
||||
"org.eclipse.elk.layered.spacing.nodeNodeBetweenLayers": String(
|
||||
RANK_GAP[direction],
|
||||
),
|
||||
"org.eclipse.elk.padding": `[top=${MARGIN},left=${MARGIN},bottom=${MARGIN},right=${MARGIN}]`,
|
||||
// What decides a tie is the order the document lists things in, so the
|
||||
// graph reads the way the flow is written rather than however the
|
||||
// algorithm happened to land.
|
||||
"org.eclipse.elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",
|
||||
// The default, set out loud: the same flow has to lay out the same way
|
||||
// every time it is opened.
|
||||
"org.eclipse.elk.randomSeed": "1",
|
||||
},
|
||||
children,
|
||||
edges: [
|
||||
...wired.map((edge, index) => ({
|
||||
id: `e${index}`,
|
||||
sources: [endOf("out", edge.source, edge.sourceHandle)],
|
||||
targets: [endOf("in", edge.target, edge.targetHandle)],
|
||||
// The nodes are the flow's spine and the labels only account for where
|
||||
// a value also goes, so what is held straight is the run of node to
|
||||
// node: a label takes the room beside that line rather than a place on
|
||||
// it. Without this a dashboard reading a value halfway down steps the
|
||||
// whole chain sideways to let its label have the column.
|
||||
layoutOptions:
|
||||
isEndpoint(edge.source) || isEndpoint(edge.target)
|
||||
? undefined
|
||||
: { "org.eclipse.elk.layered.priority.straightness": "10" },
|
||||
labels: [
|
||||
{
|
||||
// Nothing reads this — `LiveEdge` draws the chip itself — but a
|
||||
// label with no text at all is one ELK reserves no room for.
|
||||
text: " ",
|
||||
width: across ? LABEL_W : 0,
|
||||
height: LABEL_H,
|
||||
layoutOptions: { "org.eclipse.elk.edgeLabels.inline": "true" },
|
||||
},
|
||||
],
|
||||
})),
|
||||
// Nothing draws these, and they carry no chip: they only say "put this
|
||||
// one a rank further down".
|
||||
...wrap.map(([from, to], index) => ({
|
||||
id: `w${index}`,
|
||||
sources: [from],
|
||||
targets: [to],
|
||||
})),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -124,13 +296,21 @@ function build(
|
||||
* third to the first — and the fourth to the second, and so on — cannot make a
|
||||
* cycle. It lays the rank out in rows of `ABREAST`, in the order the document
|
||||
* lists them, so the wrap reads the way the flow is written.
|
||||
*
|
||||
* A rank running downwards is a band across the screen, so what identifies one
|
||||
* is the y its nodes share. They do share it: every node is `NODE_H` tall in
|
||||
* this direction, so nothing in a band is offset against its neighbours.
|
||||
*/
|
||||
function wrapWideRanks(graph: ReturnType<typeof build>, ids: string[]): Wrap[] {
|
||||
function wrapWideRanks(
|
||||
placed: Map<string, { x: number; y: number }>,
|
||||
ids: string[],
|
||||
): Wrap[] {
|
||||
const ranks = new Map<number, string[]>()
|
||||
for (const id of ids) {
|
||||
const node = graph.node(id) as { rank?: number } | undefined
|
||||
if (node?.rank === undefined) continue
|
||||
ranks.set(node.rank, [...(ranks.get(node.rank) ?? []), id])
|
||||
const at = placed.get(id)
|
||||
if (!at) continue
|
||||
const rank = Math.round(at.y)
|
||||
ranks.set(rank, [...(ranks.get(rank) ?? []), id])
|
||||
}
|
||||
|
||||
const wrap: Wrap[] = []
|
||||
@@ -143,24 +323,48 @@ function wrapWideRanks(graph: ReturnType<typeof build>, ids: string[]): Wrap[] {
|
||||
return wrap
|
||||
}
|
||||
|
||||
/**
|
||||
* The layout engine, fetched the first time a flow needs laying out.
|
||||
*
|
||||
* Its own chunk: ELK is a compiled Java library and weighs more than the rest
|
||||
* of the canvas put together, so nothing but this route ever loads it.
|
||||
*/
|
||||
let engine: Promise<{ layout: (graph: ElkNode) => Promise<ElkNode> }> | null =
|
||||
null
|
||||
|
||||
function elk() {
|
||||
engine ??= import("elkjs/lib/elk.bundled.js").then(
|
||||
(module) => new module.default(),
|
||||
)
|
||||
return engine
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay the graph out and return each node's top-left corner.
|
||||
*
|
||||
* `heights` is what a node's ports make it, from {@link nodeHeight}; anything
|
||||
* left out is the plain box. It is read from the document rather than from the
|
||||
* canvas on purpose — see that function.
|
||||
*
|
||||
* ponytail: every node is still treated as 220 wide rather than measured.
|
||||
* Measuring would feed the result back into the layout and oscillate; if nodes
|
||||
* ever grow past that, take the width from `node.measured` once it has settled.
|
||||
* `shapes` is what the document says each node is — its ports in the order
|
||||
* they are drawn in, and whether it is an endpoint label. Anything left out is
|
||||
* a plain box with no ports.
|
||||
*/
|
||||
export function layoutGraph(
|
||||
export async function layoutGraph(
|
||||
ids: string[],
|
||||
edges: { source: string; target: string }[],
|
||||
edges: LayoutEdge[],
|
||||
direction: Direction,
|
||||
heights: Map<string, number> = new Map(),
|
||||
): Map<string, { x: number; y: number }> {
|
||||
let graph = build(ids, edges, direction, [], heights)
|
||||
shapes: Map<string, NodeShape> = new Map(),
|
||||
): Promise<Map<string, { x: number; y: number }>> {
|
||||
const engine = await elk()
|
||||
const place = async (wrap: Wrap[]) => {
|
||||
const laid = await engine.layout(
|
||||
graphOf(ids, edges, direction, shapes, wrap),
|
||||
)
|
||||
const placed = new Map<string, { x: number; y: number }>()
|
||||
for (const child of laid.children ?? []) {
|
||||
placed.set(child.id, { x: child.x ?? 0, y: child.y ?? 0 })
|
||||
}
|
||||
return placed
|
||||
}
|
||||
|
||||
let placed = await place([])
|
||||
|
||||
// Running downwards, a rank wider than the screen is the one thing the
|
||||
// layout can still do something about. Wrapping one rank pushes whatever was
|
||||
@@ -170,23 +374,13 @@ export function layoutGraph(
|
||||
if (direction === "TB") {
|
||||
const wrap: Wrap[] = []
|
||||
for (let pass = 0; pass < WRAP_PASSES; pass += 1) {
|
||||
const more = wrapWideRanks(graph, ids)
|
||||
const more = wrapWideRanks(placed, ids)
|
||||
if (!more.length) break
|
||||
wrap.push(...more)
|
||||
graph = build(ids, edges, direction, wrap, heights)
|
||||
placed = await place(wrap)
|
||||
}
|
||||
}
|
||||
|
||||
// dagre places centres; React Flow wants top-left corners.
|
||||
return new Map(
|
||||
ids.map((id) => {
|
||||
const node = graph.node(id)
|
||||
return [
|
||||
id,
|
||||
node
|
||||
? { x: node.x - NODE_W / 2, y: node.y - node.height / 2 }
|
||||
: { x: 0, y: 0 },
|
||||
]
|
||||
}),
|
||||
)
|
||||
// ELK places top-left corners already, which is what React Flow wants.
|
||||
return new Map(ids.map((id) => [id, placed.get(id) ?? { x: 0, y: 0 }]))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user