Open History to see the last commit
1import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
2import type { CodeViewDiffItem, CodeViewHandle } 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 Columns2Icon,
17 FolderTreeIcon,
18 InfoIcon,
19 MessageSquareOffIcon,
20 PilcrowIcon,
21 Rows3Icon,
22 Settings2Icon,
23 TextWrapIcon,
24 TriangleAlertIcon,
25} from "lucide-react";
26import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
27import { useAtomRefresh } from "@effect/atom-react";
28import * as Schema from "effect/Schema";
29import {
30 createContext,
31 use,
32 useEffect,
33 useEffectEvent,
34 useRef,
35 useState,
36 type ReactNode,
37} from "react";
38
39import { useLocalStorage } from "~/hooks/useLocalStorage";
40import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
41import { useTheme } from "~/hooks/useTheme";
42import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
43import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
44import { canEditPullRequestComment, canResolvePullRequestThread } from "./pullRequestEditing.logic";
45import { orderDiffFiles } from "./pullRequestFileOrder.logic";
46import {
47 buildFileDiffRenderKey,
48 fnv1a32,
49 getDiffLineStat,
50 getRenderablePatch,
51 resolveDiffThemeName,
52 resolveFileDiffPath,
53 resolveFileDiffPreviousPath,
54 type RenderablePatch,
55} from "~/lib/diffRendering";
56import { APP_BASE_NAME } from "~/branding";
57import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
58import { cn } from "~/lib/utils";
59import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";
60import {
61 buildDiffReviewComment,
62 resolveDiffReviewPosition,
63 type ReviewCommentContext,
64} from "~/reviewCommentContext";
65import { pullRequestEnvironment } from "~/state/pullRequests";
66import { useEnvironmentQuery } from "~/state/query";
67import { useAtomCommand } from "~/state/use-atom-command";
68
69import { DiffPanelLoadingState } from "../DiffPanelShell";
70import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
71import { DiffFileTree } from "../diffs/DiffFileTree";
72import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";
73import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";
74import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";
75import { Button } from "../ui/button";
76import { MorphIcon } from "~/components/MorphIcon";
77import { Checkbox } from "../ui/checkbox";
78import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
79import {
80 DropdownMenu,
81 DropdownMenuCheckboxItem,
82 DropdownMenuContent,
83 DropdownMenuItem,
84 DropdownMenuRadioGroup,
85 DropdownMenuRadioItem,
86 DropdownMenuSeparator,
87 DropdownMenuTrigger,
88} from "../ui/menu";
89import { toastManager } from "../ui/toast";
90import { Toggle, ToggleGroup } from "../ui/toggle-group";
91import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
92import {
93 getReviewPositionAnchor,
94 PendingReviewCommentCard,
95 ReviewThreadCard,
96 toViewerSide,
97} from "./PullRequestReviewAnnotation";
98import {
99 isFileDiffCollapsed,
100 isLineInFileDiff,
101 toggleFileDiffFoldForViewed,
102 type DiffFoldOverride,
103} from "./pullRequestDiff.logic";
104import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
105import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState";
106import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
107import {
108 nextPendingReviewCommentId,
109 pullRequestReviewKey,
110 usePendingReviewComments,
111 usePullRequestReviewStore,
112 type PendingReviewComment,
113} from "./pullRequestReviewStore";
114
115interface ReviewAnnotationGroup {
116 readonly threads: ReadonlyArray<PullRequestReviewThread>;
117 readonly pending: ReadonlyArray<PendingReviewComment>;
118 readonly draft: boolean;
119}
120
121type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;
122
123const COMMIT_PAGE_SIZE = 10;
124
125const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";
126
127interface DiffSlice {
128 readonly cursor: string | null;
129 readonly patch: string;
130 readonly truncated: boolean;
131 readonly nextCursor: string | null;
132 readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
133}
134
135/**
136 * The viewer's own per-file counts are hidden and drawn from this side of its shadow root
137 * instead: its counts are hunk sums, and a file whose hunks the host withheld would read as
138 * an empty change rather than as the counts the host did report.
139 */
140const REPLACE_FILE_COUNTS_CSS = `
141[data-diffs-header] [data-additions-count],
142[data-diffs-header] [data-deletions-count] {
143 display: none !important;
144}`;
145
146const NO_SLICES: ReadonlyArray<DiffSlice> = [];
147
148// Each slice is parsed once per cache key and the parse lives as long as the slice does, so a
149// slice arriving costs one parse rather than one per slice already on screen.
150const sliceParses = new WeakMap<DiffSlice, Map<string, RenderablePatch | null>>();
151
152function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) {
153 let parses = sliceParses.get(slice);
154 if (parses === undefined) {
155 parses = new Map();
156 sliceParses.set(slice, parses);
157 }
158 if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null;
159 const parsed = getRenderablePatch(slice.patch, cacheKey, {
160 compactPartialHunkOffsets: true,
161 ignoreWhitespace,
162 });
163 parses.set(cacheKey, parsed);
164 return parsed;
165}
166
167interface FileViewedToggleState {
168 readonly enabled: boolean;
169 readonly isViewed: (path: string) => boolean;
170 readonly isStale: (path: string) => boolean;
171 readonly setFileViewed: (fileKey: string, path: string, viewed: boolean) => void;
172}
173
174// Header portals are memoized on the render props; the viewed toggle reads its state through
175// context so a press redraws the toggles, not every header on screen.
176const FileViewedToggleContext = createContext<FileViewedToggleState | null>(null);
177
178function FileViewedToggle({
179 fileKey,
180 path,
181 stat,
182}: {
183 readonly fileKey: string;
184 readonly path: string;
185 readonly stat: ReactNode;
186}) {
187 const viewedFiles = use(FileViewedToggleContext);
188 if (viewedFiles === null || !viewedFiles.enabled) return stat;
189 const viewed = viewedFiles.isViewed(path);
190 const stale = viewedFiles.isStale(path);
191 return (
192 <span className="flex items-center gap-3">
193 {stat}
194 <label
195 data-viewed-toggle=""
196 className="flex cursor-pointer select-none items-center gap-1.5 text-2xs text-muted-foreground"
197 onClick={(event) => event.stopPropagation()}
198 >
199 <Checkbox
200 aria-label={stale ? "Changed" : "Viewed"}
201 checked={viewed}
202 onCheckedChange={(next) => viewedFiles.setFileViewed(fileKey, path, next === true)}
203 />
204 {stale ? (
205 <Tooltip>
206 <TooltipTrigger render={<span className="text-warning-foreground" />}>
207 Changed
208 </TooltipTrigger>
209 <TooltipPopup side="bottom">
210 This file has been pushed to since you marked it viewed.
211 </TooltipPopup>
212 </Tooltip>
213 ) : (
214 <span className="@max-xs:hidden">Viewed</span>
215 )}
216 </label>
217 </span>
218 );
219}
220
221interface MutableAnnotationGroup {
222 readonly side: PullRequestDiffSide;
223 readonly line: number;
224 readonly threads: PullRequestReviewThread[];
225 readonly pending: PendingReviewComment[];
226 draft: boolean;
227}
228
229interface DraftAnchor {
230 readonly fileKey: string;
231 readonly path: string;
232 readonly oldPath: string | null;
233 readonly position: PullRequestReviewPosition;
234 readonly range: SelectedLineRange;
235}
236
237export interface PullRequestAgentSelectionInput {
238 readonly comment: ReviewCommentContext;
239 readonly request: string;
240}
241
242function PullRequestCodeTab({
243 scrollerRef,
244 environmentId,
245 reference,
246 detail,
247 selectedCommitOid,
248 onSelectedCommitChange,
249 pendingFinding,
250 fixFindingLabel = "Fix in a thread",
251 onFixFinding,
252 onAddToAgentSelection,
253 onRefresh,
254 refreshToken = 0,
255 revealRequest = null,
256}: {
257 scrollerRef: (node: HTMLDivElement | null) => void;
258 environmentId: EnvironmentId;
259 reference: PullRequestRef;
260 detail: PullRequestDetailView;
261 selectedCommitOid: string | null;
262 onSelectedCommitChange: (oid: string | null) => void;
263 pendingFinding?: string | null;
264 fixFindingLabel?: string;
265 onFixFinding?: (finding: PullRequestFinding) => void;
266 onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
267 onRefresh: () => void;
268 refreshToken?: number;
269 revealRequest?: { readonly path: string; readonly nonce: number } | null;
270}) {
271 const { resolvedTheme } = useTheme();
272 const settings = useClientSettings((settings) => ({
273 diffFilesCollapsed: settings.diffFilesCollapsed,
274 diffIgnoreWhitespace: settings.diffIgnoreWhitespace,
275 diffLayout: settings.diffLayout,
276 wordWrap: settings.wordWrap,
277 }));
278 const [toggledFiles, setToggledFiles] = useState<ReadonlySet<string>>(() => new Set());
279 const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);
280 const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);
281 const effectiveFoldOverride =
282 foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded");
283 const diffLayout = settings.diffLayout;
284 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
285 const [ignoreWhitespace, setIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
286 const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
287 PULL_REQUEST_FILE_TREE_STORAGE_KEY,
288 false,
289 Schema.Boolean,
290 );
291 const [selectedLines, setSelectedLines] = useState<{
292 id: string;
293 range: SelectedLineRange;
294 } | null>(null);
295 const [draft, setDraft] = useState<DraftAnchor | null>(null);
296 const [threadPending, setThreadPending] = useState(false);
297 const [orphansOpen, setOrphansOpen] = useState(false);
298 // Which pull request the slices belong to travels with them, so a render taken before the
299 // reset below cannot read the previous one's slices — or send its cursor to the host.
300 const [sliceState, setSliceState] = useState<{
301 readonly key: string;
302 readonly cursor: string | null;
303 readonly slices: ReadonlyArray<DiffSlice>;
304 }>({ key: "", cursor: null, slices: NO_SLICES });
305 const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup, undefined> | null>(
306 null,
307 );
308
309 const referenceKey = pullRequestReviewKey(reference);
310 const commit = selectedCommitOid;
311 const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`;
312 // The panel keeps this mounted across pull requests, so an open composer would otherwise
313 // survive the switch and attach its comment to whichever one is on screen when it is sent.
314 const [stateScopeKey, setStateScopeKey] = useState(scopeKey);
315 if (stateScopeKey !== scopeKey) {
316 setStateScopeKey(scopeKey);
317 setDraft(null);
318 setSelectedLines(null);
319 setToggledFiles(new Set());
320 setFoldOverride(null);
321 setVisibleCommitCount(COMMIT_PAGE_SIZE);
322 setOrphansOpen(false);
323 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
324 }
325
326 const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES;
327 const cursor = sliceState.key === scopeKey ? sliceState.cursor : null;
328 const diffQuery = useEnvironmentQuery(
329 pullRequestEnvironment.diff({
330 environmentId,
331 input: {
332 ...reference,
333 ...(cursor === null ? {} : { cursor }),
334 ...(commit === null ? {} : { commit }),
335 },
336 }),
337 );
338 // Pages accumulate into slices as each answer arrives, so the slice list is adjusted while
339 // rendering the answer rather than one commit later.
340 const [appliedPage, setAppliedPage] = useState<{
341 readonly data: typeof diffQuery.data;
342 readonly cursor: string | null;
343 readonly scopeKey: string;
344 } | null>(null);
345 const data = diffQuery.data;
346 if (
347 data !== null &&
348 (appliedPage?.data !== data ||
349 appliedPage.cursor !== cursor ||
350 appliedPage.scopeKey !== scopeKey)
351 ) {
352 setAppliedPage({ data, cursor, scopeKey });
353 setSliceState((previous) => {
354 const slices = previous.key === scopeKey ? previous.slices : NO_SLICES;
355 const next = {
356 cursor,
357 patch: data.patch,
358 truncated: data.truncated,
359 nextCursor: data.nextCursor,
360 omittedFileStats: data.omittedFileStats ?? [],
361 };
362 const index = slices.findIndex((slice) => slice.cursor === cursor);
363 if (index === -1) {
364 return { key: scopeKey, cursor, slices: [...slices, next] };
365 }
366 const existing = slices[index];
367 if (
368 existing !== undefined &&
369 existing.patch === next.patch &&
370 existing.truncated === next.truncated &&
371 existing.nextCursor === next.nextCursor &&
372 existing.omittedFileStats.length === next.omittedFileStats.length &&
373 existing.omittedFileStats.every((file, index) => {
374 const refreshed = next.omittedFileStats[index];
375 return (
376 refreshed !== undefined &&
377 refreshed.path === file.path &&
378 refreshed.additions === file.additions &&
379 refreshed.deletions === file.deletions
380 );
381 })
382 ) {
383 return previous;
384 }
385 // A page that came back different means the diff moved under the review. The slices
386 // after it go with the replacement: their cursors were positions in the old diff.
387 return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] };
388 });
389 }
390 const refreshFirstDiffPage = useAtomRefresh(
391 pullRequestEnvironment.diff({
392 environmentId,
393 input: { ...reference, ...(commit === null ? {} : { commit }) },
394 }),
395 );
396 const reviewKey = referenceKey;
397 const pendingComments = usePendingReviewComments(reference);
398 const addComment = usePullRequestReviewStore((store) => store.addComment);
399 const removeComment = usePullRequestReviewStore((store) => store.removeComment);
400 const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, {
401 reportFailure: false,
402 });
403 const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
404 reportFailure: false,
405 });
406 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
407 reportFailure: false,
408 });
409 const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, {
410 reportFailure: false,
411 });
412 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
413
414 const viewedFilesStore = detail.capabilities.viewedFiles;
415 const filesViewed = usePullRequestFilesViewed({
416 environmentId,
417 reference,
418 enabled: viewedFilesStore !== undefined,
419 });
420 const {
421 setViewed,
422 refresh: refreshFilesViewed,
423 enabled: filesViewedEnabled,
424 isViewed: isFileViewed,
425 isStale: isFileViewedStale,
426 } = filesViewed;
427 const appliedRefreshToken = useRef(refreshToken);
428 useEffect(() => {
429 if (appliedRefreshToken.current === refreshToken) return;
430 appliedRefreshToken.current = refreshToken;
431 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
432 refreshFirstDiffPage();
433 refreshFilesViewed();
434 }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
435
436 // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
437 // an effect reading a ref could run before that node exists and would never arm the observer.
438 const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
439 const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
440 const answeredReveal = useRef<number | null>(null);
441
442 const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
443 environmentId,
444 reference,
445 commit,
446 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
447 });
448 const hostReview = detail.capabilities.review;
449 const review = {
450 inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
451 reply: hostReview.reply && detail.viewerPermissions.comment,
452 resolve: hostReview.resolve && detail.viewerPermissions.resolve,
453 };
454 const canCommentOnLines = review.inlineComment && commit === null;
455 // The cache key carries the theme, which is what the tokenizer caches against, so a theme
456 // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page
457 // reuses its cursor, and a key of position alone would hand back the parse it replaced.
458 const parsedSlices = loadedSlices.map((slice) =>
459 parseSlice(
460 slice,
461 `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,
462 ignoreWhitespace,
463 ),
464 );
465 const files = parsedSlices.flatMap((parsed) =>
466 parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
467 );
468 const filePaths = files.map((file) => resolveFileDiffPath(file));
469 const omittedFileStats = new Map(
470 loadedSlices.flatMap((slice) =>
471 slice.omittedFileStats.map((file) => [file.path, file] as const),
472 ),
473 );
474 const sourceFileStats = new Map(
475 parsedSlices.flatMap((parsed) =>
476 parsed?.kind === "files"
477 ? parsed.files.map(
478 (file, index) =>
479 [
480 buildFileDiffRenderKey(file),
481 getDiffLineStat([parsed.sourceFiles[index] ?? file]),
482 ] as const,
483 )
484 : [],
485 ),
486 );
487 const fileTreeEntries = diffFileTreeEntries(files);
488 // Placing a conversation takes more than its file being in the diff: its line has to fall
489 // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
490 // off-diff list rather than disappearing between the two.
491 const placedThreadIds = (() => {
492 const placed = new Set<string>();
493 // A commit's diff counts lines within that commit; a review comment is anchored to the
494 // pull request's head diff. Pinning one onto the other would put the remark against
495 // whichever code happens to hold that line number in this commit, so while a commit is on
496 // screen every conversation is listed rather than placed.
497 if (commit !== null) return placed;
498 for (const file of files) {
499 const path = resolveFileDiffPath(file);
500 for (const thread of detail.reviewThreads) {
501 if (
502 thread.path === path &&
503 thread.line !== null &&
504 isLineInFileDiff(file, thread.side, thread.line)
505 ) {
506 placed.add(thread.id);
507 }
508 }
509 }
510 return placed;
511 })();
512
513 const annotatedFiles = files.map((fileDiff) => {
514 const fileKey = buildFileDiffRenderKey(fileDiff);
515 const path = resolveFileDiffPath(fileDiff);
516 const groups = new Map<string, MutableAnnotationGroup>();
517 const groupAt = (side: PullRequestDiffSide, line: number) => {
518 const key = `${side}:${line}`;
519 const existing = groups.get(key);
520 if (existing) return existing;
521 const created: MutableAnnotationGroup = {
522 side,
523 line,
524 threads: [],
525 pending: [],
526 draft: false,
527 };
528 groups.set(key, created);
529 return created;
530 };
531
532 for (const thread of detail.reviewThreads) {
533 if (thread.path !== path || thread.line === null) continue;
534 if (!placedThreadIds.has(thread.id)) continue;
535 groupAt(thread.side, thread.line).threads.push(thread);
536 }
537 if (commit === null) {
538 for (const comment of pendingComments) {
539 if (comment.path !== path) continue;
540 const anchor = getReviewPositionAnchor(comment.position);
541 groupAt(anchor.side, anchor.line).pending.push(comment);
542 }
543 }
544 if (draft?.fileKey === fileKey) {
545 const anchor = getReviewPositionAnchor(draft.position);
546 groupAt(anchor.side, anchor.line).draft = true;
547 }
548
549 const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
550 side: toViewerSide(group.side),
551 lineNumber: group.line,
552 metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
553 }));
554 return {
555 fileKey,
556 path,
557 fileDiff,
558 annotations,
559 // The viewer re-renders an item only when its version changes, so everything the
560 // annotations show has to be part of it.
561 annotationsVersion: fnv1a32(
562 annotations
563 .map(
564 ({ side, lineNumber, metadata }) =>
565 `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
566 .map((comment) => `${comment.id}:${comment.body}`)
567 .join(",")}:${metadata.threads
568 .map(
569 (thread) =>
570 `${thread.id}:${thread.isResolved ? "r" : ""}:${
571 thread.isOutdated ? "o" : ""
572 }:${thread.comments
573 .map(
574 (comment) =>
575 `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
576 comment.reactions ?? []
577 )
578 .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`)
579 .join(",")}`,
580 )
581 .join(";")}`,
582 )
583 .join(",")}`,
584 )
585 .join("|"),
586 ),
587 };
588 });
589
590 const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
591 const withheldContent =
592 loadedSlices.some((slice) => slice.truncated) ||
593 parsedSlices.some((parsed) => parsed?.kind === "raw");
594 // Only once the diff is whole: returning here while a cursor is outstanding would take the
595 // sentinel off screen and end the walk, leaving the rest of the change unasked for.
596 const rawSlices =
597 nextCursor === null
598 ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
599 : [];
600 const rawSlicesView =
601 files.length === 0 && rawSlices.length > 0 ? (
602 <div className="space-y-4 px-4 py-5">
603 {rawSlices.map((slice) => (
604 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
605 <p className="text-xs text-muted-foreground">{slice.reason}</p>
606 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
607 </div>
608 ))}
609 </div>
610 ) : null;
611 const unstructured =
612 rawSlices.length === 0 ? null : (
613 <div className="space-y-4 border-t border-border/60 px-4 py-5">
614 {rawSlices.map((slice) => (
615 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
616 <p className="text-xs text-muted-foreground">{slice.reason}</p>
617 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
618 </div>
619 ))}
620 </div>
621 );
622
623 const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
624 ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
625 const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
626 const viewedMark = filesViewedEnabled
627 ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
628 : "";
629 return {
630 id: fileKey,
631 type: "diff" as const,
632 fileDiff,
633 annotations,
634 collapsed,
635 version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
636 };
637 },
638 );
639 const fileKeys = items.map((item) => item.id);
640 const collapsedFileKeys = new Set(
641 items.filter((item) => item.collapsed === true).map((item) => item.id),
642 );
643 const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);
644
645 // A failed slice must not be asked for again on its own. The files already loaded keep the
646 // sentinel on screen, so re-arming it after a failure would request the same slice forever.
647 const canLoadNextSlice =
648 nextCursor !== null &&
649 nextCursor !== cursor &&
650 !diffQuery.isPending &&
651 diffQuery.error === null;
652 const loadNextSlice = () => {
653 if (nextCursor === null) return;
654 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
655 };
656
657 const toggleFile = (fileKey: string) =>
658 setToggledFiles((current) => {
659 const next = new Set(current);
660 if (next.has(fileKey)) next.delete(fileKey);
661 else next.add(fileKey);
662 return next;
663 });
664
665 const setFileViewed = (fileKey: string, path: string, viewed: boolean) => {
666 setViewed(path, viewed);
667 setToggledFiles((current) =>
668 toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current),
669 );
670 };
671 const fileViewedToggle = {
672 enabled: filesViewedEnabled,
673 isViewed: isFileViewed,
674 isStale: isFileViewedStale,
675 setFileViewed,
676 };
677
678 const revealFile = (path: string) => {
679 const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
680 if (item === undefined) return;
681 if (item.collapsed === true) toggleFile(item.id);
682 requestTreeReveal(item.id);
683 };
684
685 const toggleAllFiles = () => {
686 setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
687 setToggledFiles(new Set());
688 };
689
690 const orderedCommits = // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits
691 // from different zones would sort by how they were written rather than when they landed.
692 detail.commits.toSorted(
693 (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
694 );
695
696 const beginComment = (
697 range: SelectedLineRange | null,
698 context: { item: CodeViewItem<ReviewAnnotationGroup> },
699 ) => {
700 if (!range || !canCommentOnLines) return;
701 const item = context.item;
702 if (item.type !== "diff") return;
703 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
704 if (!file) return;
705 // A range collapses to its last line: only GitHub carries a multi-line comment, and one
706 // that silently lost its first line on the other hosts would be worse than one line.
707 const path = resolveFileDiffPath(file);
708 const previousPath = resolveFileDiffPreviousPath(file);
709 const sourceFile = parsedSlices
710 .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : []))
711 .find((candidate) => resolveFileDiffPath(candidate) === path);
712 const side = range.endSide ?? range.side;
713 const position =
714 (sourceFile && resolveDiffReviewPosition(sourceFile, range.end, side)) ??
715 resolveDiffReviewPosition(file, range.end, side);
716 if (position === null) return;
717 setDraft({
718 fileKey: item.id,
719 path,
720 oldPath: previousPath === path ? null : previousPath,
721 position,
722 range,
723 });
724 };
725
726 const finishSelection = (
727 anchor: DraftAnchor,
728 text: string,
729 onFinish: (comment: ReviewCommentContext) => void,
730 ) => {
731 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
732 const comment =
733 file === undefined
734 ? null
735 : buildDiffReviewComment({
736 id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
737 sectionId: `pull-request:${detail.number}`,
738 sectionTitle: `PR #${detail.number} review`,
739 filePath: anchor.path,
740 fileDiff: file,
741 range: anchor.range,
742 text,
743 });
744 setDraft(null);
745 setSelectedLines(null);
746 if (comment !== null) onFinish(comment);
747 };
748
749 // The viewer's SlotPortals memoizes each visible file's header/annotation portal on these
750 // render props and on `options` below; a fresh identity on any of them — as a plain inline
751 // function or object literal would be — invalidates that memo and recreates every portal on
752 // screen on any tab re-render (a drag-selection, a keystroke in the draft, a review-store
753 // update), which is the jank this file is otherwise clean of.
754 const renderCodeViewFooter = () =>
755 nextCursor === null ? null : (
756 <div
757 ref={setSentinel}
758 className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
759 >
760 {diffQuery.error !== null ? (
761 <>
762 <span>The rest of this diff could not be loaded.</span>
763 <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
764 Retry
765 </Button>
766 </>
767 ) : diffQuery.isPending ? (
768 "Loading more files..."
769 ) : null}
770 </div>
771 );
772
773 const renderHeaderPrefix = (item: CodeViewItem<ReviewAnnotationGroup>) => {
774 const collapsed = item.collapsed === true;
775 return (
776 <Button
777 size="icon-micro"
778 variant="ghost-muted"
779 aria-expanded={!collapsed}
780 aria-label={collapsed ? "Expand diff" : "Collapse diff"}
781 className="mr-1"
782 onClick={(event) => {
783 event.stopPropagation();
784 toggleFile(item.id);
785 }}
786 >
787 <MorphIcon className="size-4" icon={collapsed ? ChevronRight : ChevronDown} />
788 </Button>
789 );
790 };
791
792 const renderHeaderMetadata = (item: CodeViewItem<ReviewAnnotationGroup>) => {
793 if (item.type !== "diff") return null;
794 let { additions, deletions } = sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]);
795 const path = resolveFileDiffPath(item.fileDiff);
796 if (additions === 0 && deletions === 0) {
797 const withheld = omittedFileStats.get(path);
798 if (withheld) ({ additions, deletions } = withheld);
799 }
800 return (
801 <FileViewedToggle
802 fileKey={item.id}
803 path={path}
804 stat={
805 <PullRequestDiffStat
806 additions={additions}
807 deletions={deletions}
808 className="font-mono text-2xs"
809 />
810 }
811 />
812 );
813 };
814
815 const diffViewOptions = {
816 diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
817 lineDiffType: "none" as const,
818 overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
819 theme: resolveDiffThemeName(resolvedTheme),
820 preferredHighlighter: PREFERRED_HIGHLIGHTER,
821 themeType: resolvedTheme,
822 stickyHeaders: true,
823 loadDiffFiles,
824 enableGutterUtility: canCommentOnLines && draft === null,
825 enableLineSelection: canCommentOnLines && draft === null,
826 onGutterUtilityClick: beginComment,
827 onLineSelectionEnd: beginComment,
828 };
829
830 const runThreadCommand = async (
831 label: string,
832 run: () => Promise<{ readonly _tag: string }>,
833 ): Promise<boolean> => {
834 if (threadPending) return false;
835 setThreadPending(true);
836 const result = await run();
837 setThreadPending(false);
838 if (result._tag === "Failure") {
839 toastManager.add({ type: "error", title: label });
840 return false;
841 }
842 onRefresh();
843 return true;
844 };
845
846 const renderThreadCard = (thread: PullRequestReviewThread) => (
847 <ReviewThreadCard
848 // Named with the pull request too: a thread's id is the host's own, and two pull requests
849 // can hand out the same one — which would leave one card's open editor standing over the
850 // other's conversation.
851 key={`${reference.projectId}#${reference.number}:${thread.id}`}
852 thread={thread}
853 workspaceRoot={detail.workspaceRoot}
854 canReply={review.reply}
855 canResolve={review.resolve && canResolvePullRequestThread(detail, thread)}
856 canReact={detail.capabilities.reactions === true}
857 environmentId={environmentId}
858 reference={reference}
859 pending={threadPending}
860 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
861 fixLabel={fixFindingLabel}
862 {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
863 onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
864 const result = await loadThreadComments({
865 environmentId,
866 input: { ...reference, threadId: thread.id, cursor },
867 });
868 if (result._tag === "Failure") {
869 toastManager.add({
870 type: "error",
871 title: "More comments could not be loaded",
872 });
873 return null;
874 }
875 return result.value;
876 }}
877 onReply={(body) =>
878 runThreadCommand("Reply could not be posted", () =>
879 replyToThread({
880 environmentId,
881 input: { ...reference, threadId: thread.id, body },
882 }),
883 )
884 }
885 canEditComment={(comment) =>
886 canEditPullRequestComment(detail, {
887 author: comment.author,
888 kind: "review-comment",
889 canEdit: comment.canEdit,
890 })
891 }
892 onEditComment={(commentId, body) =>
893 runThreadCommand("The comment could not be saved", () =>
894 updateComment({
895 environmentId,
896 input: { ...reference, commentId, kind: "review-comment", body },
897 }),
898 )
899 }
900 onToggleResolved={() =>
901 void runThreadCommand("The conversation could not be updated", () =>
902 setThreadResolution({
903 environmentId,
904 input: { ...reference, threadId: thread.id, resolved: !thread.isResolved },
905 }),
906 )
907 }
908 onReacted={onRefresh}
909 />
910 );
911
912 const renderAnnotation = (annotation: ReviewAnnotation) => (
913 <div className="py-1 font-sans text-foreground">
914 {annotation.metadata.threads.map(renderThreadCard)}
915 {annotation.metadata.pending.map((comment) => (
916 <PendingReviewCommentCard
917 key={comment.id}
918 comment={comment}
919 onRemove={() => removeComment(reviewKey, comment.id)}
920 />
921 ))}
922 {annotation.metadata.draft && draft ? (
923 <DiffCommentAnnotation
924 kind="draft"
925 rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
926 text=""
927 submitLabel="Add to review"
928 {...(onAddToAgentSelection
929 ? {
930 secondaryAction: {
931 label: "Add to agent",
932 onAction: (text: string) =>
933 finishSelection(draft, text, (comment) =>
934 onAddToAgentSelection({ comment, request: text }),
935 ),
936 },
937 }
938 : {})}
939 onCancel={() => {
940 setDraft(null);
941 setSelectedLines(null);
942 }}
943 onComment={(body) => {
944 addComment(reviewKey, {
945 id: nextPendingReviewCommentId(),
946 path: draft.path,
947 ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),
948 position: draft.position,
949 body,
950 });
951 setDraft(null);
952 setSelectedLines(null);
953 }}
954 />
955 ) : null}
956 </div>
957 );
958
959 // A rebase or a force-push can take the scoped commit out of the change. Its diff may still
960 // be reachable on the host, but it is no longer part of what is being reviewed, so the scope
961 // goes back to the whole change rather than sitting under a name nothing matches.
962 // Including when the change reports no commits at all: the scope dropdown is the only way back
963 // to the whole diff and it is not drawn without commits to list, so a scope that outlived them
964 // would leave the tab reading one obsolete commit with nothing to press.
965 const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
966 const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
967 const changeIgnoreWhitespace = (next: boolean) => {
968 setIgnoreWhitespace(next);
969 setDraft(null);
970 setSelectedLines(null);
971 };
972 const toolbar = (
973 <div className="@container 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">
974 <div className="flex min-w-0 flex-1 items-center gap-3">
975 {orderedCommits.length > 0 ? (
976 <DropdownMenu>
977 <DropdownMenuTrigger
978 render={<Button size="xs" variant="secondary" />}
979 className="min-w-0 max-w-64"
980 aria-label={`Diff scope: ${scopeLabel}`}
981 >
982 <span className="truncate">{scopeLabel}</span>
983 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
984 </DropdownMenuTrigger>
985 <DropdownMenuContent align="start" className="max-w-[min(28rem,calc(100vw-2rem))]">
986 <DropdownMenuRadioGroup
987 value={commit ?? "all"}
988 onValueChange={(value) => onSelectedCommitChange(value === "all" ? null : value)}
989 >
990 <DropdownMenuRadioItem value="all" closeOnClick>
991 <span>All commits</span>
992 </DropdownMenuRadioItem>
993 {orderedCommits.slice(0, visibleCommitCount).map((entry) => (
994 <DropdownMenuRadioItem key={entry.oid} value={entry.oid} closeOnClick>
995 <span className="flex items-center gap-2">
996 <Tooltip>
997 <TooltipTrigger
998 render={<span className="min-w-0 truncate">{entry.messageHeadline}</span>}
999 />
1000 <TooltipPopup side="top">{entry.messageHeadline}</TooltipPopup>
1001 </Tooltip>
1002 <span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground">
1003 {entry.oid.slice(0, 7)}
1004 </span>
1005 </span>
1006 </DropdownMenuRadioItem>
1007 ))}
1008 </DropdownMenuRadioGroup>
1009 {orderedCommits.length > visibleCommitCount ? (
1010 <DropdownMenuItem
1011 closeOnClick={false}
1012 onClick={() => setVisibleCommitCount((count) => count + COMMIT_PAGE_SIZE)}
1013 >
1014 <span className="text-muted-foreground">
1015 Show more ({orderedCommits.length - visibleCommitCount} left)
1016 </span>
1017 </DropdownMenuItem>
1018 ) : null}
1019 </DropdownMenuContent>
1020 </DropdownMenu>
1021 ) : null}
1022 <PullRequestMetaLine>
1023 <span className="shrink-0 tabular-nums">
1024 {files.length} {files.length === 1 ? "file" : "files"}
1025 {nextCursor === null ? "" : "+"}
1026 </span>
1027 {filesViewed.enabled && files.length > 0 ? (
1028 <span className="flex min-w-0 items-center gap-1 tabular-nums">
1029 <span className="shrink-0">
1030 {filePaths.filter(isFileViewed).length} / {files.length}
1031 </span>
1032 <span className="truncate">
1033 {viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"}
1034 </span>
1035 {viewedFilesStore === "environment" ? (
1036 <Tooltip>
1037 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1038 <InfoIcon
1039 aria-label="These ticks are kept here, not on the host"
1040 className="text-muted-foreground size-3.5"
1041 />
1042 </TooltipTrigger>
1043 <TooltipPopup side="bottom">
1044 This host keeps no shared record of which files you have read, so these ticks
1045 are kept by this environment. They follow you between the apps connected to it,
1046 but the host's own web UI will not show them.
1047 </TooltipPopup>
1048 </Tooltip>
1049 ) : null}
1050 {filesViewed.error !== null ? (
1051 <Tooltip>
1052 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1053 <TriangleAlertIcon
1054 aria-label="Your ticks could not be read"
1055 className="size-3.5 text-warning-foreground"
1056 />
1057 </TooltipTrigger>
1058 <TooltipPopup side="bottom">
1059 The boxes below are whatever was last read, and empty if nothing has been read
1060 yet. {filesViewed.error}
1061 </TooltipPopup>
1062 </Tooltip>
1063 ) : null}
1064 {filesViewed.truncated ? (
1065 <Tooltip>
1066 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1067 <TriangleAlertIcon
1068 aria-label="This count covers only part of the change"
1069 className="size-3.5 text-warning-foreground"
1070 />
1071 </TooltipTrigger>
1072 <TooltipPopup side="bottom">
1073 This change has more files than the host will report ticks for in one read, so
1074 the count is short and some boxes below start empty.
1075 </TooltipPopup>
1076 </Tooltip>
1077 ) : null}
1078 </span>
1079 ) : null}
1080 {withheldContent ? (
1081 <Tooltip>
1082 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1083 <TriangleAlertIcon
1084 aria-label="Some of this diff was not shown"
1085 className="size-3.5 text-warning-foreground"
1086 />
1087 </TooltipTrigger>
1088 <TooltipPopup side="bottom">
1089 The host withheld part of this diff — a binary file, or a change too large to
1090 inline.
1091 </TooltipPopup>
1092 </Tooltip>
1093 ) : null}
1094 {commit !== null && review.inlineComment ? (
1095 <Tooltip>
1096 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1097 <MessageSquareOffIcon
1098 aria-label="Line comments are written from the whole change"
1099 className="size-3.5"
1100 />
1101 </TooltipTrigger>
1102 <TooltipPopup side="bottom">
1103 A comment is anchored to the whole change, so switch to All commits to write one.
1104 </TooltipPopup>
1105 </Tooltip>
1106 ) : null}
1107 </PullRequestMetaLine>
1108 </div>
1109 <div className="flex shrink-0 items-center gap-1">
1110 <DropdownMenu>
1111 <Tooltip>
1112 <TooltipTrigger
1113 render={
1114 <DropdownMenuTrigger
1115 render={<Button size="icon-sm" variant="ghost" />}
1116 className="@lg:hidden"
1117 aria-label="Diff options"
1118 />
1119 }
1120 >
1121 <Settings2Icon className="size-3.5" />
1122 </TooltipTrigger>
1123 <TooltipPopup side="top">Diff options</TooltipPopup>
1124 </Tooltip>
1125 <DropdownMenuContent align="end">
1126 <DropdownMenuCheckboxItem
1127 checked={ignoreWhitespace}
1128 onCheckedChange={(checked) => changeIgnoreWhitespace(checked)}
1129 >
1130 Hide whitespace changes
1131 </DropdownMenuCheckboxItem>
1132 <DropdownMenuCheckboxItem
1133 checked={wordWrap}
1134 onCheckedChange={(checked) => setWordWrap(checked)}
1135 >
1136 Wrap lines
1137 </DropdownMenuCheckboxItem>
1138 <DropdownMenuSeparator />
1139 <DropdownMenuRadioGroup
1140 value={diffLayout}
1141 onValueChange={(value) => {
1142 if (value === "stacked" || value === "split") {
1143 updateClientSettings({ diffLayout: value });
1144 }
1145 }}
1146 >
1147 <DropdownMenuRadioItem value="stacked" closeOnClick>
1148 Stacked
1149 </DropdownMenuRadioItem>
1150 <DropdownMenuRadioItem value="split" closeOnClick>
1151 Split
1152 </DropdownMenuRadioItem>
1153 </DropdownMenuRadioGroup>
1154 </DropdownMenuContent>
1155 </DropdownMenu>
1156 <div className="hidden items-center gap-1 @lg:flex">
1157 <Tooltip>
1158 <TooltipTrigger
1159 render={
1160 <Toggle
1161 aria-label={
1162 ignoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
1163 }
1164 variant="ghost"
1165 size="sm"
1166 pressed={ignoreWhitespace}
1167 onPressedChange={(pressed) => changeIgnoreWhitespace(Boolean(pressed))}
1168 />
1169 }
1170 >
1171 <PilcrowIcon className="size-3.5" />
1172 </TooltipTrigger>
1173 <TooltipPopup side="top">
1174 {ignoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
1175 </TooltipPopup>
1176 </Tooltip>
1177 <ToggleGroup
1178 aria-label="Diff layout"
1179 className="shrink-0"
1180 variant="segmented"
1181 value={[diffLayout]}
1182 onValueChange={(value) => {
1183 const next = value[0];
1184 if (next === "stacked" || next === "split") {
1185 updateClientSettings({ diffLayout: next });
1186 }
1187 }}
1188 >
1189 <Toggle aria-label="Stacked diff view" value="stacked">
1190 <Rows3Icon className="size-3.5" />
1191 </Toggle>
1192 <Toggle aria-label="Split diff view" value="split">
1193 <Columns2Icon className="size-3.5" />
1194 </Toggle>
1195 </ToggleGroup>
1196 <Tooltip>
1197 <TooltipTrigger
1198 render={
1199 <Toggle
1200 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1201 variant="ghost"
1202 size="sm"
1203 pressed={wordWrap}
1204 onPressedChange={(pressed) => {
1205 setWordWrap(Boolean(pressed));
1206 }}
1207 />
1208 }
1209 >
1210 <TextWrapIcon className="size-3.5" />
1211 </TooltipTrigger>
1212 <TooltipPopup side="top">
1213 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1214 </TooltipPopup>
1215 </Tooltip>
1216 </div>
1217 {fileKeys.length > 0 ? (
1218 <Tooltip>
1219 <TooltipTrigger
1220 render={
1221 <Button
1222 type="button"
1223 size="icon-sm"
1224 variant="ghost"
1225 aria-label={allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1226 onClick={toggleAllFiles}
1227 />
1228 }
1229 >
1230 <MorphIcon
1231 className="size-3.5"
1232 icon={allFilesCollapsed ? ChevronsUpDown : ChevronsDownUp}
1233 />
1234 </TooltipTrigger>
1235 <TooltipPopup side="top">
1236 {allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1237 </TooltipPopup>
1238 </Tooltip>
1239 ) : null}
1240 {fileKeys.length > 0 ? (
1241 <Tooltip>
1242 <TooltipTrigger
1243 render={
1244 <Toggle
1245 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
1246 variant="ghost"
1247 size="sm"
1248 pressed={fileTreeOpen}
1249 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
1250 />
1251 }
1252 >
1253 <FolderTreeIcon className="size-3.5" />
1254 </TooltipTrigger>
1255 <TooltipPopup side="top">
1256 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
1257 </TooltipPopup>
1258 </Tooltip>
1259 ) : null}
1260 </div>
1261 </div>
1262 );
1263 // The effects sit after every derivation: a hook between the diff's derivations and their
1264 // later readers (the viewer options, the reveal handler) would leave them uncached.
1265 useEffect(() => {
1266 if (sentinel === null || !canLoadNextSlice) return;
1267 const observer = new IntersectionObserver(
1268 (observed) => {
1269 if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
1270 },
1271 { rootMargin: "240px" },
1272 );
1273 observer.observe(sentinel);
1274 return () => observer.disconnect();
1275 }, [canLoadNextSlice, loadNextSlice, sentinel]);
1276 const answerReveal = useEffectEvent(() => {
1277 if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
1278 if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
1279 if (canLoadNextSlice) loadNextSlice();
1280 return;
1281 }
1282 answeredReveal.current = revealRequest.nonce;
1283 revealFile(revealRequest.path);
1284 });
1285 useEffect(() => {
1286 // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
1287 answerReveal();
1288 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
1289 }, [canLoadNextSlice, items, revealRequest]);
1290 useEffect(() => {
1291 if (commit !== null && selectedCommit === undefined) {
1292 onSelectedCommitChange(null);
1293 }
1294 }, [commit, onSelectedCommitChange, selectedCommit]);
1295 const withToolbar = (body: ReactNode) => (
1296 <div className="flex h-full min-h-0 flex-col">
1297 {toolbar}
1298 <div ref={scrollerRef} className="min-h-0 flex-1 overflow-auto">
1299 {body}
1300 </div>
1301 </div>
1302 );
1303
1304 if (diffQuery.isPending && loadedSlices.length === 0) {
1305 return withToolbar(<DiffPanelLoadingState label="Loading pull request diff..." />);
1306 }
1307
1308 if (diffQuery.error && loadedSlices.length === 0) {
1309 return withToolbar(
1310 <PullRequestDiffUnavailableState
1311 error={diffQuery.error}
1312 provider={detail.provider}
1313 url={detail.url}
1314 onRetry={() => diffQuery.refresh()}
1315 />,
1316 );
1317 }
1318
1319 if (rawSlicesView !== null) {
1320 return withToolbar(rawSlicesView);
1321 }
1322
1323 if (items.length === 0 && nextCursor === null) {
1324 return withToolbar(
1325 <p className="px-4 py-5 text-sm text-muted-foreground">
1326 {commit === null
1327 ? "This pull request has no file changes."
1328 : "This commit has no file changes."}
1329 </p>,
1330 );
1331 }
1332
1333 const orphanThreads = detail.reviewThreads.filter((thread) => !placedThreadIds.has(thread.id));
1334 const orphanFiles = new Map<string, PullRequestReviewThread[]>();
1335 for (const thread of orphanThreads) {
1336 const existing = orphanFiles.get(thread.path);
1337 if (existing) existing.push(thread);
1338 else orphanFiles.set(thread.path, [thread]);
1339 }
1340
1341 return (
1342 <div className="flex h-full min-h-0 flex-col">
1343 {toolbar}
1344 {orphanFiles.size > 0 ? (
1345 <div className="shrink-0 border-b border-border/60">
1346 <Collapsible open={orphansOpen} onOpenChange={setOrphansOpen}>
1347 <h2>
1348 <CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground">
1349 <span>
1350 {nextCursor === null
1351 ? "Conversations not on the current diff"
1352 : "Conversations not on the diff loaded so far"}
1353 </span>
1354 <ChevronRightIcon
1355 aria-hidden
1356 className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")}
1357 />
1358 <span aria-hidden className="tabular-nums">
1359 {orphanThreads.length}
1360 </span>
1361 <span className="sr-only">
1362 {orphanThreads.length === 1
1363 ? "1 conversation"
1364 : `${orphanThreads.length} conversations`}
1365 </span>
1366 </CollapsibleTrigger>
1367 </h2>
1368 <CollapsiblePanel>
1369 <div className="max-h-64 space-y-3 overflow-auto px-4 pb-3">
1370 {[...orphanFiles].map(([path, threads]) => (
1371 <div key={path}>
1372 <Tooltip>
1373 <TooltipTrigger
1374 render={
1375 <p className="truncate px-3 text-xs text-muted-foreground">{path}</p>
1376 }
1377 />
1378 <TooltipPopup side="top">{path}</TooltipPopup>
1379 </Tooltip>
1380 <div className="mt-1 space-y-2">
1381 {threads.map((thread) => (
1382 <div key={thread.id}>
1383 {thread.line === null ? null : (
1384 <p className="px-3 text-xs text-muted-foreground">Line {thread.line}</p>
1385 )}
1386 {renderThreadCard(thread)}
1387 </div>
1388 ))}
1389 </div>
1390 </div>
1391 ))}
1392 </div>
1393 </CollapsiblePanel>
1394 </Collapsible>
1395 </div>
1396 ) : null}
1397 <div className="flex min-h-0 flex-1 overflow-hidden">
1398 <div
1399 className="relative min-h-0 min-w-0 flex-1"
1400 // The header lives in the viewer's shadow tree, so the capture listener walks
1401 // `composedPath` — the only way to see through the shadow boundary.
1402 onClickCapture={(event) => {
1403 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1404 for (const node of composedPath) {
1405 if (!(node instanceof HTMLElement)) continue;
1406 // A control inside the header — the collapse chevron — handles itself, and
1407 // this capture listener fires before its own click does. Leave it alone or
1408 // the two toggles cancel out.
1409 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1410 return;
1411 }
1412 if (node.hasAttribute("data-viewed-toggle")) return;
1413 if (node.hasAttribute("data-diffs-header")) {
1414 const filePath = node.querySelector("[data-title]")?.textContent?.trim();
1415 if (filePath === undefined || filePath === "") return;
1416 const item = items.find(
1417 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
1418 );
1419 if (item !== undefined) toggleFile(item.id);
1420 return;
1421 }
1422 }
1423 }}
1424 >
1425 {/* The viewer virtualizes against the element it is told is scrolling and places its
1426 rows absolutely, so it has to own that element — the thread diff panel hands it the
1427 same one. Scrolling from a parent instead leaves it painting over its neighbours. */}
1428 <FileViewedToggleContext value={fileViewedToggle}>
1429 <StyledDiffCodeView<ReviewAnnotationGroup>
1430 className="@container h-full overflow-auto [scrollbar-gutter:stable]"
1431 containerRef={scrollerRef}
1432 viewerRef={setViewer}
1433 items={items}
1434 selectedLines={selectedLines}
1435 onSelectedLinesChange={setSelectedLines}
1436 options={diffViewOptions}
1437 renderCodeViewFooter={renderCodeViewFooter}
1438 renderHeaderPrefix={renderHeaderPrefix}
1439 renderHeaderMetadata={renderHeaderMetadata}
1440 renderAnnotation={renderAnnotation}
1441 // Find can ask again before the unfolded file arrives, so this unfolds and never folds.
1442 onRevealSearchMatch={(item) =>
1443 setToggledFiles((current) =>
1444 toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
1445 )
1446 }
1447 unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1448 />
1449 </FileViewedToggleContext>
1450 </div>
1451 {fileTreeOpen ? (
1452 <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">
1453 <DiffFileTree
1454 ariaLabel={`Pull request #${detail.number} files`}
1455 entries={fileTreeEntries}
1456 onSelectFile={revealFile}
1457 footer={
1458 nextCursor === null ? null : (
1459 <div className="shrink-0 border-t border-border/60 p-2">
1460 <Button
1461 type="button"
1462 size="xs"
1463 variant="outline"
1464 className="w-full"
1465 disabled={diffQuery.isPending}
1466 onClick={diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice}
1467 >
1468 {diffQuery.error !== null
1469 ? "Retry"
1470 : diffQuery.isPending
1471 ? "Loading more files..."
1472 : "Load more files"}
1473 </Button>
1474 </div>
1475 )
1476 }
1477 />
1478 </aside>
1479 ) : null}
1480 </div>
1481 {unstructured}
1482 </div>
1483 );
1484}
1485
1486export default PullRequestCodeTab;