Repository navigation
Expand file tree
/
Copy pathPullRequestCodeTab.tsx
More file actions
1702 lines (1647 loc) · 63.8 KB
/
Copy pathPullRequestCodeTab.tsx
File metadata and controls
1702 lines (1647 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
parsePullRequestAnchor,
pullRequestDiffPathMatches,
pullRequestLinkCommit,
} from "@t3tools/shared/pullRequestAnchor";
import {
capitalizeTerm,
sourceControlClients,
} from "@t3tools/client-runtime/source-control-clients";
import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react";
import type {
EnvironmentId,
PullRequestDetailView,
PullRequestDiffSide,
PullRequestDiffResult,
PullRequestOmittedFileStat,
PullRequestRef,
PullRequestReviewPosition,
PullRequestReviewThread,
PullRequestThreadCommentsResult,
} from "@t3tools/contracts";
import {
ChevronDownIcon,
ChevronRightIcon,
Columns2Icon,
FlaskConicalOffIcon,
FolderTreeIcon,
InfoIcon,
MessageSquareOffIcon,
PilcrowIcon,
Rows3Icon,
Settings2Icon,
TextWrapIcon,
TriangleAlertIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
} from "lucide-react";
import { useAtomRefresh } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import {
createContext,
use,
useEffect,
useEffectEvent,
useRef,
useState,
type ReactNode,
} from "react";
import { observeIntersection } from "~/lib/observeIntersection";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
import { useRenderedAppearance } from "~/hooks/useTheme";
import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
import {
pullRequestFindingKey,
type PullRequestChatSubject,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
import {
canEditPullRequestComment,
canResolvePullRequestThread,
} from "@t3tools/client-runtime/pull-request-editing";
import { isTestChangedFile } from "@t3tools/shared/changedFileKind";
import { orderDiffFiles } from "./pullRequestFileOrder.logic";
import {
buildFileDiffRenderKey,
fnv1a32,
getDiffLineStat,
getRenderablePatch,
resolveDiffThemeName,
resolveFileDiffPath,
resolveFileDiffPreviousPath,
type RenderablePatch,
} from "~/lib/diffRendering";
import { APP_BASE_NAME } from "~/branding";
import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
import { cn } from "~/lib/utils";
import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";
import {
buildDiffReviewComment,
resolveDiffReviewAnchor,
type ReviewCommentContext,
} from "~/reviewCommentContext";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { DiffPanelLoadingState } from "../DiffPanelShell";
import { useDiffWorkerPool } from "../DiffWorkerPoolProvider";
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
import { DiffFileTree } from "../diffs/DiffFileTree";
import { FileExplorerPane } from "../files/FileExplorerPane";
import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";
import { useHideTestFiles } from "../diffs/useHideTestFiles";
import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic";
import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../ui/menu";
import { toastManager } from "../ui/toast";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
getReviewPositionAnchor,
PendingReviewCommentCard,
ReviewThreadCard,
toViewerSide,
} from "./PullRequestReviewAnnotation";
import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
import {
getFileViewedRange,
isFileDiffCollapsed,
isLineInFileDiff,
withFileDiffFold,
type DiffFoldOverride,
type FileDiffFoldChoices,
} from "./pullRequestDiff.logic";
import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState";
import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
import {
nextPendingReviewCommentId,
pullRequestReviewKey,
usePendingReviewComments,
usePullRequestReviewStore,
type PendingReviewComment,
} from "./pullRequestReviewStore";
interface ReviewAnnotationGroup {
readonly threads: ReadonlyArray<PullRequestReviewThread>;
readonly pending: ReadonlyArray<PendingReviewComment>;
readonly draft: boolean;
}
type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;
const COMMIT_PAGE_SIZE = 10;
const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";
interface DiffSlice {
readonly source: PullRequestDiffResult;
readonly cursor: string | null;
readonly patch: string;
readonly truncated: boolean;
readonly nextCursor: string | null;
readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
}
// Show host counts outside the shadow root; hunk totals are zero when hosts withhold hunks.
const REPLACE_FILE_COUNTS_CSS = `
[data-diffs-header] [data-additions-count],
[data-diffs-header] [data-deletions-count] {
display: none !important;
}`;
const NO_SLICES: ReadonlyArray<DiffSlice> = [];
// Query results outlive the panel's slices, so their parses survive closing and reopening
// without retaining anything beyond the query cache's lifetime.
const sliceParses = new WeakMap<PullRequestDiffResult, Map<string, RenderablePatch | null>>();
function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) {
let parses = sliceParses.get(slice.source);
if (parses === undefined) {
parses = new Map();
sliceParses.set(slice.source, parses);
}
if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null;
const parsed = getRenderablePatch(slice.patch, cacheKey, {
compactPartialHunkOffsets: true,
ignoreWhitespace,
});
parses.set(cacheKey, parsed);
return parsed;
}
type DiffModel = {
readonly parsedSlices: ReadonlyArray<RenderablePatch | null>;
readonly loadedFiles: ReadonlyArray<Extract<RenderablePatch, { kind: "files" }>["files"][number]>;
readonly sourceFileStats: ReadonlyMap<string, ReturnType<typeof getDiffLineStat>>;
};
const diffModels = new WeakMap<ReadonlyArray<DiffSlice>, Map<string, DiffModel>>();
const patchHashes = new WeakMap<DiffSlice, number>();
// Hashing, ordering and counting every file of a huge pull request costs a second, and the tab
// renders far more often than its slices change, so the model is kept per slice list.
function diffModel(
slices: ReadonlyArray<DiffSlice>,
keyPrefix: string,
ignoreWhitespace: boolean,
): DiffModel {
let models = diffModels.get(slices);
if (models === undefined) diffModels.set(slices, (models = new Map()));
const cached = models.get(keyPrefix);
if (cached !== undefined) return cached;
const parsedSlices = slices.map((slice) => {
let hash = patchHashes.get(slice);
if (hash === undefined) patchHashes.set(slice, (hash = fnv1a32(slice.patch)));
// The cache key carries the theme, which the tokenizer caches against, and the patch's
// hash: a refreshed page reuses its cursor, so position alone would return a stale parse.
return parseSlice(slice, `${keyPrefix}:${slice.cursor ?? "first"}:${hash}`, ignoreWhitespace);
});
const model: DiffModel = {
parsedSlices,
loadedFiles: orderDiffFilesLikeTree(
parsedSlices.flatMap((parsed) =>
parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
),
),
sourceFileStats: new Map(
parsedSlices.flatMap((parsed) =>
parsed?.kind === "files"
? parsed.files.map(
(file, index) =>
[
buildFileDiffRenderKey(file),
getDiffLineStat([parsed.sourceFiles[index] ?? file]),
] as const,
)
: [],
),
),
};
models.set(keyPrefix, model);
return model;
}
const threadsByPathCache = new WeakMap<
ReadonlyArray<PullRequestReviewThread>,
ReadonlyMap<string, ReadonlyArray<PullRequestReviewThread>>
>();
function reviewThreadsByPath(threads: ReadonlyArray<PullRequestReviewThread>) {
let byPath = threadsByPathCache.get(threads);
if (byPath === undefined) {
const grouped = new Map<string, PullRequestReviewThread[]>();
for (const thread of threads) {
const list = grouped.get(thread.path);
if (list) list.push(thread);
else grouped.set(thread.path, [thread]);
}
threadsByPathCache.set(threads, (byPath = grouped));
}
return byPath;
}
interface FileViewedToggleState {
readonly enabled: boolean;
readonly isViewed: (path: string) => boolean;
readonly isStale: (path: string) => boolean;
readonly setFileViewed: (fileKey: string, viewed: boolean, extendRange: boolean) => void;
}
// Context updates viewed toggles without invalidating memoized header portals.
const FileViewedToggleContext = createContext<FileViewedToggleState | null>(null);
function FileViewedToggle({
fileKey,
path,
stat,
}: {
readonly fileKey: string;
readonly path: string;
readonly stat: ReactNode;
}) {
const viewedFiles = use(FileViewedToggleContext);
if (viewedFiles === null || !viewedFiles.enabled) return stat;
const viewed = viewedFiles.isViewed(path);
const stale = viewedFiles.isStale(path);
return (
<span className="flex items-center gap-3">
{stat}
<label
data-viewed-toggle=""
className="flex w-18 shrink-0 cursor-pointer select-none items-center gap-1.5 text-2xs text-muted-foreground"
onClick={(event) => event.stopPropagation()}
>
<Checkbox
aria-label={stale ? "Changed" : "Viewed"}
checked={viewed}
onCheckedChange={(next, details) =>
viewedFiles.setFileViewed(
fileKey,
next === true,
"shiftKey" in details.event && details.event.shiftKey === true,
)
}
/>
{stale ? (
<Tooltip>
<TooltipTrigger render={<span className="text-warning-foreground" />}>
Changed
</TooltipTrigger>
<TooltipPopup side="bottom">
This file has been pushed to since you marked it viewed.
</TooltipPopup>
</Tooltip>
) : (
<span className="@max-xs:hidden">Viewed</span>
)}
</label>
</span>
);
}
interface MutableAnnotationGroup {
readonly side: PullRequestDiffSide;
readonly line: number;
readonly threads: PullRequestReviewThread[];
readonly pending: PendingReviewComment[];
draft: boolean;
}
interface DraftAnchor {
readonly fileKey: string;
readonly path: string;
readonly oldPath: string | null;
readonly position: PullRequestReviewPosition;
readonly startPosition?: PullRequestReviewPosition;
readonly range: SelectedLineRange;
}
export interface PullRequestAgentSelectionInput {
readonly comment: ReviewCommentContext;
readonly request: string;
}
function PullRequestCodeTab({
scrollerRef,
environmentId,
reference,
detail,
selectedCommitOid,
onSelectedCommitChange,
pendingFinding,
fixFindingLabel = "Fix in a thread",
onFixFinding,
onAddToChat,
onAddToAgentSelection,
onRefresh,
refreshToken = 0,
backgroundRefreshToken = 0,
revealRequest = null,
revealUrl,
onRevealSettled,
}: {
scrollerRef: (node: HTMLDivElement | null) => void;
environmentId: EnvironmentId;
reference: PullRequestRef;
detail: PullRequestDetailView;
selectedCommitOid: string | null;
onSelectedCommitChange: (oid: string | null) => void;
pendingFinding?: string | null;
fixFindingLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
/** Absent where there is no composer beside the panel to add a conversation to. */
onAddToChat?: (subject: PullRequestChatSubject) => void;
onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
onRefresh: () => void;
refreshToken?: number;
backgroundRefreshToken?: number;
/** A clicked link to a file or line range, until onRevealSettled reports it shown. */
revealUrl?: string | undefined;
onRevealSettled?: ((revealUrl: string) => void) | undefined;
revealRequest?: { readonly path: string; readonly nonce: number } | null;
}) {
const resolvedTheme = useRenderedAppearance();
// Initialize the shared tokenizer and workers while the diff request is still pending.
useDiffWorkerPool();
const settings = useClientSettings((settings) => ({
diffFilesCollapsed: settings.diffFilesCollapsed,
diffIgnoreWhitespace: settings.diffIgnoreWhitespace,
diffLayout: settings.diffLayout,
wordWrap: settings.wordWrap,
}));
const [foldChoices, setFoldChoices] = useState<FileDiffFoldChoices>(() => new Map());
const [lastViewedFileKey, setLastViewedFileKey] = useState<string | null>(null);
const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);
const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);
const effectiveFoldOverride =
foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded");
const diffLayout = settings.diffLayout;
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const [ignoreWhitespace, setIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
PULL_REQUEST_FILE_TREE_STORAGE_KEY,
false,
Schema.Boolean,
);
const [hideTestFiles, setHideTestFiles] = useHideTestFiles();
const [selectedLines, setSelectedLines] = useState<{
id: string;
range: SelectedLineRange;
} | null>(null);
const [draft, setDraft] = useState<DraftAnchor | null>(null);
const [threadPending, setThreadPending] = useState(false);
const [orphansOpen, setOrphansOpen] = useState(false);
// Scope slices before reset to prevent using a previous pull request's data or cursor.
const [sliceState, setSliceState] = useState<{
readonly key: string;
readonly cursor: string | null;
readonly slices: ReadonlyArray<DiffSlice>;
}>({ key: "", cursor: null, slices: NO_SLICES });
const referenceKey = pullRequestReviewKey(reference);
// A commit opened from the timeline or left selected across a force-push may no longer be
// part of the pull request; read it as "All commits" instead of requesting its diff.
const commit =
selectedCommitOid !== null && detail.commits.some((entry) => entry.oid === selectedCommitOid)
? selectedCommitOid
: null;
const scopeKey = JSON.stringify([environmentId, referenceKey, commit]);
// The panel keeps this mounted across pull requests, so an open composer would otherwise
// survive the switch and attach its comment to whichever one is on screen when it is sent.
const [stateScopeKey, setStateScopeKey] = useState(scopeKey);
if (stateScopeKey !== scopeKey) {
setStateScopeKey(scopeKey);
setLastViewedFileKey(null);
setDraft(null);
setSelectedLines(null);
setFoldChoices(new Map());
setFoldOverride(null);
setVisibleCommitCount(COMMIT_PAGE_SIZE);
setOrphansOpen(false);
setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
}
const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES;
const cursor = sliceState.key === scopeKey ? sliceState.cursor : null;
const diffQuery = useEnvironmentQuery(
pullRequestEnvironment.diff({
environmentId,
input: {
...reference,
...(cursor === null ? {} : { cursor }),
...(commit === null ? {} : { commit }),
},
}),
);
const [appliedPage, setAppliedPage] = useState<{
readonly data: typeof diffQuery.data;
readonly cursor: string | null;
readonly scopeKey: string;
} | null>(null);
const data = diffQuery.data;
if (
data !== null &&
(appliedPage?.data !== data ||
appliedPage.cursor !== cursor ||
appliedPage.scopeKey !== scopeKey)
) {
setAppliedPage({ data, cursor, scopeKey });
setSliceState((previous) => {
const slices = previous.key === scopeKey ? previous.slices : NO_SLICES;
const next = {
source: data,
cursor,
patch: data.patch,
truncated: data.truncated,
nextCursor: data.nextCursor,
omittedFileStats: data.omittedFileStats ?? [],
};
const index = slices.findIndex((slice) => slice.cursor === cursor);
if (index === -1) {
return { key: scopeKey, cursor, slices: [...slices, next] };
}
const existing = slices[index];
if (
existing !== undefined &&
existing.patch === next.patch &&
existing.truncated === next.truncated &&
existing.nextCursor === next.nextCursor &&
existing.omittedFileStats.length === next.omittedFileStats.length &&
existing.omittedFileStats.every((file, index) => {
const refreshed = next.omittedFileStats[index];
return (
refreshed !== undefined &&
refreshed.path === file.path &&
refreshed.additions === file.additions &&
refreshed.deletions === file.deletions
);
})
) {
return previous;
}
// Drop later slices when replacing a changed page; their cursors target the old diff.
return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] };
});
}
const refreshFirstDiffPage = useAtomRefresh(
pullRequestEnvironment.diff({
environmentId,
input: { ...reference, ...(commit === null ? {} : { commit }) },
}),
);
const reviewKey = referenceKey;
const pendingComments = usePendingReviewComments(reference);
const addComment = usePullRequestReviewStore((store) => store.addComment);
const removeComment = usePullRequestReviewStore((store) => store.removeComment);
const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, {
reportFailure: false,
});
const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
reportFailure: false,
});
const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
reportFailure: false,
});
const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, {
reportFailure: false,
});
const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
const viewedFilesStore = detail.capabilities.viewedFiles;
const filesViewed = usePullRequestFilesViewed({
environmentId,
reference,
enabled: viewedFilesStore !== undefined,
});
const {
setViewed,
refresh: refreshFilesViewed,
enabled: filesViewedEnabled,
isViewed: isFileViewed,
isStale: isFileViewedStale,
} = filesViewed;
const appliedRefreshToken = useRef(refreshToken);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new refresh token clears loaded slices and refetches the first diff page and viewed files
useEffect(() => {
if (appliedRefreshToken.current === refreshToken) return;
appliedRefreshToken.current = refreshToken;
setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
// An equal refetch keeps the answer's identity, so the emptied slices refill only if the
// applied page is forgotten too.
setAppliedPage(null);
refreshFirstDiffPage();
refreshFilesViewed();
}, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
const appliedBackgroundRefreshToken = useRef(backgroundRefreshToken);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a background refresh token refetches the first diff page and viewed files while keeping slices
useEffect(() => {
if (appliedBackgroundRefreshToken.current === backgroundRefreshToken) return;
appliedBackgroundRefreshToken.current = backgroundRefreshToken;
// Keeping slices mounted preserves scroll; the page merge invalidates changed pages.
setSliceState((previous) => ({ ...previous, cursor: null }));
refreshFirstDiffPage();
refreshFilesViewed();
}, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]);
const codeViewReveal = useCodeViewFileReveal();
const answeredRevealNonce = useRef<number | null>(null);
const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
environmentId,
reference,
commit,
cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
});
const completionScope = pullRequestCompletionScope(detail, environmentId, reference);
const hostReview = detail.capabilities.review;
const review = {
inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
reply: hostReview.reply && detail.viewerPermissions.comment,
resolve: hostReview.resolve && detail.viewerPermissions.resolve,
};
const canCommentOnLines = review.inlineComment && commit === null;
const rangeComments = hostReview.rangeComment === true;
// Agent context is local, so it does not require host comment permission.
const canSelectLines =
commit === null && (review.inlineComment || onAddToAgentSelection !== undefined);
const { parsedSlices, loadedFiles, sourceFileStats } = diffModel(
loadedSlices,
`pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}`,
ignoreWhitespace,
);
const linkAnchor = parsePullRequestAnchor(revealUrl);
const linkFile =
linkAnchor?.kind === "diff"
? loadedFiles.find((file) =>
pullRequestDiffPathMatches(linkAnchor.digest, resolveFileDiffPath(file)),
)
: undefined;
const pendingLinkPath = linkFile ? resolveFileDiffPath(linkFile) : null;
// The linked file stays shown past the test-file filter after the link settles.
const [revealedLink, setRevealedLink] = useState<{
readonly scope: string;
readonly path: string;
} | null>(null);
const linkPath = pendingLinkPath ?? (revealedLink?.scope === scopeKey ? revealedLink.path : null);
const testFileCount = loadedFiles.filter((file) =>
isTestChangedFile(resolveFileDiffPath(file)),
).length;
// A requested file stays visible so a jump to a hidden test still lands.
const files = hideTestFiles
? loadedFiles.filter((file) => {
const path = resolveFileDiffPath(file);
return path === revealRequest?.path || path === linkPath || !isTestChangedFile(path);
})
: loadedFiles;
const hiddenTestFileCount = loadedFiles.length - files.length;
const filePaths = files.map((file) => resolveFileDiffPath(file));
const omittedFileStats = new Map(
loadedSlices.flatMap((slice) =>
slice.omittedFileStats.map((file) => [file.path, file] as const),
),
);
const fileTreeEntries = diffFileTreeEntries(files);
const threadsByPath = reviewThreadsByPath(detail.reviewThreads);
// File membership does not guarantee a rendered hunk for the thread.
const placedThreadIds = (() => {
const placed = new Set<string>();
// Commit diffs use different line coordinates; list conversations separately.
if (commit !== null) return placed;
for (const file of files) {
for (const thread of threadsByPath.get(resolveFileDiffPath(file)) ?? []) {
if (thread.line !== null && isLineInFileDiff(file, thread.side, thread.line)) {
placed.add(thread.id);
}
}
}
return placed;
})();
const annotatedFiles = files.map((fileDiff) => {
const fileKey = buildFileDiffRenderKey(fileDiff);
const path = resolveFileDiffPath(fileDiff);
const groups = new Map<string, MutableAnnotationGroup>();
const groupAt = (side: PullRequestDiffSide, line: number) => {
const key = `${side}:${line}`;
const existing = groups.get(key);
if (existing) return existing;
const created: MutableAnnotationGroup = {
side,
line,
threads: [],
pending: [],
draft: false,
};
groups.set(key, created);
return created;
};
for (const thread of threadsByPath.get(path) ?? []) {
if (thread.line === null || !placedThreadIds.has(thread.id)) continue;
groupAt(thread.side, thread.line).threads.push(thread);
}
if (commit === null) {
for (const comment of pendingComments) {
if (comment.path !== path) continue;
const anchor = getReviewPositionAnchor(comment.position);
groupAt(anchor.side, anchor.line).pending.push(comment);
}
}
if (draft?.fileKey === fileKey) {
const anchor = getReviewPositionAnchor(draft.position);
groupAt(anchor.side, anchor.line).draft = true;
}
const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
side: toViewerSide(group.side),
lineNumber: group.line,
metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
}));
return {
fileKey,
path,
fileDiff,
annotations,
// The viewer redraws annotations only when their version changes.
annotationsVersion: fnv1a32(
annotations
.map(
({ side, lineNumber, metadata }) =>
`${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
.map((comment) => `${comment.id}:${comment.body}`)
.join(",")}:${metadata.threads
.map(
(thread) =>
`${thread.id}:${thread.isResolved ? "r" : ""}:${
thread.isOutdated ? "o" : ""
}:${thread.comments
.map(
(comment) =>
`${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
comment.reactions ?? []
)
.map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`)
.join(",")}`,
)
.join(";")}`,
)
.join(",")}`,
)
.join("|"),
),
};
});
const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
const withheldContent =
loadedSlices.some((slice) => slice.truncated) ||
parsedSlices.some((parsed) => parsed?.kind === "raw");
// Keep the sentinel until all pages load; returning raw slices early would stop pagination.
const rawSlices =
nextCursor === null
? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
: [];
const rawSlicesView =
files.length === 0 && rawSlices.length > 0 ? (
<div className="space-y-4 px-4 py-5">
{rawSlices.map((slice) => (
<div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
<p className="text-xs text-muted-foreground">{slice.reason}</p>
<pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
</div>
))}
</div>
) : null;
const unstructured =
rawSlices.length === 0 ? null : (
<div className="space-y-4 border-t border-border/60 px-4 py-5">
{rawSlices.map((slice) => (
<div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
<p className="text-xs text-muted-foreground">{slice.reason}</p>
<pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
</div>
))}
</div>
);
// A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks.
const foldsAsViewed = (path: string) =>
foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path);
const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
const collapsed = isFileDiffCollapsed(
fileKey,
effectiveFoldOverride,
foldChoices,
foldsAsViewed(path),
);
const viewedMark = filesViewedEnabled
? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
: "";
return {
id: fileKey,
type: "diff" as const,
fileDiff,
annotations,
collapsed,
version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
};
},
);
const fileKeys = items.map((item) => item.id);
const collapsedFileKeys = new Set(
items.filter((item) => item.collapsed === true).map((item) => item.id),
);
const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);
// Do not re-arm the visible sentinel after failure; it would retry indefinitely.
const canLoadNextSlice =
nextCursor !== null &&
nextCursor !== cursor &&
!diffQuery.isPending &&
diffQuery.error === null;
const loadNextSlice = () => {
if (nextCursor === null) return;
setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
};
const sentinelRef = (node: HTMLDivElement | null) => {
if (node === null || !canLoadNextSlice) return;
return observeIntersection(
node,
(entry) => {
if (entry.isIntersecting) loadNextSlice();
},
{ rootMargin: "240px" },
);
};
const toggleFile = (fileKey: string) => {
const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path;
const viewed = path !== undefined && foldsAsViewed(path);
setFoldChoices((current) =>
withFileDiffFold(
current,
fileKey,
!isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed),
),
);
};
const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => {
const range = getFileViewedRange(
annotatedFiles,
fileKey,
extendRange ? lastViewedFileKey : null,
);
setLastViewedFileKey(fileKey);
for (const file of range) setViewed(file.path, viewed);
setFoldChoices((current) =>
range.reduce((next, file) => withFileDiffFold(next, file.fileKey, viewed), current),
);
};
const fileViewedToggle = {
enabled: filesViewedEnabled,
isViewed: isFileViewed,
isStale: isFileViewedStale,
setFileViewed,
};
const revealFile = (path: string, range?: SelectedLineRange) => {
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
if (item === undefined) return;
// Record the unfold even when already open, so a Viewed mark that loads later cannot fold it.
setFoldChoices((current) => withFileDiffFold(current, item.id, false));
if (range) setSelectedLines({ id: item.id, range });
codeViewReveal.request(item.id, range);
};
const toggleAllFiles = () => {
setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
setFoldChoices(new Map());
};
const orderedCommits = // GitLab preserves UTC offsets, so compare instants.
detail.commits.toSorted(
(left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
);
const beginComment = (
range: SelectedLineRange | null,
context: { item: CodeViewItem<ReviewAnnotationGroup> },
) => {
if (!range || !canSelectLines) return;
const item = context.item;
if (item.type !== "diff") return;
const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
if (!file) return;
// On a host without ranged comments a range collapses to its last line: one that silently
// lost its first line there would be worse than one line.
const path = resolveFileDiffPath(file);
const previousPath = resolveFileDiffPreviousPath(file);
const sourceFile = parsedSlices
.flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : []))
.find((candidate) => resolveFileDiffPath(candidate) === path);
const anchor =
(sourceFile && resolveDiffReviewAnchor(sourceFile, range, rangeComments)) ??
resolveDiffReviewAnchor(file, range, rangeComments);
if (anchor === null) return;
setDraft({
fileKey: item.id,
path,
oldPath: previousPath === path ? null : previousPath,
...anchor,
range,
});
};
const finishSelection = (
anchor: DraftAnchor,
text: string,
onFinish: (comment: ReviewCommentContext) => void,
) => {
const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
const comment =
file === undefined
? null
: buildDiffReviewComment({
id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
sectionId: `pull-request:${detail.number}`,
sectionTitle: `PR #${detail.number} review`,
filePath: anchor.path,
fileDiff: file,
range: anchor.range,
text,
});
setDraft(null);
setSelectedLines(null);
if (comment !== null) onFinish(comment);
};
// Stable props preserve viewer portals during selection, typing, and review updates.
const renderCodeViewFooter = () =>
nextCursor === null ? null : (
<div
ref={sentinelRef}
className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
>
{diffQuery.error !== null ? (
<>
<span>The rest of this diff could not be loaded.</span>
<Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
Retry
</Button>
</>
) : diffQuery.isPending ? (
"Loading more files..."
) : null}
</div>
);
const renderHeaderPrefix = (item: CodeViewItem<ReviewAnnotationGroup>) => {
const collapsed = item.collapsed === true;
return (
<Button
size="icon-micro"
variant="ghost-muted"
aria-expanded={!collapsed}
aria-label={collapsed ? "Expand diff" : "Collapse diff"}
className="mr-1"
onClick={(event) => {
event.stopPropagation();
toggleFile(item.id);
}}
>
{collapsed ? (
<ChevronRightIcon className="size-4" />
) : (
<ChevronDownIcon className="size-4" />
)}
</Button>
);
};
const renderHeaderMetadata = (item: CodeViewItem<ReviewAnnotationGroup>) => {
if (item.type !== "diff") return null;
let { additions, deletions } = sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]);
const path = resolveFileDiffPath(item.fileDiff);
if (additions === 0 && deletions === 0) {
const withheld = omittedFileStats.get(path);
if (withheld) ({ additions, deletions } = withheld);
}
return (
<FileViewedToggle
fileKey={item.id}
path={path}
stat={
<PullRequestDiffStat
additions={additions}
deletions={deletions}
className="font-mono text-2xs"
/>
}
/>
);
};
const diffViewOptions = {
diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
lineDiffType: "none" as const,
overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
theme: resolveDiffThemeName(resolvedTheme),
preferredHighlighter: PREFERRED_HIGHLIGHTER,
themeType: resolvedTheme,
stickyHeaders: true,
loadDiffFiles,
enableGutterUtility: canSelectLines && draft === null,
enableLineSelection: canSelectLines && draft === null,
onGutterUtilityClick: beginComment,
onLineSelectionEnd: beginComment,
onPostRender: codeViewReveal.flush,
// Find may repeat requests before render; only unfold, never toggle.
onRevealSearchMatch: (item: CodeViewItem<ReviewAnnotationGroup>) =>
setFoldChoices((current) => withFileDiffFold(current, item.id, false)),
};
const runThreadCommand = async (
label: string,
run: () => Promise<{ readonly _tag: string }>,
): Promise<boolean> => {
if (threadPending) return false;
setThreadPending(true);
const result = await run();
setThreadPending(false);
if (result._tag === "Failure") {
toastManager.add({ type: "error", title: label });
return false;
}
onRefresh();
return true;
};
const renderThreadCard = (thread: PullRequestReviewThread) => (
<ReviewThreadCard
// Host thread ids can collide across pull requests.