import type { CodeChange, CodeGraph } from "@refs/backend/contract"; import { Button, Input, Tabs, cn } from "@refs/design-system"; import { ArrowUUpLeftIcon, ArrowUUpRightIcon, ArrowsInIcon, ArrowsOutIcon, CaretDownIcon, CaretUpIcon } from "@refs/design-system/icons"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { ChangesPanel } from "./changes-panel"; import { CodeCard, type CardNotes } from "./code-card"; import { useFillHeight } from "./fill"; import { layoutMap } from "./layout"; import { MapView, type FocusRequest } from "./map-view"; import { CodeModel } from "./model"; import { useFileSources } from "./sources"; import { TraceLine } from "./trace-line"; interface Step { readonly id: string; readonly via: number | null; } interface Trace { readonly steps: readonly Step[]; readonly active: number; } const MAX_HISTORY = 100; const NO_FILES: ReadonlyMap = new Map(); const SVG = "http://www.w3.org/2000/svg"; function shape(name: string, attributes: Record): SVGElement { const element = document.createElementNS(SVG, name); for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value)); return element; } const SEARCH_RESULTS = 8; export interface CodeNavigatorProps { readonly graph: CodeGraph; readonly repo: string; /** A pull request's changes. With them, the navigator marks the changed code and steps through it. */ readonly changes?: readonly CodeChange[]; /** Review comments on lines, on a pull request. */ readonly notes?: CardNotes; } /** * The code navigator: a map of the commit on top and a trace below. Following a name in a card adds its * definition as the next card, so the reader builds a storyline without jumping around the code. */ export function CodeNavigator({ graph, repo, changes, notes }: CodeNavigatorProps) { const review = changes !== undefined; const model = useMemo(() => new CodeModel(graph, changes), [graph, changes]); const boxes = useMemo(() => layoutMap(model), [model]); const sources = useFileSources(repo, graph.commit, NO_FILES); const start = useMemo(() => (review ? (model.changedSymbols[0] ?? model.entryPoint()) : model.entryPoint()), [model, review]); const [trace, setTrace] = useState(() => ({ steps: start ? [{ id: start, via: null }] : [], active: 0 })); const history = useRef<{ list: Trace[]; at: number }>({ list: [trace], at: 0 }); const [fold, setFold] = useState(true); const [maxed, setMaxed] = useState(false); const [trayHeight, setTrayHeight] = useState(null); const [focus, setFocus] = useState(null); const [changesOpen, setChangesOpen] = useState(true); const [visited, setVisited] = useState>(new Set()); const [query, setQuery] = useState(""); const root = useFillHeight(); const canvas = useRef(null); const tray = useRef(null); const content = useRef(null); const links = useRef(null); const beam = useRef(null); const frame = useRef(0); useEffect(() => { if (matchMedia("(max-width: 767px)").matches) setChangesOpen(false); }, []); const record = useCallback((next: Trace) => { const past = history.current; const list = [...past.list.slice(0, past.at + 1), next].slice(-MAX_HISTORY); history.current = { list, at: list.length - 1 }; setTrace(next); }, []); const locate = useCallback((id: string, minScale = 0.8) => setFocus({ id, minScale, nonce: Date.now() }), []); const latest = useRef(trace); latest.current = trace; const follow = useCallback((index: number, line: number, to: string) => { const steps = [...latest.current.steps.slice(0, index), { id: latest.current.steps[index].id, via: line }, { id: to, via: null }]; record({ steps, active: steps.length - 1 }); }, [record]); const select = useCallback((index: number, show: boolean) => { const step = latest.current.steps[index]; if (!step) return; setTrace({ ...latest.current, active: index }); if (show) locate(step.id); }, [locate]); const fromCaller = useCallback((index: number, caller: string) => record({ steps: [{ id: caller, via: null }, ...latest.current.steps.slice(index)], active: 0 }), [record]); const close = useCallback((index: number) => { const steps = latest.current.steps.filter((_, at) => at !== index).map((step, at, all) => (at === all.length - 1 ? { ...step, via: null } : step)); record({ steps, active: Math.min(steps.length - 1, Math.max(0, latest.current.active - (index <= latest.current.active ? 1 : 0))) }); }, [record]); const begin = useCallback((id: string, show: boolean) => { record({ steps: [{ id, via: null }], active: 0 }); if (show) locate(id); }, [locate, record]); const current = trace.steps[trace.active]?.id ?? null; const changeIndex = current ? model.changedSymbols.indexOf(current) : -1; const goToChange = useCallback((id: string) => { setVisited((seen) => new Set(seen).add(id)); const index = trace.steps.findIndex((step) => step.id === id); if (index >= 0) select(index, true); else begin(id, true); }, [begin, select, trace.steps]); const stepChange = useCallback((direction: 1 | -1) => { const list = model.changedSymbols; if (!list.length) return; const next = changeIndex < 0 ? (direction > 0 ? 0 : list.length - 1) : (changeIndex + direction + list.length) % list.length; goToChange(list[next]); }, [changeIndex, goToChange, model.changedSymbols]); const travel = (direction: 1 | -1) => { const past = history.current; const at = past.at + direction; if (at < 0 || at >= past.list.length) return; history.current = { ...past, at }; setTrace(past.list[at]); }; const onSymbol = useCallback((id: string) => { const index = trace.steps.findIndex((step) => step.id === id); if (index >= 0) select(index, false); else begin(id, false); }, [begin, select, trace.steps]); const drawBeam = useCallback(() => { cancelAnimationFrame(frame.current); frame.current = requestAnimationFrame(() => { const svg = beam.current; const box = root.current?.getBoundingClientRect(); if (!svg || !box) return; const id = trace.steps[trace.active]?.id; const node = id && !maxed ? (canvas.current?.querySelector(`[data-node="${CSS.escape(id)}"]`) ?? null) : null; const card = content.current?.querySelector(`[data-card="${trace.active}"]`); const map = canvas.current?.getBoundingClientRect(); const lane = tray.current?.getBoundingClientRect(); if (!node || !card || !map || !lane || node.offsetParent === null) return void svg.replaceChildren(); const from = node.getBoundingClientRect(); const to = card.getBoundingClientRect(); const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value)); const x1 = clamp(from.left, map.left, map.right) - box.left; const x2 = clamp(from.right, map.left, map.right) - box.left; const y = clamp(from.bottom, map.top, map.bottom) - box.top; const cx1 = clamp(to.left, lane.left, lane.right) - box.left; const cx2 = clamp(to.right, lane.left, lane.right) - box.left; const cy = to.top - box.top; if (cx2 - cx1 < 4) return void svg.replaceChildren(); svg.replaceChildren( shape("path", { d: `M${x1},${y} L${cx1},${cy} L${cx2},${cy} L${x2},${y} Z`, fill: "color-mix(in oklab, var(--porcelain) 6%, transparent)" }), ...[[x1, cx1], [x2, cx2]].map(([ax, bx]) => shape("line", { x1: ax, y1: y, x2: bx, y2: cy, stroke: "var(--porcelain)", "stroke-opacity": 0.45, "stroke-dasharray": "3 4" })), ); }); }, [maxed, trace]); const settle = useRef | undefined>(undefined); /** The beam hides while the map moves and comes back once it rests, so zooming does not measure the page on every step. */ const onMapMove = useCallback(() => { beam.current?.replaceChildren(); clearTimeout(settle.current); settle.current = setTimeout(drawBeam, 140); }, [drawBeam]); const drawLinks = useCallback(() => { const svg = links.current; const holder = content.current; if (!svg || !holder) return; const base = holder.getBoundingClientRect(); const shapes: SVGElement[] = []; for (let index = 0; index < trace.steps.length - 1; index++) { const card = holder.querySelector(`[data-card="${index}"]`); const next = holder.querySelector(`[data-card="${index + 1}"]`); if (!card || !next) continue; const body = card.querySelector(".code-view")!.getBoundingClientRect(); const lead = card.querySelector(".code-map-ref[data-next]")?.closest("[data-line]"); const rect = card.getBoundingClientRect(); const head = next.firstElementChild!.getBoundingClientRect(); const y1 = Math.max(body.top + 8, Math.min(body.bottom - 8, lead ? lead.getBoundingClientRect().top + lead.offsetHeight / 2 : body.top + 20)) - base.top; const x1 = rect.right - base.left; const x2 = head.left - base.left; const y2 = head.top + head.height / 2 - base.top; shapes.push(shape("path", { d: `M${x1},${y1} C${x1 + 44},${y1} ${x2 - 44},${y2} ${x2 - 6},${y2}`, fill: "none", stroke: "var(--porcelain)", "stroke-width": 3, "stroke-linecap": "round" })); shapes.push(shape("circle", { cx: x1, cy: y1, r: 4, fill: "var(--panel)", stroke: "var(--porcelain)", "stroke-width": 2 })); } svg.setAttribute("width", String(holder.scrollWidth)); svg.setAttribute("height", String(holder.scrollHeight)); svg.replaceChildren(...shapes); }, [trace.steps]); const redraw = useCallback(() => { drawLinks(); drawBeam(); }, [drawBeam, drawLinks]); useLayoutEffect(() => { redraw(); const card = content.current?.querySelector(`[data-card="${trace.active}"]`); const lane = tray.current; if (card && lane) { const last = trace.active === trace.steps.length - 1; const left = card.offsetLeft - Math.max(16, (lane.clientWidth - card.offsetWidth) * (last ? 0.9 : 0.5)); lane.scrollTo({ left: Math.max(0, left), behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); } const late = setTimeout(redraw, 450); return () => clearTimeout(late); }, [redraw, trace, fold, maxed, trayHeight]); useEffect(() => { const resize = new ResizeObserver(redraw); if (root.current) resize.observe(root.current); return () => resize.disconnect(); }, [redraw]); useEffect(() => { const onKey = (event: KeyboardEvent) => { const target = event.target as HTMLElement | null; if (target?.closest("input, textarea, select, [contenteditable='true']")) return; if (target && target !== document.body && !root.current?.contains(target)) return; if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "z") { event.preventDefault(); travel(event.shiftKey ? 1 : -1); } else if (event.key === "]" && review) stepChange(1); else if (event.key === "[" && review) stepChange(-1); else if (event.key === "ArrowRight" && trace.active < trace.steps.length - 1) select(trace.active + 1, true); else if (event.key === "ArrowLeft" && trace.active > 0) select(trace.active - 1, true); else return; event.preventDefault(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }); const traceIds = useMemo(() => trace.steps.map((step) => step.id), [trace.steps]); const resizing = useRef<{ y: number; height: number } | null>(null); const names = trace.steps.map((step) => model.qualifiedName(step.id)); const results = useMemo(() => model.search(query, SEARCH_RESULTS), [model, query]); return (
{!maxed && ( = 0 ? current : null} focus={focus} insetLeft={review && changesOpen ? 320 : 0} canvasRef={canvas} onSymbol={onSymbol} onMove={onMapMove} overlay={review && = 0 ? current : null} visited={visited} open={changesOpen} onOpenChange={setChangesOpen} onChange={goToChange} onFile={(path) => begin(`file:${path}`, true)} />} /> )} {!maxed && (
{ resizing.current = { y: event.clientY, height: tray.current?.parentElement?.offsetHeight ?? 320 }; event.currentTarget.setPointerCapture(event.pointerId); }} onPointerMove={(event) => { const from = resizing.current; const total = root.current?.offsetHeight ?? 800; if (from) setTrayHeight(Math.max(200, Math.min(total - 160, from.height - (event.clientY - from.y)))); }} onPointerUp={() => (resizing.current = null)} /> )}
Trace ))}
)}
{trace.steps.map((step, index) => ( ))}
); }