Open History to see the last commit
1import { createHighlighterCore, type GrammarState, type HighlighterCore } from "@shikijs/core";
2import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
3import bashLanguage from "@shikijs/langs/bash";
4import diffLanguage from "@shikijs/langs/diff";
5import javascriptLanguage from "@shikijs/langs/javascript";
6import jsonLanguage from "@shikijs/langs/json";
7import jsxLanguage from "@shikijs/langs/jsx";
8import tsxLanguage from "@shikijs/langs/tsx";
9import typescriptLanguage from "@shikijs/langs/typescript";
10import yamlLanguage from "@shikijs/langs/yaml";
11import * as Schema from "effect/Schema";
12
13import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
14import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
15
16export type NativeReviewDiffHighlightScheme = "light" | "dark";
17export type NativeReviewDiffHighlightEngine = "native" | "javascript";
18
19export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
20 "NativeReviewDiffHighlighterUnavailableError",
21 {},
22) {
23 override get message(): string {
24 return "The native review diff highlighter is unavailable in this build.";
25 }
26}
27
28export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
29 NativeReviewDiffHighlighterUnavailableError,
30);
31
32export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
33 "NativeReviewDiffHighlighterInitializationError",
34 {
35 requestedEngine: Schema.Literals(["native", "javascript"]),
36 attemptedEngine: Schema.Literals(["native", "javascript"]),
37 cause: Schema.Defect(),
38 },
39) {
40 override get message(): string {
41 return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
42 }
43}
44
45export interface NativeReviewDiffHighlighterHandle {
46 readonly engine: NativeReviewDiffHighlightEngine;
47 readonly tokenize: (
48 code: string,
49 options: {
50 readonly lang: NativeReviewDiffLanguage;
51 readonly theme: string;
52 readonly signal?: AbortSignal;
53 },
54 ) => Promise<ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>>;
55}
56
57interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
58 readonly kind: "line";
59 readonly fileId: string;
60 readonly content: string;
61}
62
63interface IndexedNativeReviewDiffLineRow {
64 readonly row: NativeReviewDiffLineRow;
65 readonly rowIndex: number;
66}
67
68export interface NativeReviewDiffTokenChunk {
69 readonly chunkIndex: number;
70 readonly fileId: string;
71 readonly filePath: string;
72 readonly language: NativeReviewDiffLanguage;
73 readonly lineCount: number;
74 readonly durationMs: number;
75 readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
76}
77
78export interface StreamNativeReviewDiffTokenInput {
79 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
80 readonly files: ReadonlyArray<NativeReviewDiffFile>;
81 readonly scheme: NativeReviewDiffHighlightScheme;
82 readonly engine?: NativeReviewDiffHighlightEngine;
83 readonly chunkSize?: number;
84 readonly signal?: AbortSignal;
85 readonly onChunk: (chunk: NativeReviewDiffTokenChunk) => void;
86}
87
88export interface HighlightNativeReviewDiffVisibleRowsInput {
89 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
90 readonly files: ReadonlyArray<NativeReviewDiffFile>;
91 readonly scheme: NativeReviewDiffHighlightScheme;
92 readonly engine?: NativeReviewDiffHighlightEngine;
93 readonly firstRowIndex: number;
94 readonly lastRowIndex: number;
95 readonly overscanRows?: number;
96 readonly maxRows?: number;
97 readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
98 readonly signal?: AbortSignal;
99}
100
101const NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE = 500;
102const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
103const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
104const NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH = 1_000;
105const NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS = 8_000;
106
107const NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME = {
108 dark: "t3-pierre-dark",
109 light: "t3-pierre-light",
110} as const;
111
112const PIERRE_LIGHT_SHIKI_THEME = {
113 name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.light,
114 type: "light" as const,
115 fg: "#070707",
116 bg: "#ffffff",
117 settings: [
118 { settings: { foreground: "#070707", background: "#ffffff" } },
119 { scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
120 {
121 scope: "keyword, storage, storage.type, keyword.operator.expression",
122 settings: { foreground: "#FC2B73" },
123 },
124 {
125 scope: "entity.name.function, support.function, meta.function-call",
126 settings: { foreground: "#7B43F8" },
127 },
128 {
129 scope: "entity.name.type, support.type, support.class",
130 settings: { foreground: "#C635E4" },
131 },
132 {
133 scope: "string, constant.character, punctuation.definition.string",
134 settings: { foreground: "#199F43" },
135 },
136 {
137 scope: "constant.numeric, constant.language, constant.other",
138 settings: { foreground: "#1CA1C7" },
139 },
140 {
141 scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
142 settings: { foreground: "#D47628" },
143 },
144 {
145 scope: "entity.name.tag, support.class.component",
146 settings: { foreground: "#199F43" },
147 },
148 {
149 scope: "punctuation, meta.brace, meta.delimiter",
150 settings: { foreground: "#79797F" },
151 },
152 { scope: "invalid", settings: { foreground: "#D52C36" } },
153 ],
154};
155
156const PIERRE_DARK_SHIKI_THEME = {
157 name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.dark,
158 type: "dark" as const,
159 fg: "#adadb1",
160 bg: "#0a0a0a",
161 settings: [
162 { settings: { foreground: "#adadb1", background: "#0a0a0a" } },
163 { scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
164 {
165 scope: "keyword, storage, storage.type, keyword.operator.expression",
166 settings: { foreground: "#FF678D" },
167 },
168 {
169 scope: "entity.name.function, support.function, meta.function-call",
170 settings: { foreground: "#9D6AFB" },
171 },
172 {
173 scope: "entity.name.type, support.type, support.class",
174 settings: { foreground: "#D568EA" },
175 },
176 {
177 scope: "string, constant.character, punctuation.definition.string",
178 settings: { foreground: "#5ECC71" },
179 },
180 {
181 scope: "constant.numeric, constant.language, constant.other",
182 settings: { foreground: "#68CDF2" },
183 },
184 {
185 scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
186 settings: { foreground: "#FFA359" },
187 },
188 {
189 scope: "entity.name.tag, support.class.component",
190 settings: { foreground: "#5ECC71" },
191 },
192 {
193 scope: "punctuation, meta.brace, meta.delimiter",
194 settings: { foreground: "#79797F" },
195 },
196 { scope: "invalid", settings: { foreground: "#FF6762" } },
197 ],
198};
199
200const NATIVE_REVIEW_DIFF_SHIKI_THEMES = [
201 PIERRE_LIGHT_SHIKI_THEME,
202 PIERRE_DARK_SHIKI_THEME,
203] satisfies Parameters<typeof createHighlighterCore>[0]["themes"];
204
205const NATIVE_REVIEW_DIFF_LANGUAGES = [
206 bashLanguage,
207 diffLanguage,
208 javascriptLanguage,
209 jsonLanguage,
210 jsxLanguage,
211 tsxLanguage,
212 typescriptLanguage,
213 yamlLanguage,
214] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
215
216let nativeHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
217let javascriptHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
218
219function waitForNextFrame(): Promise<void> {
220 return new Promise((resolve) => setTimeout(resolve, 0));
221}
222
223function normalizeTokens(
224 tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
225): ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>> {
226 return tokenLines.map((line) =>
227 line.map((token) => ({
228 content: token.content,
229 color: token.color ?? null,
230 fontStyle: token.fontStyle ?? null,
231 })),
232 );
233}
234
235function createHighlighterHandle(
236 highlighter: HighlighterCore,
237 engine: NativeReviewDiffHighlightEngine,
238): NativeReviewDiffHighlighterHandle {
239 return {
240 engine,
241 async tokenize(code, { lang, theme, signal }) {
242 const lines = code.split("\n");
243 const highlighted: Array<ReadonlyArray<NativeReviewDiffToken>> = [];
244 let grammarState: GrammarState | undefined;
245 let start = 0;
246
247 while (start < lines.length) {
248 if (signal?.aborted) return [];
249
250 // Skipping this line leaves its ending grammar state unknown. Resume
251 // from a fresh state rather than leaving the rest of the segment plain:
252 // highlighted rows are cached for the sheet's lifetime, so a plain tail
253 // would stick, and which rows it covered would depend on where the
254 // first visible window happened to start.
255 if (lines[start]!.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH) {
256 highlighted.push([{ content: lines[start] || " ", color: null, fontStyle: null }]);
257 grammarState = undefined;
258 start += 1;
259 continue;
260 }
261
262 let end = start;
263 let characters = 0;
264 while (end < lines.length) {
265 const length = lines[end]!.length;
266 const nextCharacters = characters + length + (end > start ? 1 : 0);
267 if (
268 length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH ||
269 nextCharacters > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
270 ) {
271 break;
272 }
273 characters = nextCharacters;
274 end += 1;
275 }
276
277 const tokens = highlighter.codeToTokensBase(lines.slice(start, end).join("\n"), {
278 lang,
279 theme,
280 grammarState,
281 });
282 grammarState = highlighter.getLastGrammarState(tokens);
283 highlighted.push(...normalizeTokens(tokens));
284 start = end;
285 if (start < lines.length) await waitForNextFrame();
286 }
287
288 return signal?.aborted ? [] : highlighted;
289 },
290 };
291}
292
293async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
294 const nativeEngineModule = await import("react-native-shiki-engine");
295 if (!nativeEngineModule.isNativeEngineAvailable()) {
296 throw new NativeReviewDiffHighlighterUnavailableError();
297 }
298
299 const highlighter = await createHighlighterCore({
300 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
301 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
302 engine: nativeEngineModule.createNativeEngine(),
303 });
304
305 return createHighlighterHandle(highlighter, "native");
306}
307
308async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
309 const highlighter: HighlighterCore = await createHighlighterCore({
310 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
311 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
312 engine: createJavaScriptRegexEngine(),
313 });
314
315 return createHighlighterHandle(highlighter, "javascript");
316}
317
318export async function getNativeReviewDiffHighlighter(
319 engine: NativeReviewDiffHighlightEngine = "native",
320): Promise<NativeReviewDiffHighlighterHandle> {
321 if (engine === "javascript") {
322 try {
323 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
324 return await javascriptHighlighterPromise;
325 } catch (cause) {
326 javascriptHighlighterPromise = null;
327 throw new NativeReviewDiffHighlighterInitializationError({
328 requestedEngine: engine,
329 attemptedEngine: "javascript",
330 cause,
331 });
332 }
333 }
334
335 nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
336 .catch(async (cause: unknown) => {
337 const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
338 ? cause
339 : new NativeReviewDiffHighlighterInitializationError({
340 requestedEngine: engine,
341 attemptedEngine: "native",
342 cause,
343 });
344 console.warn("[debug-native-diff] native highlighter unavailable", {
345 error: nativeError,
346 });
347 try {
348 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
349 return await javascriptHighlighterPromise;
350 } catch (fallbackCause) {
351 javascriptHighlighterPromise = null;
352 throw new NativeReviewDiffHighlighterInitializationError({
353 requestedEngine: engine,
354 attemptedEngine: "javascript",
355 cause: new AggregateError(
356 [nativeError, fallbackCause],
357 "Native and JavaScript review diff highlighter initialization failed.",
358 { cause: nativeError },
359 ),
360 });
361 }
362 })
363 .catch((error) => {
364 nativeHighlighterPromise = null;
365 throw error;
366 });
367 return await nativeHighlighterPromise;
368}
369
370function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
371 return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
372}
373
374function hasConsecutiveLineNumbers(
375 previous: number | null | undefined,
376 next: number | null | undefined,
377): boolean {
378 return typeof previous === "number" && typeof next === "number" && next === previous + 1;
379}
380
381function hasOnlyCommentRowsBetween(
382 rows: ReadonlyArray<NativeReviewDiffRow>,
383 previousRowIndex: number,
384 nextRowIndex: number,
385): boolean {
386 for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
387 if (rows[rowIndex]?.kind !== "comment") {
388 return false;
389 }
390 }
391 return true;
392}
393
394function canShareGrammarContext(
395 previous: IndexedNativeReviewDiffLineRow,
396 next: IndexedNativeReviewDiffLineRow,
397 rows: ReadonlyArray<NativeReviewDiffRow>,
398): boolean {
399 if (
400 next.row.fileId !== previous.row.fileId ||
401 !hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
402 ) {
403 return false;
404 }
405
406 if (previous.row.change === "delete" || next.row.change === "delete") {
407 return (
408 previous.row.change !== "add" &&
409 next.row.change !== "add" &&
410 hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
411 );
412 }
413
414 if (previous.row.change === "add" || next.row.change === "add") {
415 return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
416 }
417
418 return (
419 previous.row.change === "context" &&
420 next.row.change === "context" &&
421 hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
422 hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
423 );
424}
425
426function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
427 const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
428 for (const row of rows) {
429 if (!isHighlightableLineRow(row)) {
430 continue;
431 }
432
433 const fileRows = rowsByFileId.get(row.fileId) ?? [];
434 fileRows.push(row);
435 rowsByFileId.set(row.fileId, fileRows);
436 }
437 return rowsByFileId;
438}
439
440function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
441 return new Map(files.map((file) => [file.id, file]));
442}
443
444function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
445 if (rows.length === 0) {
446 return 0;
447 }
448
449 return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
450}
451
452function makePlainTokenFallback(
453 row: NativeReviewDiffLineRow,
454): ReadonlyArray<NativeReviewDiffToken> {
455 return [{ content: row.content || " ", color: null, fontStyle: null }];
456}
457
458export async function highlightNativeReviewDiffVisibleRows(
459 input: HighlightNativeReviewDiffVisibleRowsInput,
460): Promise<{
461 readonly engine: NativeReviewDiffHighlightEngine;
462 readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
463 readonly rowCount: number;
464 readonly durationMs: number;
465}> {
466 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
467 if (input.signal?.aborted) {
468 return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
469 }
470
471 const startedAt = performance.now();
472 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
473 const fileMap = createFileMap(input.files);
474 const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
475 const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
476 const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
477 const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
478 const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
479
480 for (
481 let rowIndex = startIndex;
482 rowIndex <= endIndex && selectedRows.length < maxRows;
483 rowIndex += 1
484 ) {
485 const row = input.rows[rowIndex];
486 if (
487 row &&
488 isHighlightableLineRow(row) &&
489 !input.alreadyHighlightedRowIds?.has(row.id) &&
490 fileMap.has(row.fileId)
491 ) {
492 selectedRows.push({ row, rowIndex });
493 }
494 }
495
496 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
497 let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
498 let segmentFile: NativeReviewDiffFile | undefined;
499 let charactersSinceYield = 0;
500
501 const flushSegment = async () => {
502 if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
503 segmentRows = [];
504 segmentFile = undefined;
505 return;
506 }
507
508 const code = segmentRows.map(({ row }) => row.content).join("\n");
509 if (
510 charactersSinceYield > 0 &&
511 charactersSinceYield + code.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
512 ) {
513 await waitForNextFrame();
514 charactersSinceYield = 0;
515 if (input.signal?.aborted) return;
516 }
517 const tokenLines = await highlighter.tokenize(code, {
518 lang: segmentFile.language,
519 theme,
520 signal: input.signal,
521 });
522 charactersSinceYield += code.length;
523 segmentRows.forEach(({ row }, rowIndex) => {
524 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
525 });
526 segmentRows = [];
527 segmentFile = undefined;
528 };
529
530 for (const selectedRow of selectedRows) {
531 if (input.signal?.aborted) break;
532 const { row } = selectedRow;
533 const file = fileMap.get(row.fileId);
534 if (!file) {
535 continue;
536 }
537
538 const previousRow = segmentRows.at(-1);
539 if (
540 segmentFile &&
541 (segmentFile.id !== file.id ||
542 (previousRow !== undefined &&
543 !canShareGrammarContext(previousRow, selectedRow, input.rows)))
544 ) {
545 await flushSegment();
546 }
547
548 segmentFile = file;
549 segmentRows.push(selectedRow);
550 }
551 await flushSegment();
552
553 if (input.signal?.aborted) {
554 return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
555 }
556
557 return {
558 engine: highlighter.engine,
559 tokensByRowId,
560 rowCount: selectedRows.length,
561 durationMs: Math.round(performance.now() - startedAt),
562 };
563}
564
565export async function streamNativeReviewDiffTokens(
566 input: StreamNativeReviewDiffTokenInput,
567): Promise<NativeReviewDiffHighlightEngine> {
568 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
569 const rowsByFileId = groupLineRowsByFileId(input.rows);
570 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
571 const chunkSize = input.chunkSize ?? NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE;
572 let chunkIndex = 0;
573
574 for (const file of input.files) {
575 const fileRows = rowsByFileId.get(file.id) ?? [];
576 for (let startIndex = 0; startIndex < fileRows.length; startIndex += chunkSize) {
577 if (input.signal?.aborted) {
578 return highlighter.engine;
579 }
580
581 const startedAt = performance.now();
582 const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
583 const code = chunkRows.map((row) => row.content).join("\n");
584 const tokenLines = await highlighter.tokenize(code, {
585 lang: file.language,
586 theme,
587 signal: input.signal,
588 });
589 if (input.signal?.aborted) return highlighter.engine;
590 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
591
592 chunkRows.forEach((row, rowIndex) => {
593 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
594 });
595
596 input.onChunk({
597 chunkIndex,
598 fileId: file.id,
599 filePath: file.path,
600 language: file.language,
601 lineCount: chunkRows.length,
602 durationMs: Math.round(performance.now() - startedAt),
603 tokensByRowId,
604 });
605
606 chunkIndex += 1;
607 await waitForNextFrame();
608 }
609 }
610
611 return highlighter.engine;
612}