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

PullRequestCodeTab.tsx

1,497 lines56.6 KB

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