TypeScript
refactor(web): the pull request code tab keeps its caching with one "use memo" hook (#20773)
Julius Marmingeba9e9f573636
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 7ea127baa40..788cae0a712 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -243,173 +243,19 @@ export interface PullRequestAgentSelectionInput {readonly request: string;}-// These hooks call no hooks, so the compiler needs the directive to memoize them. The viewer-// and the viewed-file tracker key on the identity of what they return.-function usePullRequestDiffFileContentsLoader<E>(- getDiffFileContents: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[0],- source: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[1],-) {- "use memo";- return createPullRequestDiffFileContentsLoader(getDiffFileContents, source);-}--function useParsedDiffSlices(- loadedSlices: ReadonlyArray<DiffSlice>,- scopeKey: string,- resolvedTheme: string,- ignoreWhitespace: boolean,-) {- "use memo";- // The cache key carries the theme, which is what the tokenizer caches against, so a theme- // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page- // reuses its cursor, and a key of position alone would hand back the parse it replaced.- const parsedSlices = loadedSlices.map((slice) =>- parseSlice(- slice,- `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,- ignoreWhitespace,- ),- );- const files = parsedSlices.flatMap((parsed) =>- parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],- );- const filePaths = files.map((file) => resolveFileDiffPath(file));- const omittedFileStats = new Map(- loadedSlices.flatMap((slice) =>- slice.omittedFileStats.map((file) => [file.path, file] as const),- ),- );- const sourceFileStats = new Map(- parsedSlices.flatMap((parsed) =>- parsed?.kind === "files"- ? parsed.files.map(- (file, index) =>- [- buildFileDiffRenderKey(file),- getDiffLineStat([parsed.sourceFiles[index] ?? file]),- ] as const,- )- : [],- ),- );- const fileTreeEntries = diffFileTreeEntries(files);- return { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries };-}--function useAnnotatedDiffFiles(- files: ReadonlyArray<FileDiffMetadata>,- reviewThreads: ReadonlyArray<PullRequestReviewThread>,- pendingComments: ReadonlyArray<PendingReviewComment>,- draft: DraftAnchor | null,- scopedToCommit: boolean,-) {- "use memo";- // Placing a conversation takes more than its file being in the diff: its line has to fall- // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the- // off-diff list rather than disappearing between the two.- const placedThreadIds = (() => {- const placed = new Set<string>();- // A commit's diff counts lines within that commit; a review comment is anchored to the- // pull request's head diff. Pinning one onto the other would put the remark against- // whichever code happens to hold that line number in this commit, so while a commit is on- // screen every conversation is listed rather than placed.- if (scopedToCommit) return placed;- for (const file of files) {- const path = resolveFileDiffPath(file);- for (const thread of reviewThreads) {- if (- thread.path === path &&- 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 reviewThreads) {- if (thread.path !== path || thread.line === null) continue;- if (!placedThreadIds.has(thread.id)) continue;- groupAt(thread.side, thread.line).threads.push(thread);- }- if (!scopedToCommit) {- 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 re-renders an item only when its version changes, so everything the- // annotations show has to be part of it.- 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("|"),- ),- };- });- return { annotatedFiles, placedThreadIds };-}-+// 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: ReturnType<typeof useAnnotatedDiffFiles>["annotatedFiles"],+ 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: {@@ -605,7 +451,7 @@ function PullRequestCodeTab({reportFailure: false,});const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);- const loadDiffFiles = usePullRequestDiffFileContentsLoader(getDiffFileContents, {+ const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {environmentId,reference,commit,@@ -619,8 +465,173 @@ function PullRequestCodeTab({resolve: hostReview.resolve && detail.viewerPermissions.resolve,};const canCommentOnLines = review.inlineComment && commit === null;- const { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries } =- useParsedDiffSlices(loadedSlices, scopeKey, resolvedTheme, ignoreWhitespace);+ // The cache key carries the theme, which is what the tokenizer caches against, so a theme+ // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page+ // reuses its cursor, and a key of position alone would hand back the parse it replaced.+ const parsedSlices = loadedSlices.map((slice) =>+ parseSlice(+ slice,+ `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,+ ignoreWhitespace,+ ),+ );+ const files = parsedSlices.flatMap((parsed) =>+ parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],+ );+ const filePaths = files.map((file) => resolveFileDiffPath(file));+ const omittedFileStats = new Map(+ loadedSlices.flatMap((slice) =>+ slice.omittedFileStats.map((file) => [file.path, file] as const),+ ),+ );+ const sourceFileStats = new Map(+ parsedSlices.flatMap((parsed) =>+ parsed?.kind === "files"+ ? parsed.files.map(+ (file, index) =>+ [+ buildFileDiffRenderKey(file),+ getDiffLineStat([parsed.sourceFiles[index] ?? file]),+ ] as const,+ )+ : [],+ ),+ );+ const fileTreeEntries = diffFileTreeEntries(files);+ // Placing a conversation takes more than its file being in the diff: its line has to fall+ // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the+ // off-diff list rather than disappearing between the two.+ const placedThreadIds = (() => {+ const placed = new Set<string>();+ // A commit's diff counts lines within that commit; a review comment is anchored to the+ // pull request's head diff. Pinning one onto the other would put the remark against+ // whichever code happens to hold that line number in this commit, so while a commit is on+ // screen every conversation is listed rather than placed.+ if (commit !== null) return placed;+ for (const file of files) {+ const path = resolveFileDiffPath(file);+ for (const thread of detail.reviewThreads) {+ if (+ thread.path === path &&+ 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 detail.reviewThreads) {+ if (thread.path !== path || thread.line === null) continue;+ if (!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 re-renders an item only when its version changes, so everything the+ // annotations show has to be part of it.+ 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");+ // Only once the diff is whole: returning here while a cursor is outstanding would take the+ // sentinel off screen and end the walk, leaving the rest of the change unasked for.+ 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>+ );const viewedFilesStore = detail.capabilities.viewedFiles;const filesViewed = usePullRequestFilesViewed({environmentId,@@ -643,18 +654,6 @@ function PullRequestCodeTab({refreshFirstDiffPage();refreshFilesViewed();}, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);- const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;- const withheldContent =- loadedSlices.some((slice) => slice.truncated) ||- parsedSlices.some((parsed) => parsed?.kind === "raw");-- const { annotatedFiles, placedThreadIds } = useAnnotatedDiffFiles(- files,- detail.reviewThreads,- pendingComments,- draft,- commit !== null,- );const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);const fileKeys = items.map((item) => item.id);@@ -1336,23 +1335,8 @@ function PullRequestCodeTab({);}- // Only once the diff is whole: returning here while a cursor is outstanding would take the- // sentinel off screen and end the walk, leaving the rest of the change unasked for.- const rawSlices =- nextCursor === null- ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))- : [];- if (files.length === 0 && rawSlices.length > 0) {- return withToolbar(- <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>,- );+ if (rawSlicesView !== null) {+ return withToolbar(rawSlicesView);}if (items.length === 0 && nextCursor === null) {@@ -1373,18 +1357,6 @@ function PullRequestCodeTab({else orphanFiles.set(thread.path, [thread]);}- 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>- );-return (<div className="flex h-full min-h-0 flex-col">{toolbar}