Open History to see the last commit
1import { createHighlighterCore, 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: { readonly lang: NativeReviewDiffLanguage; readonly theme: string },
50 ) => ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>;
51}
52
53interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
54 readonly kind: "line";
55 readonly fileId: string;
56 readonly content: string;
57}
58
59export interface NativeReviewDiffTokenChunk {
60 readonly chunkIndex: number;
61 readonly fileId: string;
62 readonly filePath: string;
63 readonly language: NativeReviewDiffLanguage;
64 readonly lineCount: number;
65 readonly durationMs: number;
66 readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
67}
68
69export interface StreamNativeReviewDiffTokenInput {
70 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
71 readonly files: ReadonlyArray<NativeReviewDiffFile>;
72 readonly scheme: NativeReviewDiffHighlightScheme;
73 readonly engine?: NativeReviewDiffHighlightEngine;
74 readonly chunkSize?: number;
75 readonly signal?: AbortSignal;
76 readonly onChunk: (chunk: NativeReviewDiffTokenChunk) => void;
77}
78
79export interface HighlightNativeReviewDiffVisibleRowsInput {
80 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
81 readonly files: ReadonlyArray<NativeReviewDiffFile>;
82 readonly scheme: NativeReviewDiffHighlightScheme;
83 readonly engine?: NativeReviewDiffHighlightEngine;
84 readonly firstRowIndex: number;
85 readonly lastRowIndex: number;
86 readonly overscanRows?: number;
87 readonly maxRows?: number;
88 readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
89 readonly signal?: AbortSignal;
90}
91
92const NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE = 500;
93const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
94const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
95
96const NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME = {
97 dark: "t3-pierre-dark",
98 light: "t3-pierre-light",
99} as const;
100
101const PIERRE_LIGHT_SHIKI_THEME = {
102 name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.light,
103 type: "light" as const,
104 fg: "#070707",
105 bg: "#ffffff",
106 settings: [
107 { settings: { foreground: "#070707", background: "#ffffff" } },
108 { scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
109 {
110 scope: "keyword, storage, storage.type, keyword.operator.expression",
111 settings: { foreground: "#FC2B73" },
112 },
113 {
114 scope: "entity.name.function, support.function, meta.function-call",
115 settings: { foreground: "#7B43F8" },
116 },
117 {
118 scope: "entity.name.type, support.type, support.class",
119 settings: { foreground: "#C635E4" },
120 },
121 {
122 scope: "string, constant.character, punctuation.definition.string",
123 settings: { foreground: "#199F43" },
124 },
125 {
126 scope: "constant.numeric, constant.language, constant.other",
127 settings: { foreground: "#1CA1C7" },
128 },
129 {
130 scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
131 settings: { foreground: "#D47628" },
132 },
133 {
134 scope: "entity.name.tag, support.class.component",
135 settings: { foreground: "#199F43" },
136 },
137 {
138 scope: "punctuation, meta.brace, meta.delimiter",
139 settings: { foreground: "#79797F" },
140 },
141 { scope: "invalid", settings: { foreground: "#D52C36" } },
142 ],
143};
144
145const PIERRE_DARK_SHIKI_THEME = {
146 name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.dark,
147 type: "dark" as const,
148 fg: "#adadb1",
149 bg: "#0a0a0a",
150 settings: [
151 { settings: { foreground: "#adadb1", background: "#0a0a0a" } },
152 { scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
153 {
154 scope: "keyword, storage, storage.type, keyword.operator.expression",
155 settings: { foreground: "#FF678D" },
156 },
157 {
158 scope: "entity.name.function, support.function, meta.function-call",
159 settings: { foreground: "#9D6AFB" },
160 },
161 {
162 scope: "entity.name.type, support.type, support.class",
163 settings: { foreground: "#D568EA" },
164 },
165 {
166 scope: "string, constant.character, punctuation.definition.string",
167 settings: { foreground: "#5ECC71" },
168 },
169 {
170 scope: "constant.numeric, constant.language, constant.other",
171 settings: { foreground: "#68CDF2" },
172 },
173 {
174 scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
175 settings: { foreground: "#FFA359" },
176 },
177 {
178 scope: "entity.name.tag, support.class.component",
179 settings: { foreground: "#5ECC71" },
180 },
181 {
182 scope: "punctuation, meta.brace, meta.delimiter",
183 settings: { foreground: "#79797F" },
184 },
185 { scope: "invalid", settings: { foreground: "#FF6762" } },
186 ],
187};
188
189const NATIVE_REVIEW_DIFF_SHIKI_THEMES = [
190 PIERRE_LIGHT_SHIKI_THEME,
191 PIERRE_DARK_SHIKI_THEME,
192] satisfies Parameters<typeof createHighlighterCore>[0]["themes"];
193
194const NATIVE_REVIEW_DIFF_LANGUAGES = [
195 bashLanguage,
196 diffLanguage,
197 javascriptLanguage,
198 jsonLanguage,
199 jsxLanguage,
200 tsxLanguage,
201 typescriptLanguage,
202 yamlLanguage,
203] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
204
205let nativeHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
206let javascriptHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
207
208function waitForNextFrame(): Promise<void> {
209 return new Promise((resolve) => setTimeout(resolve, 0));
210}
211
212function normalizeTokens(
213 tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
214): ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>> {
215 return tokenLines.map((line) =>
216 line.map((token) => ({
217 content: token.content,
218 color: token.color ?? null,
219 fontStyle: token.fontStyle ?? null,
220 })),
221 );
222}
223
224async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
225 const nativeEngineModule = await import("react-native-shiki-engine");
226 if (!nativeEngineModule.isNativeEngineAvailable()) {
227 throw new NativeReviewDiffHighlighterUnavailableError();
228 }
229
230 const highlighter = await createHighlighterCore({
231 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
232 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
233 engine: nativeEngineModule.createNativeEngine(),
234 });
235
236 return {
237 engine: "native",
238 tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
239 };
240}
241
242async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
243 const highlighter: HighlighterCore = await createHighlighterCore({
244 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
245 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
246 engine: createJavaScriptRegexEngine(),
247 });
248
249 return {
250 engine: "javascript",
251 tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
252 };
253}
254
255export async function getNativeReviewDiffHighlighter(
256 engine: NativeReviewDiffHighlightEngine = "native",
257): Promise<NativeReviewDiffHighlighterHandle> {
258 if (engine === "javascript") {
259 try {
260 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
261 return await javascriptHighlighterPromise;
262 } catch (cause) {
263 javascriptHighlighterPromise = null;
264 throw new NativeReviewDiffHighlighterInitializationError({
265 requestedEngine: engine,
266 attemptedEngine: "javascript",
267 cause,
268 });
269 }
270 }
271
272 nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
273 .catch(async (cause: unknown) => {
274 const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
275 ? cause
276 : new NativeReviewDiffHighlighterInitializationError({
277 requestedEngine: engine,
278 attemptedEngine: "native",
279 cause,
280 });
281 console.warn("[debug-native-diff] native highlighter unavailable", {
282 error: nativeError,
283 });
284 try {
285 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
286 return await javascriptHighlighterPromise;
287 } catch (fallbackCause) {
288 javascriptHighlighterPromise = null;
289 throw new NativeReviewDiffHighlighterInitializationError({
290 requestedEngine: engine,
291 attemptedEngine: "javascript",
292 cause: new AggregateError(
293 [nativeError, fallbackCause],
294 "Native and JavaScript review diff highlighter initialization failed.",
295 { cause: nativeError },
296 ),
297 });
298 }
299 })
300 .catch((error) => {
301 nativeHighlighterPromise = null;
302 throw error;
303 });
304 return await nativeHighlighterPromise;
305}
306
307function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
308 return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
309}
310
311function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
312 const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
313 for (const row of rows) {
314 if (!isHighlightableLineRow(row)) {
315 continue;
316 }
317
318 const fileRows = rowsByFileId.get(row.fileId) ?? [];
319 fileRows.push(row);
320 rowsByFileId.set(row.fileId, fileRows);
321 }
322 return rowsByFileId;
323}
324
325function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
326 return new Map(files.map((file) => [file.id, file]));
327}
328
329function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
330 if (rows.length === 0) {
331 return 0;
332 }
333
334 return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
335}
336
337function makePlainTokenFallback(
338 row: NativeReviewDiffLineRow,
339): ReadonlyArray<NativeReviewDiffToken> {
340 return [{ content: row.content || " ", color: null, fontStyle: null }];
341}
342
343export async function highlightNativeReviewDiffVisibleRows(
344 input: HighlightNativeReviewDiffVisibleRowsInput,
345): Promise<{
346 readonly engine: NativeReviewDiffHighlightEngine;
347 readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
348 readonly rowCount: number;
349 readonly durationMs: number;
350}> {
351 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
352 if (input.signal?.aborted) {
353 return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
354 }
355
356 const startedAt = performance.now();
357 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
358 const fileMap = createFileMap(input.files);
359 const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
360 const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
361 const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
362 const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
363 const selectedRows: NativeReviewDiffLineRow[] = [];
364
365 for (
366 let rowIndex = startIndex;
367 rowIndex <= endIndex && selectedRows.length < maxRows;
368 rowIndex += 1
369 ) {
370 const row = input.rows[rowIndex];
371 if (
372 row &&
373 isHighlightableLineRow(row) &&
374 !input.alreadyHighlightedRowIds?.has(row.id) &&
375 fileMap.has(row.fileId)
376 ) {
377 selectedRows.push(row);
378 }
379 }
380
381 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
382 let segmentRows: NativeReviewDiffLineRow[] = [];
383 let segmentFile: NativeReviewDiffFile | undefined;
384
385 const flushSegment = () => {
386 if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
387 segmentRows = [];
388 segmentFile = undefined;
389 return;
390 }
391
392 const code = segmentRows.map((row) => row.content).join("\n");
393 const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
394 segmentRows.forEach((row, rowIndex) => {
395 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
396 });
397 segmentRows = [];
398 segmentFile = undefined;
399 };
400
401 for (const row of selectedRows) {
402 const file = fileMap.get(row.fileId);
403 if (!file) {
404 continue;
405 }
406
407 if (segmentFile && segmentFile.id !== file.id) {
408 flushSegment();
409 }
410
411 segmentFile = file;
412 segmentRows.push(row);
413 }
414 flushSegment();
415
416 return {
417 engine: highlighter.engine,
418 tokensByRowId,
419 rowCount: selectedRows.length,
420 durationMs: Math.round(performance.now() - startedAt),
421 };
422}
423
424export async function streamNativeReviewDiffTokens(
425 input: StreamNativeReviewDiffTokenInput,
426): Promise<NativeReviewDiffHighlightEngine> {
427 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
428 const rowsByFileId = groupLineRowsByFileId(input.rows);
429 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
430 const chunkSize = input.chunkSize ?? NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE;
431 let chunkIndex = 0;
432
433 for (const file of input.files) {
434 const fileRows = rowsByFileId.get(file.id) ?? [];
435 for (let startIndex = 0; startIndex < fileRows.length; startIndex += chunkSize) {
436 if (input.signal?.aborted) {
437 return highlighter.engine;
438 }
439
440 const startedAt = performance.now();
441 const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
442 const code = chunkRows.map((row) => row.content).join("\n");
443 const tokenLines = highlighter.tokenize(code, { lang: file.language, theme });
444 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
445
446 chunkRows.forEach((row, rowIndex) => {
447 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
448 });
449
450 input.onChunk({
451 chunkIndex,
452 fileId: file.id,
453 filePath: file.path,
454 language: file.language,
455 lineCount: chunkRows.length,
456 durationMs: Math.round(performance.now() - startedAt),
457 tokensByRowId,
458 });
459
460 chunkIndex += 1;
461 await waitForNextFrame();
462 }
463 }
464
465 return highlighter.engine;
466}