Skip to content
TypeScript

refactor(web): pull request code tab keeps its caching without "use memo" (#20816)

Julius Marminge78f8d38ebb8c
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
index 788cae0a712..5d06a1ff483 100644
--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
@@ -1,9 +1,4 @@
-import type {
- CodeViewItem,
- DiffLineAnnotation,
- FileDiffMetadata,
- SelectedLineRange,
-} from "@pierre/diffs";
+import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
import type {
EnvironmentId,
@@ -243,47 +238,6 @@ export interface PullRequestAgentSelectionInput {
readonly request: string;
}
-// Kept as a "use memo" hook: each item's version needs the viewed state that
-// `usePullRequestFilesViewed` returns, so items are built after that hook from `annotatedFiles`. Those
-// alias `files`, which already went through plain functions before the hook, and the hook itself has
-// to receive `filePaths`. Built inline, that straddle leaves `files` and everything derived from it
-// uncached. The viewer re-renders each item on its version.
-function useDiffItems(
- annotatedFiles: ReadonlyArray<{
- readonly fileKey: string;
- readonly path: string;
- readonly fileDiff: FileDiffMetadata;
- readonly annotations: ReviewAnnotation[];
- readonly annotationsVersion: number;
- }>,
- foldOverride: Exclude<DiffFoldOverride, null>,
- toggledFiles: ReadonlySet<string>,
- viewedFiles: {
- readonly enabled: boolean;
- readonly isViewed: (path: string) => boolean;
- readonly isStale: (path: string) => boolean;
- },
-) {
- "use memo";
- const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
- ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
- const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);
- const viewedMark = viewedFiles.enabled
- ? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}`
- : "";
- return {
- id: fileKey,
- type: "diff" as const,
- fileDiff,
- annotations,
- collapsed,
- version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
- };
- },
- );
- return items;
-}
-
function PullRequestCodeTab({
scrollerRef,
environmentId,
@@ -451,13 +405,41 @@ function PullRequestCodeTab({
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);
+ useEffect(() => {
+ if (appliedRefreshToken.current === refreshToken) return;
+ appliedRefreshToken.current = refreshToken;
+ setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
+ refreshFirstDiffPage();
+ refreshFilesViewed();
+ }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
+
+ // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
+ // an effect reading a ref could run before that node exists and would never arm the observer.
+ const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
+ const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
+ const answeredReveal = useRef<number | null>(null);
+
const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
environmentId,
reference,
commit,
cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
});
-
const hostReview = detail.capabilities.review;
const review = {
inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -632,30 +614,23 @@ function PullRequestCodeTab({
))}
</div>
);
- const viewedFilesStore = detail.capabilities.viewedFiles;
- const filesViewed = usePullRequestFilesViewed({
- environmentId,
- reference,
- enabled: viewedFilesStore !== undefined,
- paths: filePaths,
- });
- const {
- setViewed,
- refresh: refreshFilesViewed,
- enabled: filesViewedEnabled,
- isViewed: isFileViewed,
- isStale: isFileViewedStale,
- } = filesViewed;
- const appliedRefreshToken = useRef(refreshToken);
- useEffect(() => {
- if (appliedRefreshToken.current === refreshToken) return;
- appliedRefreshToken.current = refreshToken;
- setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
- refreshFirstDiffPage();
- refreshFilesViewed();
- }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
- const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);
+ const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
+ ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
+ const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
+ 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),
@@ -674,21 +649,6 @@ function PullRequestCodeTab({
setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
};
- // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
- // an effect reading a ref could run before that node exists and would never arm the observer.
- const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
- useEffect(() => {
- if (sentinel === null || !canLoadNextSlice) return;
- const observer = new IntersectionObserver(
- (observed) => {
- if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
- },
- { rootMargin: "240px" },
- );
- observer.observe(sentinel);
- return () => observer.disconnect();
- }, [canLoadNextSlice, loadNextSlice, sentinel]);
-
const toggleFile = (fileKey: string) =>
setToggledFiles((current) => {
const next = new Set(current);
@@ -710,28 +670,12 @@ function PullRequestCodeTab({
setFileViewed,
};
- const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
const revealFile = (path: string) => {
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
if (item === undefined) return;
if (item.collapsed === true) toggleFile(item.id);
requestTreeReveal(item.id);
};
- const answeredReveal = useRef<number | null>(null);
- const answerReveal = useEffectEvent(() => {
- if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
- if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
- if (canLoadNextSlice) loadNextSlice();
- return;
- }
- answeredReveal.current = revealRequest.nonce;
- revealFile(revealRequest.path);
- });
- useEffect(() => {
- // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
- answerReveal();
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
- }, [canLoadNextSlice, items, revealRequest]);
const toggleAllFiles = () => {
setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
@@ -1014,11 +958,6 @@ function PullRequestCodeTab({
// to the whole diff and it is not drawn without commits to list, so a scope that outlived them
// would leave the tab reading one obsolete commit with nothing to press.
const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
- useEffect(() => {
- if (commit !== null && selectedCommit === undefined) {
- onSelectedCommitChange(null);
- }
- }, [commit, onSelectedCommitChange, selectedCommit]);
const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
const changeIgnoreWhitespace = (next: boolean) => {
setIgnoreWhitespace(next);
@@ -1083,7 +1022,7 @@ function PullRequestCodeTab({
{filesViewed.enabled && files.length > 0 ? (
<span className="flex min-w-0 items-center gap-1 tabular-nums">
<span className="shrink-0">
- {filesViewed.viewedCount} / {files.length}
+ {filePaths.filter(isFileViewed).length} / {files.length}
</span>
<span className="truncate">
{viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"}
@@ -1316,6 +1255,38 @@ function PullRequestCodeTab({
</div>
</div>
);
+ // The effects sit after every derivation: a hook between the diff's derivations and their
+ // later readers (the viewer options, the reveal handler) would leave them uncached.
+ useEffect(() => {
+ if (sentinel === null || !canLoadNextSlice) return;
+ const observer = new IntersectionObserver(
+ (observed) => {
+ if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
+ },
+ { rootMargin: "240px" },
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [canLoadNextSlice, loadNextSlice, sentinel]);
+ const answerReveal = useEffectEvent(() => {
+ if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
+ if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
+ if (canLoadNextSlice) loadNextSlice();
+ return;
+ }
+ answeredReveal.current = revealRequest.nonce;
+ revealFile(revealRequest.path);
+ });
+ useEffect(() => {
+ // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
+ answerReveal();
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
+ }, [canLoadNextSlice, items, revealRequest]);
+ useEffect(() => {
+ if (commit !== null && selectedCommit === undefined) {
+ onSelectedCommitChange(null);
+ }
+ }, [commit, onSelectedCommitChange, selectedCommit]);
const withToolbar = (body: ReactNode) => (
<div className="flex h-full min-h-0 flex-col">
{toolbar}
diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts
index 4a74f3d01c7..cbf36cc8588 100644
--- a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
- countViewedFiles,
isFileViewed,
isStaleViewedState,
revertFileViewedOverlay,
@@ -47,14 +46,6 @@ describe("isFileViewed", () => {
});
});
-describe("countViewedFiles", () => {
- it("counts only the files on screen, presses included", () => {
- expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, NO_OVERLAY)).toBe(1);
- expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, new Map([["b.ts", true]]))).toBe(2);
- expect(countViewedFiles(["b.ts"], states, NO_OVERLAY)).toBe(0);
- });
-});
-
describe("settleFileViewedOverlay", () => {
it("drops a press the host has caught up on", () => {
const settled = settleFileViewedOverlay(
diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts
index 215781a3581..652fb3c2db2 100644
--- a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts
@@ -28,17 +28,6 @@ export function isFileViewed(
return pressed ?? isViewedState(states?.get(path));
}
-export function countViewedFiles(
- paths: ReadonlyArray<string>,
- states: FileViewedStates | null,
- overlay: FileViewedOverlay,
-): number {
- return paths.reduce(
- (total, path) => (isFileViewed(path, states, overlay) ? total + 1 : total),
- 0,
- );
-}
-
/**
* A press is held until a read that could have seen it comes back, rather than cleared when the
* write succeeds: that read is a separate round trip, and dropping the press in between flashes
diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
index 993e8837320..d1a29ec19ee 100644
--- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
@@ -41,7 +41,6 @@ const reference: PullRequestRef = {
repository: "acme/web",
number: 42,
};
-const paths = ["a.ts"];
function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesViewedResult {
return { files: [{ path: "a.ts", state }], truncated: false };
@@ -54,7 +53,7 @@ function Probe(_props: { readonly view: PullRequestFilesViewedView }) {
}
function Surface() {
- const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true, paths });
+ const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
return <Probe view={view} />;
}
@@ -110,7 +109,6 @@ describe("a mark whose file was pushed to before the read that followed it", ()
expect(view().isViewed("a.ts")).toBe(false);
expect(view().isStale("a.ts")).toBe(true);
- expect(view().viewedCount).toBe(0);
});
it("stays given way to on every later read, having nothing left to recover", async () => {
diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts
index 86396134f9b..9756e49bfd7 100644
--- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts
+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts
@@ -9,7 +9,6 @@ import { useStableCallback } from "~/hooks/useStableCallback";
import { toastManager } from "../ui/toast";
import {
- countViewedFiles,
isFileViewed,
isStaleViewedState,
revertFileViewedOverlay,
@@ -29,7 +28,6 @@ export interface PullRequestFilesViewedView {
readonly isViewed: (path: string) => boolean;
readonly isStale: (path: string) => boolean;
readonly setViewed: (path: string, viewed: boolean) => void;
- readonly viewedCount: number;
readonly truncated: boolean;
readonly error: string | null;
readonly refresh: () => void;
@@ -39,9 +37,8 @@ export function usePullRequestFilesViewed(options: {
readonly environmentId: EnvironmentId;
readonly reference: PullRequestRef;
readonly enabled: boolean;
- readonly paths: ReadonlyArray<string>;
}): PullRequestFilesViewedView {
- const { environmentId, reference, enabled, paths } = options;
+ const { environmentId, reference, enabled } = options;
const query = useEnvironmentQuery(
enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
);
@@ -154,7 +151,6 @@ export function usePullRequestFilesViewed(options: {
isViewed: (path: string) => isFileViewed(path, states, overlay),
isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
setViewed,
- viewedCount: countViewedFiles(paths, states, overlay),
truncated,
error,
refresh,