Edges follow ELK's routes: layoutGraph returns each edge's start, bends, end and chip point, LiveEdge draws them square with rounded corners, moved onto the drawn handles, and keeps the curve for an edge whose node moved since; a feedback edge clears the nodes it passes

This commit is contained in:
2026-10-15 18:24:38 +02:00
parent ff17d08254
commit 453b0be6f6
6 changed files with 432 additions and 68 deletions
+109 -19
View File
@@ -1,7 +1,7 @@
import type { ElkNode, ElkPort } from "elkjs/lib/elk-api"
/**
* Where the nodes of a flow go.
* Where the nodes of a flow go, and how the edges between them run.
*
* Nothing on this canvas is placed by hand: a flow is a graph the editor draws,
* not a picture someone arranges. That is the design decision — a canvas nobody
@@ -128,12 +128,35 @@ export type NodeShape = {
}
export type LayoutEdge = {
id: string
source: string
target: string
sourceHandle?: string | null
targetHandle?: string | null
}
export type Point = { x: number; y: number }
/**
* The way the layout routed an edge: from the source port through its bends to
* the target port, square to the ranks. `from` and `to` are where its two
* nodes were placed, so a drawing can tell when either has moved since.
*/
export type Route = {
points: Point[]
/** Where the room reserved for the edge's value chip is centred. */
label: Point
from: Point
to: Point
}
export type Layout = {
/** Each node's top-left corner. */
positions: Map<string, Point>
/** By edge id. An edge whose ends the layout did not know has none. */
routes: Map<string, Route>
}
const EMPTY: NodeShape = { requires: [], provides: [] }
/**
@@ -152,6 +175,14 @@ function sizeOf(shape: NodeShape, direction: Direction) {
}
}
/** The edges the layout can place: both of their nodes are in it. */
function wiredOf(ids: string[], edges: LayoutEdge[]): LayoutEdge[] {
const known = new Set(ids)
return edges.filter(
(edge) => known.has(edge.source) && known.has(edge.target),
)
}
/** A wire the layout adds and nobody draws: "put this one a rank further on". */
type Wrap = [string, string]
@@ -224,10 +255,7 @@ function graphOf(
}
})
const known = new Set(ids)
const wired = edges.filter(
(edge) => known.has(edge.source) && known.has(edge.target),
)
const wired = wiredOf(ids, edges)
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.
@@ -269,8 +297,8 @@ function graphOf(
: { "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.
// Only where it lands is read — `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,
@@ -301,10 +329,7 @@ function graphOf(
* 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(
placed: Map<string, { x: number; y: number }>,
ids: string[],
): Wrap[] {
function wrapWideRanks(placed: Map<string, Point>, ids: string[]): Wrap[] {
const ranks = new Map<number, string[]>()
for (const id of ids) {
const at = placed.get(id)
@@ -340,7 +365,7 @@ function elk() {
}
/**
* Lay the graph out and return each node's top-left corner.
* Lay the graph out: each node's top-left corner, and the route of each edge.
*
* `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
@@ -351,20 +376,20 @@ export async function layoutGraph(
edges: LayoutEdge[],
direction: Direction,
shapes: Map<string, NodeShape> = new Map(),
): Promise<Map<string, { x: number; y: number }>> {
): Promise<Layout> {
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 }>()
const placed = new Map<string, Point>()
for (const child of laid.children ?? []) {
placed.set(child.id, { x: child.x ?? 0, y: child.y ?? 0 })
}
return placed
return { placed, laid }
}
let placed = await place([])
let { placed, laid } = 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
@@ -377,10 +402,75 @@ export async function layoutGraph(
const more = wrapWideRanks(placed, ids)
if (!more.length) break
wrap.push(...more)
placed = await place(wrap)
;({ placed, laid } = await place(wrap))
}
}
// 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 }]))
// ELK places top-left corners already, which is what React Flow wants, and
// routes every edge in the same frame: they all hang off the root.
const positions = new Map(
ids.map((id) => [id, placed.get(id) ?? { x: 0, y: 0 }]),
)
const wired = wiredOf(ids, edges)
// How far across the nodes reach, for `longestRun`.
let [left, right] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]
for (const [id, at] of positions) {
left = Math.min(left, at.x)
right = Math.max(
right,
at.x + sizeOf(shapes.get(id) ?? EMPTY, direction).width,
)
}
const routes = new Map<string, Route>()
for (const edge of laid.edges ?? []) {
const index = Number(edge.id.slice(1))
const section = edge.sections?.[0]
// The wrap wires are `w`; only the ones somebody draws are `e`.
if (!edge.id.startsWith("e") || !section) continue
const label = edge.labels?.[0]
const { source, target, id } = wired[index]
const points = [
section.startPoint,
...(section.bendPoints ?? []),
section.endPoint,
]
const room = label
? {
x: (label.x ?? 0) + (label.width ?? 0) / 2,
y: (label.y ?? 0) + (label.height ?? 0) / 2,
}
: section.startPoint
routes.set(id, {
points,
label:
direction === "TB" && (room.x < left || room.x > right)
? (longestRun(points) ?? room)
: room,
from: positions.get(source) ?? { x: 0, y: 0 },
to: positions.get(target) ?? { x: 0, y: 0 },
})
}
return { positions, routes }
}
/**
* The middle of a route's longest run across the flow, running downwards.
*
* Where the chip of an edge goes when ELK put its label outside every node's
* column, on a lane round the side of the graph. A label is given no width in
* this direction (see {@link LABEL_W}), so a chip centred on that lane would
* hang half of itself past the edge of the fit. On a run across, its width
* lies along the line.
*/
function longestRun(points: Point[]): Point | null {
let best: Point | null = null
let longest = 0
for (let i = 1; i < points.length; i += 1) {
const [a, b] = [points[i - 1], points[i]]
const length = Math.abs(b.x - a.x)
if (a.y !== b.y || length <= longest) continue
longest = length
best = { x: (a.x + b.x) / 2, y: a.y }
}
return best
}