1
0
Fork 0
polaris-task-force/src/components/admin/tech-tree/RoutedEdge.tsx
Z8MB1E d43b2ef658 feat(tech-tree): drag groups, snap to grid, and route edges around nodes
Round out the canvas editing experience.

- Dragging one card of a multi-selection now moves and persists the whole
  selection (React Flow hands the full dragged set to onNodeDragStop).
- A category band is draggable by its header, which moves every technology in
  that band; the band body stays click-through.
- A "Snap: On/Off" toolbar toggle (default on, remembered per browser) snaps
  dragged cards to a 46px grid that divides the column and row steps, so
  snapped cards line up with the automatic layout.
- Connection lines are adjustable: select an edge to reveal "+" handles at each
  segment's midpoint (click to add a bend), drag bends to reroute, and
  double-click a bend to remove it. Routes persist per browser.
- Edges route around technologies they are not connected to, and corners are
  rounded, so lines no longer cut through unrelated cards.
- Ctrl/Cmd-clicking to multi-select no longer pops the side panel over the
  canvas.
2026-10-03 03:28:27 -04:00

204 lines
6.9 KiB
TypeScript

"use client";
import { BaseEdge, EdgeLabelRenderer, useReactFlow, type EdgeProps } from "@xyflow/react";
import React from "react";
import { buildRoutePath, type RouteWaypoint } from "./edgeRoutes";
import {
routeAroundObstacles,
segmentCrossesRect,
type RoutePoint,
type RouteRect,
} from "./edgeRouting";
export type RoutedEdgeData = {
/** User-placed waypoints for this edge (empty = automatic routing). */
waypoints: RouteWaypoint[];
/** "source:target" key used to persist the route. */
routeId: string;
/** Technology ids at each end, so the edge may connect to them. */
sourceId: number;
targetId: number;
/** Node rectangles the edge should route around. */
obstacles: RouteRect[];
/** Where the automatic vertical run sits (0..1). */
stepPosition: number;
editable: boolean;
onRouteChange: (routeId: string, waypoints: RouteWaypoint[]) => void;
};
/**
* A prerequisite edge. It draws a polyline from the source handle through any
* user waypoints to the target handle, bending around technologies it is not
* connected to, with rounded corners at each bend.
*
* Interaction (only when `editable`):
* - Select the edge to reveal "+" handles at each segment's midpoint; click one
* to add a bend there.
* - Drag a waypoint dot to move it.
* - Double-click a waypoint dot to remove it.
*/
export function RoutedEdge({
id,
sourceX,
sourceY,
targetX,
targetY,
markerEnd,
style,
data,
selected,
}: EdgeProps) {
const route = data as unknown as RoutedEdgeData | undefined;
const waypoints = route?.waypoints ?? [];
const editable = route?.editable ?? false;
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).
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[] = [
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);
const path = routed.length >= 2 ? buildRoutePath(routed) : "";
const commit = (next: RouteWaypoint[]) => route?.onRouteChange(route.routeId, next);
const onHandlePointerDown =
(index: number) => (event: React.PointerEvent<HTMLDivElement>) => {
if (!editable) return;
event.stopPropagation();
event.preventDefault();
dragIndexRef.current = index;
event.currentTarget.setPointerCapture(event.pointerId);
};
const onHandlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const index = dragIndexRef.current;
if (index === null) return;
const point = screenToFlowPosition({ x: event.clientX, y: event.clientY });
commit(
waypoints.map((wp, i) =>
i === index ? { x: Math.round(point.x), y: Math.round(point.y) } : wp,
),
);
};
const onHandlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
if (dragIndexRef.current === null) return;
dragIndexRef.current = null;
try {
event.currentTarget.releasePointerCapture(event.pointerId);
} catch {
// capture may already be released
}
};
const onHandleDoubleClick = (index: number) => (event: React.MouseEvent) => {
if (!editable) return;
event.stopPropagation();
commit(waypoints.filter((_, i) => i !== index));
};
// Midpoints of the UNROUTED segments, for the "add a bend" handles (a routed
// detour is not a place the user can insert a waypoint at).
const midpoints: { x: number; y: number; insertAt: number }[] = [];
for (let i = 0; i < base.length - 1; i += 1) {
midpoints.push({
x: (base[i].x + base[i + 1].x) / 2,
y: (base[i].y + base[i + 1].y) / 2,
insertAt: i,
});
}
const addAt = (index: number, point: RouteWaypoint) => {
const next = [...waypoints];
next.splice(index, 0, point);
commit(next);
};
return (
<>
<BaseEdge id={id} path={path} markerEnd={markerEnd} style={style} />
<EdgeLabelRenderer>
{selected && editable
? midpoints.map((mid, i) => (
<div
key={`${route?.routeId}-mid-${i}`}
className="nodrag nopan"
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${mid.x}px, ${mid.y}px)`,
pointerEvents: "all",
}}
>
<button
type="button"
aria-label="Add route bend"
title="Add a bend here"
data-testid="tech-edge-add-bend"
onPointerDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
addAt(mid.insertAt, { x: Math.round(mid.x), y: Math.round(mid.y) });
}}
className="flex h-4 w-4 items-center justify-center rounded-full border border-[#a5f3fc]/70 bg-black/80 font-mono text-[10px] leading-none text-[#a5f3fc] hover:border-[#a5f3fc] hover:bg-[#22d3ee]/25"
>
+
</button>
</div>
))
: null}
{waypoints.map((wp, index) => (
<div
key={`${route?.routeId}-wp-${index}`}
className="nodrag nopan"
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${wp.x}px, ${wp.y}px)`,
pointerEvents: "all",
}}
>
<div
role="button"
aria-label="Route waypoint"
title="Drag to move, double-click to remove"
data-testid="tech-edge-waypoint"
onPointerDown={onHandlePointerDown(index)}
onPointerMove={onHandlePointerMove}
onPointerUp={onHandlePointerUp}
onDoubleClick={onHandleDoubleClick(index)}
className="h-3 w-3 rounded-full border border-[#a5f3fc]/80 bg-[#22d3ee]/90 shadow-[0_0_6px_rgba(34,211,238,0.7)]"
style={{ cursor: "grab" }}
/>
</div>
))}
</EdgeLabelRenderer>
</>
);
}