564 lines · 25.6 KBRaw
| 1 | import { Button, Shimmer, Tabs, cn } from "@refs/design-system"; |
| 2 | import { FrameCornersIcon, MinusIcon, PlusIcon } from "@refs/design-system/icons"; |
| 3 | import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react"; |
| 4 | import { CODE_TOP, LINE_HEIGHT, codeLineCount, type Box } from "./layout"; |
| 5 | import type { CodeModel, DiffStatus, NodeId, NodeKind } from "./model"; |
| 6 | import type { FileSources } from "./sources"; |
| 7 | |
| 8 | export type Level = "architecture" | "package" | "module" | "code"; |
| 9 | |
| 10 | const LEVELS: readonly { value: Level; label: string }[] = [ |
| 11 | { value: "architecture", label: "Architecture" }, |
| 12 | { value: "package", label: "Package" }, |
| 13 | { value: "module", label: "Module" }, |
| 14 | { value: "code", label: "Code" }, |
| 15 | ]; |
| 16 | const LEVEL_SCALE: Record<Exclude<Level, "architecture">, number> = { package: 0.3, module: 0.6, code: 1 }; |
| 17 | const MIN_SCALE = 0.004; |
| 18 | const MAX_SCALE = 3; |
| 19 | const MAX_CODE_BLOCKS = 80; |
| 20 | /** Labels that keep their size on screen are resized only when the zoom moves this much, so zooming stays smooth. */ |
| 21 | const INVERSE_STEP = 0.2; |
| 22 | /** Labels and code fill in once the map has rested this long, so a zoom moves only one layer. */ |
| 23 | const SETTLE_MS = 120; |
| 24 | const PLACEHOLDER_WIDTHS = ["w-3/4", "w-1/2", "w-5/6", "w-2/5", "w-2/3", "w-3/5"]; |
| 25 | |
| 26 | export function levelAt(scale: number): Level { |
| 27 | return scale < 0.2 ? "architecture" : scale < 0.42 ? "package" : scale < 0.78 ? "module" : "code"; |
| 28 | } |
| 29 | |
| 30 | /** A request to bring a block into view. A new `nonce` repeats the request for the same block. */ |
| 31 | export interface FocusRequest { |
| 32 | readonly id: NodeId; |
| 33 | readonly minScale?: number; |
| 34 | readonly nonce: number; |
| 35 | } |
| 36 | |
| 37 | interface View { |
| 38 | scale: number; |
| 39 | tx: number; |
| 40 | ty: number; |
| 41 | } |
| 42 | |
| 43 | export interface MapViewProps { |
| 44 | readonly model: CodeModel; |
| 45 | readonly boxes: ReadonlyMap<NodeId, Box>; |
| 46 | readonly sources: FileSources; |
| 47 | readonly review: boolean; |
| 48 | readonly trace: readonly string[]; |
| 49 | readonly active: string | null; |
| 50 | readonly current: string | null; |
| 51 | readonly focus: FocusRequest | null; |
| 52 | /** Room on the leading side that a panel covers, so fitting leaves it clear. */ |
| 53 | readonly insetLeft: number; |
| 54 | readonly canvasRef: RefObject<HTMLDivElement | null>; |
| 55 | readonly onSymbol: (id: string) => void; |
| 56 | readonly onMove: () => void; |
| 57 | readonly overlay?: ReactNode; |
| 58 | } |
| 59 | |
| 60 | /** The map: every block of the commit on one canvas. Zooming changes the level of detail, from folders down to the code. */ |
| 61 | export function MapView({ model, boxes, sources, review, trace, active, current, focus, insetLeft, canvasRef, onSymbol, onMove, overlay }: MapViewProps) { |
| 62 | const world = useRef<HTMLDivElement>(null); |
| 63 | const view = useRef<View>({ scale: 1, tx: 0, ty: 0 }); |
| 64 | const [level, setLevel] = useState<Level>("architecture"); |
| 65 | const [visible, setVisible] = useState<ReadonlySet<NodeId>>(new Set()); |
| 66 | const frame = useRef(0); |
| 67 | const rest = useRef(0); |
| 68 | const [settling, setSettling] = useState(false); |
| 69 | const inverse = useRef(1); |
| 70 | const shownLevel = useRef<Level | null>(null); |
| 71 | const root = boxes.get("root")!; |
| 72 | |
| 73 | const labels = useRef<LabelLayer>({}); |
| 74 | const candidates = useMemo(() => labelCandidates(model, boxes, review), [model, boxes, review]); |
| 75 | const leaves = useMemo(() => [...boxes].filter(([id]) => model.symbol(id) && !model.kids(id).length), [boxes, model]); |
| 76 | const size = useRef({ width: 0, height: 0 }); |
| 77 | const bounds = useRef<DOMRect | null>(null); |
| 78 | /** Until the reader pans or zooms, the map keeps fitting itself as its frame changes size. */ |
| 79 | const touched = useRef(false); |
| 80 | const measureVisible = useCallback(() => { |
| 81 | const { width, height } = size.current; |
| 82 | labels.current.set?.(placeLabels(candidates, view.current, width, height)); |
| 83 | if (!width || levelAt(view.current.scale) !== "code") return setVisible((was) => (was.size ? new Set() : was)); |
| 84 | const { scale, tx, ty } = view.current; |
| 85 | const x0 = -tx / scale; |
| 86 | const y0 = -ty / scale; |
| 87 | const x1 = x0 + width / scale; |
| 88 | const y1 = y0 + height / scale; |
| 89 | const seen = new Set<NodeId>(); |
| 90 | for (const [id, box] of leaves) { |
| 91 | if (seen.size >= MAX_CODE_BLOCKS) break; |
| 92 | if (box.x < x1 && box.x + box.w > x0 && box.y < y1 && box.y + box.h > y0) seen.add(id); |
| 93 | } |
| 94 | setVisible((was) => (was.size === seen.size && [...seen].every((id) => was.has(id)) ? was : seen)); |
| 95 | sources.request([...new Set([...seen].map((id) => model.symbol(id)!.file))]); |
| 96 | }, [canvasRef, candidates, leaves, model, sources]); |
| 97 | |
| 98 | const apply = useCallback( |
| 99 | (animate: boolean) => { |
| 100 | const element = world.current; |
| 101 | if (!element) return; |
| 102 | const { scale, tx, ty } = view.current; |
| 103 | const animated = animate && !matchMedia("(prefers-reduced-motion: reduce)").matches; |
| 104 | element.style.transition = animated ? "transform 380ms var(--ease-out)" : "none"; |
| 105 | clearTimeout(rest.current); |
| 106 | if (animated) { |
| 107 | element.style.willChange = "transform"; |
| 108 | setSettling(true); |
| 109 | rest.current = window.setTimeout(() => { |
| 110 | element.style.willChange = "auto"; |
| 111 | setSettling(false); |
| 112 | }, 420); |
| 113 | } |
| 114 | element.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`; |
| 115 | const next = levelAt(scale); |
| 116 | if (next !== shownLevel.current || Math.abs(inverse.current * scale - 1) > INVERSE_STEP) { |
| 117 | inverse.current = 1 / scale; |
| 118 | shownLevel.current = next; |
| 119 | element.style.setProperty("--inv", String(inverse.current)); |
| 120 | setLevel(next); |
| 121 | } |
| 122 | onMove(); |
| 123 | labels.current.hide?.(); |
| 124 | clearTimeout(frame.current); |
| 125 | frame.current = window.setTimeout(measureVisible, animate ? 400 : SETTLE_MS); |
| 126 | }, |
| 127 | [measureVisible, onMove], |
| 128 | ); |
| 129 | |
| 130 | const fit = useCallback( |
| 131 | (animate: boolean) => { |
| 132 | const canvas = canvasRef.current; |
| 133 | if (!canvas) return; |
| 134 | const width = canvas.clientWidth - insetLeft; |
| 135 | const scale = Math.max(MIN_SCALE, Math.min((width - 64) / root.w, (canvas.clientHeight - 88) / root.h, 1)); |
| 136 | view.current = { scale, tx: insetLeft + (width - root.w * scale) / 2, ty: (canvas.clientHeight - root.h * scale) / 2 + 20 }; |
| 137 | apply(animate); |
| 138 | }, |
| 139 | [apply, canvasRef, insetLeft, root], |
| 140 | ); |
| 141 | |
| 142 | const zoomTo = useCallback( |
| 143 | (id: NodeId, minScale = 0) => { |
| 144 | touched.current = true; |
| 145 | const canvas = canvasRef.current; |
| 146 | const box = boxes.get(id); |
| 147 | if (!canvas || !box) return; |
| 148 | const width = canvas.clientWidth - insetLeft; |
| 149 | const scale = Math.min(MAX_SCALE, Math.max(minScale, Math.min((width - 80) / box.w, (canvas.clientHeight - 96) / box.h, 1.1))); |
| 150 | const shownHeight = Math.min(box.h, (canvas.clientHeight - 96) / scale); |
| 151 | view.current = { scale, tx: insetLeft + width / 2 - (box.x + box.w / 2) * scale, ty: canvas.clientHeight / 2 - (box.y + shownHeight / 2) * scale + 20 }; |
| 152 | apply(true); |
| 153 | }, |
| 154 | [apply, boxes, canvasRef, insetLeft], |
| 155 | ); |
| 156 | |
| 157 | const zoomBy = useCallback( |
| 158 | (factor: number, cx?: number, cy?: number) => { |
| 159 | const canvas = canvasRef.current; |
| 160 | if (!canvas) return; |
| 161 | const x = cx ?? canvas.clientWidth / 2; |
| 162 | const y = cy ?? canvas.clientHeight / 2; |
| 163 | const { scale, tx, ty } = view.current; |
| 164 | const next = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale * factor)); |
| 165 | view.current = { scale: next, tx: x - ((x - tx) * next) / scale, ty: y - ((y - ty) * next) / scale }; |
| 166 | apply(false); |
| 167 | }, |
| 168 | [apply, canvasRef], |
| 169 | ); |
| 170 | |
| 171 | const chooseLevel = (next: Level) => { |
| 172 | touched.current = next !== "architecture"; |
| 173 | if (next === "architecture") return fit(true); |
| 174 | const canvas = canvasRef.current; |
| 175 | if (!canvas) return; |
| 176 | const anchor = active ? boxes.get(active) : undefined; |
| 177 | const { scale, tx, ty } = view.current; |
| 178 | const cx = anchor ? anchor.x + anchor.w / 2 : (insetLeft + (canvas.clientWidth - insetLeft) / 2 - tx) / scale; |
| 179 | const cy = anchor ? anchor.y + Math.min(anchor.h / 2, 160) : (canvas.clientHeight / 2 - ty) / scale; |
| 180 | const target = LEVEL_SCALE[next]; |
| 181 | view.current = { scale: target, tx: insetLeft + (canvas.clientWidth - insetLeft) / 2 - cx * target, ty: canvas.clientHeight / 2 - cy * target }; |
| 182 | apply(true); |
| 183 | }; |
| 184 | |
| 185 | const latest = useRef({ apply, fit, zoomTo, zoomBy, measureVisible }); |
| 186 | latest.current = { apply, fit, zoomTo, zoomBy, measureVisible }; |
| 187 | useLayoutEffect(() => latest.current.fit(false), [root.w, root.h, insetLeft]); |
| 188 | useEffect(() => { |
| 189 | if (focus) latest.current.zoomTo(focus.id, focus.minScale); |
| 190 | }, [focus]); |
| 191 | useEffect(() => { |
| 192 | const canvas = canvasRef.current; |
| 193 | if (!canvas) return; |
| 194 | const onWheel = (event: WheelEvent) => { |
| 195 | if ((event.target as Element).closest("[data-map-chrome]")) return; |
| 196 | event.preventDefault(); |
| 197 | touched.current = true; |
| 198 | const rect = bounds.current ?? (bounds.current = canvas.getBoundingClientRect()); |
| 199 | if (!event.ctrlKey && Math.abs(event.deltaX) > Math.abs(event.deltaY)) { |
| 200 | view.current = { ...view.current, tx: view.current.tx - event.deltaX }; |
| 201 | return latest.current.apply(false); |
| 202 | } |
| 203 | latest.current.zoomBy(Math.exp(-event.deltaY * (event.ctrlKey ? 0.012 : 0.0018)), event.clientX - rect.left, event.clientY - rect.top); |
| 204 | }; |
| 205 | canvas.addEventListener("wheel", onWheel, { passive: false }); |
| 206 | size.current = { width: canvas.clientWidth, height: canvas.clientHeight }; |
| 207 | const forget = () => (bounds.current = null); |
| 208 | window.addEventListener("scroll", forget, { passive: true }); |
| 209 | window.addEventListener("resize", forget); |
| 210 | canvas.addEventListener("pointerenter", forget); |
| 211 | const resize = new ResizeObserver(() => { |
| 212 | size.current = { width: canvas.clientWidth, height: canvas.clientHeight }; |
| 213 | bounds.current = null; |
| 214 | if (touched.current) latest.current.measureVisible(); |
| 215 | else latest.current.fit(false); |
| 216 | }); |
| 217 | resize.observe(canvas); |
| 218 | return () => { |
| 219 | canvas.removeEventListener("wheel", onWheel); |
| 220 | window.removeEventListener("scroll", forget); |
| 221 | window.removeEventListener("resize", forget); |
| 222 | canvas.removeEventListener("pointerenter", forget); |
| 223 | resize.disconnect(); |
| 224 | }; |
| 225 | }, [canvasRef]); |
| 226 | |
| 227 | const drag = useRef<{ x: number; y: number; tx: number; ty: number; moved: boolean } | null>(null); |
| 228 | const moved = useRef(false); |
| 229 | const onPointerDown = (event: React.PointerEvent) => { |
| 230 | if ((event.target as Element).closest("[data-map-chrome]")) return; |
| 231 | drag.current = { x: event.clientX, y: event.clientY, tx: view.current.tx, ty: view.current.ty, moved: false }; |
| 232 | moved.current = false; |
| 233 | }; |
| 234 | const onPointerMove = (event: React.PointerEvent) => { |
| 235 | const start = drag.current; |
| 236 | if (!start) return; |
| 237 | const dx = event.clientX - start.x; |
| 238 | const dy = event.clientY - start.y; |
| 239 | if (!start.moved && Math.abs(dx) + Math.abs(dy) < 4) return; |
| 240 | if (!start.moved) (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId); |
| 241 | touched.current = true; |
| 242 | start.moved = moved.current = true; |
| 243 | view.current = { ...view.current, tx: start.tx + dx, ty: start.ty + dy }; |
| 244 | apply(false); |
| 245 | }; |
| 246 | const onPointerUp = () => { |
| 247 | drag.current = null; |
| 248 | }; |
| 249 | |
| 250 | const traced = useMemo(() => new Map(trace.map((id, index) => [id, index])), [trace]); |
| 251 | const holders = useMemo(() => new Set(trace.flatMap((id) => model.chain(id).slice(0, -1))), [model, trace]); |
| 252 | const order = useMemo(() => [...boxes.keys()].filter((id) => id !== "root").sort((a, b) => model.chain(a).length - model.chain(b).length), [boxes, model]); |
| 253 | |
| 254 | const choose = useRef({ onSymbol, zoomTo }); |
| 255 | choose.current = { onSymbol, zoomTo }; |
| 256 | const pick = useCallback( |
| 257 | (id: NodeId) => { |
| 258 | if (moved.current) return; |
| 259 | if (id.startsWith("dir:")) choose.current.zoomTo(id); |
| 260 | else choose.current.onSymbol(id); |
| 261 | }, |
| 262 | [model], |
| 263 | ); |
| 264 | |
| 265 | const nodes = useMemo( |
| 266 | () => |
| 267 | order.map((id) => ( |
| 268 | <MapNode |
| 269 | key={id} |
| 270 | id={id} |
| 271 | model={model} |
| 272 | box={boxes.get(id)!} |
| 273 | kind={model.kind(id)} |
| 274 | status={review ? model.status(id) : "none"} |
| 275 | trace={traced.get(id)} |
| 276 | holds={holders.has(id)} |
| 277 | active={id === active} |
| 278 | current={id === current} |
| 279 | lines={visible.has(id) ? (sources.lines(model.symbol(id)!.file) ?? "loading") : null} |
| 280 | onPick={pick} |
| 281 | /> |
| 282 | )), |
| 283 | [active, current, holders, model, order, pick, review, sources, traced, visible, boxes], |
| 284 | ); |
| 285 | return ( |
| 286 | <div |
| 287 | ref={canvasRef} |
| 288 | data-level={level} |
| 289 | aria-busy={settling || undefined} |
| 290 | className={cn("code-map relative min-h-0 flex-1 cursor-grab touch-none overflow-hidden bg-rail select-none active:cursor-grabbing", review && "code-map-review")} |
| 291 | onPointerDown={onPointerDown} |
| 292 | onPointerMove={onPointerMove} |
| 293 | onPointerUp={onPointerUp} |
| 294 | onPointerCancel={onPointerUp} |
| 295 | > |
| 296 | <div ref={world} className="code-map-world absolute top-0 left-0 origin-top-left" style={{ width: root.w, height: root.h }}> |
| 297 | <MapEdges model={model} boxes={boxes} level={level} trace={trace} review={review} /> |
| 298 | {nodes} |
| 299 | </div> |
| 300 | <div data-map-chrome className="material-popup absolute top-3 left-3 z-10 flex max-w-[calc(100%-1.5rem)] items-center gap-1 rounded-panel p-1 shadow-surface"> |
| 301 | <div className="min-w-0 overflow-x-auto [scrollbar-width:none]"> |
| 302 | <Tabs variant="segmented" value={level} onValueChange={(value) => chooseLevel(value as Level)} tabs={LEVELS.map(({ value, label }) => ({ value, label }))} listClassName="bg-transparent shadow-none max-sm:auto-cols-max" /> |
| 303 | </div> |
| 304 | <span aria-hidden className="mx-0.5 h-4 w-px bg-hairline" /> |
| 305 | <Button size="sm" variant="ghost" shape="square" aria-label="Zoom out" icon={<MinusIcon />} onClick={() => ((touched.current = true), zoomBy(1 / 1.35))} /> |
| 306 | <Button size="sm" variant="ghost" shape="square" aria-label="Zoom in" icon={<PlusIcon />} onClick={() => ((touched.current = true), zoomBy(1.35))} /> |
| 307 | <Button size="sm" variant="ghost" shape="square" aria-label="Show the whole map" icon={<FrameCornersIcon />} onClick={() => fit(true)} /> |
| 308 | </div> |
| 309 | <MapLabels controller={labels.current} onPick={pick} /> |
| 310 | {settling && <div aria-hidden className="code-map-settling shimmer pointer-events-none absolute inset-0 rounded-none bg-transparent" />} |
| 311 | {overlay} |
| 312 | </div> |
| 313 | ); |
| 314 | } |
| 315 | |
| 316 | interface Label { |
| 317 | readonly id: NodeId; |
| 318 | readonly kind: "folder" | "file" | "diff"; |
| 319 | readonly x: number; |
| 320 | readonly y: number; |
| 321 | readonly text: string; |
| 322 | readonly added?: number; |
| 323 | readonly removed?: number; |
| 324 | } |
| 325 | |
| 326 | const CHARACTER = 7.3; |
| 327 | const MAX_LABELS = 240; |
| 328 | |
| 329 | interface Candidate { |
| 330 | readonly id: NodeId; |
| 331 | readonly kind: Label["kind"]; |
| 332 | readonly box: Box; |
| 333 | readonly text: string; |
| 334 | readonly added?: number; |
| 335 | readonly removed?: number; |
| 336 | } |
| 337 | |
| 338 | /** Every label the outer levels may show, in the order they claim space: the largest changes, then folders, then the largest files. */ |
| 339 | function labelCandidates(model: CodeModel, boxes: ReadonlyMap<NodeId, Box>, review: boolean): Candidate[] { |
| 340 | const size = (id: NodeId) => boxes.get(id)!.w * boxes.get(id)!.h; |
| 341 | const changed = review |
| 342 | ? [...boxes.keys()] |
| 343 | .filter((id) => id.startsWith("file:") && (model.diff(id).added || model.diff(id).removed)) |
| 344 | .sort((a, b) => model.diff(b).added + model.diff(b).removed - (model.diff(a).added + model.diff(a).removed)) |
| 345 | .map((id): Candidate => { |
| 346 | const { added, removed } = model.diff(id); |
| 347 | return { id, kind: "diff", box: boxes.get(id)!, text: `${added ? `+${added}` : ""}${added && removed ? " " : ""}${removed ? `−${removed}` : ""}`, added, removed }; |
| 348 | }) |
| 349 | : []; |
| 350 | const named = [...boxes.keys()] |
| 351 | .filter((id) => id.startsWith("dir:") || id.startsWith("file:")) |
| 352 | .sort((a, b) => Number(b.startsWith("dir:")) - Number(a.startsWith("dir:")) || size(b) - size(a)) |
| 353 | .map((id): Candidate => ({ id, kind: id.startsWith("dir:") ? "folder" : "file", box: boxes.get(id)!, text: model.label(id) })); |
| 354 | return [...changed, ...named]; |
| 355 | } |
| 356 | |
| 357 | const CELL = 96; |
| 358 | |
| 359 | /** |
| 360 | * Places the labels for the current view in screen space. A label that would cover one already placed is left out, |
| 361 | * so the names that show are always readable. A grid of cells keeps the overlap check cheap. |
| 362 | */ |
| 363 | function placeLabels(candidates: readonly Candidate[], view: View, width: number, height: number): Label[] { |
| 364 | const level = levelAt(view.scale); |
| 365 | if (level !== "architecture" && level !== "package") return []; |
| 366 | const grid = new Map<number, { x: number; y: number; w: number; h: number }[]>(); |
| 367 | const cells = (rect: { x: number; y: number; w: number; h: number }) => { |
| 368 | const keys: number[] = []; |
| 369 | for (let cx = Math.floor(rect.x / CELL); cx <= Math.floor((rect.x + rect.w) / CELL); cx++) for (let cy = Math.floor(rect.y / CELL); cy <= Math.floor((rect.y + rect.h) / CELL); cy++) keys.push(cx * 10007 + cy); |
| 370 | return keys; |
| 371 | }; |
| 372 | const free = (rect: { x: number; y: number; w: number; h: number }) => |
| 373 | cells(rect).every((key) => !(grid.get(key) ?? []).some((other) => rect.x < other.x + other.w && rect.x + rect.w > other.x && rect.y < other.y + other.h && rect.y + rect.h > other.y)); |
| 374 | const take = (rect: { x: number; y: number; w: number; h: number }) => { |
| 375 | for (const key of cells(rect)) (grid.get(key) ?? grid.set(key, []).get(key)!).push(rect); |
| 376 | }; |
| 377 | const placed: Label[] = []; |
| 378 | for (const candidate of candidates) { |
| 379 | if (placed.length >= MAX_LABELS) break; |
| 380 | const x = candidate.box.x * view.scale + view.tx; |
| 381 | const y = candidate.box.y * view.scale + view.ty; |
| 382 | const w = candidate.box.w * view.scale; |
| 383 | const h = candidate.box.h * view.scale; |
| 384 | if (x + w < 0 || x > width || y + h < 0 || y > height) continue; |
| 385 | if (candidate.kind === "diff") { |
| 386 | const pillWidth = candidate.text.length * CHARACTER + 16; |
| 387 | const pill = { x: Math.min(x + w - pillWidth + 6, width - pillWidth - 4), y: y - 10, w: pillWidth, h: 20 }; |
| 388 | if (!free(pill)) continue; |
| 389 | take(pill); |
| 390 | placed.push({ id: candidate.id, kind: "diff", x: pill.x, y: pill.y, text: candidate.text, added: candidate.added, removed: candidate.removed }); |
| 391 | continue; |
| 392 | } |
| 393 | if (w < 28) continue; |
| 394 | const room = Math.floor((w - 14) / CHARACTER); |
| 395 | if (room < 4) continue; |
| 396 | const text = candidate.text.length <= room ? candidate.text : `${candidate.text.slice(0, room - 1)}…`; |
| 397 | const label = { x: x + 6, y: y + (candidate.kind === "folder" ? 6 : 5), w: text.length * CHARACTER + 8, h: 18 }; |
| 398 | if (!free(label)) continue; |
| 399 | take(label); |
| 400 | placed.push({ id: candidate.id, kind: candidate.kind, x: label.x, y: label.y, text }); |
| 401 | } |
| 402 | return placed; |
| 403 | } |
| 404 | |
| 405 | interface LabelLayer { |
| 406 | set?: (next: readonly Label[]) => void; |
| 407 | hide?: () => void; |
| 408 | } |
| 409 | |
| 410 | /** The screen-space labels. They hide while the map moves and are placed again when it rests. */ |
| 411 | function MapLabels({ controller, onPick }: { controller: LabelLayer; onPick: (id: NodeId) => void }) { |
| 412 | const [labels, setLabels] = useState<readonly Label[]>([]); |
| 413 | const layer = useRef<HTMLDivElement>(null); |
| 414 | useEffect(() => { |
| 415 | controller.set = (next) => { |
| 416 | setLabels(next); |
| 417 | if (layer.current) layer.current.style.opacity = "1"; |
| 418 | }; |
| 419 | controller.hide = () => { |
| 420 | if (layer.current) layer.current.style.opacity = "0"; |
| 421 | }; |
| 422 | return () => { |
| 423 | controller.set = undefined; |
| 424 | controller.hide = undefined; |
| 425 | }; |
| 426 | }, [controller]); |
| 427 | return ( |
| 428 | <div ref={layer} aria-hidden className="pointer-events-none absolute inset-0 overflow-hidden transition-opacity duration-150"> |
| 429 | {labels.map((label) => |
| 430 | label.kind === "diff" ? ( |
| 431 | <span key={`d:${label.id}`} className="absolute flex h-5 items-center gap-1.5 rounded-chip bg-raised px-1.5 font-mono text-xs whitespace-nowrap shadow-control" style={{ left: label.x, top: label.y }}> |
| 432 | {label.added ? <span className="text-success">+{label.added}</span> : null} |
| 433 | {label.removed ? <span className="text-danger">−{label.removed}</span> : null} |
| 434 | </span> |
| 435 | ) : ( |
| 436 | <button |
| 437 | key={label.id} |
| 438 | type="button" |
| 439 | tabIndex={-1} |
| 440 | title={label.kind === "folder" ? `Zoom into ${label.text}` : `Open ${label.text}`} |
| 441 | className={cn("pointer-events-auto absolute cursor-pointer rounded-chip px-1 font-mono text-xs leading-[18px] whitespace-nowrap hover:bg-hover hover:text-ink", label.kind === "folder" ? "text-muted" : "bg-[color-mix(in_oklab,var(--ground)_75%,transparent)] text-ink")} |
| 442 | style={{ left: label.x, top: label.y }} |
| 443 | onClick={(event) => { |
| 444 | event.stopPropagation(); |
| 445 | onPick(label.id); |
| 446 | }} |
| 447 | > |
| 448 | {label.text} |
| 449 | </button> |
| 450 | ), |
| 451 | )} |
| 452 | </div> |
| 453 | ); |
| 454 | } |
| 455 | |
| 456 | interface MapNodeProps { |
| 457 | readonly id: NodeId; |
| 458 | readonly model: CodeModel; |
| 459 | readonly box: Box; |
| 460 | readonly kind: NodeKind; |
| 461 | readonly status: DiffStatus; |
| 462 | readonly trace: number | undefined; |
| 463 | readonly holds: boolean; |
| 464 | readonly active: boolean; |
| 465 | readonly current: boolean; |
| 466 | readonly lines: readonly string[] | "loading" | null; |
| 467 | readonly onPick: (id: NodeId) => void; |
| 468 | } |
| 469 | |
| 470 | const MapNode = memo(function MapNode({ id, model, box, kind, status, trace, holds, active, current, lines, onPick }: MapNodeProps) { |
| 471 | const symbol = model.symbol(id); |
| 472 | const leaf = !!symbol && !model.kids(id).length; |
| 473 | const role = kind === "folder" ? "folder" : kind === "file" ? "file" : leaf ? "code" : "class"; |
| 474 | const diff = model.diff(id); |
| 475 | const added = symbol && model.change(symbol.file) ? new Set(model.change(symbol.file)!.added) : null; |
| 476 | const meta = kind === "file" ? `${model.kids(id).length} ${model.kids(id).length === 1 ? "symbol" : "symbols"} · ${model.fileLines(id.slice(5))} lines` : null; |
| 477 | return ( |
| 478 | <div |
| 479 | data-node={id} |
| 480 | data-role={role} |
| 481 | data-status={status} |
| 482 | data-traced={trace !== undefined || undefined} |
| 483 | data-holds={holds || undefined} |
| 484 | data-active={active || undefined} |
| 485 | data-current={current || undefined} |
| 486 | className="code-map-node absolute" |
| 487 | style={{ left: box.x, top: box.y, width: box.w, height: box.h }} |
| 488 | onClick={(event) => { |
| 489 | event.stopPropagation(); |
| 490 | onPick(id); |
| 491 | }} |
| 492 | > |
| 493 | <div className="code-map-head"> |
| 494 | {role !== "folder" && <span className="code-map-kind">{kind}</span>} |
| 495 | <span className="code-map-name">{model.label(id)}</span> |
| 496 | </div> |
| 497 | {meta && <div className="code-map-meta">{meta}</div>} |
| 498 | {leaf && lines === "loading" && ( |
| 499 | <div className="absolute inset-x-3 flex flex-col gap-1.5" style={{ top: CODE_TOP }}> |
| 500 | {Array.from({ length: Math.min(6, codeLineCount(model, id)) }, (_, index) => ( |
| 501 | <Shimmer key={index} className={cn("h-2.5", PLACEHOLDER_WIDTHS[index % PLACEHOLDER_WIDTHS.length])} /> |
| 502 | ))} |
| 503 | </div> |
| 504 | )} |
| 505 | {leaf && Array.isArray(lines) && ( |
| 506 | <pre className="code-map-code" style={{ top: CODE_TOP, lineHeight: `${LINE_HEIGHT}px` }}> |
| 507 | {lines.slice(symbol.start - 1, symbol.start - 1 + codeLineCount(model, id)).map((text, index) => ( |
| 508 | <div key={index} data-added={added?.has(symbol.start + index) || undefined}> |
| 509 | {text || " "} |
| 510 | </div> |
| 511 | ))} |
| 512 | </pre> |
| 513 | )} |
| 514 | {(diff.added > 0 || diff.removed > 0) && ( |
| 515 | <span className="code-map-diff" aria-label={`${diff.added} lines added, ${diff.removed} removed`}> |
| 516 | {diff.added > 0 && <span className="text-success">+{diff.added}</span>} |
| 517 | {diff.removed > 0 && <span className="text-danger">−{diff.removed}</span>} |
| 518 | </span> |
| 519 | )} |
| 520 | {trace !== undefined && <span className="code-map-station">{trace + 1}</span>} |
| 521 | </div> |
| 522 | ); |
| 523 | }); |
| 524 | |
| 525 | /** Lines between blocks. Zoomed out they join folders and files; zoomed in only the traced path shows, so the code stays readable. */ |
| 526 | function MapEdges({ model, boxes, level, trace, review }: { model: CodeModel; boxes: ReadonlyMap<NodeId, Box>; level: Level; trace: readonly string[]; review: boolean }) { |
| 527 | const paths = useMemo(() => { |
| 528 | const onTrace = new Set(trace); |
| 529 | const zoomedIn = level === "module" || level === "code"; |
| 530 | const holder = (chain: readonly NodeId[]) => (level === "architecture" ? (chain[1] ?? chain[0]) : (chain.find((id) => id.startsWith("file:")) ?? chain[chain.length - 1])); |
| 531 | const joined = new Map<string, { a: NodeId; b: NodeId; hot: boolean; quiet: boolean }>(); |
| 532 | for (const edge of model.graph.edges) { |
| 533 | const hot = onTrace.has(edge.from) && onTrace.has(edge.to); |
| 534 | if (zoomedIn && !hot) continue; |
| 535 | const a = hot ? edge.from : holder(model.chain(edge.from)); |
| 536 | const b = hot ? edge.to : holder(model.chain(edge.to)); |
| 537 | if (a === b || !boxes.has(a) || !boxes.has(b) || model.chain(a).includes(b) || model.chain(b).includes(a)) continue; |
| 538 | const key = `${a}\u0000${b}`; |
| 539 | const quiet = review && model.status(edge.from) === "none" && model.status(edge.to) === "none"; |
| 540 | const known = joined.get(key); |
| 541 | if (known) joined.set(key, { ...known, hot: known.hot || hot, quiet: known.quiet && quiet }); |
| 542 | else joined.set(key, { a, b, hot, quiet }); |
| 543 | } |
| 544 | return [...joined.values()].map(({ a, b, hot, quiet }) => { |
| 545 | const A = boxes.get(a)!; |
| 546 | const B = boxes.get(b)!; |
| 547 | const forward = A.x + A.w <= B.x; |
| 548 | const x1 = forward ? A.x + A.w : A.x; |
| 549 | const x2 = forward ? B.x : B.x + B.w; |
| 550 | const y1 = A.y + Math.min(A.h / 2, 40); |
| 551 | const y2 = B.y + Math.min(B.h / 2, 40); |
| 552 | const bend = Math.max(40, Math.abs(x2 - x1) * 0.45) * (forward ? 1 : -1); |
| 553 | return { key: `${a}>${b}`, d: `M${x1},${y1} C${x1 + bend},${y1} ${x2 - bend},${y2} ${x2},${y2}`, hot, quiet }; |
| 554 | }); |
| 555 | }, [boxes, level, model, review, trace]); |
| 556 | const root = boxes.get("root")!; |
| 557 | return ( |
| 558 | <svg aria-hidden className="pointer-events-none absolute top-0 left-0 overflow-visible" width={root.w} height={root.h}> |
| 559 | {paths.map((path) => ( |
| 560 | <path key={path.key} d={path.d} fill="none" vectorEffect="non-scaling-stroke" strokeLinecap="round" stroke={path.hot ? "var(--porcelain)" : "var(--line)"} strokeWidth={path.hot ? 3 : 1.25} opacity={path.quiet ? 0.35 : 1} /> |
| 561 | ))} |
| 562 | </svg> |
| 563 | ); |
| 564 | } |