Two routing defects on the dialogue canvas: - Return edges entering the same handle detoured through identical corners, stacking into one thick bundle on the left of the target. Each edge now derives a stable lane offset from its id, so parallel detours run in visibly separate lanes. - Long leftward runs relied on greedy corner-hopping alone, which could still leave a segment cutting under a card. Back edges now try structured bus routes (corridor above or below every card, then swing in to the entry handle) and score candidates by residual crossings, picking the first clean shape. The router also re-runs until clean (bounded to three passes) instead of trusting one greedy pass. Verified on doc #2: all seven edges route with zero card crossings and no stacked lanes; tech-tree edge-routing specs still pass.
176 lines
6.1 KiB
TypeScript
176 lines
6.1 KiB
TypeScript
"use client";
|
|
|
|
/**
|
|
* Flow edge that routes around node cards instead of cutting through them.
|
|
*
|
|
* 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.
|
|
*/
|
|
import { useMemo } from "react";
|
|
import { BaseEdge, EdgeLabelRenderer, Position, useStore, type EdgeProps } from "@xyflow/react";
|
|
|
|
import {
|
|
buildRoutePath,
|
|
polylineMidpoint,
|
|
routeAroundObstacles,
|
|
ROUTE_CLEARANCE,
|
|
segmentCrossesRect,
|
|
type RoutePoint,
|
|
type RouteRect,
|
|
} 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,
|
|
target,
|
|
sourceX,
|
|
sourceY,
|
|
targetX,
|
|
targetY,
|
|
sourcePosition,
|
|
targetPosition,
|
|
markerEnd,
|
|
label,
|
|
}: 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[] = [];
|
|
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 });
|
|
});
|
|
const forward = all.filter((r) => r.id !== source && r.id !== target);
|
|
return { forwardObstacles: forward, allObstacles: all };
|
|
}, [nodeLookup, source, target]);
|
|
|
|
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 path = buildRoutePath(routed);
|
|
const mid = polylineMidpoint(routed.length >= 2 ? routed : [start, end]);
|
|
|
|
const labelText = typeof label === "string" || typeof label === "number" ? String(label) : null;
|
|
|
|
return (
|
|
<>
|
|
<BaseEdge id={id} path={path} markerEnd={markerEnd} />
|
|
{labelText ? (
|
|
<EdgeLabelRenderer>
|
|
<div
|
|
className="nodrag nopan pointer-events-none rounded-sm border border-white/15 bg-zinc-950/90 px-1.5 py-0.5 font-mono text-[10px] leading-none text-zinc-300"
|
|
style={{
|
|
position: "absolute",
|
|
transform: `translate(-50%, -50%) translate(${mid.x}px, ${mid.y}px)`,
|
|
}}
|
|
>
|
|
{labelText}
|
|
</div>
|
|
</EdgeLabelRenderer>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|