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