1
0
Fork 0

refactor(flow): share the edge shape builder between both flow canvases

Extract the dialogue canvas's routing upgrades into routeEdge() in the
shared lib: perpendicular handle stubs, candidate scoring (Z-step vs
straight for forward edges, top/bottom bus corridors for back edges),
per-edge detour lane spreading, and multi-pass obstacle clearing. The
NPC dialogue RoutedFlowEdge becomes a thin renderer over it, and the
tech tree RoutedEdge now inherits the same logic while keeping its own
features intact: manual waypoints route verbatim (and define the
add-a-bend base), per-source stepPosition lanes feed the Z-step, and
its fixed right/left handles map to the new direction params.

New pure spec covers the Z-step shape, blocked-forward detouring,
back-edge bus routing, per-id lane spread, and waypoint pass-through.
This commit is contained in:
Jason Fraley 2026-10-06 14:47:14 -04:00
parent 28bb08f43e
commit efab41ba29
4 changed files with 300 additions and 142 deletions

View file

@ -5,58 +5,25 @@
*
* The dialogue graph loops back a lot (a choice returning to an earlier
* line), and plain Bezier connectors sliced straight through unrelated
* cards, which made return paths impossible to trace. This edge builds a
* short orthogonal base polyline (perpendicular stubs at each handle so
* lines leave cards at right angles) and hands it to the shared detour
* router (`@/lib/flow-edge-routing`), then renders the result with rounded
* corners, an arrowhead, and the condition label as a chip at the path
* midpoint so text stays readable over other geometry.
* cards, which made return paths impossible to trace. All shape logic lives
* in the shared `routeEdge` (`@/lib/flow-edge-routing`, also used by the
* tech tree); this component gathers the card rectangles from the React Flow
* store and renders the result with rounded corners, an arrowhead, and the
* condition label as a chip at the path midpoint so text stays readable
* over other geometry.
*/
import { useMemo } from "react";
import { BaseEdge, EdgeLabelRenderer, Position, useStore, type EdgeProps } from "@xyflow/react";
import { BaseEdge, EdgeLabelRenderer, useStore, type EdgeProps } from "@xyflow/react";
import {
buildRoutePath,
polylineMidpoint,
routeAroundObstacles,
ROUTE_CLEARANCE,
segmentCrossesRect,
routeEdge,
type RoutePoint,
type RouteRect,
type StubDirection,
} from "@/lib/flow-edge-routing";
/** How far the line leaves a handle before it may bend (px). */
const STUB = 24;
/**
* Detour lanes come in three depths so edges that enter the same handle (or
* loop around the same card) don't collapse onto one identical lane and read
* as a single thick bundle. The depth is derived from the edge id, so it is
* stable across renders and differs between edges with overwhelming
* probability.
*/
const LANE_STEPS = [0, 16, 32];
function laneFor(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) | 0;
return LANE_STEPS[Math.abs(h) % LANE_STEPS.length];
}
function stubFor(point: RoutePoint, position: Position | null, length: number): RoutePoint {
switch (position) {
case Position.Left:
return { x: point.x - length, y: point.y };
case Position.Right:
return { x: point.x + length, y: point.y };
case Position.Top:
return { x: point.x, y: point.y - length };
case Position.Bottom:
return { x: point.x, y: point.y + length };
default:
return point;
}
}
export function RoutedFlowEdge({
id,
source,
@ -72,83 +39,30 @@ export function RoutedFlowEdge({
}: EdgeProps) {
const nodeLookup = useStore((s) => s.nodeLookup);
// For left-to-right edges the two endpoint cards never sit in the path, so
// they stay out of the obstacle list. Back edges do cross their own ends,
// so there every card (including ours) is an obstacle and the line loops
// around the cards instead of through them.
const { forwardObstacles, allObstacles } = useMemo(() => {
const all: RouteRect[] = [];
const nodes = useMemo(() => {
const rects: RouteRect[] = [];
nodeLookup.forEach((node) => {
const width = node.measured?.width ?? 0;
const height = node.measured?.height ?? 0;
if (!width || !height) return;
const { x, y } = node.internals.positionAbsolute;
all.push({ id: node.id, x, y, width, height });
rects.push({ id: node.id, x, y, width, height });
});
const forward = all.filter((r) => r.id !== source && r.id !== target);
return { forwardObstacles: forward, allObstacles: all };
}, [nodeLookup, source, target]);
return rects;
}, [nodeLookup]);
const start: RoutePoint = { x: sourceX, y: sourceY };
const end: RoutePoint = { x: targetX, y: targetY };
const sStub = stubFor(start, sourcePosition, STUB);
const tStub = stubFor(end, targetPosition, STUB);
const isBackEdge = end.x < start.x;
const obstacles = isBackEdge ? allObstacles : forwardObstacles;
const lane = laneFor(id ?? "");
const margin = ROUTE_CLEARANCE + lane;
const routed = (() => {
const crossingCount = (points: RoutePoint[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => segmentCrossesRect(points[i], points[i + 1], r))) n += 1;
}
return n;
};
const candidates: RoutePoint[][] = [];
if (isBackEdge && obstacles.length > 0) {
// Structured "bus routes" for return edges: leave the source, run along
// a corridor above or below every card, then swing in to the target's
// entry handle. Greedy detouring alone thrashes on long leftward runs,
// so try the structured shapes first and let the router clean up.
const topY = Math.min(...obstacles.map((r) => r.y)) - ROUTE_CLEARANCE - lane;
const botY = Math.max(...obstacles.map((r) => r.y + r.height)) + ROUTE_CLEARANCE + lane;
const bus = (y: number): RoutePoint[] => [
start,
sStub,
{ x: sStub.x, y },
{ x: tStub.x, y },
tStub,
end,
];
candidates.push(bus(topY), bus(botY), [start, sStub, tStub, end]);
} else if (isBackEdge) {
candidates.push([start, sStub, tStub, end]);
} else {
// Forward edges prefer the tidy Z-step; a stubbed straight line is the
// fallback when the step would slice through cards.
const midX = (sStub.x + tStub.x) / 2;
candidates.push(
[start, sStub, { x: midX, y: sStub.y }, { x: midX, y: tStub.y }, tStub, end],
[start, sStub, tStub, end],
);
}
let best: RoutePoint[] | null = null;
let bestScore = Number.POSITIVE_INFINITY;
for (const candidate of candidates) {
const cleaned = routeAroundObstacles(candidate, obstacles, margin);
const score = crossingCount(cleaned);
if (score < bestScore) {
best = cleaned;
bestScore = score;
}
if (score === 0) break;
}
return best ?? [start, end];
})();
const { points: routed } = routeEdge({
id,
start,
end,
sourceDirection: sourcePosition as StubDirection | null,
targetDirection: targetPosition as StubDirection | null,
nodes,
sourceId: source,
targetId: target,
});
const path = buildRoutePath(routed);
const mid = polylineMidpoint(routed.length >= 2 ? routed : [start, end]);

View file

@ -4,12 +4,7 @@ import { BaseEdge, EdgeLabelRenderer, useReactFlow, type EdgeProps } from "@xyfl
import React from "react";
import { buildRoutePath, type RouteWaypoint } from "./edgeRoutes";
import {
routeAroundObstacles,
segmentCrossesRect,
type RoutePoint,
type RouteRect,
} from "./edgeRouting";
import { routeEdge, type RoutePoint, type RouteRect } from "./edgeRouting";
export type RoutedEdgeData = {
/** User-placed waypoints for this edge (empty = automatic routing). */
@ -55,36 +50,25 @@ export function RoutedEdge({
const { screenToFlowPosition } = useReactFlow();
const dragIndexRef = React.useRef<number | null>(null);
const obstacles = (route?.obstacles ?? []).filter(
(r) => r.id !== route?.sourceId && r.id !== route?.targetId,
);
// Preferred shape: the user's waypoints if routed, else the automatic
// "out, across, in" path. If that path would cut through a node, fall back to
// the direct line so the router can bend around the obstacles (a midpoint
// sitting inside a box leaves the router nothing to work with).
// Shared shape builder (same logic as the dialogue canvas): forward edges
// take a stubbed Z-step at the source's lane (stepPosition), back edges try
// bus corridors around the cards, and every candidate is detoured around
// unrelated technologies with the cleanest result winning. User waypoints,
// when present, are routed verbatim.
const start: RoutePoint = { x: sourceX, y: sourceY };
const end: RoutePoint = { x: targetX, y: targetY };
const stepX = sourceX + (targetX - sourceX) * (route?.stepPosition ?? 0.5);
const orthogonal: RoutePoint[] = [
const { points: routed, base } = routeEdge({
id: route?.routeId,
start,
{ x: stepX, y: sourceY },
{ x: stepX, y: targetY },
end,
];
const hasCrossing = (pts: RoutePoint[]) =>
pts.some(
(p, i) => i < pts.length - 1 && obstacles.some((r) => segmentCrossesRect(p, pts[i + 1], r)),
);
const base: RoutePoint[] =
waypoints.length > 0
? [start, ...waypoints, end]
: hasCrossing(orthogonal)
? [start, end]
: orthogonal;
const routed = routeAroundObstacles(base, obstacles);
sourceDirection: "right",
targetDirection: "left",
nodes: route?.obstacles ?? [],
sourceId: route?.sourceId,
targetId: route?.targetId,
waypoints: waypoints.length > 0 ? waypoints : undefined,
stepPosition: route?.stepPosition,
});
const path = routed.length >= 2 ? buildRoutePath(routed) : "";
const commit = (next: RouteWaypoint[]) => route?.onRouteChange(route.routeId, next);

View file

@ -230,3 +230,152 @@ export function polylineMidpoint(points: RoutePoint[]): RoutePoint {
}
return points[points.length - 1];
}
// ---------------------------------------------------------------------------
// Edge shape builder
// ---------------------------------------------------------------------------
/** How far a line leaves its handle before it may bend (px). */
export const EDGE_STUB = 24;
/** Which side of its card a handle sits on. */
export type StubDirection = "left" | "right" | "top" | "bottom";
function stubFor(point: RoutePoint, direction: StubDirection | null | undefined, length: number): RoutePoint {
switch (direction) {
case "left":
return { x: point.x - length, y: point.y };
case "right":
return { x: point.x + length, y: point.y };
case "top":
return { x: point.x, y: point.y - length };
case "bottom":
return { x: point.x, y: point.y + length };
default:
return point;
}
}
/**
* Detour lanes come in three depths so edges that enter the same handle (or
* loop around the same card) don't collapse onto one identical lane and read
* as a single thick bundle. The depth is derived from the edge id, so it is
* stable across renders and differs between edges with overwhelming
* probability.
*/
const LANE_STEPS = [0, 16, 32];
export function laneFor(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) | 0;
return LANE_STEPS[Math.abs(h) % LANE_STEPS.length];
}
export type EdgeRouteInput = {
/** Edge identity, used to spread detour lanes. */
id?: string;
start: RoutePoint;
end: RoutePoint;
sourceDirection?: StubDirection | null;
targetDirection?: StubDirection | null;
/** Rectangles of every node card on the canvas. */
nodes: RouteRect[];
sourceId?: number | string;
targetId?: number | string;
/** Manual waypoints: routed verbatim (cleaned), skipping auto candidates. */
waypoints?: RoutePoint[];
/** Where the forward Z-step's vertical run sits (0..1). */
stepPosition?: number;
stubLength?: number;
};
export type EdgeRouteResult = {
/** Final polyline to render (detoured, clean when possible). */
points: RoutePoint[];
/** The winning unrouted base shape (for "add a bend" handles). */
base: RoutePoint[];
};
/**
* Build the full route for one edge between two cards.
*
* Forward edges prefer a tidy Z-step (perpendicular stubs at each handle);
* back edges try structured "bus routes" that run along a corridor above or
* below every card before swinging into the entry handle. Candidates are
* scored by residual crossings after detouring, and the cleanest wins.
* Back edges treat ALL cards as obstacles (including their own ends, which
* the line must loop around); forward edges exclude their own endpoints.
*/
export function routeEdge(input: EdgeRouteInput): EdgeRouteResult {
const {
id = "",
start,
end,
sourceDirection,
targetDirection,
nodes,
sourceId,
targetId,
waypoints,
stepPosition = 0.5,
stubLength = EDGE_STUB,
} = input;
const endpointFree = nodes.filter((r) => r.id !== sourceId && r.id !== targetId);
const isBackEdge = end.x < start.x;
const obstacles = isBackEdge ? nodes : endpointFree;
const lane = laneFor(id);
const margin = ROUTE_CLEARANCE + lane;
const sStub = stubFor(start, sourceDirection, stubLength);
const tStub = stubFor(end, targetDirection, stubLength);
const crossingCount = (points: RoutePoint[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => crosses(points[i], points[i + 1], r))) n += 1;
}
return n;
};
if (waypoints && waypoints.length > 0) {
const base = [start, ...waypoints, end];
return { points: routeAroundObstacles(base, obstacles, margin), base };
}
const candidates: RoutePoint[][] = [];
if (isBackEdge && obstacles.length > 0) {
const topY = Math.min(...obstacles.map((r) => r.y)) - ROUTE_CLEARANCE - lane;
const botY = Math.max(...obstacles.map((r) => r.y + r.height)) + ROUTE_CLEARANCE + lane;
const bus = (y: number): RoutePoint[] => [
start,
sStub,
{ x: sStub.x, y },
{ x: tStub.x, y },
tStub,
end,
];
candidates.push(bus(topY), bus(botY), [start, sStub, tStub, end]);
} else if (isBackEdge) {
candidates.push([start, sStub, tStub, end]);
} else {
const stepX = sStub.x + (tStub.x - sStub.x) * stepPosition;
candidates.push(
[start, sStub, { x: stepX, y: sStub.y }, { x: stepX, y: tStub.y }, tStub, end],
[start, sStub, tStub, end],
);
}
let best: RoutePoint[] | null = null;
let bestBase = candidates[0];
let bestScore = Number.POSITIVE_INFINITY;
for (const candidate of candidates) {
const cleaned = routeAroundObstacles(candidate, obstacles, margin);
const score = crossingCount(cleaned);
if (score < bestScore) {
best = cleaned;
bestBase = candidate;
bestScore = score;
}
if (score === 0) break;
}
return { points: best ?? [start, end], base: bestBase };
}

View file

@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import {
laneFor,
routeEdge,
segmentCrossesRect,
type RoutePoint,
type RouteRect,
} from "@/lib/flow-edge-routing";
const crossings = (points: RoutePoint[], rects: RouteRect[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (rects.some((r) => segmentCrossesRect(points[i], points[i + 1], r))) n += 1;
}
return n;
};
const A: RouteRect = { id: "a", x: 0, y: 0, width: 200, height: 100 };
const B: RouteRect = { id: "b", x: 600, y: 0, width: 200, height: 100 };
const BLOCKER: RouteRect = { id: "x", x: 340, y: -20, width: 80, height: 140 };
describe("shared edge router (routeEdge)", () => {
it("draws a stubbed Z-step for a clear forward edge", () => {
const { points } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B],
sourceId: "a",
targetId: "b",
});
// start, sStub, two step corners (coincident on a straight run), tStub,
// end — no detours needed.
expect(points).toHaveLength(6);
expect(points[0]).toEqual({ x: 200, y: 50 });
expect(points[1]).toEqual({ x: 224, y: 50 }); // 24px stub off the handle
expect(points[2]).toEqual({ x: 400, y: 50 });
expect(points[3]).toEqual({ x: 400, y: 50 });
expect(points[points.length - 1]).toEqual({ x: 600, y: 50 });
expect(points[points.length - 2]).toEqual({ x: 576, y: 50 });
});
it("routes a blocked forward edge with zero card crossings", () => {
const { points } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "a",
targetId: "b",
});
expect(crossings(points, [BLOCKER])).toBe(0);
});
it("sends a back edge around the cards via a bus corridor", () => {
const { points } = routeEdge({
id: "back",
start: { x: 800, y: 50 },
end: { x: 0, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "b",
targetId: "a",
});
expect(crossings(points, [A, B, BLOCKER])).toBe(0);
// It must actually leave the card band (above or below everything).
const ys = points.map((p) => p.y);
expect(Math.min(...ys) < -20 || Math.max(...ys) > 120).toBe(true);
});
it("spreads detour lanes per edge id", () => {
const route = (id: string) =>
JSON.stringify(
routeEdge({
id,
start: { x: 800, y: 50 },
end: { x: 0, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "b",
targetId: "a",
}).points,
);
// laneFor buckets ids into distinct depths; these two land on different ones.
expect(laneFor("e1")).not.toBe(laneFor("e2"));
expect(route("e1")).not.toBe(route("e2"));
});
it("routes manual waypoints verbatim as the base shape", () => {
const wp: RoutePoint[] = [{ x: 400, y: 300 }];
const { base } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B],
sourceId: "a",
targetId: "b",
waypoints: wp,
});
expect(base).toEqual([{ x: 200, y: 50 }, ...wp, { x: 600, y: 50 }]);
});
});