Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestCodeTab.tsx

1,374 lines56.2 KB

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