Open History to see the last commit
1import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
2import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
3import type {
4 EnvironmentId,
5 PullRequestDetailView,
6 PullRequestDiffSide,
7 PullRequestOmittedFileStat,
8 PullRequestRef,
9 PullRequestReviewPosition,
10 PullRequestReviewThread,
11 PullRequestThreadCommentsResult,
12} from "@t3tools/contracts";
13import {
14 ChevronDownIcon,
15 ChevronRightIcon,
16 ChevronsDownUpIcon,
17 ChevronsUpDownIcon,
18 Columns2Icon,
19 FolderTreeIcon,
20 MessageSquareIcon,
21 MessageSquareOffIcon,
22 Rows3Icon,
23 TextWrapIcon,
24 TriangleAlertIcon,
25 XIcon,
26} from "lucide-react";
27import { useAtomRefresh } from "@effect/atom-react";
28import * as Schema from "effect/Schema";
29import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
30
31import { useLocalStorage } from "~/hooks/useLocalStorage";
32import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
33import { useTheme } from "~/hooks/useTheme";
34import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
35import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
36import { canEditPullRequestComment } from "./pullRequestEditing.logic";
37import { orderDiffFiles } from "./pullRequestFileOrder.logic";
38import {
39 buildFileDiffRenderKey,
40 fnv1a32,
41 getRenderablePatch,
42 resolveDiffThemeName,
43 resolveFileDiffPath,
44 resolveFileDiffPreviousPath,
45 type RenderablePatch,
46} from "~/lib/diffRendering";
47import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
48import { cn } from "~/lib/utils";
49import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";
50import {
51 buildDiffReviewComment,
52 resolveDiffReviewPosition,
53 type ReviewCommentContext,
54} from "~/reviewCommentContext";
55import { pullRequestEnvironment } from "~/state/pullRequests";
56import { useEnvironmentQuery } from "~/state/query";
57import { useAtomCommand } from "~/state/use-atom-command";
58
59import { DiffPanelLoadingState } from "../DiffPanelShell";
60import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
61import { DiffFileTree } from "../diffs/DiffFileTree";
62import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";
63import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";
64import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";
65import { Button } from "../ui/button";
66import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
67import {
68 DropdownMenu,
69 DropdownMenuContent,
70 DropdownMenuItem,
71 DropdownMenuTrigger,
72} from "../ui/menu";
73import { toastManager } from "../ui/toast";
74import { Toggle, ToggleGroup } from "../ui/toggle-group";
75import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
76import { PendingReviewCommentCard, ReviewThreadCard } from "./PullRequestReviewAnnotation";
77import { PullRequestReviewBar } from "./PullRequestReviewBar";
78import {
79 isFileDiffCollapsed,
80 isLineInFileDiff,
81 type DiffFoldOverride,
82} from "./pullRequestDiff.logic";
83import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
84import {
85 nextPendingReviewCommentId,
86 pullRequestReviewKey,
87 usePendingReviewComments,
88 usePullRequestReviewStore,
89 type PendingReviewComment,
90} from "./pullRequestReviewStore";
91
92/** Everything pinned to one line of one file: what is already there, and what is being added. */
93interface ReviewAnnotationGroup {
94 readonly threads: ReadonlyArray<PullRequestReviewThread>;
95 readonly pending: ReadonlyArray<PendingReviewComment>;
96 readonly draft: boolean;
97}
98
99type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;
100
101/** Commits per press of "Show more" in the scope menu. */
102const COMMIT_PAGE_SIZE = 10;
103
104const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";
105
106/** One answer from the host: a whole number of files, and where the next one carries on. */
107interface DiffSlice {
108 /** What was asked for, null being the first slice. Identifies the slice among the loaded ones. */
109 readonly cursor: string | null;
110 readonly patch: string;
111 readonly truncated: boolean;
112 readonly nextCursor: string | null;
113 readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
114}
115
116/**
117 * The viewer's own per-file counts are hidden and drawn from this side of its shadow root
118 * instead: its counts are hunk sums, and a file whose hunks the host withheld would read as
119 * an empty change rather than as the counts the host did report.
120 */
121const REPLACE_FILE_COUNTS_CSS = `
122[data-diffs-header] [data-additions-count],
123[data-diffs-header] [data-deletions-count] {
124 display: none !important;
125}`;
126
127/** Nothing loaded yet, as one identity, so the memos below do not see a new array every render. */
128const NO_SLICES: ReadonlyArray<DiffSlice> = [];
129
130/** A group while it is still gathering what belongs on its line. */
131interface MutableAnnotationGroup {
132 readonly side: PullRequestDiffSide;
133 readonly line: number;
134 readonly threads: PullRequestReviewThread[];
135 readonly pending: PendingReviewComment[];
136 draft: boolean;
137}
138
139interface DraftAnchor {
140 readonly fileKey: string;
141 readonly path: string;
142 /** What the file was called before the change, for the hosts that resolve a position by both. */
143 readonly oldPath: string | null;
144 readonly position: PullRequestReviewPosition;
145 /** The whole selection, which the comment collapses to one line but a question keeps. */
146 readonly range: SelectedLineRange;
147}
148
149/** A range of the diff and the reader's request for the agent. */
150export interface PullRequestAgentSelectionInput {
151 /** The marked lines, already in the shape the composer draws and the agent reads. */
152 readonly comment: ReviewCommentContext;
153 readonly request: string;
154}
155
156/** The contract's sides named the way the diff viewer names them, and back again. */
157function toViewerSide(side: PullRequestDiffSide) {
158 return side === "left" ? ("deletions" as const) : ("additions" as const);
159}
160
161function getReviewPositionAnchor(position: PullRequestReviewPosition): {
162 line: number;
163 side: PullRequestDiffSide;
164} {
165 switch (position.kind) {
166 case "added":
167 return { line: position.newLine, side: "right" };
168 case "deleted":
169 return { line: position.oldLine, side: "left" };
170 case "context":
171 return {
172 line: position.side === "left" ? position.oldLine : position.newLine,
173 side: position.side,
174 };
175 }
176}
177
178/**
179 * Whether the viewer draws this line at all. A line counts the new file on the right and the old
180 * one on the left, and each hunk covers one run of each; a line outside every run — a
181 * conversation the host could not mark outdated, or one under a hunk it withheld — has no row to
182 * be pinned to, however much its file looks like a match.
183 */
184/**
185 * The pull request's patch, with the review written against it. Conversations already on the
186 * host sit under the line they were written on, and a new comment joins the review being
187 * drafted rather than being posted as it is typed.
188 */
189function PullRequestCodeTab({
190 environmentId,
191 reference,
192 detail,
193 selectedCommitOid,
194 onSelectedCommitChange,
195 pendingFinding,
196 fixFindingLabel = "Fix in a thread",
197 onFixFinding,
198 onAddToAgentSelection,
199 onRefresh,
200 refreshToken = 0,
201}: {
202 environmentId: EnvironmentId;
203 reference: PullRequestRef;
204 detail: PullRequestDetailView;
205 /** Commit whose diff is open. Null keeps the whole pull-request diff selected. */
206 selectedCommitOid: string | null;
207 onSelectedCommitChange: (oid: string | null) => void;
208 /** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
209 pendingFinding?: string | null;
210 fixFindingLabel?: string;
211 onFixFinding?: (finding: PullRequestFinding) => void;
212 /** Absent where there is no active agent composer to receive a local comment. */
213 onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
214 onRefresh: () => void;
215 /** Bumped by the panel's refresh button: drop the accumulated pages and re-read the diff. */
216 refreshToken?: number;
217}) {
218 const { resolvedTheme } = useTheme();
219 const settings = useClientSettings();
220 const [toggledFiles, setToggledFiles] = useState<ReadonlySet<string>>(() => new Set());
221 // A change of any size can carry hundreds of commits, and a menu that long is a scroll rather
222 // than a choice. The rest arrive ten at a time, on request.
223 const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);
224 /** Set once the reader has asked for every file at once, until they pick a file apart again. */
225 const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);
226 const diffLayout = settings.diffLayout;
227 const updateClientSettings = useUpdateClientSettings();
228 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
229 const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
230 PULL_REQUEST_FILE_TREE_STORAGE_KEY,
231 false,
232 Schema.Boolean,
233 );
234 const [selectedLines, setSelectedLines] = useState<{
235 id: string;
236 range: SelectedLineRange;
237 } | null>(null);
238 const [draft, setDraft] = useState<DraftAnchor | null>(null);
239 const [threadPending, setThreadPending] = useState(false);
240 const [orphansOpen, setOrphansOpen] = useState(false);
241 // Closed by default so the review form does not permanently eat vertical space below the
242 // diff; opened on demand as a floating overlay instead.
243 const [reviewOpen, setReviewOpen] = useState(false);
244 // Which pull request the slices belong to travels with them, so a render taken before the
245 // reset below cannot read the previous one's slices — or send its cursor to the host.
246 const [sliceState, setSliceState] = useState<{
247 readonly key: string;
248 readonly cursor: string | null;
249 readonly slices: ReadonlyArray<DiffSlice>;
250 }>({ key: "", cursor: null, slices: NO_SLICES });
251 const parseCache = useRef(new Map<string, RenderablePatch>());
252 const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup> | null>(null);
253
254 const referenceKey = pullRequestReviewKey(reference);
255 const commit = selectedCommitOid;
256 // One commit's own changes and the whole change are two different diffs, paged separately, so
257 // everything below is keyed by both.
258 const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`;
259 // The panel keeps this mounted across pull requests, so an open composer would otherwise
260 // survive the switch and attach its comment to whichever one is on screen when it is sent.
261 useEffect(() => {
262 setDraft(null);
263 setSelectedLines(null);
264 setToggledFiles(new Set());
265 setFoldOverride(null);
266 setVisibleCommitCount(COMMIT_PAGE_SIZE);
267 setOrphansOpen(false);
268 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
269 parseCache.current.clear();
270 }, [scopeKey]);
271
272 const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES;
273 const cursor = sliceState.key === scopeKey ? sliceState.cursor : null;
274 const diffQuery = useEnvironmentQuery(
275 pullRequestEnvironment.diff({
276 environmentId,
277 input: {
278 ...reference,
279 ...(cursor === null ? {} : { cursor }),
280 ...(commit === null ? {} : { commit }),
281 },
282 }),
283 );
284 // Each answer is kept as its own slice. Concatenating the patches and re-parsing the growing
285 // text would cost more with every slice, which is the wall the slicing exists to remove.
286 useEffect(() => {
287 const data = diffQuery.data;
288 if (data === null) return;
289 setSliceState((previous) => {
290 const slices = previous.key === scopeKey ? previous.slices : NO_SLICES;
291 const next = {
292 cursor,
293 patch: data.patch,
294 truncated: data.truncated,
295 nextCursor: data.nextCursor,
296 omittedFileStats: data.omittedFileStats ?? [],
297 };
298 const index = slices.findIndex((slice) => slice.cursor === cursor);
299 if (index === -1) {
300 return { key: scopeKey, cursor, slices: [...slices, next] };
301 }
302 const existing = slices[index];
303 if (
304 existing !== undefined &&
305 existing.patch === next.patch &&
306 existing.truncated === next.truncated &&
307 existing.nextCursor === next.nextCursor &&
308 existing.omittedFileStats.length === next.omittedFileStats.length &&
309 existing.omittedFileStats.every((file, index) => {
310 const refreshed = next.omittedFileStats[index];
311 return (
312 refreshed !== undefined &&
313 refreshed.path === file.path &&
314 refreshed.additions === file.additions &&
315 refreshed.deletions === file.deletions
316 );
317 })
318 ) {
319 return previous;
320 }
321 // A page that came back different means the diff moved under the review. The slices
322 // after it go with the replacement: their cursors were positions in the old diff.
323 return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] };
324 });
325 }, [cursor, diffQuery.data, scopeKey]);
326 // The refresh button rereads from the first page rather than the page the reader is on:
327 // pages are positions in one snapshot of the diff, and a fresh snapshot starts over.
328 const refreshFirstDiffPage = useAtomRefresh(
329 pullRequestEnvironment.diff({
330 environmentId,
331 input: { ...reference, ...(commit === null ? {} : { commit }) },
332 }),
333 );
334 const appliedRefreshToken = useRef(refreshToken);
335 useEffect(() => {
336 if (appliedRefreshToken.current === refreshToken) return;
337 appliedRefreshToken.current = refreshToken;
338 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
339 refreshFirstDiffPage();
340 }, [refreshToken, scopeKey, refreshFirstDiffPage]);
341 const reviewKey = referenceKey;
342 const pendingComments = usePendingReviewComments(reference);
343 const addComment = usePullRequestReviewStore((store) => store.addComment);
344 const removeComment = usePullRequestReviewStore((store) => store.removeComment);
345 const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, {
346 reportFailure: false,
347 });
348 const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
349 reportFailure: false,
350 });
351 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
352 reportFailure: false,
353 });
354 const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, {
355 reportFailure: false,
356 });
357 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
358 const loadDiffFiles = useMemo(
359 () =>
360 createPullRequestDiffFileContentsLoader(getDiffFileContents, {
361 environmentId,
362 reference,
363 commit,
364 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
365 }),
366 [commit, detail.updatedAt, environmentId, getDiffFileContents, reference, referenceKey],
367 );
368
369 // What is offered is the intersection of two different questions: what this host can do at
370 // all, and what this account may do on this repository. Either one saying no means a control
371 // that would only ever end in a refusal.
372 const review = useMemo(() => {
373 const hostReview = detail.capabilities.review;
374 const viewer = detail.viewerPermissions;
375 return {
376 inlineComment: hostReview.inlineComment && viewer.comment,
377 reply: hostReview.reply && viewer.comment,
378 resolve: hostReview.resolve && viewer.resolve,
379 verdicts: hostReview.verdicts.filter((verdict) => viewer.verdicts.includes(verdict)),
380 };
381 }, [detail.capabilities.review, detail.viewerPermissions]);
382 // A comment is posted against the pull request's head diff, so a line number taken from one
383 // commit's own diff would land somewhere else entirely. Commenting waits for the whole change.
384 const canCommentOnLines = review.inlineComment && commit === null;
385 // Every slice is parsed on its own and the result held, so a slice arriving costs one parse
386 // rather than one per slice already on screen. Its cache key carries the theme, which is what
387 // the tokenizer caches against, so a theme change is still a fresh parse.
388 const parsedSlices = useMemo(
389 () =>
390 loadedSlices.map((slice) => {
391 // The patch's own hash is part of the key: a refreshed page reuses its cursor, and a
392 // key of position alone would keep handing back the parse of the patch it replaced.
393 const cacheKey = `pull-request:${scopeKey}:${resolvedTheme}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`;
394 const cached = parseCache.current.get(cacheKey);
395 if (cached) return cached;
396 const parsed = getRenderablePatch(slice.patch, cacheKey, {
397 compactPartialHunkOffsets: true,
398 });
399 if (parsed) parseCache.current.set(cacheKey, parsed);
400 return parsed;
401 }),
402 [loadedSlices, resolvedTheme, scopeKey],
403 );
404 // Ordered within a slice rather than across them: ordering the accumulated set would let a late
405 // slice push a file the reader is part way through further down the page.
406 const files = useMemo(
407 () =>
408 parsedSlices.flatMap((parsed) =>
409 parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
410 ),
411 [parsedSlices],
412 );
413 const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
414 // What a slice withheld: the host declining to inline part of it, or a patch the viewer could
415 // not structure and so dropped. Neither says anything about there being more to fetch.
416 const withheldContent =
417 loadedSlices.some((slice) => slice.truncated) ||
418 parsedSlices.some((parsed) => parsed?.kind === "raw");
419
420 // Placing a conversation takes more than its file being in the diff: its line has to fall
421 // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
422 // off-diff list rather than disappearing between the two.
423 const placedThreadIds = useMemo(() => {
424 const placed = new Set<string>();
425 // A commit's diff counts lines within that commit; a review comment is anchored to the
426 // pull request's head diff. Pinning one onto the other would put the remark against
427 // whichever code happens to hold that line number in this commit, so while a commit is on
428 // screen every conversation is listed rather than placed.
429 if (commit !== null) return placed;
430 for (const file of files) {
431 const path = resolveFileDiffPath(file);
432 for (const thread of detail.reviewThreads) {
433 if (
434 thread.path === path &&
435 thread.line !== null &&
436 isLineInFileDiff(file, thread.side, thread.line)
437 ) {
438 placed.add(thread.id);
439 }
440 }
441 }
442 return placed;
443 }, [commit, detail.reviewThreads, files]);
444
445 const items = useMemo<CodeViewDiffItem<ReviewAnnotationGroup>[]>(
446 () =>
447 files.map((fileDiff) => {
448 const fileKey = buildFileDiffRenderKey(fileDiff);
449 const path = resolveFileDiffPath(fileDiff);
450 // One annotation per line, so a line that already carries a conversation shows a new
451 // comment underneath it rather than in place of it.
452 const groups = new Map<string, MutableAnnotationGroup>();
453 const groupAt = (side: PullRequestDiffSide, line: number) => {
454 const key = `${side}:${line}`;
455 const existing = groups.get(key);
456 if (existing) return existing;
457 const created: MutableAnnotationGroup = {
458 side,
459 line,
460 threads: [],
461 pending: [],
462 draft: false,
463 };
464 groups.set(key, created);
465 return created;
466 };
467
468 for (const thread of detail.reviewThreads) {
469 if (thread.path !== path || thread.line === null) continue;
470 if (!placedThreadIds.has(thread.id)) continue;
471 groupAt(thread.side, thread.line).threads.push(thread);
472 }
473 // Pending comments anchor to the head diff exactly like host threads do, so a
474 // commit's diff must not place them either — the same line means other code there.
475 if (commit === null) {
476 for (const comment of pendingComments) {
477 if (comment.path !== path) continue;
478 const anchor = getReviewPositionAnchor(comment.position);
479 groupAt(anchor.side, anchor.line).pending.push(comment);
480 }
481 }
482 if (draft?.fileKey === fileKey) {
483 const anchor = getReviewPositionAnchor(draft.position);
484 groupAt(anchor.side, anchor.line).draft = true;
485 }
486
487 const collapsed = isFileDiffCollapsed(
488 fileKey,
489 foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded"),
490 toggledFiles,
491 );
492
493 const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
494 side: toViewerSide(group.side),
495 lineNumber: group.line,
496 metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
497 }));
498 return {
499 id: fileKey,
500 type: "diff" as const,
501 fileDiff,
502 annotations,
503 collapsed,
504 // The viewer re-renders an item only when its version changes, so everything the
505 // annotations show has to be part of it.
506 version: fnv1a32(
507 `${collapsed ? "1" : "0"}:${annotations
508 .map(
509 ({ side, lineNumber, metadata }) =>
510 `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
511 .map((comment) => `${comment.id}:${comment.body}`)
512 .join(",")}:${metadata.threads
513 .map(
514 (thread) =>
515 `${thread.id}:${thread.isResolved ? "r" : ""}:${
516 thread.isOutdated ? "o" : ""
517 }:${thread.comments
518 .map(
519 (comment) =>
520 `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
521 comment.reactions ?? []
522 )
523 .map(
524 (r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`,
525 )
526 .join(",")}`,
527 )
528 .join(";")}`,
529 )
530 .join(",")}`,
531 )
532 .join("|")}`,
533 ),
534 };
535 }),
536 [
537 commit,
538 detail.reviewThreads,
539 draft,
540 files,
541 foldOverride,
542 pendingComments,
543 placedThreadIds,
544 settings.diffFilesCollapsed,
545 toggledFiles,
546 ],
547 );
548 const omittedFileStats = useMemo(
549 () =>
550 new Map(
551 loadedSlices.flatMap((slice) =>
552 slice.omittedFileStats.map((file) => [file.path, file] as const),
553 ),
554 ),
555 [loadedSlices],
556 );
557 const fileKeys = useMemo(() => items.map((item) => item.id), [items]);
558 const collapsedFileKeys = useMemo(
559 () => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)),
560 [items],
561 );
562 const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);
563 const fileTreeEntries = useMemo(() => diffFileTreeEntries(files), [files]);
564
565 // A failed slice must not be asked for again on its own. The files already loaded keep the
566 // sentinel on screen, so re-arming it after a failure would request the same slice forever.
567 const canLoadNextSlice =
568 nextCursor !== null &&
569 nextCursor !== cursor &&
570 !diffQuery.isPending &&
571 diffQuery.error === null;
572 const loadNextSlice = useCallback(() => {
573 if (nextCursor === null) return;
574 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
575 }, [nextCursor]);
576
577 // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
578 // an effect reading a ref could run before that node exists and would never arm the observer.
579 const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
580 useEffect(() => {
581 if (sentinel === null || !canLoadNextSlice) return;
582 const observer = new IntersectionObserver(
583 (observed) => {
584 if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
585 },
586 // Start the next slice slightly before the sentinel is on screen.
587 { rootMargin: "240px" },
588 );
589 observer.observe(sentinel);
590 return () => observer.disconnect();
591 }, [canLoadNextSlice, loadNextSlice, sentinel]);
592
593 // A stable identity: the viewer's SlotPortals memoizes each file's header/annotation portal on
594 // these render props, so a fresh function here would recreate every visible file's portal on
595 // every tab re-render (a line-selection drag, a keystroke in the draft, a review-store update).
596 const toggleFile = useCallback(
597 (fileKey: string) =>
598 setToggledFiles((current) => {
599 // The override becomes this file's new default the moment it is folded into the set below,
600 // so nothing has to be re-derived when the reader goes back to choosing one at a time.
601 const next = new Set(current);
602 if (next.has(fileKey)) next.delete(fileKey);
603 else next.add(fileKey);
604 return next;
605 }),
606 [],
607 );
608
609 const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
610 const revealFile = useCallback(
611 (path: string) => {
612 const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
613 if (item === undefined) return;
614 if (item.collapsed === true) toggleFile(item.id);
615 requestTreeReveal(item.id);
616 },
617 [items, requestTreeReveal, toggleFile],
618 );
619
620 const toggleAllFiles = () => {
621 // Held as an override of the default rather than as the file keys on screen: a diff that is
622 // still paging would otherwise bring its next slice in folded, moments after the reader
623 // asked for everything to be open.
624 setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
625 setToggledFiles(new Set());
626 };
627
628 // Newest first: the last commit is the one a reader coming back to a change is looking for.
629 const orderedCommits = useMemo(
630 () =>
631 // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits
632 // from different zones would sort by how they were written rather than when they landed.
633 detail.commits.toSorted(
634 (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
635 ),
636 [detail.commits],
637 );
638
639 const beginComment = useCallback(
640 (range: SelectedLineRange | null, context: { item: CodeViewItem<ReviewAnnotationGroup> }) => {
641 if (!range || !canCommentOnLines) return;
642 const item = context.item;
643 if (item.type !== "diff") return;
644 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
645 if (!file) return;
646 // A range collapses to its last line: only GitHub carries a multi-line comment, and one
647 // that silently lost its first line on the other hosts would be worse than one line.
648 const path = resolveFileDiffPath(file);
649 const previousPath = resolveFileDiffPreviousPath(file);
650 const position = resolveDiffReviewPosition(file, range.end, range.endSide ?? range.side);
651 if (position === null) return;
652 setDraft({
653 fileKey: item.id,
654 path,
655 oldPath: previousPath === path ? null : previousPath,
656 position,
657 range,
658 });
659 },
660 [canCommentOnLines, files],
661 );
662
663 // Built here because the parsed diff only lives here, and built by the same function the
664 // thread panel's own line selection uses — the gesture is the same one, so a second reading of
665 // the hunks would only be a second place for it to drift.
666 const finishSelection = useCallback(
667 (anchor: DraftAnchor, text: string, onFinish: (comment: ReviewCommentContext) => void) => {
668 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
669 const comment =
670 file === undefined
671 ? null
672 : buildDiffReviewComment({
673 id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
674 sectionId: `pull-request:${detail.number}`,
675 sectionTitle: `PR #${detail.number} review`,
676 filePath: anchor.path,
677 fileDiff: file,
678 range: anchor.range,
679 text,
680 });
681 setDraft(null);
682 setSelectedLines(null);
683 if (comment !== null) onFinish(comment);
684 },
685 [detail.number, files],
686 );
687
688 // The viewer's SlotPortals memoizes each visible file's header/annotation portal on these
689 // render props and on `options` below; a fresh identity on any of them — as a plain inline
690 // function or object literal would be — invalidates that memo and recreates every portal on
691 // screen on any tab re-render (a drag-selection, a keystroke in the draft, a review-store
692 // update), which is the jank this file is otherwise clean of.
693 const renderCodeViewFooter = useCallback(
694 () =>
695 // Only while something is still owed. A finished diff whose query fails on a later
696 // refresh — a reconnect re-runs every one of them — is whole on screen already, and
697 // saying otherwise sends the reader looking for files that are all there.
698 nextCursor === null ? null : (
699 <div
700 ref={setSentinel}
701 className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
702 >
703 {diffQuery.error !== null ? (
704 <>
705 <span>The rest of this diff could not be loaded.</span>
706 <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
707 Retry
708 </Button>
709 </>
710 ) : diffQuery.isPending ? (
711 "Loading more files..."
712 ) : null}
713 </div>
714 ),
715 [nextCursor, diffQuery.error, diffQuery.isPending, diffQuery.refresh],
716 );
717
718 const renderHeaderPrefix = useCallback(
719 (item: CodeViewItem<ReviewAnnotationGroup>) => {
720 // The item the viewer is drawing already carries the state the memo settled on, so the
721 // chevron follows it rather than recomputing the default here.
722 const collapsed = item.collapsed === true;
723 return (
724 <Button
725 size="icon-micro"
726 variant="ghost-muted"
727 aria-expanded={!collapsed}
728 aria-label={collapsed ? "Expand diff" : "Collapse diff"}
729 className="mr-1 rounded hover:bg-transparent"
730 onClick={(event) => {
731 event.stopPropagation();
732 toggleFile(item.id);
733 }}
734 >
735 {collapsed ? (
736 <ChevronRightIcon className="size-4" />
737 ) : (
738 <ChevronDownIcon className="size-4" />
739 )}
740 </Button>
741 );
742 },
743 [toggleFile],
744 );
745
746 const renderHeaderMetadata = useCallback(
747 (item: CodeViewItem<ReviewAnnotationGroup>) => {
748 if (item.type !== "diff") return null;
749 let additions = 0;
750 let deletions = 0;
751 for (const hunk of item.fileDiff.hunks) {
752 additions += hunk.additionLines;
753 deletions += hunk.deletionLines;
754 }
755 if (additions === 0 && deletions === 0) {
756 const withheld = omittedFileStats.get(resolveFileDiffPath(item.fileDiff));
757 if (withheld) ({ additions, deletions } = withheld);
758 }
759 return (
760 <PullRequestDiffStat
761 additions={additions}
762 deletions={deletions}
763 className="font-mono text-[11px]"
764 />
765 );
766 },
767 [omittedFileStats],
768 );
769
770 const diffViewOptions = useMemo(
771 () => ({
772 diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
773 lineDiffType: "none" as const,
774 overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
775 theme: resolveDiffThemeName(resolvedTheme),
776 preferredHighlighter: PREFERRED_HIGHLIGHTER,
777 themeType: resolvedTheme,
778 stickyHeaders: true,
779 loadDiffFiles,
780 enableGutterUtility: canCommentOnLines && draft === null,
781 enableLineSelection: canCommentOnLines && draft === null,
782 // Two gestures reach the same place: dragging the line numbers selects a range, and the
783 // gutter's own button comments on the one line it sits on. They are separate callbacks in
784 // the viewer, so a reader who only ever presses the button gets nothing unless both are
785 // wired.
786 onGutterUtilityClick: beginComment,
787 onLineSelectionEnd: beginComment,
788 }),
789 [diffLayout, wordWrap, resolvedTheme, loadDiffFiles, canCommentOnLines, draft, beginComment],
790 );
791
792 const runThreadCommand = useCallback(
793 async (label: string, run: () => Promise<{ readonly _tag: string }>): Promise<boolean> => {
794 if (threadPending) return false;
795 setThreadPending(true);
796 const result = await run();
797 setThreadPending(false);
798 if (result._tag === "Failure") {
799 toastManager.add({ type: "error", title: label });
800 return false;
801 }
802 onRefresh();
803 return true;
804 },
805 [onRefresh, threadPending],
806 );
807
808 // A conversation is the same card wired to the same commands whether it sits on its line or
809 // was stranded off the diff; only where it is drawn differs.
810 const renderThreadCard = useCallback(
811 (thread: PullRequestReviewThread) => (
812 <ReviewThreadCard
813 // Named with the pull request too: a thread's id is the host's own, and two pull requests
814 // can hand out the same one — which would leave one card's open editor standing over the
815 // other's conversation.
816 key={`${reference.projectId}#${reference.number}:${thread.id}`}
817 thread={thread}
818 workspaceRoot={detail.workspaceRoot}
819 canReply={review.reply}
820 canResolve={review.resolve}
821 canReact={detail.capabilities.reactions === true}
822 environmentId={environmentId}
823 reference={reference}
824 pending={threadPending}
825 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
826 fixLabel={fixFindingLabel}
827 {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
828 onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
829 const result = await loadThreadComments({
830 environmentId,
831 input: { ...reference, threadId: thread.id, cursor },
832 });
833 if (result._tag === "Failure") {
834 toastManager.add({
835 type: "error",
836 title: "More comments could not be loaded",
837 });
838 return null;
839 }
840 return result.value;
841 }}
842 onReply={(body) =>
843 runThreadCommand("Reply could not be posted", () =>
844 replyToThread({
845 environmentId,
846 input: { ...reference, threadId: thread.id, body },
847 }),
848 )
849 }
850 // A conversation on a line is made of review comments, whatever the host filed them as.
851 canEditComment={(comment) =>
852 canEditPullRequestComment(detail, { author: comment.author, kind: "review-comment" })
853 }
854 onEditComment={(commentId, body) =>
855 runThreadCommand("The comment could not be saved", () =>
856 updateComment({
857 environmentId,
858 input: { ...reference, commentId, kind: "review-comment", body },
859 }),
860 )
861 }
862 onToggleResolved={() =>
863 void runThreadCommand("The conversation could not be updated", () =>
864 setThreadResolution({
865 environmentId,
866 input: { ...reference, threadId: thread.id, resolved: !thread.isResolved },
867 }),
868 )
869 }
870 onReacted={onRefresh}
871 />
872 ),
873 [
874 detail,
875 environmentId,
876 fixFindingLabel,
877 loadThreadComments,
878 onRefresh,
879 onFixFinding,
880 pendingFinding,
881 reference,
882 replyToThread,
883 review.reply,
884 review.resolve,
885 runThreadCommand,
886 setThreadResolution,
887 threadPending,
888 updateComment,
889 ],
890 );
891
892 const renderAnnotation = useCallback(
893 (annotation: ReviewAnnotation) => (
894 <div className="py-1 font-sans text-foreground">
895 {annotation.metadata.threads.map(renderThreadCard)}
896 {annotation.metadata.pending.map((comment) => (
897 <PendingReviewCommentCard
898 key={comment.id}
899 comment={comment}
900 onRemove={() => removeComment(reviewKey, comment.id)}
901 />
902 ))}
903 {annotation.metadata.draft && draft ? (
904 <DiffCommentAnnotation
905 kind="draft"
906 rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
907 text=""
908 submitLabel="Add to review"
909 {...(onAddToAgentSelection
910 ? {
911 secondaryAction: {
912 label: "Add to agent",
913 onAction: (text: string) =>
914 finishSelection(draft, text, (comment) =>
915 onAddToAgentSelection({ comment, request: text }),
916 ),
917 },
918 }
919 : {})}
920 onCancel={() => {
921 setDraft(null);
922 setSelectedLines(null);
923 }}
924 onComment={(body) => {
925 addComment(reviewKey, {
926 id: nextPendingReviewCommentId(),
927 path: draft.path,
928 ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),
929 position: draft.position,
930 body,
931 });
932 setDraft(null);
933 setSelectedLines(null);
934 }}
935 />
936 ) : null}
937 </div>
938 ),
939 [
940 addComment,
941 draft,
942 finishSelection,
943 onAddToAgentSelection,
944 removeComment,
945 renderThreadCard,
946 reviewKey,
947 ],
948 );
949
950 /**
951 * The review overlay belongs to the pull request, not to the patch: a change whose diff
952 * cannot be structured — or read at all — is still one a reviewer can approve or reject, so
953 * it survives every branch below. It floats over the scroll area rather than sitting in the
954 * layout flow, so the diff keeps the full height instead of permanently losing a strip to a
955 * footer most reviews never touch. Hidden entirely where the host offers no verdicts, same as
956 * the bar it wraps did.
957 */
958 const reviewOverlay =
959 review.verdicts.length === 0 ? null : (
960 <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10">
961 {reviewOpen ? (
962 <div
963 className={cn(
964 "surface-glass pointer-events-auto absolute inset-x-3 rounded-xl border border-border/60 shadow-lg",
965 detail.capabilities.comment && detail.viewerPermissions.comment
966 ? "bottom-16"
967 : "bottom-3",
968 )}
969 >
970 <Button
971 type="button"
972 size="icon-sm"
973 variant="ghost"
974 aria-label="Close review"
975 className="absolute right-2 top-2"
976 onClick={() => setReviewOpen(false)}
977 >
978 <XIcon className="size-3.5" />
979 </Button>
980 <PullRequestReviewBar
981 environmentId={environmentId}
982 reference={reference}
983 verdicts={review.verdicts}
984 requestChangesSummaryRequired={detail.provider === "forgejo"}
985 onSubmitted={() => {
986 onRefresh();
987 setReviewOpen(false);
988 }}
989 />
990 </div>
991 ) : (
992 <Button
993 className={cn(
994 "pointer-events-auto absolute bottom-3 rounded-full shadow-lg",
995 detail.capabilities.comment && detail.viewerPermissions.comment
996 ? "right-16"
997 : "right-4",
998 )}
999 onClick={() => setReviewOpen(true)}
1000 size="compact"
1001 variant="glass"
1002 >
1003 <MessageSquareIcon className="size-3.5" />
1004 Review
1005 {pendingComments.length > 0 ? (
1006 <span className="flex size-4 items-center justify-center rounded-full bg-accent text-[10px] tabular-nums text-accent-foreground">
1007 {pendingComments.length}
1008 </span>
1009 ) : null}
1010 </Button>
1011 )}
1012 </div>
1013 );
1014 // A rebase or a force-push can take the scoped commit out of the change. Its diff may still
1015 // be reachable on the host, but it is no longer part of what is being reviewed, so the scope
1016 // goes back to the whole change rather than sitting under a name nothing matches.
1017 //
1018 // Including when the change reports no commits at all: the scope dropdown is the only way back
1019 // to the whole diff and it is not drawn without commits to list, so a scope that outlived them
1020 // would leave the tab reading one obsolete commit with nothing to press.
1021 const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
1022 useEffect(() => {
1023 if (commit !== null && selectedCommit === undefined) {
1024 onSelectedCommitChange(null);
1025 }
1026 }, [commit, onSelectedCommitChange, selectedCommit]);
1027 const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
1028 /**
1029 * The same controls the thread diff panel carries, in the same order, minus the
1030 * ignore-whitespace toggle: that is `git diff -w` on the server, and no host's pull request
1031 * diff API offers it.
1032 */
1033 const toolbar = (
1034 <div className="flex h-10 min-h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 bg-background px-4 text-xs text-muted-foreground">
1035 <div className="flex min-w-0 flex-1 items-center gap-3">
1036 {/* A host that reports no commits has nothing to scope by, and a dropdown whose only
1037 entry is the scope already showing is a control that does nothing. */}
1038 {orderedCommits.length > 0 ? (
1039 <DropdownMenu>
1040 <DropdownMenuTrigger
1041 className="inline-flex h-6 min-w-0 max-w-64 items-center gap-1 rounded-md bg-accent px-2 text-xs font-medium text-accent-foreground outline-none transition-colors hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-ring"
1042 aria-label={`Diff scope: ${scopeLabel}`}
1043 >
1044 <span className="truncate">{scopeLabel}</span>
1045 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
1046 </DropdownMenuTrigger>
1047 <DropdownMenuContent align="start" className="w-80">
1048 <DropdownMenuItem
1049 className={commit === null ? "bg-foreground/[0.08]" : undefined}
1050 onClick={() => onSelectedCommitChange(null)}
1051 >
1052 <span>All commits</span>
1053 </DropdownMenuItem>
1054 {orderedCommits.slice(0, visibleCommitCount).map((entry) => (
1055 <DropdownMenuItem
1056 key={entry.oid}
1057 className={entry.oid === commit ? "bg-foreground/[0.08]" : undefined}
1058 onClick={() => onSelectedCommitChange(entry.oid)}
1059 >
1060 {/* Headlines run long, and the abbreviated oid after one is what a reader
1061 matches against the commit list on the host. */}
1062 <Tooltip>
1063 <TooltipTrigger
1064 render={<span className="min-w-0 truncate">{entry.messageHeadline}</span>}
1065 />
1066 <TooltipPopup side="top">{entry.messageHeadline}</TooltipPopup>
1067 </Tooltip>
1068 <span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground">
1069 {entry.oid.slice(0, 7)}
1070 </span>
1071 </DropdownMenuItem>
1072 ))}
1073 {orderedCommits.length > visibleCommitCount ? (
1074 // Kept out of the radio group: it changes how much of the list is on screen
1075 // rather than what the diff is scoped to.
1076 <DropdownMenuItem
1077 closeOnClick={false}
1078 onClick={() => setVisibleCommitCount((count) => count + COMMIT_PAGE_SIZE)}
1079 >
1080 <span className="text-muted-foreground">
1081 Show more ({orderedCommits.length - visibleCommitCount} left)
1082 </span>
1083 </DropdownMenuItem>
1084 ) : null}
1085 </DropdownMenuContent>
1086 </DropdownMenu>
1087 ) : null}
1088 {/* One count, and the caveats as icons that carry their own words. Spelled out they
1089 competed for a strip this narrow and every one of them truncated to nothing. */}
1090 <PullRequestMetaLine className="shrink-0">
1091 <span className="shrink-0 tabular-nums">
1092 {files.length} {files.length === 1 ? "file" : "files"}
1093 {nextCursor === null ? "" : "+"}
1094 </span>
1095 {withheldContent ? (
1096 <Tooltip>
1097 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1098 <TriangleAlertIcon
1099 aria-label="Some of this diff was not shown"
1100 className="size-3.5 text-amber-600 dark:text-amber-500"
1101 />
1102 </TooltipTrigger>
1103 <TooltipPopup side="bottom">
1104 The host withheld part of this diff — a binary file, or a change too large to
1105 inline.
1106 </TooltipPopup>
1107 </Tooltip>
1108 ) : null}
1109 {commit !== null && review.inlineComment ? (
1110 <Tooltip>
1111 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1112 <MessageSquareOffIcon
1113 aria-label="Line comments are written from the whole change"
1114 className="size-3.5"
1115 />
1116 </TooltipTrigger>
1117 <TooltipPopup side="bottom">
1118 A comment is anchored to the whole change, so switch to All commits to write one.
1119 </TooltipPopup>
1120 </Tooltip>
1121 ) : null}
1122 </PullRequestMetaLine>
1123 </div>
1124 <div className="flex shrink-0 items-center gap-1">
1125 {fileKeys.length > 0 ? (
1126 <Tooltip>
1127 <TooltipTrigger
1128 render={
1129 <Button
1130 type="button"
1131 size="icon-sm"
1132 variant="ghost"
1133 aria-label={allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1134 onClick={toggleAllFiles}
1135 />
1136 }
1137 >
1138 {allFilesCollapsed ? (
1139 <ChevronsUpDownIcon className="size-3.5" />
1140 ) : (
1141 <ChevronsDownUpIcon className="size-3.5" />
1142 )}
1143 </TooltipTrigger>
1144 <TooltipPopup side="top">
1145 {allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1146 </TooltipPopup>
1147 </Tooltip>
1148 ) : null}
1149 <ToggleGroup
1150 aria-label="Diff layout"
1151 className="shrink-0"
1152 variant="segmented"
1153 value={[diffLayout]}
1154 onValueChange={(value) => {
1155 const next = value[0];
1156 if (next === "stacked" || next === "split") {
1157 updateClientSettings({ diffLayout: next });
1158 }
1159 }}
1160 >
1161 <Toggle aria-label="Stacked diff view" value="stacked">
1162 <Rows3Icon className="size-3.5" />
1163 </Toggle>
1164 <Toggle aria-label="Split diff view" value="split">
1165 <Columns2Icon className="size-3.5" />
1166 </Toggle>
1167 </ToggleGroup>
1168 <Tooltip>
1169 <TooltipTrigger
1170 render={
1171 <Toggle
1172 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1173 variant="ghost"
1174 size="sm"
1175 pressed={wordWrap}
1176 onPressedChange={(pressed) => {
1177 setWordWrap(Boolean(pressed));
1178 }}
1179 />
1180 }
1181 >
1182 <TextWrapIcon className="size-3.5" />
1183 </TooltipTrigger>
1184 <TooltipPopup side="top">
1185 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1186 </TooltipPopup>
1187 </Tooltip>
1188 {fileKeys.length > 0 ? (
1189 <Tooltip>
1190 <TooltipTrigger
1191 render={
1192 <Toggle
1193 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
1194 variant="ghost"
1195 size="sm"
1196 pressed={fileTreeOpen}
1197 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
1198 />
1199 }
1200 >
1201 <FolderTreeIcon className="size-3.5" />
1202 </TooltipTrigger>
1203 <TooltipPopup side="top">
1204 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
1205 </TooltipPopup>
1206 </Tooltip>
1207 ) : null}
1208 </div>
1209 </div>
1210 );
1211 // The toolbar rides above every branch below, not just the one with a patch in it: a commit
1212 // whose diff is empty or unreadable still needs the scope dropdown that got the reader there.
1213 const withReviewBar = (body: ReactNode) => (
1214 <div className="flex h-full min-h-0 flex-col">
1215 {toolbar}
1216 {/* The overlay is anchored to this wrapper, not the scroller: absolute positioning
1217 inside an overflowing element tracks the content's bottom edge, which would carry
1218 the trigger away with the first scroll. */}
1219 <div className="relative min-h-0 flex-1">
1220 <div className="h-full overflow-auto">{body}</div>
1221 {reviewOverlay}
1222 </div>
1223 </div>
1224 );
1225
1226 // Under the toolbar rather than in place of it, so choosing a commit does not take the
1227 // dropdown that was just used off the screen while its diff loads.
1228 if (diffQuery.isPending && loadedSlices.length === 0) {
1229 return withReviewBar(<DiffPanelLoadingState label="Loading pull request diff..." />);
1230 }
1231
1232 // A slice that fails once there are files on screen is reported at the end of them instead:
1233 // the diff already read is worth more than the error that stopped it growing.
1234 if (diffQuery.error && loadedSlices.length === 0) {
1235 return withReviewBar(
1236 <p className="px-4 py-5 text-sm text-muted-foreground">{diffQuery.error}</p>,
1237 );
1238 }
1239
1240 // A patch the viewer cannot structure (binary, or a format it does not parse) still has to
1241 // be readable, so it falls back to the raw text rather than an empty tab. Only once the diff
1242 // is whole: returning here while a cursor is outstanding would take the sentinel off screen
1243 // and end the walk, leaving the rest of the change unasked for.
1244 const rawSlices =
1245 nextCursor === null
1246 ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
1247 : [];
1248 if (files.length === 0 && rawSlices.length > 0) {
1249 return withReviewBar(
1250 <div className="space-y-4 px-4 py-5">
1251 {rawSlices.map((slice) => (
1252 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1253 <p className="text-xs text-muted-foreground">{slice.reason}</p>
1254 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1255 </div>
1256 ))}
1257 </div>,
1258 );
1259 }
1260
1261 if (items.length === 0 && nextCursor === null) {
1262 return withReviewBar(
1263 <p className="px-4 py-5 text-sm text-muted-foreground">
1264 {commit === null
1265 ? "This pull request has no file changes."
1266 : "This commit has no file changes."}
1267 </p>,
1268 );
1269 }
1270
1271 const orphanThreads = detail.reviewThreads.filter((thread) => !placedThreadIds.has(thread.id));
1272 // A file carrying five stranded conversations should read as that file once rather than as
1273 // five copies of its path.
1274 const orphanFiles = new Map<string, PullRequestReviewThread[]>();
1275 for (const thread of orphanThreads) {
1276 const existing = orphanFiles.get(thread.path);
1277 if (existing) existing.push(thread);
1278 else orphanFiles.set(thread.path, [thread]);
1279 }
1280
1281 const unstructured =
1282 rawSlices.length === 0 ? null : (
1283 // A slice the viewer cannot structure is still part of the change. Shown under the files
1284 // that did parse rather than dropped, because the alternative is a diff that silently
1285 // omits whatever the viewer could not read.
1286 <div className="space-y-4 border-t border-border/60 px-4 py-5">
1287 {rawSlices.map((slice) => (
1288 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1289 <p className="text-xs text-muted-foreground">{slice.reason}</p>
1290 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1291 </div>
1292 ))}
1293 </div>
1294 );
1295
1296 return (
1297 <div className="flex h-full min-h-0 flex-col">
1298 {toolbar}
1299 {/* Above the code, closed, and counted: these belong to the change rather than to any
1300 line of it, and in the stream they read as cards dropped into the patch. */}
1301 {orphanFiles.size > 0 ? (
1302 <Collapsible
1303 className="shrink-0 border-b border-border/60"
1304 open={orphansOpen}
1305 onOpenChange={setOrphansOpen}
1306 >
1307 {/* Still a heading, so the section keeps its place in a screen reader's outline;
1308 the count is spelled out there rather than left as a bare number. */}
1309 <h2>
1310 <CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground">
1311 {/* While slices are still arriving a conversation may simply belong to a file
1312 that has not landed yet, which is not the same as being off the diff. */}
1313 <span>
1314 {nextCursor === null
1315 ? "Conversations not on the current diff"
1316 : "Conversations not on the diff loaded so far"}
1317 </span>
1318 <ChevronRightIcon
1319 aria-hidden
1320 className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")}
1321 />
1322 <span aria-hidden className="tabular-nums">
1323 {orphanThreads.length}
1324 </span>
1325 <span className="sr-only">
1326 {orphanThreads.length === 1
1327 ? "1 conversation"
1328 : `${orphanThreads.length} conversations`}
1329 </span>
1330 </CollapsibleTrigger>
1331 </h2>
1332 <CollapsiblePanel>
1333 {/* Capped: opened on a change with dozens of them, this would otherwise leave no
1334 room for the diff it sits above. */}
1335 <div className="max-h-64 space-y-3 overflow-auto px-4 pb-3">
1336 {[...orphanFiles].map(([path, threads]) => (
1337 <div key={path}>
1338 <Tooltip>
1339 <TooltipTrigger
1340 render={<p className="truncate px-3 text-xs text-muted-foreground">{path}</p>}
1341 />
1342 <TooltipPopup side="top">{path}</TooltipPopup>
1343 </Tooltip>
1344 <div className="mt-1 space-y-2">
1345 {threads.map((thread) => (
1346 <div key={thread.id}>
1347 {thread.line === null ? null : (
1348 <p className="px-3 text-xs text-muted-foreground">Line {thread.line}</p>
1349 )}
1350 {renderThreadCard(thread)}
1351 </div>
1352 ))}
1353 </div>
1354 </div>
1355 ))}
1356 </div>
1357 </CollapsiblePanel>
1358 </Collapsible>
1359 ) : null}
1360 <div className="flex min-h-0 flex-1 overflow-hidden">
1361 {/* Relative wrapper so the review overlay floats over the diff rather than pushing it
1362 up; the viewer inside still owns its own scrolling. */}
1363 <div
1364 className="relative min-h-0 min-w-0 flex-1"
1365 // The chevron answers this too, but the whole header row is the target a reader
1366 // actually aims for. The header lives in the viewer's shadow tree, so the capture
1367 // listener walks `composedPath` — the only way to see through the shadow boundary.
1368 onClickCapture={(event) => {
1369 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1370 for (const node of composedPath) {
1371 if (!(node instanceof HTMLElement)) continue;
1372 // A control inside the header — the collapse chevron — handles itself, and
1373 // this capture listener fires before its own click does. Leave it alone or
1374 // the two toggles cancel out.
1375 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1376 return;
1377 }
1378 if (node.hasAttribute("data-diffs-header")) {
1379 const filePath = node.querySelector("[data-title]")?.textContent?.trim();
1380 if (filePath === undefined || filePath === "") return;
1381 const item = items.find(
1382 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
1383 );
1384 if (item !== undefined) toggleFile(item.id);
1385 return;
1386 }
1387 }
1388 }}
1389 >
1390 {/* The viewer virtualizes against the element it is told is scrolling and places its
1391 rows absolutely, so it has to own that element — the thread diff panel hands it the
1392 same one. Scrolling from a parent instead leaves it painting over its neighbours. */}
1393 <StyledDiffCodeView<ReviewAnnotationGroup>
1394 // Keep scrollbar space stable so file metadata and line numbers do not shift as a
1395 // diff crosses the overflow boundary. The viewer is itself focusable for keyboard
1396 // interaction, but its native host outline clips and competes with the focus
1397 // indicators on its actual controls.
1398 className="h-full overflow-auto [scrollbar-gutter:stable]"
1399 viewerRef={setViewer}
1400 items={items}
1401 selectedLines={selectedLines}
1402 onSelectedLinesChange={setSelectedLines}
1403 options={diffViewOptions}
1404 // The viewer owns the scroll container, so the sentinel that asks for the next slice
1405 // has to live inside it — at the end of the files, where reaching it means the reader
1406 // is running out of diff.
1407 renderCodeViewFooter={renderCodeViewFooter}
1408 renderHeaderPrefix={renderHeaderPrefix}
1409 renderHeaderMetadata={renderHeaderMetadata}
1410 renderAnnotation={renderAnnotation}
1411 unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1412 />
1413 {reviewOverlay}
1414 </div>
1415 {fileTreeOpen ? (
1416 <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">
1417 <DiffFileTree
1418 ariaLabel={`Pull request #${detail.number} files`}
1419 entries={fileTreeEntries}
1420 onSelectFile={revealFile}
1421 // The tree lists only what has arrived; a footer says so while the diff is still
1422 // paging, and lets the reader pull the rest in without scrolling for it.
1423 footer={
1424 nextCursor === null ? null : (
1425 <div className="shrink-0 border-t border-border/60 p-2">
1426 <Button
1427 type="button"
1428 size="xs"
1429 variant="outline"
1430 className="w-full"
1431 disabled={diffQuery.isPending}
1432 onClick={diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice}
1433 >
1434 {diffQuery.error !== null
1435 ? "Retry"
1436 : diffQuery.isPending
1437 ? "Loading more files..."
1438 : "Load more files"}
1439 </Button>
1440 </div>
1441 )
1442 }
1443 />
1444 </aside>
1445 ) : null}
1446 </div>
1447 {unstructured}
1448 </div>
1449 );
1450}
1451
1452export default PullRequestCodeTab;