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