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