Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
4import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
5import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
6
7const tokenization = vi.hoisted(() => ({
8 calls: [] as string[],
9 afterCall: undefined as (() => void) | undefined,
10}));
11
12vi.mock("@shikijs/core", async (importOriginal) => {
13 const original = await importOriginal<typeof import("@shikijs/core")>();
14 return {
15 ...original,
16 createHighlighterCore: async (...args: Parameters<typeof original.createHighlighterCore>) => {
17 const highlighter = await original.createHighlighterCore(...args);
18 return {
19 ...highlighter,
20 codeToTokensBase: (...input: Parameters<typeof highlighter.codeToTokensBase>) => {
21 tokenization.calls.push(input[0]);
22 const result = highlighter.codeToTokensBase(...input);
23 tokenization.afterCall?.();
24 return result;
25 },
26 };
27 },
28 };
29});
30
31vi.mock("react-native-shiki-engine", async () => {
32 const { createJavaScriptRegexEngine } = await import("@shikijs/engine-javascript");
33 return { isNativeEngineAvailable: () => true, createNativeEngine: createJavaScriptRegexEngine };
34});
35
36afterEach(() => {
37 tokenization.calls = [];
38 tokenization.afterCall = undefined;
39});
40
41const TYPESCRIPT_FILE: NativeReviewDiffFile = {
42 id: "file-1",
43 path: "example.ts",
44 language: "typescript",
45 additions: 0,
46 deletions: 0,
47};
48
49function makeLine(
50 input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
51): NativeReviewDiffRow {
52 return {
53 kind: "line",
54 fileId: TYPESCRIPT_FILE.id,
55 ...input,
56 };
57}
58
59function makeHunk(id: string): NativeReviewDiffRow {
60 return {
61 kind: "hunk",
62 id,
63 fileId: TYPESCRIPT_FILE.id,
64 text: "@@",
65 };
66}
67
68function highlight(
69 rows: ReadonlyArray<NativeReviewDiffRow>,
70 alreadyHighlightedRowIds?: ReadonlySet<string>,
71) {
72 return highlightNativeReviewDiffVisibleRows({
73 rows,
74 files: [TYPESCRIPT_FILE],
75 scheme: "dark",
76 engine: "javascript",
77 firstRowIndex: 0,
78 lastRowIndex: rows.length - 1,
79 overscanRows: 0,
80 maxRows: 100,
81 alreadyHighlightedRowIds,
82 });
83}
84
85describe("highlightNativeReviewDiffVisibleRows", () => {
86 it("does not carry grammar state across hunk boundaries", async () => {
87 const exportRow = makeLine({
88 id: "export-row",
89 content: "export async function run() {}",
90 change: "add",
91 oldLineNumber: null,
92 newLineNumber: 100,
93 });
94 const rows = [
95 makeHunk("hunk-1"),
96 makeLine({
97 id: "import-open",
98 content: "import {",
99 change: "context",
100 oldLineNumber: 1,
101 newLineNumber: 1,
102 }),
103 makeLine({
104 id: "import-entry",
105 content: " Model,",
106 change: "context",
107 oldLineNumber: 2,
108 newLineNumber: 2,
109 }),
110 makeHunk("hunk-2"),
111 exportRow,
112 ];
113
114 const [highlighted, standalone] = await Promise.all([
115 highlight(rows),
116 highlight([makeHunk("standalone-hunk"), exportRow]),
117 ]);
118
119 expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
120 });
121
122 it("keeps grammar state across inline comment rows", async () => {
123 const openingRow = makeLine({
124 id: "template-open",
125 content: "const message = `open",
126 change: "add",
127 oldLineNumber: null,
128 newLineNumber: 1,
129 });
130 const closingRow = makeLine({
131 id: "template-close",
132 content: "closed`;",
133 change: "add",
134 oldLineNumber: null,
135 newLineNumber: 2,
136 });
137 const trailingRow = makeLine({
138 id: "trailing-row",
139 content: "export const answer = 42;",
140 change: "add",
141 oldLineNumber: null,
142 newLineNumber: 3,
143 });
144 const commentRow: NativeReviewDiffRow = {
145 kind: "comment",
146 id: "comment-1",
147 fileId: TYPESCRIPT_FILE.id,
148 commentText: "Review note",
149 };
150
151 const [withComment, contiguous] = await Promise.all([
152 highlight([openingRow, commentRow, closingRow, trailingRow]),
153 highlight([openingRow, closingRow, trailingRow]),
154 ]);
155
156 expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
157 });
158
159 it("does not join unhighlighted rows across cached gaps", async () => {
160 const trailingRow = makeLine({
161 id: "trailing-row",
162 content: "export const answer = 42;",
163 change: "add",
164 oldLineNumber: null,
165 newLineNumber: 3,
166 });
167 const rows = [
168 makeLine({
169 id: "template-open",
170 content: "const message = `open",
171 change: "add",
172 oldLineNumber: null,
173 newLineNumber: 1,
174 }),
175 makeLine({
176 id: "template-close",
177 content: "closed`;",
178 change: "add",
179 oldLineNumber: null,
180 newLineNumber: 2,
181 }),
182 trailingRow,
183 ];
184
185 const [highlighted, standalone] = await Promise.all([
186 highlight(rows, new Set(["template-close"])),
187 highlight([trailingRow]),
188 ]);
189
190 expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
191 standalone.tokensByRowId[trailingRow.id],
192 );
193 });
194});
195
196describe.each(["native", "javascript"] as const)("%s highlighting budgets", (engine) => {
197 const highlightRows = (rows: ReadonlyArray<NativeReviewDiffRow>, signal?: AbortSignal) =>
198 highlightNativeReviewDiffVisibleRows({
199 rows,
200 files: [TYPESCRIPT_FILE],
201 scheme: "dark",
202 engine,
203 firstRowIndex: 0,
204 lastRowIndex: rows.length - 1,
205 overscanRows: 0,
206 signal,
207 });
208
209 const line = (id: number, content: string) =>
210 makeLine({
211 id: `line-${id}`,
212 content,
213 change: "add",
214 oldLineNumber: null,
215 newLineNumber: id,
216 });
217
218 it("keeps only the long line plain and resumes highlighting after it", async () => {
219 const longLine = `${"x".repeat(1_001)} /*`;
220 const rows = [
221 line(1, "export const before = 1;"),
222 line(2, longLine),
223 { kind: "comment", id: "note", commentText: "Check this", fileId: TYPESCRIPT_FILE.id },
224 line(3, "export const inside = 'x';"),
225 makeHunk("next-hunk"),
226 line(100, "export const after = 2;"),
227 ] satisfies ReadonlyArray<NativeReviewDiffRow>;
228 const result = await highlightRows(rows);
229
230 expect(result.engine).toBe(engine);
231 expect(Object.keys(result.tokensByRowId)).toEqual(["line-1", "line-2", "line-3", "line-100"]);
232 expect(result.tokensByRowId["line-2"]).toEqual([
233 { content: longLine, color: null, fontStyle: null },
234 ]);
235 for (const id of ["line-1", "line-3", "line-100"]) {
236 expect(result.tokensByRowId[id]?.some((token) => token.color !== null)).toBe(true);
237 }
238 expect(tokenization.calls.some((code) => code.includes(longLine))).toBe(false);
239 });
240
241 it("highlights the rows after a long line the same regardless of the first window", async () => {
242 const rows = [
243 line(1, "export const before = 1;"),
244 line(2, `const data = "${"x".repeat(1_050)}";`),
245 line(3, "export const inside = 'x';"),
246 line(4, "export const after = 2;"),
247 ];
248 const spanning = await highlightRows(rows);
249 const afterLongLine = await highlightNativeReviewDiffVisibleRows({
250 rows,
251 files: [TYPESCRIPT_FILE],
252 scheme: "dark",
253 engine,
254 firstRowIndex: 2,
255 lastRowIndex: 3,
256 overscanRows: 0,
257 });
258
259 for (const id of ["line-3", "line-4"]) {
260 expect(spanning.tokensByRowId[id]?.some((token) => token.color !== null)).toBe(true);
261 expect(afterLongLine.tokensByRowId[id]).toEqual(spanning.tokensByRowId[id]);
262 }
263 });
264
265 it("preserves multiline grammar and row mapping across character-limited batches", async () => {
266 const opening = line(1, "const message = `open");
267 const body = Array.from({ length: 40 }, (_, index) => line(index + 2, "inside ".repeat(45)));
268 const closing = line(42, "closed`; ");
269 const trailing = line(43, "export const after = 2;");
270 const result = await highlightRows([opening, ...body, closing, trailing]);
271 const calls = [...tokenization.calls];
272 const expected = await highlightRows([
273 opening,
274 { ...closing, newLineNumber: 2 },
275 { ...trailing, newLineNumber: 3 },
276 ]);
277
278 expect(calls.length).toBeGreaterThan(1);
279 expect(calls.every((code) => code.length <= 8_000)).toBe(true);
280 expect(result.rowCount).toBe(43);
281 for (const row of [opening, ...body, closing, trailing]) {
282 expect(result.tokensByRowId[row.id]?.map((token) => token.content).join("")).toBe(
283 row.content,
284 );
285 }
286 expect(result.tokensByRowId[closing.id]).toEqual(expected.tokensByRowId[closing.id]);
287 expect(result.tokensByRowId[trailing.id]).toEqual(expected.tokensByRowId[trailing.id]);
288 });
289
290 it("stops before later batches and publishes no partial result after cancellation", async () => {
291 const controller = new AbortController();
292 tokenization.afterCall = () => controller.abort();
293 const rows = Array.from({ length: 30 }, (_, index) => line(index + 1, `// ${"x".repeat(400)}`));
294
295 const result = await highlightRows(rows, controller.signal);
296
297 expect(tokenization.calls).toHaveLength(1);
298 expect(result.rowCount).toBe(0);
299 expect(result.tokensByRowId).toEqual({});
300 });
301});