Skip to content
refs
360 lines · 18.4 KBRaw
1import type { CodeChange, CodeGraph } from "@refs/backend/contract";
2import { Button, Input, Tabs, cn } from "@refs/design-system";
3import { ArrowUUpLeftIcon, ArrowUUpRightIcon, ArrowsInIcon, ArrowsOutIcon, CaretDownIcon, CaretUpIcon } from "@refs/design-system/icons";
4import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
5import { ChangesPanel } from "./changes-panel";
6import { CodeCard, type CardNotes } from "./code-card";
7import { useFillHeight } from "./fill";
8import { layoutMap } from "./layout";
9import { MapView, type FocusRequest } from "./map-view";
10import { CodeModel } from "./model";
11import { useFileSources } from "./sources";
12import { TraceLine } from "./trace-line";
13
14interface Step {
15 readonly id: string;
16 readonly via: number | null;
17}
18
19interface Trace {
20 readonly steps: readonly Step[];
21 readonly active: number;
22}
23
24const MAX_HISTORY = 100;
25const NO_FILES: ReadonlyMap<string, string> = new Map();
26const SVG = "http://www.w3.org/2000/svg";
27
28function shape(name: string, attributes: Record<string, string | number>): SVGElement {
29 const element = document.createElementNS(SVG, name);
30 for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));
31 return element;
32}
33const SEARCH_RESULTS = 8;
34
35export interface CodeNavigatorProps {
36 readonly graph: CodeGraph;
37 readonly repo: string;
38 /** A pull request's changes. With them, the navigator marks the changed code and steps through it. */
39 readonly changes?: readonly CodeChange[];
40 /** Review comments on lines, on a pull request. */
41 readonly notes?: CardNotes;
42}
43
44/**
45 * The code navigator: a map of the commit on top and a trace below. Following a name in a card adds its
46 * definition as the next card, so the reader builds a storyline without jumping around the code.
47 */
48export function CodeNavigator({ graph, repo, changes, notes }: CodeNavigatorProps) {
49 const review = changes !== undefined;
50 const model = useMemo(() => new CodeModel(graph, changes), [graph, changes]);
51 const boxes = useMemo(() => layoutMap(model), [model]);
52 const sources = useFileSources(repo, graph.commit, NO_FILES);
53 const start = useMemo(() => (review ? (model.changedSymbols[0] ?? model.entryPoint()) : model.entryPoint()), [model, review]);
54
55 const [trace, setTrace] = useState<Trace>(() => ({ steps: start ? [{ id: start, via: null }] : [], active: 0 }));
56 const history = useRef<{ list: Trace[]; at: number }>({ list: [trace], at: 0 });
57 const [fold, setFold] = useState(true);
58 const [maxed, setMaxed] = useState(false);
59 const [trayHeight, setTrayHeight] = useState<number | null>(null);
60 const [focus, setFocus] = useState<FocusRequest | null>(null);
61 const [changesOpen, setChangesOpen] = useState(true);
62 const [visited, setVisited] = useState<ReadonlySet<string>>(new Set());
63 const [query, setQuery] = useState("");
64 const root = useFillHeight<HTMLDivElement>();
65 const canvas = useRef<HTMLDivElement>(null);
66 const tray = useRef<HTMLDivElement>(null);
67 const content = useRef<HTMLDivElement>(null);
68 const links = useRef<SVGSVGElement>(null);
69 const beam = useRef<SVGSVGElement>(null);
70 const frame = useRef(0);
71
72 useEffect(() => {
73 if (matchMedia("(max-width: 767px)").matches) setChangesOpen(false);
74 }, []);
75
76 const record = useCallback((next: Trace) => {
77 const past = history.current;
78 const list = [...past.list.slice(0, past.at + 1), next].slice(-MAX_HISTORY);
79 history.current = { list, at: list.length - 1 };
80 setTrace(next);
81 }, []);
82 const locate = useCallback((id: string, minScale = 0.8) => setFocus({ id, minScale, nonce: Date.now() }), []);
83
84 const latest = useRef(trace);
85 latest.current = trace;
86 const follow = useCallback((index: number, line: number, to: string) => {
87 const steps = [...latest.current.steps.slice(0, index), { id: latest.current.steps[index].id, via: line }, { id: to, via: null }];
88 record({ steps, active: steps.length - 1 });
89 }, [record]);
90 const select = useCallback((index: number, show: boolean) => {
91 const step = latest.current.steps[index];
92 if (!step) return;
93 setTrace({ ...latest.current, active: index });
94 if (show) locate(step.id);
95 }, [locate]);
96 const fromCaller = useCallback((index: number, caller: string) => record({ steps: [{ id: caller, via: null }, ...latest.current.steps.slice(index)], active: 0 }), [record]);
97 const close = useCallback((index: number) => {
98 const steps = latest.current.steps.filter((_, at) => at !== index).map((step, at, all) => (at === all.length - 1 ? { ...step, via: null } : step));
99 record({ steps, active: Math.min(steps.length - 1, Math.max(0, latest.current.active - (index <= latest.current.active ? 1 : 0))) });
100 }, [record]);
101 const begin = useCallback((id: string, show: boolean) => {
102 record({ steps: [{ id, via: null }], active: 0 });
103 if (show) locate(id);
104 }, [locate, record]);
105
106 const current = trace.steps[trace.active]?.id ?? null;
107 const changeIndex = current ? model.changedSymbols.indexOf(current) : -1;
108 const goToChange = useCallback((id: string) => {
109 setVisited((seen) => new Set(seen).add(id));
110 const index = trace.steps.findIndex((step) => step.id === id);
111 if (index >= 0) select(index, true);
112 else begin(id, true);
113 }, [begin, select, trace.steps]);
114 const stepChange = useCallback((direction: 1 | -1) => {
115 const list = model.changedSymbols;
116 if (!list.length) return;
117 const next = changeIndex < 0 ? (direction > 0 ? 0 : list.length - 1) : (changeIndex + direction + list.length) % list.length;
118 goToChange(list[next]);
119 }, [changeIndex, goToChange, model.changedSymbols]);
120 const travel = (direction: 1 | -1) => {
121 const past = history.current;
122 const at = past.at + direction;
123 if (at < 0 || at >= past.list.length) return;
124 history.current = { ...past, at };
125 setTrace(past.list[at]);
126 };
127
128 const onSymbol = useCallback((id: string) => {
129 const index = trace.steps.findIndex((step) => step.id === id);
130 if (index >= 0) select(index, false);
131 else begin(id, false);
132 }, [begin, select, trace.steps]);
133
134 const drawBeam = useCallback(() => {
135 cancelAnimationFrame(frame.current);
136 frame.current = requestAnimationFrame(() => {
137 const svg = beam.current;
138 const box = root.current?.getBoundingClientRect();
139 if (!svg || !box) return;
140 const id = trace.steps[trace.active]?.id;
141 const node = id && !maxed ? (canvas.current?.querySelector<HTMLElement>(`[data-node="${CSS.escape(id)}"]`) ?? null) : null;
142 const card = content.current?.querySelector<HTMLElement>(`[data-card="${trace.active}"]`);
143 const map = canvas.current?.getBoundingClientRect();
144 const lane = tray.current?.getBoundingClientRect();
145 if (!node || !card || !map || !lane || node.offsetParent === null) return void svg.replaceChildren();
146 const from = node.getBoundingClientRect();
147 const to = card.getBoundingClientRect();
148 const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value));
149 const x1 = clamp(from.left, map.left, map.right) - box.left;
150 const x2 = clamp(from.right, map.left, map.right) - box.left;
151 const y = clamp(from.bottom, map.top, map.bottom) - box.top;
152 const cx1 = clamp(to.left, lane.left, lane.right) - box.left;
153 const cx2 = clamp(to.right, lane.left, lane.right) - box.left;
154 const cy = to.top - box.top;
155 if (cx2 - cx1 < 4) return void svg.replaceChildren();
156 svg.replaceChildren(
157 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)" }),
158 ...[[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" })),
159 );
160 });
161 }, [maxed, trace]);
162
163 const settle = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
164 /** The beam hides while the map moves and comes back once it rests, so zooming does not measure the page on every step. */
165 const onMapMove = useCallback(() => {
166 beam.current?.replaceChildren();
167 clearTimeout(settle.current);
168 settle.current = setTimeout(drawBeam, 140);
169 }, [drawBeam]);
170
171 const drawLinks = useCallback(() => {
172 const svg = links.current;
173 const holder = content.current;
174 if (!svg || !holder) return;
175 const base = holder.getBoundingClientRect();
176 const shapes: SVGElement[] = [];
177 for (let index = 0; index < trace.steps.length - 1; index++) {
178 const card = holder.querySelector<HTMLElement>(`[data-card="${index}"]`);
179 const next = holder.querySelector<HTMLElement>(`[data-card="${index + 1}"]`);
180 if (!card || !next) continue;
181 const body = card.querySelector<HTMLElement>(".code-view")!.getBoundingClientRect();
182 const lead = card.querySelector<HTMLElement>(".code-map-ref[data-next]")?.closest<HTMLElement>("[data-line]");
183 const rect = card.getBoundingClientRect();
184 const head = next.firstElementChild!.getBoundingClientRect();
185 const y1 = Math.max(body.top + 8, Math.min(body.bottom - 8, lead ? lead.getBoundingClientRect().top + lead.offsetHeight / 2 : body.top + 20)) - base.top;
186 const x1 = rect.right - base.left;
187 const x2 = head.left - base.left;
188 const y2 = head.top + head.height / 2 - base.top;
189 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" }));
190 shapes.push(shape("circle", { cx: x1, cy: y1, r: 4, fill: "var(--panel)", stroke: "var(--porcelain)", "stroke-width": 2 }));
191 }
192 svg.setAttribute("width", String(holder.scrollWidth));
193 svg.setAttribute("height", String(holder.scrollHeight));
194 svg.replaceChildren(...shapes);
195 }, [trace.steps]);
196
197 const redraw = useCallback(() => {
198 drawLinks();
199 drawBeam();
200 }, [drawBeam, drawLinks]);
201
202 useLayoutEffect(() => {
203 redraw();
204 const card = content.current?.querySelector<HTMLElement>(`[data-card="${trace.active}"]`);
205 const lane = tray.current;
206 if (card && lane) {
207 const last = trace.active === trace.steps.length - 1;
208 const left = card.offsetLeft - Math.max(16, (lane.clientWidth - card.offsetWidth) * (last ? 0.9 : 0.5));
209 lane.scrollTo({ left: Math.max(0, left), behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
210 }
211 const late = setTimeout(redraw, 450);
212 return () => clearTimeout(late);
213 }, [redraw, trace, fold, maxed, trayHeight]);
214 useEffect(() => {
215 const resize = new ResizeObserver(redraw);
216 if (root.current) resize.observe(root.current);
217 return () => resize.disconnect();
218 }, [redraw]);
219
220 useEffect(() => {
221 const onKey = (event: KeyboardEvent) => {
222 const target = event.target as HTMLElement | null;
223 if (target?.closest("input, textarea, select, [contenteditable='true']")) return;
224 if (target && target !== document.body && !root.current?.contains(target)) return;
225 if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "z") {
226 event.preventDefault();
227 travel(event.shiftKey ? 1 : -1);
228 } else if (event.key === "]" && review) stepChange(1);
229 else if (event.key === "[" && review) stepChange(-1);
230 else if (event.key === "ArrowRight" && trace.active < trace.steps.length - 1) select(trace.active + 1, true);
231 else if (event.key === "ArrowLeft" && trace.active > 0) select(trace.active - 1, true);
232 else return;
233 event.preventDefault();
234 };
235 window.addEventListener("keydown", onKey);
236 return () => window.removeEventListener("keydown", onKey);
237 });
238
239 const traceIds = useMemo(() => trace.steps.map((step) => step.id), [trace.steps]);
240 const resizing = useRef<{ y: number; height: number } | null>(null);
241 const names = trace.steps.map((step) => model.qualifiedName(step.id));
242 const results = useMemo(() => model.search(query, SEARCH_RESULTS), [model, query]);
243
244 return (
245 <div ref={root} className="relative flex flex-col overflow-hidden rounded-panel bg-panel shadow-card">
246 {!maxed && (
247 <MapView
248 model={model}
249 boxes={boxes}
250 sources={sources}
251 review={review}
252 trace={traceIds}
253 active={current}
254 current={changeIndex >= 0 ? current : null}
255 focus={focus}
256 insetLeft={review && changesOpen ? 320 : 0}
257 canvasRef={canvas}
258 onSymbol={onSymbol}
259 onMove={onMapMove}
260 overlay={review && <ChangesPanel model={model} current={changeIndex >= 0 ? current : null} visited={visited} open={changesOpen} onOpenChange={setChangesOpen} onChange={goToChange} onFile={(path) => begin(`file:${path}`, true)} />}
261 />
262 )}
263 {!maxed && (
264 <div
265 role="separator"
266 aria-orientation="horizontal"
267 aria-label="Resize the trace"
268 className="relative h-2 shrink-0 cursor-ns-resize bg-ground shadow-[inset_0_1px_0_var(--hairline)] after:absolute after:top-[3px] after:left-1/2 after:h-[3px] after:w-9 after:-translate-x-1/2 after:rounded-full after:bg-line"
269 onPointerDown={(event) => {
270 resizing.current = { y: event.clientY, height: tray.current?.parentElement?.offsetHeight ?? 320 };
271 event.currentTarget.setPointerCapture(event.pointerId);
272 }}
273 onPointerMove={(event) => {
274 const from = resizing.current;
275 const total = root.current?.offsetHeight ?? 800;
276 if (from) setTrayHeight(Math.max(200, Math.min(total - 160, from.height - (event.clientY - from.y))));
277 }}
278 onPointerUp={() => (resizing.current = null)}
279 />
280 )}
281 <section aria-label="Trace" className={cn("flex min-h-[12.5rem] flex-col bg-ground", maxed ? "flex-1" : "shrink-0")} style={maxed ? undefined : { height: trayHeight ?? "44%" }}>
282 <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-3 py-1.5">
283 <span className="caption text-faint">Trace</span>
284 <Button size="sm" variant="ghost" shape="square" aria-label="Back" icon={<ArrowUUpLeftIcon />} disabled={history.current.at <= 0} onClick={() => travel(-1)} />
285 <Button size="sm" variant="ghost" shape="square" aria-label="Forward" icon={<ArrowUUpRightIcon />} disabled={history.current.at >= history.current.list.length - 1} onClick={() => travel(1)} />
286 <TraceLine names={names} active={trace.active} onSelect={(index) => select(index, true)} />
287 <span className="caption text-faint tabular-nums">{trace.steps.length ? `${trace.active + 1} of ${trace.steps.length}` : ""}</span>
288 {trace.steps.length === 1 && <span className="caption hidden text-faint lg:inline">Select an underlined name to follow it</span>}
289 <span className="flex-1" />
290 {review && model.changedSymbols.length > 0 && (
291 <span className="flex items-center gap-0.5 rounded-control px-1 shadow-[inset_0_0_0_1px_var(--hairline)]">
292 <Button size="sm" variant="ghost" shape="square" aria-label="Previous change" title="Previous change ( [ )" icon={<CaretUpIcon />} onClick={() => stepChange(-1)} />
293 <span className="caption min-w-24 text-center text-muted tabular-nums">{changeIndex >= 0 ? `Change ${changeIndex + 1} of ${model.changedSymbols.length}` : `${model.changedSymbols.length} changes`}</span>
294 <Button size="sm" variant="ghost" shape="square" aria-label="Next change" title="Next change ( ] )" icon={<CaretDownIcon />} onClick={() => stepChange(1)} />
295 </span>
296 )}
297 {review && (
298 <Tabs
299 variant="segmented"
300 value={fold ? "diff" : "all"}
301 onValueChange={(value) => setFold(value === "diff")}
302 tabs={[
303 { value: "diff", label: "Diff only" },
304 { value: "all", label: "All code" },
305 ]}
306 />
307 )}
308 <div className="relative">
309 <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Trace from a symbol" aria-label="Trace from a symbol" className="w-44" onKeyDown={(event) => {
310 if (event.key === "Enter" && results[0]) {
311 begin(results[0].id, true);
312 setQuery("");
313 }
314 if (event.key === "Escape") setQuery("");
315 }} />
316 {results.length > 0 && (
317 <div className="material-popup absolute top-full right-0 z-30 mt-1 w-72 rounded-panel p-1 shadow-surface">
318 {results.map((symbol) => (
319 <button key={symbol.id} type="button" className="flex h-8 w-full min-w-0 cursor-pointer items-center gap-2 rounded-control px-2 text-left text-compact hover:bg-hover" onClick={() => (begin(symbol.id, true), setQuery(""))}>
320 <span className="truncate font-mono text-xs text-ink">{model.qualifiedName(symbol.id)}</span>
321 <span className="ml-auto truncate font-mono text-xs text-faint">{symbol.file}</span>
322 </button>
323 ))}
324 </div>
325 )}
326 </div>
327 <Button size="sm" icon={maxed ? <ArrowsInIcon /> : <ArrowsOutIcon />} onClick={() => setMaxed(!maxed)}>
328 {maxed ? "Show the map" : "Focus"}
329 </Button>
330 </div>
331 <div ref={tray} className="min-h-0 flex-1 overflow-x-auto overflow-y-hidden" onScroll={drawBeam}>
332 <div ref={content} className="relative flex h-full gap-14 px-4 pt-1 pb-4" style={{ width: `max(100%, calc(${trace.steps.length} * min(30rem, 86vw) + ${Math.max(0, trace.steps.length - 1) * 3.5 + 2}rem))` }}>
333 <svg ref={links} aria-hidden className="pointer-events-none absolute top-0 left-0 z-10 overflow-visible" />
334 {trace.steps.map((step, index) => (
335 <CodeCard
336 key={`${index}:${step.id}`}
337 model={model}
338 index={index}
339 id={step.id}
340 via={step.via}
341 next={trace.steps[index + 1]?.id ?? null}
342 active={index === trace.active}
343 sources={sources}
344 commit={graph.commit}
345 fold={review && fold}
346 onFollow={follow}
347 onSelect={select}
348 onCaller={fromCaller}
349 onScroll={redraw}
350 onClose={close}
351 notes={notes}
352 />
353 ))}
354 </div>
355 </div>
356 </section>
357 <svg ref={beam} aria-hidden className="pointer-events-none absolute inset-0 z-20 size-full overflow-visible" />
358 </div>
359 );
360}