Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { highlightCode } from "../../lib/highlights";
4
5import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
6import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
7import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
8import { buildNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
9import { buildReviewParsedDiff } from "../review/reviewModel";
10
11const tokenization = vi.hoisted(() => ({
12 calls: [] as string[],
13 afterCall: undefined as (() => void) | undefined,
14}));
15
16vi.mock("expo", async () => {
17 const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");
18 const module = createWasmHighlightsModule();
19 return {
20 requireOptionalNativeModule: () => ({
21 tokenize(code: string, language: number) {
22 tokenization.calls.push(code);
23 const records = module.tokenize(code, language);
24 tokenization.afterCall?.();
25 return records;
26 },
27 }),
28 };
29});
30
31afterEach(() => {
32 tokenization.calls = [];
33 tokenization.afterCall = undefined;
34});
35
36const TYPESCRIPT_FILE: NativeReviewDiffFile = {
37 id: "file-1",
38 path: "example.ts",
39 language: "typescript",
40 additions: 0,
41 deletions: 0,
42};
43
44function makeLine(
45 input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
46): NativeReviewDiffRow {
47 return {
48 kind: "line",
49 fileId: TYPESCRIPT_FILE.id,
50 ...input,
51 };
52}
53
54function makeHunk(id: string): NativeReviewDiffRow {
55 return {
56 kind: "hunk",
57 id,
58 fileId: TYPESCRIPT_FILE.id,
59 text: "@@",
60 };
61}
62
63function highlight(
64 rows: ReadonlyArray<NativeReviewDiffRow>,
65 alreadyHighlightedRowIds?: ReadonlySet<string>,
66) {
67 return highlightNativeReviewDiffVisibleRows({
68 rows,
69 files: [TYPESCRIPT_FILE],
70 scheme: "dark",
71 firstRowIndex: 0,
72 lastRowIndex: rows.length - 1,
73 overscanRows: 0,
74 maxRows: 100,
75 alreadyHighlightedRowIds,
76 });
77}
78
79describe("highlightNativeReviewDiffVisibleRows", () => {
80 it("keeps overscan within the visible files, including a file header at the viewport edge", async () => {
81 const loadedFiles: string[] = [];
82 const files = Array.from({ length: 14 }, (_, index) => {
83 const id = `file-${index}`;
84 const source = Array.from({ length: 3 }, (_, line) => `const value${line} = ${line};`);
85 return {
86 ...TYPESCRIPT_FILE,
87 id,
88 loadContents: async () => {
89 loadedFiles.push(id);
90 return { oldContents: "", newContents: source.join("\n") };
91 },
92 rows: [
93 { kind: "file", id: `${id}-header`, fileId: id },
94 ...source.map((content, line) => ({
95 ...makeLine({
96 id: `${id}-line-${line + 1}`,
97 content,
98 change: "add",
99 oldLineNumber: null,
100 newLineNumber: line + 1,
101 }),
102 fileId: id,
103 })),
104 ] satisfies NativeReviewDiffRow[],
105 };
106 });
107 const input = {
108 rows: files.flatMap((file) => file.rows),
109 files,
110 scheme: "dark" as const,
111 firstRowIndex: 30,
112 lastRowIndex: 32,
113 };
114 const viewport = await highlightNativeReviewDiffVisibleRows({ ...input, overscanRows: 0 });
115 const visibleIds = ["file-7-line-2", "file-7-line-3"];
116 expect(Object.keys(viewport.tokensByRowId)).toEqual(visibleIds);
117 const overscan = await highlightNativeReviewDiffVisibleRows({
118 ...input,
119 overscanRows: 160,
120 alreadyHighlightedRowIds: new Set(visibleIds),
121 });
122 expect(Object.keys(overscan.tokensByRowId).sort()).toEqual([
123 "file-7-line-1",
124 "file-8-line-1",
125 "file-8-line-2",
126 "file-8-line-3",
127 ]);
128 for (const tokens of Object.values({ ...viewport.tokensByRowId, ...overscan.tokensByRowId })) {
129 expect(tokens.some((token) => token.color !== null)).toBe(true);
130 }
131 expect([...new Set(loadedFiles)].sort()).toEqual(["file-7", "file-8"]);
132 });
133
134 it("skips collapsed code before the row cap and restores it on expansion", async () => {
135 const collapsedSource = Array.from(
136 { length: 100_000 },
137 (_, index) => `int hidden${index} = 1;`,
138 );
139 const expandedSource = [
140 "/* open",
141 ...Array.from({ length: 222 }, () => "still a comment"),
142 "*/ int visible = 1;",
143 ];
144 const collapsedLoad = vi.fn(async () => ({
145 oldContents: "",
146 newContents: collapsedSource.join("\n"),
147 }));
148 const expandedLoad = vi.fn(async () => ({
149 oldContents: "",
150 newContents: expandedSource.join("\n"),
151 }));
152 const files = [
153 {
154 ...TYPESCRIPT_FILE,
155 id: "collapsed",
156 language: "c",
157 path: "highlights.c",
158 loadContents: collapsedLoad,
159 },
160 {
161 ...TYPESCRIPT_FILE,
162 id: "expanded",
163 language: "c",
164 path: "highlights.h",
165 loadContents: expandedLoad,
166 },
167 ];
168 const rows = [collapsedSource, expandedSource].flatMap((source, fileIndex) => {
169 const fileId = files[fileIndex]!.id;
170 return [
171 { kind: "file", id: `${fileId}-header`, fileId },
172 ...source.map((content, index) => ({
173 ...makeLine({
174 id: `${fileId}-${index}`,
175 content,
176 change: "add",
177 newLineNumber: index + 1,
178 }),
179 fileId,
180 })),
181 ] satisfies NativeReviewDiffRow[];
182 });
183 const input = {
184 rows,
185 files,
186 scheme: "dark" as const,
187 firstRowIndex: 0,
188 lastRowIndex: rows.length - 1,
189 };
190 // A collapsed header and the next expanded header can share an iOS viewport,
191 // with 100,000 zero-height code rows between their canonical indices.
192 const viewport = await highlightNativeReviewDiffVisibleRows({
193 ...input,
194 collapsedFileIds: new Set(["collapsed"]),
195 overscanRows: 0,
196 });
197 expect(Object.keys(viewport.tokensByRowId)).toEqual(
198 expandedSource.map((_, index) => `expanded-${index}`),
199 );
200 const overscan = await highlightNativeReviewDiffVisibleRows({
201 ...input,
202 collapsedFileIds: new Set(["collapsed"]),
203 lastRowIndex: 100_002,
204 alreadyHighlightedRowIds: new Set(["expanded-0"]),
205 });
206 expect(Object.keys(overscan.tokensByRowId)).toEqual(
207 Array.from({ length: 160 }, (_, index) => `expanded-${index + 1}`),
208 );
209 expect(overscan.tokensByRowId["expanded-1"]).toEqual(
210 highlightCode(expandedSource.join("\n"), "c", "dark")[1],
211 );
212 expect(collapsedLoad).not.toHaveBeenCalled();
213 expect(expandedLoad).toHaveBeenCalled();
214
215 const expanded = await highlightNativeReviewDiffVisibleRows({
216 ...input,
217 lastRowIndex: 400,
218 collapsedFileIds: new Set(),
219 overscanRows: 0,
220 });
221 expect(expanded.rowCount).toBe(360);
222 expect(expanded.tokensByRowId["collapsed-0"]).toBeDefined();
223 expect(collapsedLoad).toHaveBeenCalledTimes(1);
224 });
225
226 it("delivers the dominant viewport file before fetching a smaller blocked neighbor", async () => {
227 const neighborStarted = Promise.withResolvers<void>();
228 const neighborResponse = Promise.withResolvers<{ oldContents: string; newContents: string }>();
229 const source = Array.from({ length: 27 }, (_, index) => `const value${index} = true;`).join(
230 "\n",
231 );
232 const chunks = vi.fn();
233 const rows = [
234 ...Array.from({ length: 5 }, (_, index) => ({
235 ...makeLine({
236 id: `neighbor-${index}`,
237 content: `const value${index} = true;`,
238 change: "add",
239 oldLineNumber: null,
240 newLineNumber: index + 1,
241 }),
242 fileId: "neighbor",
243 })),
244 ...Array.from({ length: 27 }, (_, index) =>
245 makeLine({
246 id: `selected-${index}`,
247 content: `const value${index} = true;`,
248 change: "delete",
249 oldLineNumber: index + 1,
250 newLineNumber: null,
251 }),
252 ),
253 ];
254 const highlighting = highlightNativeReviewDiffVisibleRows({
255 rows,
256 files: [
257 {
258 ...TYPESCRIPT_FILE,
259 id: "neighbor",
260 loadContents: () => {
261 neighborStarted.resolve();
262 return neighborResponse.promise;
263 },
264 },
265 {
266 ...TYPESCRIPT_FILE,
267 loadContents: async () => ({ oldContents: source, newContents: "" }),
268 },
269 ],
270 scheme: "dark",
271 firstRowIndex: 0,
272 lastRowIndex: rows.length - 1,
273 overscanRows: 0,
274 onChunk: chunks,
275 });
276 try {
277 await neighborStarted.promise;
278 expect(chunks).toHaveBeenCalledTimes(1);
279 expect(Object.keys(chunks.mock.calls[0]![0].tokensByRowId)).toEqual(
280 Array.from({ length: 27 }, (_, index) => `selected-${index}`),
281 );
282 expect(
283 chunks.mock.calls[0]![0].tokensByRowId["selected-0"].some(
284 (token: { color: string | null }) => token.color !== null,
285 ),
286 ).toBe(true);
287 } finally {
288 neighborResponse.resolve({ oldContents: "", newContents: source });
289 await highlighting;
290 }
291 });
292
293 it("does not carry grammar state across hunk boundaries", async () => {
294 const exportRow = makeLine({
295 id: "export-row",
296 content: "export async function run() {}",
297 change: "add",
298 oldLineNumber: null,
299 newLineNumber: 100,
300 });
301 const rows = [
302 makeHunk("hunk-1"),
303 makeLine({
304 id: "import-open",
305 content: "import {",
306 change: "context",
307 oldLineNumber: 1,
308 newLineNumber: 1,
309 }),
310 makeLine({
311 id: "import-entry",
312 content: " Model,",
313 change: "context",
314 oldLineNumber: 2,
315 newLineNumber: 2,
316 }),
317 makeHunk("hunk-2"),
318 exportRow,
319 ];
320
321 const [highlighted, standalone] = await Promise.all([
322 highlight(rows),
323 highlight([makeHunk("standalone-hunk"), exportRow]),
324 ]);
325
326 expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
327 });
328
329 it("keeps grammar state across inline comment rows", async () => {
330 const openingRow = makeLine({
331 id: "template-open",
332 content: "const message = `open",
333 change: "add",
334 oldLineNumber: null,
335 newLineNumber: 1,
336 });
337 const closingRow = makeLine({
338 id: "template-close",
339 content: "closed`;",
340 change: "add",
341 oldLineNumber: null,
342 newLineNumber: 2,
343 });
344 const trailingRow = makeLine({
345 id: "trailing-row",
346 content: "export const answer = 42;",
347 change: "add",
348 oldLineNumber: null,
349 newLineNumber: 3,
350 });
351 const commentRow: NativeReviewDiffRow = {
352 kind: "comment",
353 id: "comment-1",
354 fileId: TYPESCRIPT_FILE.id,
355 commentText: "Review note",
356 };
357
358 const [withComment, contiguous] = await Promise.all([
359 highlight([openingRow, commentRow, closingRow, trailingRow]),
360 highlight([openingRow, closingRow, trailingRow]),
361 ]);
362
363 expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
364 });
365
366 it("does not join unhighlighted rows across cached gaps", async () => {
367 const trailingRow = makeLine({
368 id: "trailing-row",
369 content: "export const answer = 42;",
370 change: "add",
371 oldLineNumber: null,
372 newLineNumber: 3,
373 });
374 const rows = [
375 makeLine({
376 id: "template-open",
377 content: "const message = `open",
378 change: "add",
379 oldLineNumber: null,
380 newLineNumber: 1,
381 }),
382 makeLine({
383 id: "template-close",
384 content: "closed`;",
385 change: "add",
386 oldLineNumber: null,
387 newLineNumber: 2,
388 }),
389 trailingRow,
390 ];
391
392 const [highlighted, standalone] = await Promise.all([
393 highlight(rows, new Set(["template-close"])),
394 highlight([trailingRow]),
395 ]);
396
397 expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
398 standalone.tokensByRowId[trailingRow.id],
399 );
400 });
401});
402
403// These complete sources are independent of the diff row selection below.
404const OLD_SOURCE = [
405 "export function render(name: string) {",
406 " const heading = `Hello ${name}",
407 "Welcome to the archive.",
408 "Your saved reports follow.",
409 " `;",
410 " /* Historical formatting rules:",
411 " * Keep the title and summary together.",
412 " * Preserve links in the footer.",
413 " */",
414 " return heading.trim();",
415 "}",
416];
417const NEW_SOURCE = [
418 "export function render(name: string) {",
419 " const heading = `Greetings ${name}",
420 "Welcome to the workspace.",
421 "Your saved reports follow.",
422 " `;",
423 " /* Current formatting rules:",
424 " * Keep the title and summary together.",
425 " * Highlight links in the footer.",
426 " */",
427 " return heading.trim();",
428 "}",
429];
430
431function authoritativeTokens(source: ReadonlyArray<string>) {
432 return highlightCode(source.join("\n"), "typescript", "dark");
433}
434
435function sourceRow(change: "context" | "add" | "delete", lineNumber: number) {
436 return makeLine({
437 id: `${change}-${lineNumber}`,
438 content: (change === "delete" ? OLD_SOURCE : NEW_SOURCE)[lineNumber - 1]!,
439 change,
440 oldLineNumber: change === "add" ? null : lineNumber,
441 newLineNumber: change === "delete" ? null : lineNumber,
442 });
443}
444
445function completeDiffRows() {
446 return [
447 sourceRow("context", 1),
448 sourceRow("delete", 2),
449 sourceRow("delete", 3),
450 sourceRow("add", 2),
451 sourceRow("add", 3),
452 sourceRow("context", 4),
453 sourceRow("context", 5),
454 sourceRow("delete", 6),
455 sourceRow("add", 6),
456 sourceRow("context", 7),
457 sourceRow("delete", 8),
458 sourceRow("add", 8),
459 sourceRow("context", 9),
460 sourceRow("context", 10),
461 sourceRow("context", 11),
462 ];
463}
464
465describe("source context", () => {
466 it("highlights parsed CRLF patch rows using omitted full-source templates and comments", async () => {
467 const newSource = [...OLD_SOURCE];
468 newSource[2] = NEW_SOURCE[2]!;
469 newSource[7] = NEW_SOURCE[7]!;
470 const parsed = buildReviewParsedDiff(
471 [
472 "diff --git a/example.ts b/example.ts",
473 "--- a/example.ts",
474 "+++ b/example.ts",
475 "@@ -3,2 +3,2 @@",
476 `-${OLD_SOURCE[2]}\r`,
477 `+${newSource[2]}\r`,
478 ` ${newSource[3]}\r`,
479 "@@ -7,3 +7,3 @@",
480 ` ${newSource[6]}\r`,
481 `-${OLD_SOURCE[7]}\r`,
482 `+${newSource[7]}\r`,
483 ` ${newSource[8]}\r`,
484 "",
485 ].join("\n"),
486 "crlf-context",
487 );
488 expect(parsed.kind).toBe("files");
489 const { rows, files } = buildNativeReviewDiffData(parsed);
490 const lineRows = rows.filter((row) => row.kind === "line");
491 expect(lineRows).toHaveLength(7);
492 const originalContents = lineRows.map((row) => row.content);
493 expect(originalContents.every((content) => content?.endsWith("\r"))).toBe(true);
494 const oldTokens = await authoritativeTokens(OLD_SOURCE);
495 const newTokens = await authoritativeTokens(newSource);
496 const result = await highlightNativeReviewDiffVisibleRows({
497 rows,
498 files: files.map((file) => ({
499 ...file,
500 loadContents: async () => ({
501 oldContents: `${OLD_SOURCE.join("\r\n")}\r\n`,
502 newContents: `${newSource.join("\r\n")}\r\n`,
503 }),
504 })),
505 scheme: "dark",
506 firstRowIndex: 0,
507 lastRowIndex: rows.length - 1,
508 overscanRows: 0,
509 });
510 for (const row of lineRows) {
511 const expected =
512 row.change === "delete"
513 ? oldTokens[row.oldLineNumber! - 1]
514 : newTokens[row.newLineNumber! - 1];
515 const tokens = result.tokensByRowId[row.id];
516 expect(tokens, row.id).toEqual(expected);
517 expect(
518 tokens?.every((token) => token.color !== null),
519 row.id,
520 ).toBe(true);
521 expect(tokens?.[0]?.color, row.id).toBe(
522 (row.newLineNumber ?? row.oldLineNumber)! <= 4 ? "#5ecc71" : "#737373",
523 );
524 }
525 expect(lineRows.map((row) => row.content)).toEqual(originalContents);
526 expect(result.retryableRowIds).toEqual([]);
527 });
528
529 it("matches full OLD/NEW source across replacement runs and shared multiline context", async () => {
530 const rows = completeDiffRows();
531 const oldTokens = await authoritativeTokens(OLD_SOURCE);
532 const newTokens = await authoritativeTokens(NEW_SOURCE);
533 const result = await highlightNativeReviewDiffVisibleRows({
534 rows,
535 files: [TYPESCRIPT_FILE],
536 scheme: "dark",
537 firstRowIndex: 0,
538 lastRowIndex: rows.length - 1,
539 overscanRows: 0,
540 });
541 for (const row of rows) {
542 const expected =
543 row.change === "delete"
544 ? oldTokens[row.oldLineNumber! - 1]
545 : newTokens[row.newLineNumber! - 1];
546 expect(result.tokensByRowId[row.id], row.id).toEqual(expected);
547 }
548 });
549
550 it("uses NEW grammar for shared rows when OLD remains inside a comment", async () => {
551 const oldSource = ["/* Retired renderer", "const value = 3;", "finish();"];
552 const newSource = ["// Active renderer", "const value = 3;", "finish();"];
553 const rows = [
554 makeLine({
555 id: "old-open",
556 content: oldSource[0],
557 change: "delete",
558 oldLineNumber: 1,
559 newLineNumber: null,
560 }),
561 makeLine({
562 id: "new-open",
563 content: newSource[0],
564 change: "add",
565 oldLineNumber: null,
566 newLineNumber: 1,
567 }),
568 makeLine({
569 id: "shared",
570 content: newSource[1],
571 change: "context",
572 oldLineNumber: 2,
573 newLineNumber: 2,
574 }),
575 makeLine({
576 id: "old-tail",
577 content: oldSource[2],
578 change: "delete",
579 oldLineNumber: 3,
580 newLineNumber: null,
581 }),
582 makeLine({
583 id: "new-tail",
584 content: newSource[2],
585 change: "add",
586 oldLineNumber: null,
587 newLineNumber: 3,
588 }),
589 ];
590 const oldTokens = await authoritativeTokens(oldSource);
591 const newTokens = await authoritativeTokens(newSource);
592 const result = await highlightNativeReviewDiffVisibleRows({
593 rows,
594 files: [TYPESCRIPT_FILE],
595 scheme: "dark",
596 firstRowIndex: 0,
597 lastRowIndex: rows.length - 1,
598 overscanRows: 0,
599 });
600 expect(oldTokens[1]).not.toEqual(newTokens[1]);
601 expect(result.tokensByRowId.shared).toEqual(newTokens[1]);
602 expect(result.tokensByRowId["old-tail"]).toEqual(oldTokens[2]);
603 expect(result.tokensByRowId["new-tail"]).toEqual(newTokens[2]);
604 });
605
606 it("leaves mismatched and unavailable source revisions plain", async () => {
607 const rows = [sourceRow("add", 3)];
608 for (const source of [null, { oldContents: "", newContents: "different revision" }]) {
609 const result = await highlightNativeReviewDiffVisibleRows({
610 rows,
611 files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],
612 scheme: "dark",
613 firstRowIndex: 0,
614 lastRowIndex: 0,
615 overscanRows: 0,
616 });
617 expect(result.tokensByRowId[rows[0]!.id]).toEqual([
618 { content: NEW_SOURCE[2], color: null, fontStyle: null },
619 ]);
620 }
621 });
622});
623
624it("reuses full native records across viewport and theme changes and evicts old entries", async () => {
625 const sources = Array.from({ length: 9 }, (_, i) => ({
626 oldContents: "",
627 newContents: `/* ${i}\ninside\n*/\nconst tail = 2;`,
628 }));
629 const rows = [
630 makeLine({
631 id: "body",
632 content: "inside",
633 change: "add",
634 oldLineNumber: null,
635 newLineNumber: 2,
636 }),
637 makeLine({
638 id: "tail",
639 content: "const tail = 2;",
640 change: "add",
641 oldLineNumber: null,
642 newLineNumber: 4,
643 }),
644 ];
645 const input = {
646 rows,
647 scheme: "dark" as const,
648 firstRowIndex: 0,
649 lastRowIndex: 0,
650 overscanRows: 0,
651 };
652 const files = [{ ...TYPESCRIPT_FILE, loadContents: async () => sources[0]! }];
653 const initial = await highlightNativeReviewDiffVisibleRows({ ...input, files });
654 const moved = await highlightNativeReviewDiffVisibleRows({
655 ...input,
656 files,
657 firstRowIndex: 1,
658 lastRowIndex: 1,
659 });
660 await highlightNativeReviewDiffVisibleRows({ ...input, files, scheme: "light" });
661 expect(tokenization.calls).toEqual([sources[0]!.newContents]);
662 expect(initial.tokensByRowId.body).toEqual(
663 highlightCode(sources[0]!.newContents, "typescript", "dark")[1],
664 );
665 expect(moved.tokensByRowId.tail).toEqual(
666 highlightCode(sources[0]!.newContents, "typescript", "dark")[3],
667 );
668 tokenization.calls = [];
669 for (const source of sources.slice(1)) {
670 await highlightNativeReviewDiffVisibleRows({
671 ...input,
672 files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],
673 });
674 }
675 await highlightNativeReviewDiffVisibleRows({ ...input, files });
676 expect(tokenization.calls).toHaveLength(9);
677 expect(tokenization.calls.at(-1)).toBe(sources[0]!.newContents);
678});
679
680it("reuses segment records across themes and replaces records when the language changes", async () => {
681 const rows = [
682 makeLine({
683 id: "line",
684 content: "const value = 1;",
685 change: "add",
686 oldLineNumber: null,
687 newLineNumber: 1,
688 }),
689 ];
690 const input = {
691 rows,
692 files: [TYPESCRIPT_FILE],
693 scheme: "dark" as const,
694 firstRowIndex: 0,
695 lastRowIndex: 0,
696 overscanRows: 0,
697 };
698 const first = await highlightNativeReviewDiffVisibleRows(input);
699 await highlightNativeReviewDiffVisibleRows({ ...input, scheme: "light" });
700 expect(tokenization.calls).toEqual([rows[0]!.content]);
701 await highlightNativeReviewDiffVisibleRows({
702 ...input,
703 files: [{ ...TYPESCRIPT_FILE, language: "c" }],
704 });
705 const restored = await highlightNativeReviewDiffVisibleRows(input);
706 expect(tokenization.calls).toHaveLength(3);
707 expect(restored.tokensByRowId).toEqual(first.tokensByRowId);
708});
709
710it("uses full grammar after an oversized line and expands only selected rows in a 100k-line C source", async () => {
711 const contents = [
712 " ".repeat(1_001) + "/*",
713 ...Array.from({ length: 99_997 }, (_, i) => `comment ${i}: int value = 1;`),
714 "*/",
715 "int done = 2;",
716 ].join("\n");
717 expect(contents.length).toBeGreaterThan(500_000);
718 const source = { oldContents: "", newContents: contents };
719 const rows = [
720 makeLine({
721 id: "body",
722 content: "comment 99996: int value = 1;",
723 change: "add",
724 oldLineNumber: null,
725 newLineNumber: 99_998,
726 }),
727 makeLine({
728 id: "end",
729 content: "int done = 2;",
730 change: "add",
731 oldLineNumber: null,
732 newLineNumber: 100_000,
733 }),
734 ];
735 const input = {
736 rows,
737 files: [{ ...TYPESCRIPT_FILE, language: "c", loadContents: async () => source }],
738 scheme: "dark" as const,
739 firstRowIndex: 0,
740 lastRowIndex: 0,
741 overscanRows: 0,
742 };
743 const result = await highlightNativeReviewDiffVisibleRows(input);
744 expect(Object.keys(result.tokensByRowId)).toEqual(["body"]);
745 expect(result.tokensByRowId.body).toEqual([
746 { content: rows[0]!.content, color: "#737373", fontStyle: 0 },
747 ]);
748 const moved = await highlightNativeReviewDiffVisibleRows({
749 ...input,
750 firstRowIndex: 1,
751 lastRowIndex: 1,
752 });
753 expect(moved.tokensByRowId.end?.some((token) => token.color !== "#737373")).toBe(true);
754 expect(tokenization.calls).toEqual([contents]);
755});
756
757it("publishes no cancelled file chunk and never tokenizes its next side", async () => {
758 const controller = new AbortController();
759 tokenization.afterCall = () => controller.abort();
760 const chunks = vi.fn();
761 const result = await highlightNativeReviewDiffVisibleRows({
762 rows: [sourceRow("delete", 3), sourceRow("add", 3)],
763 files: [
764 {
765 ...TYPESCRIPT_FILE,
766 loadContents: async () => ({
767 oldContents: OLD_SOURCE.join("\n"),
768 newContents: NEW_SOURCE.join("\n"),
769 }),
770 },
771 ],
772 scheme: "dark",
773 firstRowIndex: 0,
774 lastRowIndex: 1,
775 overscanRows: 0,
776 signal: controller.signal,
777 onChunk: chunks,
778 });
779 expect(tokenization.calls).toHaveLength(1);
780 expect(chunks).not.toHaveBeenCalled();
781 expect(result.tokensByRowId).toEqual({});
782 expect(result.rowCount).toBe(0);
783});
784
785it("does not tokenize or publish a source that arrives after cancellation", async () => {
786 const controller = new AbortController();
787 const started = Promise.withResolvers<void>();
788 const response = Promise.withResolvers<{ oldContents: string; newContents: string }>();
789 const chunks = vi.fn();
790 const work = highlightNativeReviewDiffVisibleRows({
791 rows: [sourceRow("add", 3)],
792 files: [
793 {
794 ...TYPESCRIPT_FILE,
795 loadContents: () => {
796 started.resolve();
797 return response.promise;
798 },
799 },
800 ],
801 scheme: "dark",
802 firstRowIndex: 0,
803 lastRowIndex: 0,
804 signal: controller.signal,
805 onChunk: chunks,
806 });
807 await started.promise;
808 controller.abort();
809 response.resolve({ oldContents: "", newContents: NEW_SOURCE.join("\n") });
810 expect((await work).rowCount).toBe(0);
811 expect(tokenization.calls).toEqual([]);
812 expect(chunks).not.toHaveBeenCalled();
813});