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

PullRequestCodeTab.tsx

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