repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(diff-review): remove stale browser source

88aac9fdb21514b1ebcc84b40cc59d8802ed5101

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/diff-review/FEATURE-PARITY.md

Modified
1 1 # Feature Parity: Browser SPA → SSR
3 -## Source of truth: browser/index.ts features
3 +## Source of truth: current SSR features
5 -| # | Feature | Browser impl | SSR plan | Test strategy |
5 +| # | Feature | Historical browser impl | Current SSR impl | Test strategy |
6 6 | -- | --------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
7 7 | 1 | **File tree** | `FileTree` web-component with search, expand, git status colors, rename decorations | `@pierre/trees/ssr` `preloadFileTree` + `serializeFileTreeSsrPayload` | Unit: assert serialized HTML contains all paths, git status attributes, search input. E2E: Playwright clicks a file, asserts diff scrolls into view. |
8 8 | 2 | **Diff rendering** | `FileDiff` web-component, split view, syntax highlight, hover highlight, line selection | `@pierre/diffs/ssr` `preloadPatchDiff` per file or `preloadMultiFileDiff` | Unit: assert `prerenderedHTML` contains changed lines, line numbers, syntax tokens. E2E: Playwright asserts split columns exist. |

extensions/diff-review/browser/index.ts

Deleted
deleted file mode 100644
1 -// @ts-expect-error — CSS side-effect import for bundler
2 -import "./style.css";
3 -import type {
4 - DiffLineAnnotation,
5 - FileDiff,
6 - FileDiffMetadata,
7 - SelectedLineRange,
8 -} from "@pierre/diffs";
9 -import type {
10 - FileTree,
11 - FileTreeRowDecorationRenderer,
12 - GitStatusEntry,
13 -} from "@pierre/trees";
14 -import {
15 - HEARTBEAT_INTERVAL_MS,
16 - REVIEW_POLL_INTERVAL_MS,
17 -} from "../constants.js";
18 -import type {
19 - FindingDraft,
20 - ReviewCategory,
21 - ReviewPayload,
22 - ReviewSeverity,
23 - ReviewSide,
24 -} from "../types.js";
25 -import { DIFF_FONT_CSS, TREE_CSS } from "./shadow-css.js";
26 -import { NUGU_CODE_THEME, registerNuguCodeTheme } from "./theme.js";
28 -type FindingMeta = {
29 - findingId: string;
30 - severity: ReviewSeverity;
31 - category: ReviewCategory;
32 - comment: string;
33 -};
34 -type ThemeMode = "system" | "dark" | "light";
35 -type PaneSide = "left" | "right";
36 -type ReviewSelection = {
37 - file: string;
38 - side: ReviewSide;
39 - startLine: number;
40 - endLine: number;
41 -};
42 -type ViewPoint = { x: number; y: number };
43 -type SearchEntry = {
44 - file: string;
45 - side: "additions" | "deletions";
46 - line: number;
47 - text: string;
48 -};
49 -type SearchMatch = SearchEntry & { matchStart: number; matchEnd: number };
51 -type Elements = {
52 - app: HTMLElement;
53 - meta: HTMLElement;
54 - summary: HTMLElement;
55 - findingCount: HTMLElement;
56 - drawerCount: HTMLElement;
57 - tree: HTMLElement;
58 - diffs: HTMLElement;
59 - inlineFinding: HTMLElement;
60 - selection: HTMLElement;
61 - severity: HTMLSelectElement;
62 - severitySub: HTMLElement;
63 - category: HTMLSelectElement;
64 - categorySub: HTMLElement;
65 - comment: HTMLTextAreaElement;
66 - add: HTMLButtonElement;
67 - inlineCancel: HTMLButtonElement;
68 - findings: HTMLElement;
69 - notes: HTMLTextAreaElement;
70 - search: HTMLInputElement;
71 - searchClear: HTMLButtonElement;
72 - searchResults: HTMLElement;
73 - cancel: HTMLButtonElement;
74 - submit: HTMLButtonElement;
75 - status: HTMLElement;
76 - themeMode: HTMLSelectElement;
77 - leftSplitter: HTMLElement;
78 - rightSplitter: HTMLElement;
79 - toggleLeft: HTMLButtonElement;
80 - toggleRight: HTMLButtonElement;
81 -};
83 -const ROUTES = {
84 - review: "/api/review",
85 - heartbeat: "/api/heartbeat",
86 - cancel: "/api/cancel",
87 - validateFinding: "/api/finding/validate",
88 - submit: "/api/submit",
89 -} as const;
90 -const THEME_STORAGE_KEY = "diff-review-theme";
91 -const LAYOUT_STORAGE_KEY = "diff-review-layout";
92 -const REVIEW_CATEGORIES = [
93 - "bug",
94 - "style",
95 - "perf",
96 - "question",
97 -] as const satisfies readonly ReviewCategory[];
98 -const REVIEW_SEVERITIES = [
99 - "high",
100 - "medium",
101 - "low",
102 -] as const satisfies readonly ReviewSeverity[];
103 -const THEME_MODES = [
104 - "system",
105 - "dark",
106 - "light",
107 -] as const satisfies readonly ThemeMode[];
108 -const SEVERITY_SUBS: Record<string, string> = {
109 - high: "ship it to prod, coward",
110 - medium: "suspicious little gremlin",
111 - low: "tiny crime, still crime",
113 -const CATEGORY_SUBS: Record<string, string> = {
114 - bug: "exquisite disaster",
115 - style: "crimes against taste",
116 - perf: "artisanal slowness",
117 - question: "explain yourself",
119 -const PANE_LIMITS = {
120 - left: { min: 180, max: 560, fallback: 288 },
121 - right: { min: 280, max: 680, fallback: 382 },
122 -} as const;
124 -type LayoutState = {
125 - left: number;
126 - right: number;
127 - leftCollapsed: boolean;
128 - rightCollapsed: boolean;
131 -const token = new URLSearchParams(location.search).get("token") ?? "";
132 -const els: Elements = {
133 - app: must("app"),
134 - meta: must("meta"),
135 - summary: must("summary"),
136 - findingCount: must("finding-count"),
137 - drawerCount: must("drawer-count"),
138 - tree: must("tree"),
139 - diffs: must("diffs"),
140 - inlineFinding: must("inline-finding"),
141 - selection: must("selection"),
142 - severity: mustSelect("severity"),
143 - severitySub: must("severity-sub"),
144 - category: mustSelect("category"),
145 - categorySub: must("category-sub"),
146 - comment: mustText("comment"),
147 - add: mustButton("add"),
148 - inlineCancel: mustButton("inline-cancel"),
149 - findings: must("findings"),
150 - notes: mustText("notes"),
151 - search: must("search") as HTMLInputElement,
152 - searchClear: mustButton("search-clear"),
153 - searchResults: must("search-results"),
154 - cancel: mustButton("cancel"),
155 - submit: mustButton("submit"),
156 - status: must("status"),
157 - themeMode: mustSelect("theme-mode"),
158 - leftSplitter: must("left-splitter"),
159 - rightSplitter: must("right-splitter"),
160 - toggleLeft: mustButton("toggle-left"),
161 - toggleRight: mustButton("toggle-right"),
164 -const findings: FindingDraft[] = [];
165 -const diffViews = new Map<string, FileDiff<FindingMeta>>();
166 -const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
167 -let fileTree: FileTree | undefined;
168 -let selectedFile: string | undefined;
169 -let selected: ReviewSelection | undefined;
170 -let lastDiffPointer: ViewPoint | undefined;
171 -let searchIndex: SearchEntry[] = [];
172 -let searchResults: SearchMatch[] = [];
173 -let searchActiveIndex = -1;
174 -let searchDebounce: number | undefined;
175 -let diffsModule: typeof import("@pierre/diffs") | undefined;
176 -let treesModule: typeof import("@pierre/trees") | undefined;
177 -let heartbeat: number | undefined;
178 -let reviewPoll: number | undefined;
179 -let reviewHash = "";
180 -let renderGeneration = 0;
181 -let searchIndexing = false;
182 -let notesGrowFrame: number | undefined;
183 -let closing = false;
184 -let themeMode: ThemeMode = readThemeMode();
186 -applyThemeMode(themeMode);
187 -els.themeMode.value = themeMode;
188 -applyLayout(readLayout());
190 -main().catch((err) => setDisconnectedStatus(err));
191 -window.addEventListener("pagehide", closeFromBrowser);
192 -systemTheme.addEventListener("change", () => {
193 - if (themeMode === "system") applyThemeMode(themeMode);
194 -});
196 -async function main() {
197 - if (!token) throw new Error("Missing review token");
198 - setStatus("Loading review…");
199 - const reviewPromise = api<ReviewPayload>(ROUTES.review);
200 - setStatus("Loading diff renderer…");
201 - await loadRendererModules();
202 - const review = await reviewPromise;
203 - startHeartbeat();
204 - startReviewPolling();
205 - wireActions();
206 - await renderReview(review);
207 - setStatus("Ready");
210 -async function loadRendererModules() {
211 - if (diffsModule && treesModule) return;
212 - const [diffs, trees] = await Promise.all([
213 - import("@pierre/diffs"),
214 - import("@pierre/trees"),
215 - ]);
216 - diffsModule = diffs;
217 - treesModule = trees;
218 - registerNuguCodeTheme(diffs.registerCustomCSSVariableTheme);
221 -function diffs() {
222 - if (!diffsModule) throw new Error("Diff renderer not loaded");
223 - return diffsModule;
226 -function trees() {
227 - if (!treesModule) throw new Error("File tree renderer not loaded");
228 - return treesModule;
231 -async function renderReview(review: ReviewPayload) {
232 - const generation = ++renderGeneration;
233 - reviewHash = hashReview(review);
234 - renderMeta(review);
235 - renderTree(review);
236 - const fileDiffs = await renderDiffs(review, generation);
237 - if (!fileDiffs || generation !== renderGeneration) return;
238 - renderAnnotations();
239 - void buildSearchIndex(fileDiffs, generation);
242 -function renderMeta(review: ReviewPayload) {
243 - const totals = review.files.reduce(
244 - (sum, file) => ({
245 - additions: sum.additions + file.additions,
246 - deletions: sum.deletions + file.deletions,
247 - }),
248 - { additions: 0, deletions: 0 },
249 - );
250 - els.meta.replaceChildren(
251 - metaChip("round", String(review.round)),
252 - metaChip("reviewing", sourceLabel(review.source)),
253 - );
255 - els.summary.replaceChildren();
256 - const stats = document.createElement("span");
257 - stats.className = "summary-stats";
258 - stats.textContent = `${review.files.length} files · +${totals.additions} −${totals.deletions}`;
259 - els.summary.appendChild(stats);
260 - if (review.skippedFiles.length > 0) {
261 - const skipped = document.createElement("span");
262 - skipped.className = "summary-skipped";
263 - skipped.textContent = `skipped ${review.skippedFiles.length} oversized/binary file${review.skippedFiles.length === 1 ? "" : "s"}`;
264 - els.summary.appendChild(skipped);
266 - const hint = document.createElement("span");
267 - hint.className = "summary-hint";
268 - hint.textContent =
269 - "Click a changed line, describe issue, send findings to Pi.";
270 - els.summary.appendChild(hint);
271 - updateFindingCount();
274 -function sourceLabel(source: ReviewPayload["source"]): string {
275 - const scope = source.files?.length
276 - ? ` · ${source.files.length} path${source.files.length === 1 ? "" : "s"}`
277 - : "";
278 - if (source.kind === "working-tree") return `unstaged changes${scope}`;
279 - if (source.kind === "staged") return `staged changes${scope}`;
280 - return `changes vs ${source.base}${scope}`;
283 -function metaChip(label: string, value: string) {
284 - const chip = document.createElement("span");
285 - chip.className = `meta-chip meta-${label}`;
286 - const labelNode = document.createElement("span");
287 - labelNode.className = "meta-label";
288 - labelNode.textContent = label;
289 - const valueNode = document.createElement("span");
290 - valueNode.className = "meta-value";
291 - valueNode.textContent = value;
292 - chip.append(labelNode, valueNode);
293 - return chip;
296 -function renderTree(review: ReviewPayload) {
297 - fileTree?.cleanUp();
298 - const skipped = skippedFilesByPath(review);
299 - const reviewPaths = review.files.flatMap((file) =>
300 - file.prevPath && file.prevPath !== file.path
301 - ? [file.prevPath, file.path]
302 - : [file.path],
303 - );
304 - const paths = [
305 - ...reviewPaths,
306 - ...[...skipped.keys()].filter((path) => !reviewPaths.includes(path)),
307 - ];
308 - fileTree = new (trees().FileTree)({
309 - paths,
310 - search: true,
311 - unsafeCSS: TREE_CSS,
312 - initialExpansion: "open",
313 - initialSelectedPaths:
314 - selectedFile && review.files.some((file) => file.path === selectedFile)
315 - ? [selectedFile]
316 - : [],
317 - gitStatus: [
318 - ...review.files.flatMap((file) => treeGitStatusEntries(file)),
319 - ...[...skipped.keys()].map((path) => ({
320 - path,
321 - status: "ignored" as const,
322 - })),
323 - ] satisfies GitStatusEntry[],
324 - renderRowDecoration: treeRowDecoration(review, skipped),
325 - onSelectionChange: ([path]) => {
326 - const renamedTarget = path
327 - ? renamedTargetForPrevPath(review, path)
328 - : undefined;
329 - if (renamedTarget) {
330 - fileTree?.getItem(path)?.deselect();
331 - fileTree?.getItem(renamedTarget)?.select();
332 - selectFile(renamedTarget, true);
333 - return;
335 - if (path && skipped.has(path)) {
336 - fileTree?.getItem(path)?.deselect();
337 - if (selectedFile) fileTree?.getItem(selectedFile)?.select();
338 - setStatus(`Skipped ${path}: ${skipped.get(path)}`);
339 - return;
341 - selectFile(path, true);
342 - },
343 - });
344 - fileTree.render({ fileTreeContainer: els.tree });
345 - wireTreeSearchClear(fileTree);
348 -function treeGitStatusEntries(
349 - file: ReviewPayload["files"][number],
350 -): GitStatusEntry[] {
351 - if (file.status === "renamed" && file.prevPath && file.prevPath !== file.path)
352 - return [
353 - { path: file.prevPath, status: "deleted" },
354 - { path: file.path, status: "renamed" },
355 - ];
356 - return [{ path: file.path, status: toGitStatus(file.status) }];
359 -function renamedTargetForPrevPath(review: ReviewPayload, path: string) {
360 - return review.files.find(
361 - (file) => file.status === "renamed" && file.prevPath === path,
362 - )?.path;
365 -function treeRowDecoration(
366 - review: ReviewPayload,
367 - skipped: ReadonlyMap<string, string>,
368 -): FileTreeRowDecorationRenderer {
369 - return ({ row }) => {
370 - if (row.kind !== "file") return null;
371 - const reason = skipped.get(row.path);
372 - if (reason) return { text: "skip", title: reason };
373 - const renameSource = review.files.find(
374 - (file) => file.status === "renamed" && file.prevPath === row.path,
375 - );
376 - if (renameSource)
377 - return { text: "from", title: `renamed to ${renameSource.path}` };
378 - const renameTarget = review.files.find(
379 - (file) =>
380 - file.status === "renamed" && file.path === row.path && file.prevPath,
381 - );
382 - if (renameTarget?.prevPath)
383 - return { text: "to", title: `renamed from ${renameTarget.prevPath}` };
384 - return null;
385 - };
388 -function wireTreeSearchClear(tree: FileTree) {
389 - const root = els.tree.shadowRoot;
390 - if (!root) return;
392 - const sync = () => {
393 - const container = root.querySelector<HTMLElement>(
394 - "[data-file-tree-search-container]",
395 - );
396 - const input = root.querySelector<HTMLInputElement>(
397 - "[data-file-tree-search-input]",
398 - );
399 - if (!container || !input || container.querySelector(".tree-search-clear"))
400 - return;
401 - const clear = document.createElement("button");
402 - clear.type = "button";
403 - clear.className = "tree-search-clear";
404 - clear.textContent = "×";
405 - clear.setAttribute("aria-label", "Clear file search");
406 - clear.addEventListener("pointerdown", (event) => event.preventDefault());
407 - clear.addEventListener("click", (event) => {
408 - event.preventDefault();
409 - tree.setSearch("");
410 - input.value = "";
411 - input.focus();
412 - });
413 - container.appendChild(clear);
414 - };
416 - sync();
417 - const observer = new MutationObserver(sync);
418 - observer.observe(root, { childList: true, subtree: true });
419 - const cleanup = tree.cleanUp.bind(tree);
420 - tree.cleanUp = () => {
421 - observer.disconnect();
422 - cleanup();
423 - };
426 -function skippedFilesByPath(review: ReviewPayload): Map<string, string> {
427 - const skipped = new Map<string, string>();
428 - for (const entry of review.skippedFiles) {
429 - const { path, reason } = parseSkippedFile(entry);
430 - skipped.set(path, reason);
432 - return skipped;
435 -function parseSkippedFile(entry: string): { path: string; reason: string } {
436 - const match = /^(.*) \(([^()]*)\)$/.exec(entry);
437 - if (!match) return { path: entry, reason: "oversized/binary" };
438 - return { path: match[1], reason: match[2] };
441 -async function renderDiffs(
442 - review: ReviewPayload,
443 - generation: number,
444 -): Promise<FileDiffMetadata[] | undefined> {
445 - for (const view of diffViews.values()) view.cleanUp();
446 - diffViews.clear();
447 - els.diffs.replaceChildren();
448 - clearSelection(false);
450 - const files = diffs()
451 - .parsePatchFiles(review.diffText, `diff-review-${review.round}`, true)
452 - .flatMap((patch) => patch.files);
453 - for (let index = 0; index < files.length; index++) {
454 - if (generation !== renderGeneration) return undefined;
455 - renderFileDiff(files[index]);
456 - if (files.length > 1)
457 - setStatus(`Rendering ${index + 1}/${files.length} files…`);
458 - await yieldToBrowser();
460 - return files;
463 -function renderFileDiff(fileDiff: FileDiffMetadata) {
464 - const section = fileSection(fileDiff);
465 - const view = new (diffs().FileDiff)<FindingMeta>({
466 - theme: { dark: NUGU_CODE_THEME, light: NUGU_CODE_THEME },
467 - diffStyle: "split",
468 - overflow: "scroll",
469 - enableLineSelection: true,
470 - enableGutterUtility: true,
471 - lineHoverHighlight: "both",
472 - themeType: themeMode,
473 - unsafeCSS: DIFF_FONT_CSS,
474 - onLineSelected: (range) =>
475 - setSelection(fileDiff.name, range, lastDiffPointer),
476 - onGutterUtilityClick: (range) =>
477 - setSelection(fileDiff.name, range, lastDiffPointer),
478 - onLineClick: ({ lineNumber, annotationSide, event }) =>
479 - setSelection(
480 - fileDiff.name,
481 - singleLineRange(lineNumber, annotationSide),
482 - eventPoint(event),
483 - ),
484 - onLineNumberClick: ({ lineNumber, annotationSide, event }) =>
485 - setSelection(
486 - fileDiff.name,
487 - singleLineRange(lineNumber, annotationSide),
488 - eventPoint(event),
489 - ),
490 - renderAnnotation: renderAnnotation,
491 - });
492 - view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
493 - diffViews.set(fileDiff.name, view);
496 -function fileSection(fileDiff: FileDiffMetadata) {
497 - const section = document.createElement("section");
498 - section.className = "file-section";
499 - section.dataset.fileSection = fileDiff.name;
500 - if (fileDiff.name === selectedFile) section.dataset.selectedFile = "true";
502 - const title = document.createElement("h2");
503 - title.className = "file-title";
504 - title.textContent = fileTitle(fileDiff);
505 - section.appendChild(title);
506 - els.diffs.appendChild(section);
507 - return section;
510 -function fileTitle(fileDiff: FileDiffMetadata) {
511 - return fileDiff.prevName && fileDiff.prevName !== fileDiff.name
512 - ? `${fileDiff.prevName} → ${fileDiff.name}`
513 - : fileDiff.name;
516 -function renderAnnotation(annotation: DiffLineAnnotation<FindingMeta>) {
517 - const chip = document.createElement("div");
518 - chip.className = "finding-chip";
519 - chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
520 - return chip;
523 -function setSelection(
524 - file: string,
525 - range: SelectedLineRange | null,
526 - point?: ViewPoint,
527 -) {
528 - const next = normalizeSelection(file, range);
529 - if (!next) {
530 - clearSelection(false);
531 - return;
533 - selected = next;
534 - els.add.disabled = false;
535 - els.selection.className = "selection-active";
536 - els.selection.textContent = selectionLabel(next);
537 - showFindingForm(next, point);
540 -function showFindingForm(selection: ReviewSelection, point?: ViewPoint) {
541 - const anchor = point ?? lineAnchor(selection) ?? centerPoint();
542 - els.inlineFinding.hidden = false;
543 - els.inlineFinding.dataset.open = "true";
544 - positionFindingForm(anchor);
545 - requestAnimationFrame(() => {
546 - positionFindingForm(anchor);
547 - els.comment.focus();
548 - });
551 -function hideFindingForm() {
552 - els.inlineFinding.hidden = true;
553 - delete els.inlineFinding.dataset.open;
556 -function positionFindingForm(point: ViewPoint) {
557 - const margin = 12;
558 - const gap = 14;
559 - const rect = els.inlineFinding.getBoundingClientRect();
560 - const width = rect.width || 360;
561 - const height = rect.height || 280;
562 - let left = point.x + gap;
563 - let top = point.y - 22;
564 - if (left + width + margin > window.innerWidth) left = point.x - width - gap;
565 - left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
566 - top = Math.max(margin, Math.min(top, window.innerHeight - height - margin));
567 - els.inlineFinding.style.left = `${Math.round(left)}px`;
568 - els.inlineFinding.style.top = `${Math.round(top)}px`;
571 -function lineAnchor(selection: ReviewSelection): ViewPoint | undefined {
572 - const section = document.querySelector<HTMLElement>(
573 - `[data-file-section="${cssEscape(selection.file)}"]`,
574 - );
575 - const container = section?.querySelector(
576 - "diffs-container",
577 - ) as HTMLElement | null;
578 - const root = container?.shadowRoot;
579 - const line = root?.querySelector<HTMLElement>(
580 - `[data-${selection.side}] [data-line="${selection.startLine}"]`,
581 - );
582 - if (!line) return undefined;
583 - const rect = line.getBoundingClientRect();
584 - return { x: rect.left + 24, y: rect.top + rect.height / 2 };
587 -function centerPoint(): ViewPoint {
588 - return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
591 -function eventPoint(event: MouseEvent | PointerEvent): ViewPoint {
592 - return { x: event.clientX, y: event.clientY };
595 -function normalizeSelection(
596 - file: string,
597 - range: SelectedLineRange | null,
598 -): ReviewSelection | undefined {
599 - if (!range) return undefined;
600 - const side = range.side;
601 - const endSide = range.endSide ?? side;
602 - if (!isReviewSide(side) || endSide !== side) return undefined;
603 - return {
604 - file,
605 - side,
606 - startLine: Math.min(range.start, range.end),
607 - endLine: Math.max(range.start, range.end),
608 - };
611 -function singleLineRange(
612 - lineNumber: number,
613 - side: SelectedLineRange["side"],
614 -): SelectedLineRange | null {
615 - return side
616 - ? { start: lineNumber, end: lineNumber, side, endSide: side }
617 - : null;
620 -function selectionLabel(selection: ReviewSelection) {
621 - const { file, startLine, endLine, side } = selection;
622 - return `${file}:${startLine}${startLine === endLine ? "" : `-${endLine}`} ${side}`;
625 -function wireActions() {
626 - els.themeMode.addEventListener("change", updateThemeMode);
627 - els.severity.addEventListener("change", () => {
628 - els.severitySub.textContent = SEVERITY_SUBS[els.severity.value] ?? "";
629 - });
630 - els.category.addEventListener("change", () => {
631 - els.categorySub.textContent = CATEGORY_SUBS[els.category.value] ?? "";
632 - });
633 - els.add.addEventListener("click", addFinding);
634 - els.submit.addEventListener("click", submitReview);
635 - els.cancel.addEventListener("click", cancelReview);
636 - els.toggleLeft.addEventListener("click", () => togglePane("left"));
637 - els.toggleRight.addEventListener("click", () => togglePane("right"));
638 - els.leftSplitter.addEventListener("pointerdown", (event) =>
639 - startPaneResize("left", event),
640 - );
641 - els.rightSplitter.addEventListener("pointerdown", (event) =>
642 - startPaneResize("right", event),
643 - );
644 - els.diffs.addEventListener(
645 - "pointerdown",
646 - (event) => {
647 - lastDiffPointer = eventPoint(event);
648 - },
649 - true,
650 - );
651 - els.diffs.addEventListener(
652 - "pointerup",
653 - (event) => {
654 - lastDiffPointer = eventPoint(event);
655 - },
656 - true,
657 - );
658 - els.inlineCancel.addEventListener("click", () => {
659 - clearFindingForm();
660 - clearSelection(true);
661 - });
662 - els.comment.addEventListener("keydown", (event) => {
663 - if ((event.metaKey || event.ctrlKey) && event.key === "Enter")
664 - void addFinding();
665 - if (event.key === "Escape") clearSelection(true);
666 - });
667 - els.notes.addEventListener("input", () => scheduleNotesAutoGrow());
668 - scheduleNotesAutoGrow();
669 - els.search.addEventListener("input", () => {
670 - window.clearTimeout(searchDebounce);
671 - searchDebounce = window.setTimeout(runSearch, 120);
672 - });
673 - els.searchClear.addEventListener("click", () => clearCodeSearch(true));
674 - els.search.addEventListener("search", () => {
675 - if (!els.search.value.trim()) clearCodeSearch(false);
676 - });
677 - els.search.addEventListener("keydown", (event) => {
678 - if (isEscapeKey(event)) {
679 - event.preventDefault();
680 - event.stopPropagation();
681 - closeCodeSearchPopup();
682 - return;
684 - if (event.key === "ArrowDown" || event.key === "ArrowUp") {
685 - event.preventDefault();
686 - navigateSearch(event.key === "ArrowDown" ? 1 : -1);
687 - return;
689 - if (event.key === "Enter") {
690 - event.preventDefault();
691 - if (searchResults.length === 0) return;
692 - const idx = searchActiveIndex >= 0 ? searchActiveIndex : 0;
693 - jumpToMatch(searchResults[idx], idx);
694 - hideSearch();
696 - });
697 - document.addEventListener(
698 - "keydown",
699 - (event) => {
700 - if (!isEscapeKey(event) || els.searchResults.hidden) return;
701 - event.preventDefault();
702 - event.stopPropagation();
703 - closeCodeSearchPopup();
704 - },
705 - true,
706 - );
707 - document.addEventListener("click", (event) => {
708 - if (
709 - !els.searchResults.contains(event.target as Node) &&
710 - event.target !== els.search
712 - hideSearch();
713 - });
716 -function scheduleNotesAutoGrow() {
717 - if (notesGrowFrame !== undefined) return;
718 - notesGrowFrame = requestAnimationFrame(() => {
719 - notesGrowFrame = undefined;
720 - autoGrowTextarea(els.notes);
721 - });
724 -function autoGrowTextarea(textarea: HTMLTextAreaElement) {
725 - textarea.style.height = "auto";
726 - textarea.style.height = `${textarea.scrollHeight}px`;
729 -function yieldToBrowser() {
730 - return new Promise<void>((resolve) => {
731 - const requestIdle = window.requestIdleCallback as
732 - | ((callback: () => void, options?: { timeout: number }) => number)
733 - | undefined;
734 - if (requestIdle) requestIdle(() => resolve(), { timeout: 80 });
735 - else requestAnimationFrame(() => resolve());
736 - });
739 -function updateThemeMode() {
740 - themeMode = themeModeFromValue(els.themeMode.value);
741 - localStorage.setItem(THEME_STORAGE_KEY, themeMode);
742 - applyThemeMode(themeMode);
743 - for (const view of diffViews.values()) view.setThemeType(themeMode);
746 -function togglePane(side: PaneSide) {
747 - const layout = readLayout();
748 - if (side === "left") layout.leftCollapsed = !layout.leftCollapsed;
749 - else layout.rightCollapsed = !layout.rightCollapsed;
750 - applyLayout(layout);
751 - writeLayout(layout);
754 -function startPaneResize(side: PaneSide, event: PointerEvent) {
755 - if ((event.target as HTMLElement).closest("button")) return;
756 - event.preventDefault();
757 - const layout = readLayout();
758 - if (side === "left") layout.leftCollapsed = false;
759 - else layout.rightCollapsed = false;
760 - els.app.dataset.resizing = side;
761 - try {
762 - els.app.setPointerCapture?.(event.pointerId);
763 - } catch {}
765 - const move = (moveEvent: PointerEvent) => {
766 - const next = { ...layout };
767 - if (side === "left") next.left = clampPane("left", moveEvent.clientX);
768 - else next.right = clampPane("right", window.innerWidth - moveEvent.clientX);
769 - applyLayout(next);
770 - writeLayout(next);
771 - };
772 - const stop = () => {
773 - delete els.app.dataset.resizing;
774 - window.removeEventListener("pointermove", move);
775 - window.removeEventListener("pointerup", stop);
776 - window.removeEventListener("pointercancel", stop);
777 - };
779 - window.addEventListener("pointermove", move);
780 - window.addEventListener("pointerup", stop, { once: true });
781 - window.addEventListener("pointercancel", stop, { once: true });
784 -function readLayout(): LayoutState {
785 - const stored = localStorage.getItem(LAYOUT_STORAGE_KEY);
786 - if (!stored) return defaultLayout();
787 - try {
788 - const value = JSON.parse(stored) as Partial<LayoutState>;
789 - return {
790 - left: clampPane("left", value.left),
791 - right: clampPane("right", value.right),
792 - leftCollapsed: value.leftCollapsed === true,
793 - rightCollapsed: value.rightCollapsed === true,
794 - };
795 - } catch {
796 - return defaultLayout();
800 -function writeLayout(layout: LayoutState) {
801 - localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(layout));
804 -function defaultLayout(): LayoutState {
805 - return {
806 - left: PANE_LIMITS.left.fallback,
807 - right: PANE_LIMITS.right.fallback,
808 - leftCollapsed: false,
809 - rightCollapsed: false,
810 - };
813 -function applyLayout(layout: LayoutState) {
814 - els.app.style.setProperty(
815 - "--left-pane",
816 - `${layout.leftCollapsed ? 0 : layout.left}px`,
817 - );
818 - els.app.style.setProperty(
819 - "--right-pane",
820 - `${layout.rightCollapsed ? 0 : layout.right}px`,
821 - );
822 - els.app.dataset.leftCollapsed = String(layout.leftCollapsed);
823 - els.app.dataset.rightCollapsed = String(layout.rightCollapsed);
824 - els.toggleLeft.textContent = layout.leftCollapsed ? "›" : "‹";
825 - els.toggleRight.textContent = layout.rightCollapsed ? "‹" : "›";
826 - els.toggleLeft.setAttribute(
827 - "aria-label",
828 - layout.leftCollapsed ? "Expand file tree" : "Collapse file tree",
829 - );
830 - els.toggleRight.setAttribute(
831 - "aria-label",
832 - layout.rightCollapsed ? "Expand review panel" : "Collapse review panel",
833 - );
836 -function clampPane(side: PaneSide, value: unknown) {
837 - const limits = PANE_LIMITS[side];
838 - const width =
839 - typeof value === "number" && Number.isFinite(value)
840 - ? value
841 - : limits.fallback;
842 - return Math.min(limits.max, Math.max(limits.min, Math.round(width)));
845 -async function addFinding() {
846 - const draft = draftFromSelection();
847 - if (!draft) return;
848 - els.add.disabled = true;
849 - try {
850 - await api(ROUTES.validateFinding, postJson(draft));
851 - findings.push(draft);
852 - clearFindingForm();
853 - clearSelection(true);
854 - renderFindings();
855 - renderAnnotations();
856 - setStatus("Finding added");
857 - } catch (err) {
858 - setStatus(errorMessage(err), "error");
859 - } finally {
860 - els.add.disabled = !selected;
864 -function draftFromSelection(): FindingDraft | undefined {
865 - if (!selected) return undefined;
866 - const comment = els.comment.value.trim();
867 - if (!comment) {
868 - setStatus("Comment required", "error");
869 - return undefined;
871 - return {
872 - ...selected,
873 - category: categoryFromValue(els.category.value),
874 - severity: severityFromValue(els.severity.value),
875 - comment,
876 - };
879 -async function submitReview() {
880 - if (
881 - findings.length === 0 &&
882 - !els.notes.value.trim() &&
883 - !confirm("Send empty review to Pi?")
885 - return;
886 - setDoneButtonsDisabled(true);
887 - try {
888 - await api(ROUTES.submit, postJson({ notes: els.notes.value, findings }));
889 - findings.splice(0);
890 - els.notes.value = "";
891 - renderFindings();
892 - renderAnnotations();
893 - setStatus("Sent to Pi — keep reviewing or close tab to end", "ok");
894 - } catch (err) {
895 - setStatus(errorMessage(err), "error");
896 - } finally {
897 - setDoneButtonsDisabled(false);
901 -async function cancelReview() {
902 - closing = true;
903 - setDoneButtonsDisabled(true);
904 - await api(ROUTES.cancel, postJson({})).catch(() => undefined);
905 - cleanup();
906 - setStatus("Closed — return to Pi");
909 -function setDoneButtonsDisabled(disabled: boolean) {
910 - els.submit.disabled = disabled;
911 - els.cancel.disabled = disabled;
914 -function clearFindingForm() {
915 - els.comment.value = "";
918 -function clearSelection(clearViews: boolean) {
919 - selected = undefined;
920 - els.add.disabled = true;
921 - els.selection.className = "selection-empty";
922 - els.selection.textContent = "Click an added or deleted line.";
923 - hideFindingForm();
924 - if (clearViews)
925 - for (const view of diffViews.values()) view.setSelectedLines(null);
928 -function renderFindings() {
929 - els.findings.replaceChildren();
930 - els.findings.className = findings.length === 0 ? "empty-list" : "";
931 - if (findings.length === 0) {
932 - els.findings.textContent = "No findings yet.";
933 - updateFindingCount();
934 - return;
936 - findings.forEach((finding, index) =>
937 - els.findings.appendChild(findingItem(finding, index)),
938 - );
939 - updateFindingCount();
942 -function findingItem(finding: FindingDraft, index: number) {
943 - const item = document.createElement("div");
944 - item.className = `finding-item severity-${finding.severity}`;
945 - item.tabIndex = 0;
946 - item.addEventListener("click", () => selectFile(finding.file, true));
947 - item.addEventListener("keydown", (event) => {
948 - if (event.key === "Enter") selectFile(finding.file, true);
949 - });
951 - const head = document.createElement("div");
952 - head.className = "finding-item-head";
954 - const number = document.createElement("span");
955 - number.className = "finding-number";
956 - number.textContent = String(index + 1);
958 - const severity = document.createElement("span");
959 - severity.className = `finding-pill ${finding.severity}`;
960 - severity.textContent = finding.severity;
962 - const category = document.createElement("span");
963 - category.className = "finding-pill category";
964 - category.textContent = finding.category;
966 - const remove = document.createElement("button");
967 - remove.className = "remove-finding";
968 - remove.type = "button";
969 - remove.textContent = "×";
970 - remove.title = "Remove finding";
971 - remove.addEventListener("click", (event) => {
972 - event.stopPropagation();
973 - removeFinding(index);
974 - });
976 - const location = document.createElement("div");
977 - location.className = "finding-location";
978 - location.textContent = selectionLabel(finding);
980 - const text = document.createElement("div");
981 - text.className = "finding-comment";
982 - text.textContent = finding.comment;
984 - head.append(number, severity, category, remove);
985 - item.append(head, location, text);
986 - return item;
989 -function removeFinding(index: number) {
990 - findings.splice(index, 1);
991 - renderFindings();
992 - renderAnnotations();
995 -function updateFindingCount() {
996 - els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
997 - els.drawerCount.textContent = String(findings.length);
1000 -function renderAnnotations() {
1001 - for (const [file, view] of diffViews) {
1002 - view.setLineAnnotations(annotationsFor(file));
1003 - view.rerender();
1007 -async function buildSearchIndex(
1008 - fileDiffs: FileDiffMetadata[],
1009 - generation: number,
1010 -) {
1011 - searchIndexing = true;
1012 - searchIndex = [];
1013 - const restoreStatus =
1014 - els.status.textContent === "Ready" ? "Ready" : undefined;
1015 - const entries: SearchEntry[] = [];
1016 - for (let index = 0; index < fileDiffs.length; index++) {
1017 - if (generation !== renderGeneration) {
1018 - searchIndexing = false;
1019 - return;
1021 - entries.push(...searchEntriesForFile(fileDiffs[index]));
1022 - if (fileDiffs.length > 1)
1023 - setStatus(`Indexing search ${index + 1}/${fileDiffs.length} files…`);
1024 - await yieldToBrowser();
1026 - if (generation !== renderGeneration) {
1027 - searchIndexing = false;
1028 - return;
1030 - searchIndex = entries;
1031 - searchIndexing = false;
1032 - if (els.search.value.trim()) runSearch();
1033 - if (restoreStatus && els.status.textContent.startsWith("Indexing search"))
1034 - setStatus(restoreStatus);
1037 -function searchEntriesForFile(fileDiff: FileDiffMetadata): SearchEntry[] {
1038 - const entries: SearchEntry[] = [];
1039 - for (const hunk of fileDiff.hunks) {
1040 - let additionLine = hunk.additionStart;
1041 - let deletionLine = hunk.deletionStart;
1042 - for (const content of hunk.hunkContent) {
1043 - if (content.type === "context") {
1044 - for (let i = 0; i < content.lines; i++) {
1045 - const text = fileDiff.additionLines[content.additionLineIndex + i];
1046 - if (text !== undefined)
1047 - entries.push({
1048 - file: fileDiff.name,
1049 - side: "additions",
1050 - line: additionLine + i,
1051 - text,
1052 - });
1054 - additionLine += content.lines;
1055 - deletionLine += content.lines;
1056 - } else {
1057 - for (let i = 0; i < content.deletions; i++) {
1058 - const text = fileDiff.deletionLines[content.deletionLineIndex + i];
1059 - if (text !== undefined)
1060 - entries.push({
1061 - file: fileDiff.name,
1062 - side: "deletions",
1063 - line: deletionLine + i,
1064 - text,
1065 - });
1067 - for (let i = 0; i < content.additions; i++) {
1068 - const text = fileDiff.additionLines[content.additionLineIndex + i];
1069 - if (text !== undefined)
1070 - entries.push({
1071 - file: fileDiff.name,
1072 - side: "additions",
1073 - line: additionLine + i,
1074 - text,
1075 - });
1077 - deletionLine += content.deletions;
1078 - additionLine += content.additions;
1082 - return entries;
1085 -function runSearch() {
1086 - const query = els.search.value.trim();
1087 - if (!query) {
1088 - searchResults = [];
1089 - searchActiveIndex = -1;
1090 - hideSearch();
1091 - return;
1093 - if (searchIndexing) {
1094 - els.searchResults.hidden = false;
1095 - els.searchResults.replaceChildren();
1096 - const empty = document.createElement("div");
1097 - empty.className = "search-empty";
1098 - empty.textContent = "Indexing search…";
1099 - els.searchResults.appendChild(empty);
1100 - return;
1102 - searchResults = searchCode(query);
1103 - searchActiveIndex = -1;
1104 - if (searchResults.length === 0) {
1105 - els.searchResults.hidden = false;
1106 - els.searchResults.replaceChildren();
1107 - const empty = document.createElement("div");
1108 - empty.className = "search-empty";
1109 - empty.textContent = "No matches.";
1110 - els.searchResults.appendChild(empty);
1111 - updateSearchBadge();
1112 - return;
1114 - renderSearchResults();
1115 - updateSearchBadge();
1118 -function renderSearchResults() {
1119 - els.searchResults.hidden = false;
1120 - els.searchResults.replaceChildren();
1121 - const max = Math.min(searchResults.length, 200);
1122 - for (let i = 0; i < max; i++)
1123 - els.searchResults.appendChild(searchResultItem(searchResults[i], i));
1124 - if (searchResults.length > max) {
1125 - const more = document.createElement("div");
1126 - more.className = "search-more";
1127 - more.textContent = `${searchResults.length - max} more matches`;
1128 - els.searchResults.appendChild(more);
1132 -function navigateSearch(delta: 1 | -1) {
1133 - if (searchResults.length === 0) return;
1134 - searchActiveIndex =
1135 - searchActiveIndex < 0
1136 - ? 0
1137 - : Math.max(
1138 - 0,
1139 - Math.min(searchResults.length - 1, searchActiveIndex + delta),
1140 - );
1141 - const items =
1142 - els.searchResults.querySelectorAll<HTMLElement>(".search-result");
1143 - items.forEach((el, i) =>
1144 - el.classList.toggle("search-result-active", i === searchActiveIndex),
1145 - );
1146 - const active = items[searchActiveIndex];
1147 - active?.scrollIntoView({ block: "nearest" });
1148 - jumpToMatch(searchResults[searchActiveIndex], searchActiveIndex);
1149 - updateSearchBadge();
1152 -function updateSearchBadge() {
1153 - const badge = document.querySelector<HTMLElement>("#search-badge");
1154 - if (!badge) return;
1155 - if (searchResults.length === 0) {
1156 - badge.hidden = true;
1157 - return;
1159 - badge.hidden = false;
1160 - badge.textContent =
1161 - searchActiveIndex >= 0
1162 - ? `${searchActiveIndex + 1}/${searchResults.length}`
1163 - : `${searchResults.length}`;
1166 -function searchCode(query: string): SearchMatch[] {
1167 - const hits: SearchMatch[] = [];
1168 - const isRegex = query.startsWith("/") && query.endsWith("/");
1169 - const pattern = isRegex
1170 - ? query.slice(1, -1)
1171 - : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1172 - let re: RegExp;
1173 - try {
1174 - re = new RegExp(pattern, "i");
1175 - } catch {
1176 - return hits;
1178 - for (const entry of searchIndex) {
1179 - const m = re.exec(entry.text);
1180 - if (m && m.index >= 0) {
1181 - hits.push({
1182 - ...entry,
1183 - matchStart: m.index,
1184 - matchEnd: m.index + m[0].length,
1185 - });
1186 - if (hits.length >= 500) break;
1189 - return hits;
1192 -function searchResultItem(match: SearchMatch, index: number) {
1193 - const item = document.createElement("div");
1194 - item.className = "search-result";
1195 - item.tabIndex = -1;
1196 - item.addEventListener("click", () => {
1197 - searchActiveIndex = index;
1198 - jumpToMatch(match, index);
1199 - renderSearchResults();
1200 - updateSearchBadge();
1201 - });
1203 - const file = document.createElement("span");
1204 - file.className = "search-result-file";
1205 - file.textContent = match.file;
1207 - const loc = document.createElement("span");
1208 - loc.className = "search-result-loc";
1209 - loc.textContent = `:${match.line} ${match.side === "additions" ? "+" : "-"}`;
1211 - const preview = document.createElement("div");
1212 - preview.className = "search-result-preview";
1213 - const before = match.text.slice(
1214 - Math.max(0, match.matchStart - 20),
1215 - match.matchStart,
1216 - );
1217 - const matched = match.text.slice(match.matchStart, match.matchEnd);
1218 - const after = match.text.slice(match.matchEnd, match.matchEnd + 40);
1219 - preview.textContent = before;
1220 - const mark = document.createElement("mark");
1221 - mark.textContent = matched;
1222 - preview.appendChild(mark);
1223 - preview.append(after);
1225 - item.append(file, loc, preview);
1226 - return item;
1229 -function jumpToMatch(match: SearchMatch, _index: number) {
1230 - selectFile(match.file, false);
1231 - requestAnimationFrame(() => {
1232 - const section = document.querySelector<HTMLElement>(
1233 - `[data-file-section="${cssEscape(match.file)}"]`,
1234 - );
1235 - const container = section?.querySelector(
1236 - "diffs-container",
1237 - ) as HTMLElement | null;
1238 - const root = container?.shadowRoot;
1239 - const sideRoot = root?.querySelector<HTMLElement>(
1240 - match.side === "additions" ? "[data-additions]" : "[data-deletions]",
1241 - );
1242 - const line = sideRoot?.querySelector<HTMLElement>(
1243 - `[data-line="${match.line}"]`,
1244 - );
1245 - if (line) {
1246 - const lineIndex = line.getAttribute("data-line-index");
1247 - const gutter = lineIndex
1248 - ? sideRoot?.querySelector<HTMLElement>(
1249 - `[data-column-number][data-line-index="${cssEscape(lineIndex)}"]`,
1251 - : sideRoot?.querySelector<HTMLElement>(
1252 - `[data-column-number="${match.line}"]`,
1253 - );
1254 - scrollDiffLineIntoView(line);
1255 - flashSearchHighlight([line, gutter]);
1257 - });
1260 -function scrollDiffLineIntoView(line: HTMLElement) {
1261 - const scroller = els.diffs;
1262 - const lineRect = line.getBoundingClientRect();
1263 - const scrollerRect = scroller.getBoundingClientRect();
1264 - const nextTop =
1265 - scroller.scrollTop +
1266 - lineRect.top -
1267 - scrollerRect.top -
1268 - scrollerRect.height / 2 +
1269 - lineRect.height / 2;
1270 - scroller.scrollTo({ top: Math.max(0, nextTop), behavior: "smooth" });
1273 -function flashSearchHighlight(elements: Array<HTMLElement | undefined | null>) {
1274 - const targets = elements.filter((element): element is HTMLElement =>
1275 - Boolean(element),
1276 - );
1277 - for (const target of targets) target.classList.remove("search-highlight");
1278 - if (targets[0]) void targets[0].offsetWidth;
1279 - for (const target of targets) target.classList.add("search-highlight");
1282 -function isEscapeKey(event: KeyboardEvent) {
1283 - return event.key === "Escape" || event.key === "Esc";
1286 -function cancelPendingSearch() {
1287 - window.clearTimeout(searchDebounce);
1288 - searchDebounce = undefined;
1291 -function closeCodeSearchPopup() {
1292 - cancelPendingSearch();
1293 - searchActiveIndex = -1;
1294 - hideSearch();
1297 -function clearCodeSearch(refocus: boolean) {
1298 - cancelPendingSearch();
1299 - els.search.value = "";
1300 - searchResults = [];
1301 - searchActiveIndex = -1;
1302 - hideSearch();
1303 - updateSearchBadge();
1304 - if (refocus) els.search.focus();
1307 -function hideSearch() {
1308 - els.searchResults.hidden = true;
1309 - updateSearchBadge();
1312 -function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
1313 - return findings
1314 - .filter((finding) => finding.file === file)
1315 - .map((finding, index) => ({
1316 - side: finding.side,
1317 - lineNumber: finding.startLine,
1318 - metadata: {
1319 - findingId: String(index),
1320 - severity: finding.severity,
1321 - category: finding.category,
1322 - comment: finding.comment,
1323 - },
1324 - }));
1327 -async function api<T = unknown>(
1328 - path: string,
1329 - init: RequestInit = {},
1330 -): Promise<T> {
1331 - const res = await fetch(path, {
1332 - ...init,
1333 - headers: {
1334 - Authorization: `Bearer ${token}`,
1335 - "Content-Type": "application/json",
1336 - ...(init.headers ?? {}),
1337 - },
1338 - });
1339 - const body = await res.text();
1340 - const data = body ? JSON.parse(body) : undefined;
1341 - if (!res.ok)
1342 - throw new Error(errorPayload(data) ?? `${res.status} ${res.statusText}`);
1343 - return data as T;
1346 -function postJson(body: unknown): RequestInit {
1347 - return { method: "POST", body: JSON.stringify(body) };
1350 -function errorPayload(value: unknown) {
1351 - return value &&
1352 - typeof value === "object" &&
1353 - "error" in value &&
1354 - typeof value.error === "string"
1355 - ? value.error
1356 - : undefined;
1359 -function startHeartbeat() {
1360 - heartbeat = window.setInterval(
1361 - () => api(ROUTES.heartbeat, postJson({})).catch(() => undefined),
1362 - HEARTBEAT_INTERVAL_MS,
1363 - );
1366 -function startReviewPolling() {
1367 - reviewPoll = window.setInterval(refreshReview, REVIEW_POLL_INTERVAL_MS);
1370 -async function refreshReview() {
1371 - try {
1372 - const review = await api<ReviewPayload>(ROUTES.review);
1373 - const nextHash = hashReview(review);
1374 - if (nextHash === reviewHash) return;
1375 - await renderReview(review);
1376 - setStatus("Diff updated", "ok");
1377 - } catch (err) {
1378 - setDisconnectedStatus(err);
1382 -function hashReview(review: ReviewPayload) {
1383 - return `${review.diffText}\0${review.skippedFiles.join("\0")}`;
1386 -function stopHeartbeat() {
1387 - if (heartbeat !== undefined) window.clearInterval(heartbeat);
1388 - heartbeat = undefined;
1391 -function stopReviewPolling() {
1392 - if (reviewPoll !== undefined) window.clearInterval(reviewPoll);
1393 - reviewPoll = undefined;
1396 -function cleanup() {
1397 - stopHeartbeat();
1398 - stopReviewPolling();
1399 - fileTree?.cleanUp();
1400 - for (const view of diffViews.values()) view.cleanUp();
1403 -function closeFromBrowser() {
1404 - if (closing) return;
1405 - closing = true;
1406 - navigator.sendBeacon?.(
1407 - ROUTES.cancel,
1408 - new Blob(["{}"], { type: "application/json" }),
1409 - );
1410 - cleanup();
1413 -function setStatus(text: string, tone: "neutral" | "error" | "ok" = "neutral") {
1414 - els.status.textContent = text;
1415 - els.status.className = tone === "neutral" ? "" : tone;
1418 -function setDisconnectedStatus(err: unknown) {
1419 - const message = errorMessage(err);
1420 - const disconnected =
1421 - /networkerror|failed to fetch|load failed|fetch resource/i.test(message);
1422 - setStatus(
1423 - disconnected ? "Disconnected. Run /diff-review, then refresh." : message,
1424 - "error",
1425 - );
1428 -function readThemeMode(): ThemeMode {
1429 - return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
1432 -function applyThemeMode(mode: ThemeMode) {
1433 - document.documentElement.dataset.theme =
1434 - mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
1435 - document.documentElement.dataset.themeMode = mode;
1436 - const icon = document.querySelector<HTMLElement>(".theme-icon");
1437 - if (icon)
1438 - icon.textContent = mode === "dark" ? "☾" : mode === "light" ? "☼" : "◐";
1441 -function selectFile(path: string | undefined, scroll: boolean) {
1442 - selectedFile = path;
1443 - applySelectedFileEmphasis();
1444 - if (scroll) scrollToFile(path);
1447 -function applySelectedFileEmphasis() {
1448 - for (const section of els.diffs.querySelectorAll<HTMLElement>(
1449 - "[data-file-section]",
1450 - )) {
1451 - const active = section.dataset.fileSection === selectedFile;
1452 - if (active) section.dataset.selectedFile = "true";
1453 - else delete section.dataset.selectedFile;
1457 -function scrollToFile(path: string | undefined) {
1458 - if (!path) return;
1459 - const section = document.querySelector<HTMLElement>(
1460 - `[data-file-section="${cssEscape(path)}"]`,
1461 - );
1462 - if (!section) return;
1463 - const scroller = els.diffs;
1464 - const top =
1465 - section.getBoundingClientRect().top -
1466 - scroller.getBoundingClientRect().top +
1467 - scroller.scrollTop;
1468 - scroller.scrollTo({ top: Math.max(0, top - 2), behavior: "smooth" });
1471 -function toGitStatus(
1472 - status: ReviewPayload["files"][number]["status"],
1473 -): GitStatusEntry["status"] {
1474 - if (status === "added" || status === "deleted" || status === "renamed")
1475 - return status;
1476 - return "modified";
1479 -function themeModeFromValue(value: unknown): ThemeMode {
1480 - return isOneOf(value, THEME_MODES) ? value : "system";
1483 -function categoryFromValue(value: unknown): ReviewCategory {
1484 - if (isOneOf(value, REVIEW_CATEGORIES)) return value;
1485 - throw new Error(`Invalid category: ${String(value)}`);
1488 -function severityFromValue(value: unknown): ReviewSeverity {
1489 - if (isOneOf(value, REVIEW_SEVERITIES)) return value;
1490 - throw new Error(`Invalid severity: ${String(value)}`);
1493 -function isReviewSide(value: unknown): value is ReviewSide {
1494 - return value === "additions" || value === "deletions";
1497 -function isOneOf<T extends string>(
1498 - value: unknown,
1499 - choices: readonly T[],
1500 -): value is T {
1501 - return typeof value === "string" && choices.includes(value as T);
1504 -function must(id: keyof Elements | string) {
1505 - const el = document.getElementById(id);
1506 - if (!el) throw new Error(`Missing #${id}`);
1507 - return el;
1510 -function mustButton(id: string) {
1511 - return must(id) as HTMLButtonElement;
1513 -function mustSelect(id: string) {
1514 - return must(id) as HTMLSelectElement;
1516 -function mustText(id: string) {
1517 - return must(id) as HTMLTextAreaElement;
1520 -function cssEscape(value: string) {
1521 - return CSS.escape(value);
1524 -function errorMessage(err: unknown) {
1525 - return err instanceof Error ? err.message : String(err);