Skip to content
TypeScript

perf(mobile): reuse diff rows during comment edits (#9693)

Theo Browne777f5bb2e11f
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
index 3a291b2e788..ffc4a71f7a1 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vite-plus/test";
+import { describe, expect, it, vi } from "vite-plus/test";
import {
DEFAULT_MOBILE_THEME_ID,
getMobileThemeVariables,
@@ -9,12 +9,14 @@ import {
import { readDefaultMobileThemeVariables } from "../../lib/mobileTheme.test-support";
import {
+ buildNativeReviewDiffData,
createNativeReviewDiffTheme,
getCachedNativeReviewDiffData,
type BuildNativeReviewDiffDataInput,
} from "./nativeReviewDiffAdapter";
import type { ReviewInlineComment } from "./reviewCommentSelection";
import { buildReviewParsedDiff } from "./reviewModel";
+import * as ReviewWordDiffs from "./reviewWordDiffs";
const parsedDiff = buildReviewParsedDiff(
[
@@ -46,6 +48,23 @@ function buildInput(comments: BuildNativeReviewDiffDataInput["comments"]) {
return { parsedDiff, comments } satisfies BuildNativeReviewDiffDataInput;
}
+function filesPatch(paths: ReadonlyArray<string>) {
+ return paths
+ .map((path) =>
+ [
+ `diff --git a/${path} b/${path}`,
+ `--- a/${path}`,
+ `+++ b/${path}`,
+ "@@ -1,2 +1,2 @@",
+ '-const first = renderPanel({ label: "before", enabled: true });',
+ '-const second = renderPanel({ label: "before", enabled: true });',
+ '+const first = renderPanel({ label: "after", enabled: true });',
+ '+const second = renderPanel({ label: "after", enabled: true });',
+ ].join("\n"),
+ )
+ .join("\n");
+}
+
function appTheme(themeId: MobileThemeId, appearance: MobileThemeAppearance) {
return themeId === DEFAULT_MOBILE_THEME_ID
? readDefaultMobileThemeVariables(appearance)
@@ -67,6 +86,107 @@ describe("getCachedNativeReviewDiffData", () => {
expect(equivalent).toBe(first);
expect(changed).not.toBe(first);
+ expect(changed.rows.find((row) => row.kind === "comment")?.commentText).toBe("Changed");
+ });
+
+ it("reuses source rows and word matching when a file comment changes", () => {
+ const diff = buildReviewParsedDiff(filesPatch(["example.ts", "second.ts"]), "comment-reuse");
+ const matchWords = vi.spyOn(ReviewWordDiffs, "computeWordAltDiffRanges");
+ try {
+ const base = getCachedNativeReviewDiffData({ parsedDiff: diff });
+ expect(matchWords).toHaveBeenCalledTimes(4);
+ expect(base.rows.filter((row) => row.wordDiffRanges?.length)).toHaveLength(8);
+ const firstComment = makeComment("First file comment");
+ const secondComment = {
+ ...makeComment("Second file comment"),
+ id: "comment-2",
+ filePath: "second.ts",
+ };
+ const first = getCachedNativeReviewDiffData({
+ parsedDiff: diff,
+ comments: [firstComment, secondComment],
+ });
+ const changed = getCachedNativeReviewDiffData({
+ parsedDiff: diff,
+ comments: [{ ...firstComment, text: "Changed first comment" }, secondComment],
+ });
+
+ expect(matchWords).toHaveBeenCalledTimes(4);
+ expect(changed.files).toBe(base.files);
+ expect(changed.commentTargetsByRowId).toBe(base.commentTargetsByRowId);
+ expect(changed.rowIdByCommentLineId).toBe(base.rowIdByCommentLineId);
+ expect(changed.rows.find((row) => row.id === secondComment.id)).toBe(
+ first.rows.find((row) => row.id === secondComment.id),
+ );
+ const sourceRows = changed.rows.filter((row) => row.kind !== "comment");
+ for (const [index, row] of sourceRows.entries()) {
+ expect(row).toBe(base.rows[index]);
+ }
+ const removed = getCachedNativeReviewDiffData({ parsedDiff: diff, comments: [] });
+ expect(removed.rows).toEqual(base.rows);
+ expect(matchWords).toHaveBeenCalledTimes(4);
+ expect(first.rows.find((row) => row.id === firstComment.id)?.commentText).toBe(
+ "First file comment",
+ );
+ } finally {
+ matchWords.mockRestore();
+ }
+ });
+
+ it("updates comment titles and locations without changing source coordinates", () => {
+ const diff = buildReviewParsedDiff(filesPatch(["example.ts", "second.ts"]), "comment-metadata");
+ const comment = makeComment("Review this line");
+ const first = getCachedNativeReviewDiffData({ parsedDiff: diff, comments: [comment] });
+ const renamed = getCachedNativeReviewDiffData({
+ parsedDiff: diff,
+ comments: [{ ...comment, sectionTitle: "Branch comparison" }],
+ });
+ expect(renamed.rows.find((row) => row.id === comment.id)?.commentSectionTitle).toBe(
+ "Branch comparison",
+ );
+ const moved = getCachedNativeReviewDiffData({
+ parsedDiff: diff,
+ comments: [{ ...comment, filePath: "second.ts", endIndex: 99, rangeLabel: "+2" }],
+ });
+ const commentIndex = moved.rows.findIndex((row) => row.id === comment.id);
+ expect(moved.rows[commentIndex]).toMatchObject({
+ kind: "comment",
+ filePath: "second.ts",
+ commentRangeLabel: "+2",
+ });
+ expect(moved.rows[commentIndex - 1]).toMatchObject({
+ kind: "line",
+ change: "add",
+ newLineNumber: 2,
+ });
+ expect(moved.rows.filter((row) => row.kind !== "comment")).toEqual(
+ first.rows.filter((row) => row.kind !== "comment"),
+ );
+ expect(first.rows.find((row) => row.id === comment.id)?.commentSectionTitle).toBe(
+ "Dirty worktree",
+ );
+ });
+
+ it("keeps cached IDs and targets local to each parsed section and file layout", () => {
+ const original = filesPatch(["example.ts", "second.ts"]);
+ const variants = [
+ buildReviewParsedDiff(original, "first-section"),
+ buildReviewParsedDiff(original, "second-section"),
+ buildReviewParsedDiff(
+ filesPatch(["inserted.ts", "example.ts", "second.ts"]),
+ "first-section",
+ ),
+ buildReviewParsedDiff(filesPatch(["second.ts", "example.ts"]), "first-section"),
+ buildReviewParsedDiff(filesPatch(["example.ts"]), "first-section"),
+ buildReviewParsedDiff(
+ original.replaceAll("@@ -1,2 +1,2 @@", "@@ -7,2 +12,2 @@"),
+ "first-section",
+ ),
+ ];
+ for (const diff of [...variants, variants[0]!]) {
+ const input = { parsedDiff: diff, comments: [makeComment("Coordinates")] };
+ expect(getCachedNativeReviewDiffData(input)).toEqual(buildNativeReviewDiffData(input));
+ }
});
});
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
index a45a955d331..3c2eb9016fe 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
@@ -105,10 +105,26 @@ export interface BuildNativeReviewDiffDataInput {
}
interface CachedNativeReviewDiffData {
+ readonly prepared: PreparedNativeReviewDiffData;
readonly commentsKey: string;
readonly data: NativeReviewDiffData;
}
+interface PreparedNativeReviewFileRows {
+ readonly fileId: string;
+ readonly filePath: string;
+ readonly lineCount: number;
+ readonly rows: ReadonlyArray<NativeReviewDiffRow>;
+ commentedRows: {
+ readonly commentsKey: string;
+ readonly rows: ReadonlyArray<NativeReviewDiffRow>;
+ } | null;
+}
+
+interface PreparedNativeReviewDiffData extends Omit<NativeReviewDiffData, "rows"> {
+ readonly fileRows: ReadonlyArray<PreparedNativeReviewFileRows>;
+}
+
const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
@@ -116,19 +132,18 @@ function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment
return "none";
}
- return comments
- .map((comment) =>
- [
- comment.id,
- comment.sectionId,
- comment.filePath,
- comment.startIndex,
- comment.endIndex,
- comment.rangeLabel,
- comment.text,
- ].join("\u001f"),
- )
- .join("\u001e");
+ return JSON.stringify(
+ comments.map((comment) => [
+ comment.id,
+ comment.sectionId,
+ comment.sectionTitle,
+ comment.filePath,
+ comment.startIndex,
+ comment.endIndex,
+ comment.rangeLabel,
+ comment.text,
+ ]),
+ );
}
export function createNativeReviewDiffTheme(
@@ -378,12 +393,11 @@ function mapLineRow(
};
}
-function mapFileRows(
+function prepareFileRows(
file: ReviewRenderableFile,
- comments: ReadonlyArray<ReviewInlineComment>,
commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
rowIdByCommentLineId: Map<string, string>,
-): ReadonlyArray<NativeReviewDiffRow> {
+): PreparedNativeReviewFileRows {
const rows: NativeReviewDiffRow[] = [
{
kind: "file",
@@ -398,22 +412,6 @@ function mapFileRows(
];
const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
- const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
- comments.forEach((comment) => {
- if (comment.filePath !== file.path) {
- return;
- }
- const endIndex = Math.min(comment.endIndex, lineRows.length - 1);
- if (endIndex < 0) {
- return;
- }
- const existing = commentsByEndIndex.get(endIndex);
- if (existing) {
- existing.push(comment);
- return;
- }
- commentsByEndIndex.set(endIndex, [comment]);
- });
let lineIndex = 0;
file.rows.forEach((row, rowIndex) => {
if (row.kind === "hunk") {
@@ -434,37 +432,70 @@ function mapFileRows(
lines: lineRows,
lineIndex,
});
- const commentsForLine = commentsByEndIndex.get(lineIndex) ?? [];
- for (const comment of commentsForLine) {
+ lineIndex += 1;
+ });
+
+ rows.push(...noticeRowsForFile(file));
+ return {
+ fileId: file.id,
+ filePath: file.path,
+ lineCount: lineRows.length,
+ // Comments must not split the source deletion/addition runs used for word matching.
+ rows: addNativeWordDiffRanges(rows),
+ commentedRows: null,
+ };
+}
+
+function insertFileComments(
+ file: PreparedNativeReviewFileRows,
+ comments: ReadonlyArray<ReviewInlineComment>,
+): ReadonlyArray<NativeReviewDiffRow> {
+ if (comments.length === 0) {
+ file.commentedRows = null;
+ return file.rows;
+ }
+ const commentsKey = buildReviewCommentsCacheKey(comments);
+ if (file.commentedRows?.commentsKey === commentsKey) {
+ return file.commentedRows.rows;
+ }
+
+ const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
+ for (const comment of comments) {
+ const endIndex = Math.min(comment.endIndex, file.lineCount - 1);
+ if (endIndex < 0) continue;
+ const existing = commentsByEndIndex.get(endIndex);
+ if (existing) {
+ existing.push(comment);
+ } else {
+ commentsByEndIndex.set(endIndex, [comment]);
+ }
+ }
+ const rows: NativeReviewDiffRow[] = [];
+ let lineIndex = 0;
+ for (const row of file.rows) {
+ rows.push(row);
+ if (row.kind !== "line") continue;
+ for (const comment of commentsByEndIndex.get(lineIndex) ?? []) {
rows.push({
kind: "comment",
id: comment.id,
- fileId: file.id,
- filePath: file.path,
+ fileId: file.fileId,
+ filePath: file.filePath,
commentText: comment.text,
commentRangeLabel: comment.rangeLabel,
commentSectionTitle: comment.sectionTitle,
});
}
lineIndex += 1;
- });
-
- rows.push(...noticeRowsForFile(file));
+ }
+ file.commentedRows = { commentsKey, rows };
return rows;
}
-export function buildNativeReviewDiffData(
- input: BuildNativeReviewDiffDataInput,
-): NativeReviewDiffData;
-export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
-export function buildNativeReviewDiffData(
- input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
-): NativeReviewDiffData {
- const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
- const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
+function prepareNativeReviewDiffData(parsedDiff: ReviewParsedDiff): PreparedNativeReviewDiffData {
if (parsedDiff.kind !== "files") {
return {
- rows: [],
+ fileRows: [],
files: [],
commentTargetsByRowId: new Map(),
rowIdByCommentLineId: new Map(),
@@ -482,14 +513,12 @@ export function buildNativeReviewDiffData(
}));
const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
const rowIdByCommentLineId = new Map<string, string>();
- const rows = addNativeWordDiffRanges(
- Arr.flatMap(parsedDiff.files, (file) =>
- mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId),
- ),
+ const fileRows = parsedDiff.files.map((file) =>
+ prepareFileRows(file, commentTargetsByRowId, rowIdByCommentLineId),
);
return {
- rows,
+ fileRows,
files,
commentTargetsByRowId,
rowIdByCommentLineId,
@@ -498,10 +527,47 @@ export function buildNativeReviewDiffData(
};
}
+function buildCommentedNativeReviewDiffData(
+ prepared: PreparedNativeReviewDiffData,
+ comments: ReadonlyArray<ReviewInlineComment>,
+): NativeReviewDiffData {
+ const commentsByFilePath = new Map<string, ReviewInlineComment[]>();
+ for (const comment of comments) {
+ const existing = commentsByFilePath.get(comment.filePath);
+ if (existing) {
+ existing.push(comment);
+ } else {
+ commentsByFilePath.set(comment.filePath, [comment]);
+ }
+ }
+ return {
+ rows: Arr.flatMap(prepared.fileRows, (file) =>
+ insertFileComments(file, commentsByFilePath.get(file.filePath) ?? []),
+ ),
+ files: prepared.files,
+ commentTargetsByRowId: prepared.commentTargetsByRowId,
+ rowIdByCommentLineId: prepared.rowIdByCommentLineId,
+ additions: prepared.additions,
+ deletions: prepared.deletions,
+ };
+}
+
+export function buildNativeReviewDiffData(
+ input: BuildNativeReviewDiffDataInput,
+): NativeReviewDiffData;
+export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
+export function buildNativeReviewDiffData(
+ input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
+): NativeReviewDiffData {
+ const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
+ const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
+ return buildCommentedNativeReviewDiffData(prepareNativeReviewDiffData(parsedDiff), comments);
+}
+
/**
- * Reuses the expensive flattened native row model across React development
- * render probes and unrelated draft updates. Only the latest comment version
- * is retained for each parsed diff so editing a comment cannot grow the cache.
+ * Prepares source rows once per parsed diff, including its section-specific IDs.
+ * Comment edits reuse those rows, word ranges, and targets. Each file retains
+ * only its latest comment overlay, and the weak key releases old parsed diffs.
*/
export function getCachedNativeReviewDiffData(
input: BuildNativeReviewDiffDataInput,
@@ -513,10 +579,8 @@ export function getCachedNativeReviewDiffData(
return cached.data;
}
- const data = buildNativeReviewDiffData({
- parsedDiff: input.parsedDiff,
- comments,
- });
- nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data });
+ const prepared = cached?.prepared ?? prepareNativeReviewDiffData(input.parsedDiff);
+ const data = buildCommentedNativeReviewDiffData(prepared, comments);
+ nativeReviewDiffDataCache.set(input.parsedDiff, { prepared, commentsKey, data });
return data;
}