import type { MapBox, MapLink } from "./network-map-layout" /** Find a clear horizontal track between the sides facing the connection after dragging. */ export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) { const { x1, y1, x2, y2, cx } = link const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x)) const first = stub(x1), last = stub(x2) const middle = (y1 + y2) / 2 const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2)) const crosses = (a: number, b: number, low: number, size: number) => Math.min(a, b) < low + size && Math.max(a, b) > low const horizontal = (a: number, b: number, y: number) => obstacles.some(box => y > box.y && y < box.y + box.h && crosses(a, b, box.x, box.w)) const vertical = (x: number, a: number, b: number) => obstacles.some(box => x > box.x && x < box.x + box.w && crosses(a, b, box.y, box.h)) if (horizontal(x1, first, y1) || horizontal(last, x2, y2)) return null const candidates = [middle, y1, y2, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16]), ...usedTracks.flatMap(y => [y - 18, y + 18])] const legal = candidates.filter(y => !vertical(first, y1, y) && !horizontal(first, last, y) && !vertical(last, y, y2)) .sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b) const markerX = (first + last) / 2 const markerFits = (y: number) => !boxes.some(box => crosses(markerX - 17, markerX + 17, box.x, box.w) && crosses(y - 7, y + 7, box.y, box.h)) const y = legal.find(candidate => markerFits(candidate) && usedTracks.every(track => Math.abs(candidate - track) >= 18)) ?? legal[0] if (y === undefined) return null return { d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`, marker: markerFits(y) ? { x: markerX, y } : undefined, track: y, } }