Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nativeReviewDiffHighlighter.test.ts

338 lines10.2 KB

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 };
58​
59function makeHunk(id: string): NativeReviewDiffRow {
60 return {
61 kind: "hunk",
62 id,
63 fileId: TYPESCRIPT_FILE.id,
64 text: "@@",
65 };
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 });
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 it("keeps deletion grammar state out of addition rows", async () => {
196 const additionRow = makeLine({
197 id: "addition-row",
198 content: "export const answer = 42;",
199 change: "add",
200 oldLineNumber: null,
201 newLineNumber: 1,
202 });
203 const rows = [
204 makeLine({
205 id: "deletion-row",
206 content: "const removed = `open",
207 change: "delete",
208 oldLineNumber: 1,
209 newLineNumber: null,
210 }),
211 additionRow,
212 ];
213​
214 const [highlighted, standalone] = await Promise.all([
215 highlight(rows),
216 highlight([additionRow]),
217 ]);
218​
219 expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
220 standalone.tokensByRowId[additionRow.id],
221 );
222 });
223});
224​
225describe.each(["native", "javascript"] as const)("%s highlighting budgets", (engine) => {
226 const highlightRows = (rows: ReadonlyArray<NativeReviewDiffRow>, signal?: AbortSignal) =>
227 highlightNativeReviewDiffVisibleRows({
228 rows,
229 files: [TYPESCRIPT_FILE],
230 scheme: "dark",
231 engine,
232 firstRowIndex: 0,
233 lastRowIndex: rows.length - 1,
234 overscanRows: 0,
235 signal,
236 });
237​
238 const line = (id: number, content: string) =>
239 makeLine({
240 id: `line-${id}`,
241 content,
242 change: "add",
243 oldLineNumber: null,
244 newLineNumber: id,
245 });
246​
247 it("still highlights a line at the length limit", async () => {
248 const content = `// ${"x".repeat(997)}`;
249 const result = await highlightRows([line(1, content)]);
250​
251 expect(tokenization.calls).toEqual([content]);
252 expect(result.tokensByRowId["line-1"]?.some((token) => token.color !== null)).toBe(true);
253 });
254​
255 it("keeps only the long line plain and resumes highlighting after it", async () => {
256 const longLine = `${"x".repeat(1_001)} /*`;
257 const rows = [
258 line(1, "export const before = 1;"),
259 line(2, longLine),
260 { kind: "comment", id: "note", commentText: "Check this", fileId: TYPESCRIPT_FILE.id },
261 line(3, "export const inside = 'x';"),
262 makeHunk("next-hunk"),
263 line(100, "export const after = 2;"),
264 ] satisfies ReadonlyArray<NativeReviewDiffRow>;
265 const result = await highlightRows(rows);
266​
267 expect(result.engine).toBe(engine);
268 expect(Object.keys(result.tokensByRowId)).toEqual(["line-1", "line-2", "line-3", "line-100"]);
269 expect(result.tokensByRowId["line-2"]).toEqual([
270 { content: longLine, color: null, fontStyle: null },
271 ]);
272 for (const id of ["line-1", "line-3", "line-100"]) {
273 expect(result.tokensByRowId[id]?.some((token) => token.color !== null)).toBe(true);
274 }
275 expect(tokenization.calls.some((code) => code.includes(longLine))).toBe(false);
276 });
277​
278 it("highlights the rows after a long line the same regardless of the first window", async () => {
279 const rows = [
280 line(1, "export const before = 1;"),
281 line(2, `const data = "${"x".repeat(1_050)}";`),
282 line(3, "export const inside = 'x';"),
283 line(4, "export const after = 2;"),
284 ];
285 const spanning = await highlightRows(rows);
286 const afterLongLine = await highlightNativeReviewDiffVisibleRows({
287 rows,
288 files: [TYPESCRIPT_FILE],
289 scheme: "dark",
290 engine,
291 firstRowIndex: 2,
292 lastRowIndex: 3,
293 overscanRows: 0,
294 });
295​
296 for (const id of ["line-3", "line-4"]) {
297 expect(spanning.tokensByRowId[id]?.some((token) => token.color !== null)).toBe(true);
298 expect(afterLongLine.tokensByRowId[id]).toEqual(spanning.tokensByRowId[id]);
299 }
300 });
301​
302 it("preserves multiline grammar and row mapping across character-limited batches", async () => {
303 const opening = line(1, "const message = `open");
304 const body = Array.from({ length: 40 }, (_, index) => line(index + 2, "inside ".repeat(45)));
305 const closing = line(42, "closed`; ");
306 const trailing = line(43, "export const after = 2;");
307 const result = await highlightRows([opening, ...body, closing, trailing]);
308 const calls = [...tokenization.calls];
309 const expected = await highlightRows([
310 opening,
311 { ...closing, newLineNumber: 2 },
312 { ...trailing, newLineNumber: 3 },
313 ]);
314​
315 expect(calls.length).toBeGreaterThan(1);
316 expect(calls.every((code) => code.length <= 8_000)).toBe(true);
317 expect(result.rowCount).toBe(43);
318 for (const row of [opening, ...body, closing, trailing]) {
319 expect(result.tokensByRowId[row.id]?.map((token) => token.content).join("")).toBe(
320 row.content,
321 );
322 }
323 expect(result.tokensByRowId[closing.id]).toEqual(expected.tokensByRowId[closing.id]);
324 expect(result.tokensByRowId[trailing.id]).toEqual(expected.tokensByRowId[trailing.id]);
325 });
326​
327 it("stops before later batches and publishes no partial result after cancellation", async () => {
328 const controller = new AbortController();
329 tokenization.afterCall = () => controller.abort();
330 const rows = Array.from({ length: 30 }, (_, index) => line(index + 1, `// ${"x".repeat(400)}`));
331​
332 const result = await highlightRows(rows, controller.signal);
333​
334 expect(tokenization.calls).toHaveLength(1);
335 expect(result.rowCount).toBe(0);
336 expect(result.tokensByRowId).toEqual({});
337 });
338});