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