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