/** * Every measured node box, in flow units, for the edge router (FZ-9208). * * One list per `nodes` array: React Flow hands a new array on every change, * so the WeakMap below builds the boxes once per change and every edge shares * them, together with the spatial index `edgeRoute` keys on the same array. * A node with no measured size yet is left out; it has no box to avoid. * The edge list rides along so edges sharing a gap get their own tracks * (FZ-9291); it changes identity on its own, so it keys a second level. */ import { useStore } from "../react-flow/xy"; import { edgeClearance } from "./edgeRoute"; import type { EdgeLink, EdgeObstacle, EdgeObstacles } from "./edgeRoute"; interface StoreNode { readonly id: string; readonly hidden?: boolean; readonly measured?: { readonly width?: number; readonly height?: number }; } interface StoreInternalNode { readonly internals: { readonly positionAbsolute: { readonly x: number; readonly y: number } }; readonly measured?: { readonly width?: number; readonly height?: number }; } interface StoreEdge { readonly source: string; readonly target: string; readonly hidden?: boolean; } interface ObstacleState { readonly nodes: readonly StoreNode[]; readonly edges?: readonly StoreEdge[]; readonly nodeLookup: ReadonlyMap; } const cache = new WeakMap>(); const noEdges: readonly StoreEdge[] = []; export function edgeObstaclesFor(state: ObstacleState): EdgeObstacles { const edges = state.edges ?? noEdges; let byEdges = cache.get(state.nodes); if (!byEdges) { byEdges = new WeakMap(); cache.set(state.nodes, byEdges); } const known = byEdges.get(edges); if (known) return known; const boxes: EdgeObstacle[] = []; for (const node of state.nodes) { if (node.hidden) continue; const internal = state.nodeLookup.get(node.id); const width = internal?.measured?.width ?? node.measured?.width; const height = internal?.measured?.height ?? node.measured?.height; if (!internal || !width || !height) continue; const { x, y } = internal.internals.positionAbsolute; boxes.push({ id: node.id, x, y, width, height }); } const links: EdgeLink[] = edges .filter((edge) => !edge.hidden) .map(({ source, target }) => ({ source, target })); const obstacles = { boxes, clearance: edgeClearance, links }; byEdges.set(edges, obstacles); return obstacles; } export function useEdgeObstacles(): EdgeObstacles { return useStore((state) => edgeObstaclesFor(state as unknown as ObstacleState)); }