Skip to content

Commit 7edc350

Browse files
refactor(web): pull request code tab keeps its caching without "use memo"
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b987b57 commit 7edc350

5 files changed

Lines changed: 81 additions & 136 deletions

File tree

‎apps/web/src/components/pullRequest/PullRequestCodeTab.tsx‎

Lines changed: 79 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
import type {
2-
CodeViewItem,
3-
DiffLineAnnotation,
4-
FileDiffMetadata,
5-
SelectedLineRange,
6-
} from "@pierre/diffs";
1+
import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
72
import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
83
import type {
94
EnvironmentId,
@@ -243,47 +238,6 @@ export interface PullRequestAgentSelectionInput {
243238
readonly request: string;
244239
}
245240

246-
// Kept as a "use memo" hook: each item's version needs the viewed state that
247-
// `usePullRequestFilesViewed` returns, so items are built after that hook from `annotatedFiles`. Those
248-
// alias `files`, which already went through plain functions before the hook, and the hook itself has
249-
// to receive `filePaths`. Built inline, that straddle leaves `files` and everything derived from it
250-
// uncached. The viewer re-renders each item on its version.
251-
function useDiffItems(
252-
annotatedFiles: ReadonlyArray<{
253-
readonly fileKey: string;
254-
readonly path: string;
255-
readonly fileDiff: FileDiffMetadata;
256-
readonly annotations: ReviewAnnotation[];
257-
readonly annotationsVersion: number;
258-
}>,
259-
foldOverride: Exclude<DiffFoldOverride, null>,
260-
toggledFiles: ReadonlySet<string>,
261-
viewedFiles: {
262-
readonly enabled: boolean;
263-
readonly isViewed: (path: string) => boolean;
264-
readonly isStale: (path: string) => boolean;
265-
},
266-
) {
267-
"use memo";
268-
const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
269-
({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
270-
const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);
271-
const viewedMark = viewedFiles.enabled
272-
? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}`
273-
: "";
274-
return {
275-
id: fileKey,
276-
type: "diff" as const,
277-
fileDiff,
278-
annotations,
279-
collapsed,
280-
version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
281-
};
282-
},
283-
);
284-
return items;
285-
}
286-
287241
function PullRequestCodeTab({
288242
scrollerRef,
289243
environmentId,
@@ -451,13 +405,41 @@ function PullRequestCodeTab({
451405
reportFailure: false,
452406
});
453407
const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
408+
409+
const viewedFilesStore = detail.capabilities.viewedFiles;
410+
const filesViewed = usePullRequestFilesViewed({
411+
environmentId,
412+
reference,
413+
enabled: viewedFilesStore !== undefined,
414+
});
415+
const {
416+
setViewed,
417+
refresh: refreshFilesViewed,
418+
enabled: filesViewedEnabled,
419+
isViewed: isFileViewed,
420+
isStale: isFileViewedStale,
421+
} = filesViewed;
422+
const appliedRefreshToken = useRef(refreshToken);
423+
useEffect(() => {
424+
if (appliedRefreshToken.current === refreshToken) return;
425+
appliedRefreshToken.current = refreshToken;
426+
setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
427+
refreshFirstDiffPage();
428+
refreshFilesViewed();
429+
}, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
430+
431+
// The sentinel is held as state rather than a ref because the viewer mounts its own footer:
432+
// an effect reading a ref could run before that node exists and would never arm the observer.
433+
const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
434+
const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
435+
const answeredReveal = useRef<number | null>(null);
436+
454437
const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
455438
environmentId,
456439
reference,
457440
commit,
458441
cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
459442
});
460-
461443
const hostReview = detail.capabilities.review;
462444
const review = {
463445
inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -632,30 +614,23 @@ function PullRequestCodeTab({
632614
))}
633615
</div>
634616
);
635-
const viewedFilesStore = detail.capabilities.viewedFiles;
636-
const filesViewed = usePullRequestFilesViewed({
637-
environmentId,
638-
reference,
639-
enabled: viewedFilesStore !== undefined,
640-
paths: filePaths,
641-
});
642-
const {
643-
setViewed,
644-
refresh: refreshFilesViewed,
645-
enabled: filesViewedEnabled,
646-
isViewed: isFileViewed,
647-
isStale: isFileViewedStale,
648-
} = filesViewed;
649-
const appliedRefreshToken = useRef(refreshToken);
650-
useEffect(() => {
651-
if (appliedRefreshToken.current === refreshToken) return;
652-
appliedRefreshToken.current = refreshToken;
653-
setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
654-
refreshFirstDiffPage();
655-
refreshFilesViewed();
656-
}, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
657617

658-
const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);
618+
const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
619+
({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
620+
const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
621+
const viewedMark = filesViewedEnabled
622+
? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
623+
: "";
624+
return {
625+
id: fileKey,
626+
type: "diff" as const,
627+
fileDiff,
628+
annotations,
629+
collapsed,
630+
version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
631+
};
632+
},
633+
);
659634
const fileKeys = items.map((item) => item.id);
660635
const collapsedFileKeys = new Set(
661636
items.filter((item) => item.collapsed === true).map((item) => item.id),
@@ -674,21 +649,6 @@ function PullRequestCodeTab({
674649
setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
675650
};
676651

677-
// The sentinel is held as state rather than a ref because the viewer mounts its own footer:
678-
// an effect reading a ref could run before that node exists and would never arm the observer.
679-
const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
680-
useEffect(() => {
681-
if (sentinel === null || !canLoadNextSlice) return;
682-
const observer = new IntersectionObserver(
683-
(observed) => {
684-
if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
685-
},
686-
{ rootMargin: "240px" },
687-
);
688-
observer.observe(sentinel);
689-
return () => observer.disconnect();
690-
}, [canLoadNextSlice, loadNextSlice, sentinel]);
691-
692652
const toggleFile = (fileKey: string) =>
693653
setToggledFiles((current) => {
694654
const next = new Set(current);
@@ -710,28 +670,12 @@ function PullRequestCodeTab({
710670
setFileViewed,
711671
};
712672

713-
const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
714673
const revealFile = (path: string) => {
715674
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
716675
if (item === undefined) return;
717676
if (item.collapsed === true) toggleFile(item.id);
718677
requestTreeReveal(item.id);
719678
};
720-
const answeredReveal = useRef<number | null>(null);
721-
const answerReveal = useEffectEvent(() => {
722-
if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
723-
if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
724-
if (canLoadNextSlice) loadNextSlice();
725-
return;
726-
}
727-
answeredReveal.current = revealRequest.nonce;
728-
revealFile(revealRequest.path);
729-
});
730-
useEffect(() => {
731-
// oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
732-
answerReveal();
733-
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
734-
}, [canLoadNextSlice, items, revealRequest]);
735679

736680
const toggleAllFiles = () => {
737681
setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
@@ -1014,11 +958,6 @@ function PullRequestCodeTab({
1014958
// to the whole diff and it is not drawn without commits to list, so a scope that outlived them
1015959
// would leave the tab reading one obsolete commit with nothing to press.
1016960
const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
1017-
useEffect(() => {
1018-
if (commit !== null && selectedCommit === undefined) {
1019-
onSelectedCommitChange(null);
1020-
}
1021-
}, [commit, onSelectedCommitChange, selectedCommit]);
1022961
const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
1023962
const changeIgnoreWhitespace = (next: boolean) => {
1024963
setIgnoreWhitespace(next);
@@ -1083,7 +1022,7 @@ function PullRequestCodeTab({
10831022
{filesViewed.enabled && files.length > 0 ? (
10841023
<span className="flex min-w-0 items-center gap-1 tabular-nums">
10851024
<span className="shrink-0">
1086-
{filesViewed.viewedCount} / {files.length}
1025+
{filePaths.filter(isFileViewed).length} / {files.length}
10871026
</span>
10881027
<span className="truncate">
10891028
{viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"}
@@ -1316,6 +1255,38 @@ function PullRequestCodeTab({
13161255
</div>
13171256
</div>
13181257
);
1258+
// The effects sit after every derivation: a hook between the diff's derivations and their
1259+
// later readers (the viewer options, the reveal handler) would leave them uncached.
1260+
useEffect(() => {
1261+
if (sentinel === null || !canLoadNextSlice) return;
1262+
const observer = new IntersectionObserver(
1263+
(observed) => {
1264+
if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
1265+
},
1266+
{ rootMargin: "240px" },
1267+
);
1268+
observer.observe(sentinel);
1269+
return () => observer.disconnect();
1270+
}, [canLoadNextSlice, loadNextSlice, sentinel]);
1271+
const answerReveal = useEffectEvent(() => {
1272+
if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
1273+
if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
1274+
if (canLoadNextSlice) loadNextSlice();
1275+
return;
1276+
}
1277+
answeredReveal.current = revealRequest.nonce;
1278+
revealFile(revealRequest.path);
1279+
});
1280+
useEffect(() => {
1281+
// oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
1282+
answerReveal();
1283+
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
1284+
}, [canLoadNextSlice, items, revealRequest]);
1285+
useEffect(() => {
1286+
if (commit !== null && selectedCommit === undefined) {
1287+
onSelectedCommitChange(null);
1288+
}
1289+
}, [commit, onSelectedCommitChange, selectedCommit]);
13191290
const withToolbar = (body: ReactNode) => (
13201291
<div className="flex h-full min-h-0 flex-col">
13211292
{toolbar}

‎apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { describe, expect, it } from "vite-plus/test";
22

33
import {
4-
countViewedFiles,
54
isFileViewed,
65
isStaleViewedState,
76
revertFileViewedOverlay,
@@ -47,14 +46,6 @@ describe("isFileViewed", () => {
4746
});
4847
});
4948

50-
describe("countViewedFiles", () => {
51-
it("counts only the files on screen, presses included", () => {
52-
expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, NO_OVERLAY)).toBe(1);
53-
expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, new Map([["b.ts", true]]))).toBe(2);
54-
expect(countViewedFiles(["b.ts"], states, NO_OVERLAY)).toBe(0);
55-
});
56-
});
57-
5849
describe("settleFileViewedOverlay", () => {
5950
it("drops a press the host has caught up on", () => {
6051
const settled = settleFileViewedOverlay(

‎apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,6 @@ export function isFileViewed(
2828
return pressed ?? isViewedState(states?.get(path));
2929
}
3030

31-
export function countViewedFiles(
32-
paths: ReadonlyArray<string>,
33-
states: FileViewedStates | null,
34-
overlay: FileViewedOverlay,
35-
): number {
36-
return paths.reduce(
37-
(total, path) => (isFileViewed(path, states, overlay) ? total + 1 : total),
38-
0,
39-
);
40-
}
41-
4231
/**
4332
* A press is held until a read that could have seen it comes back, rather than cleared when the
4433
* write succeeds: that read is a separate round trip, and dropping the press in between flashes

‎apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ const reference: PullRequestRef = {
4141
repository: "acme/web",
4242
number: 42,
4343
};
44-
const paths = ["a.ts"];
4544

4645
function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesViewedResult {
4746
return { files: [{ path: "a.ts", state }], truncated: false };
@@ -54,7 +53,7 @@ function Probe(_props: { readonly view: PullRequestFilesViewedView }) {
5453
}
5554

5655
function Surface() {
57-
const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true, paths });
56+
const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
5857
return <Probe view={view} />;
5958
}
6059

@@ -110,7 +109,6 @@ describe("a mark whose file was pushed to before the read that followed it", ()
110109

111110
expect(view().isViewed("a.ts")).toBe(false);
112111
expect(view().isStale("a.ts")).toBe(true);
113-
expect(view().viewedCount).toBe(0);
114112
});
115113

116114
it("stays given way to on every later read, having nothing left to recover", async () => {

‎apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import { useStableCallback } from "~/hooks/useStableCallback";
99

1010
import { toastManager } from "../ui/toast";
1111
import {
12-
countViewedFiles,
1312
isFileViewed,
1413
isStaleViewedState,
1514
revertFileViewedOverlay,
@@ -29,7 +28,6 @@ export interface PullRequestFilesViewedView {
2928
readonly isViewed: (path: string) => boolean;
3029
readonly isStale: (path: string) => boolean;
3130
readonly setViewed: (path: string, viewed: boolean) => void;
32-
readonly viewedCount: number;
3331
readonly truncated: boolean;
3432
readonly error: string | null;
3533
readonly refresh: () => void;
@@ -39,9 +37,8 @@ export function usePullRequestFilesViewed(options: {
3937
readonly environmentId: EnvironmentId;
4038
readonly reference: PullRequestRef;
4139
readonly enabled: boolean;
42-
readonly paths: ReadonlyArray<string>;
4340
}): PullRequestFilesViewedView {
44-
const { environmentId, reference, enabled, paths } = options;
41+
const { environmentId, reference, enabled } = options;
4542
const query = useEnvironmentQuery(
4643
enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
4744
);
@@ -154,7 +151,6 @@ export function usePullRequestFilesViewed(options: {
154151
isViewed: (path: string) => isFileViewed(path, states, overlay),
155152
isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
156153
setViewed,
157-
viewedCount: countViewedFiles(paths, states, overlay),
158154
truncated,
159155
error,
160156
refresh,

0 commit comments

Comments
 (0)