"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 (
<>
{labelText ? (
{labelText}
) : null}
>
);
}