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