Skip to content
TypeScript

perf(mobile): bound diff syntax highlighting work (#9673)

Theo Browne3b6be3ef4daa
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
index 9e1480d1de9..00679afa4a6 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
@@ -1,8 +1,47 @@
-import { describe, expect, it } from "vite-plus/test";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
-import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
+import {
+ highlightNativeReviewDiffVisibleRows,
+ streamNativeReviewDiffTokens,
+ type NativeReviewDiffTokenChunk,
+} from "./nativeReviewDiffHighlighter";
+
+const tokenization = vi.hoisted(() => ({
+ calls: [] as string[],
+ afterCall: undefined as (() => void) | undefined,
+}));
+
+vi.mock("@shikijs/core", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@shikijs/core")>();
+ return {
+ ...original,
+ createHighlighterCore: async (...args: Parameters<typeof original.createHighlighterCore>) => {
+ const highlighter = await original.createHighlighterCore(...args);
+ return {
+ ...highlighter,
+ codeToTokensBase: (...input: Parameters<typeof highlighter.codeToTokensBase>) => {
+ tokenization.calls.push(input[0]);
+ const result = highlighter.codeToTokensBase(...input);
+ tokenization.afterCall?.();
+ return result;
+ },
+ };
+ },
+ };
+});
+
+// Exercise the native entry path without requiring an iOS or Android runtime.
+vi.mock("react-native-shiki-engine", async () => {
+ const { createJavaScriptRegexEngine } = await import("@shikijs/engine-javascript");
+ return { isNativeEngineAvailable: () => true, createNativeEngine: createJavaScriptRegexEngine };
+});
+
+afterEach(() => {
+ tokenization.calls = [];
+ tokenization.afterCall = undefined;
+});
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
id: "file-1",
@@ -187,3 +226,113 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
);
});
});
+
+describe.each(["native", "javascript"] as const)("%s highlighting budgets", (engine) => {
+ const highlightRows = (rows: ReadonlyArray<NativeReviewDiffRow>, signal?: AbortSignal) =>
+ highlightNativeReviewDiffVisibleRows({
+ rows,
+ files: [TYPESCRIPT_FILE],
+ scheme: "dark",
+ engine,
+ firstRowIndex: 0,
+ lastRowIndex: rows.length - 1,
+ overscanRows: 0,
+ signal,
+ });
+
+ const line = (id: number, content: string) =>
+ makeLine({
+ id: `line-${id}`,
+ content,
+ change: "add",
+ oldLineNumber: null,
+ newLineNumber: id,
+ });
+
+ it("still highlights a line at the length limit", async () => {
+ const content = `// ${"x".repeat(997)}`;
+ const result = await highlightRows([line(1, content)]);
+
+ expect(tokenization.calls).toEqual([content]);
+ expect(result.tokensByRowId["line-1"]?.some((token) => token.color !== null)).toBe(true);
+ });
+
+ it("keeps long lines and unknown following syntax plain until the next hunk", async () => {
+ const longLine = `${"x".repeat(1_001)} /*`;
+ const rows = [
+ line(1, "export const before = 1;"),
+ line(2, longLine),
+ { kind: "comment", id: "note", commentText: "Check this", fileId: TYPESCRIPT_FILE.id },
+ line(3, "inside the comment */"),
+ makeHunk("next-hunk"),
+ line(100, "export const after = 2;"),
+ ] satisfies ReadonlyArray<NativeReviewDiffRow>;
+ const result = await highlightRows(rows);
+
+ expect(result.engine).toBe(engine);
+ expect(Object.keys(result.tokensByRowId)).toEqual(["line-1", "line-2", "line-3", "line-100"]);
+ expect(result.tokensByRowId["line-2"]).toEqual([
+ { content: longLine, color: null, fontStyle: null },
+ ]);
+ expect(result.tokensByRowId["line-3"]).toEqual([
+ { content: "inside the comment */", color: null, fontStyle: null },
+ ]);
+ expect(result.tokensByRowId["line-1"]?.some((token) => token.color !== null)).toBe(true);
+ expect(result.tokensByRowId["line-100"]?.some((token) => token.color !== null)).toBe(true);
+ expect(tokenization.calls.some((code) => code.includes(longLine))).toBe(false);
+ });
+
+ it("preserves multiline grammar and row mapping across character-limited batches", async () => {
+ const opening = line(1, "const message = `open");
+ const body = Array.from({ length: 40 }, (_, index) => line(index + 2, "inside ".repeat(45)));
+ const closing = line(42, "closed`; ");
+ const trailing = line(43, "export const after = 2;");
+ const result = await highlightRows([opening, ...body, closing, trailing]);
+ const calls = [...tokenization.calls];
+ const expected = await highlightRows([
+ opening,
+ { ...closing, newLineNumber: 2 },
+ { ...trailing, newLineNumber: 3 },
+ ]);
+
+ expect(calls.length).toBeGreaterThan(1);
+ expect(calls.every((code) => code.length <= 8_000)).toBe(true);
+ expect(result.rowCount).toBe(43);
+ for (const row of [opening, ...body, closing, trailing]) {
+ expect(result.tokensByRowId[row.id]?.map((token) => token.content).join("")).toBe(
+ row.content,
+ );
+ }
+ expect(result.tokensByRowId[closing.id]).toEqual(expected.tokensByRowId[closing.id]);
+ expect(result.tokensByRowId[trailing.id]).toEqual(expected.tokensByRowId[trailing.id]);
+ });
+
+ it("stops before later batches and publishes no partial result after cancellation", async () => {
+ const controller = new AbortController();
+ tokenization.afterCall = () => controller.abort();
+ const rows = Array.from({ length: 30 }, (_, index) => line(index + 1, `// ${"x".repeat(400)}`));
+
+ const result = await highlightRows(rows, controller.signal);
+
+ expect(tokenization.calls).toHaveLength(1);
+ expect(result.rowCount).toBe(0);
+ expect(result.tokensByRowId).toEqual({});
+ });
+
+ it("applies the same long-line guard to streamed token chunks", async () => {
+ const content = "x".repeat(10_000);
+ const chunks: NativeReviewDiffTokenChunk[] = [];
+
+ await streamNativeReviewDiffTokens({
+ rows: [line(1, content)],
+ files: [TYPESCRIPT_FILE],
+ scheme: "dark",
+ engine,
+ onChunk: (chunk) => chunks.push(chunk),
+ });
+
+ expect(chunks).toHaveLength(1);
+ expect(chunks[0]?.tokensByRowId["line-1"]).toEqual([{ content, color: null, fontStyle: null }]);
+ expect(tokenization.calls).toHaveLength(0);
+ });
+});
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
index 14158e61c7d..383e1e73a85 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
@@ -1,4 +1,4 @@
-import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
+import { createHighlighterCore, type GrammarState, type HighlighterCore } from "@shikijs/core";
import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
import bashLanguage from "@shikijs/langs/bash";
import diffLanguage from "@shikijs/langs/diff";
@@ -46,8 +46,12 @@ export interface NativeReviewDiffHighlighterHandle {
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokenize: (
code: string,
- options: { readonly lang: NativeReviewDiffLanguage; readonly theme: string },
- ) => ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>;
+ options: {
+ readonly lang: NativeReviewDiffLanguage;
+ readonly theme: string;
+ readonly signal?: AbortSignal;
+ },
+ ) => Promise<ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>>;
}
interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
@@ -97,6 +101,8 @@ export interface HighlightNativeReviewDiffVisibleRowsInput {
const NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE = 500;
const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
+const NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH = 1_000;
+const NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS = 8_000;
const NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME = {
dark: "t3-pierre-dark",
@@ -226,6 +232,63 @@ function normalizeTokens(
);
}
+function createHighlighterHandle(
+ highlighter: HighlighterCore,
+ engine: NativeReviewDiffHighlightEngine,
+): NativeReviewDiffHighlighterHandle {
+ return {
+ engine,
+ async tokenize(code, { lang, theme, signal }) {
+ const lines = code.split("\n");
+ const highlighted: Array<ReadonlyArray<NativeReviewDiffToken>> = [];
+ let grammarState: GrammarState | undefined;
+ let start = 0;
+
+ while (start < lines.length) {
+ if (signal?.aborted) return [];
+
+ // Skipping this line leaves its ending grammar state unknown. Keep the
+ // rest of this contiguous segment plain instead of guessing its syntax.
+ if (lines[start]!.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH) {
+ highlighted.push(
+ ...lines
+ .slice(start)
+ .map((content) => [{ content: content || " ", color: null, fontStyle: null }]),
+ );
+ break;
+ }
+
+ let end = start;
+ let characters = 0;
+ while (end < lines.length) {
+ const length = lines[end]!.length;
+ const nextCharacters = characters + length + (end > start ? 1 : 0);
+ if (
+ length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH ||
+ nextCharacters > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
+ ) {
+ break;
+ }
+ characters = nextCharacters;
+ end += 1;
+ }
+
+ const tokens = highlighter.codeToTokensBase(lines.slice(start, end).join("\n"), {
+ lang,
+ theme,
+ grammarState,
+ });
+ grammarState = highlighter.getLastGrammarState(tokens);
+ highlighted.push(...normalizeTokens(tokens));
+ start = end;
+ if (start < lines.length) await waitForNextFrame();
+ }
+
+ return signal?.aborted ? [] : highlighted;
+ },
+ };
+}
+
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
const nativeEngineModule = await import("react-native-shiki-engine");
if (!nativeEngineModule.isNativeEngineAvailable()) {
@@ -238,10 +301,7 @@ async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHigh
engine: nativeEngineModule.createNativeEngine(),
});
- return {
- engine: "native",
- tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
- };
+ return createHighlighterHandle(highlighter, "native");
}
async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
@@ -251,10 +311,7 @@ async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiff
engine: createJavaScriptRegexEngine(),
});
- return {
- engine: "javascript",
- tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
- };
+ return createHighlighterHandle(highlighter, "javascript");
}
export async function getNativeReviewDiffHighlighter(
@@ -438,8 +495,9 @@ export async function highlightNativeReviewDiffVisibleRows(
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
let segmentFile: NativeReviewDiffFile | undefined;
+ let charactersSinceYield = 0;
- const flushSegment = () => {
+ const flushSegment = async () => {
if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
segmentRows = [];
segmentFile = undefined;
@@ -447,7 +505,20 @@ export async function highlightNativeReviewDiffVisibleRows(
}
const code = segmentRows.map(({ row }) => row.content).join("\n");
- const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
+ if (
+ charactersSinceYield > 0 &&
+ charactersSinceYield + code.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
+ ) {
+ await waitForNextFrame();
+ charactersSinceYield = 0;
+ if (input.signal?.aborted) return;
+ }
+ const tokenLines = await highlighter.tokenize(code, {
+ lang: segmentFile.language,
+ theme,
+ signal: input.signal,
+ });
+ charactersSinceYield += code.length;
segmentRows.forEach(({ row }, rowIndex) => {
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
});
@@ -456,6 +527,7 @@ export async function highlightNativeReviewDiffVisibleRows(
};
for (const selectedRow of selectedRows) {
+ if (input.signal?.aborted) break;
const { row } = selectedRow;
const file = fileMap.get(row.fileId);
if (!file) {
@@ -469,13 +541,17 @@ export async function highlightNativeReviewDiffVisibleRows(
(previousRow !== undefined &&
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
) {
- flushSegment();
+ await flushSegment();
}
segmentFile = file;
segmentRows.push(selectedRow);
}
- flushSegment();
+ await flushSegment();
+
+ if (input.signal?.aborted) {
+ return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
+ }
return {
engine: highlighter.engine,
@@ -504,7 +580,12 @@ export async function streamNativeReviewDiffTokens(
const startedAt = performance.now();
const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
const code = chunkRows.map((row) => row.content).join("\n");
- const tokenLines = highlighter.tokenize(code, { lang: file.language, theme });
+ const tokenLines = await highlighter.tokenize(code, {
+ lang: file.language,
+ theme,
+ signal: input.signal,
+ });
+ if (input.signal?.aborted) return highlighter.engine;
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
chunkRows.forEach((row, rowIndex) => {