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

nativeReviewDiffHighlighter.ts

611 lines19.8 KB

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 }
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 }
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>>>;
56​
57interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
58 readonly kind: "line";
59 readonly fileId: string;
60 readonly content: string;
62​
63interface IndexedNativeReviewDiffLineRow {
64 readonly row: NativeReviewDiffLineRow;
65 readonly rowIndex: number;
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>>;
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;
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;
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));
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 );
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. Keep the
251 // rest of this contiguous segment plain instead of guessing its syntax.
252 if (lines[start]!.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH) {
253 highlighted.push(
254 ...lines
255 .slice(start)
256 .map((content) => [{ content: content || " ", color: null, fontStyle: null }]),
257 );
258 break;
259 }
260​
261 let end = start;
262 let characters = 0;
263 while (end < lines.length) {
264 const length = lines[end]!.length;
265 const nextCharacters = characters + length + (end > start ? 1 : 0);
266 if (
267 length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_LINE_LENGTH ||
268 nextCharacters > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
269 ) {
270 break;
271 }
272 characters = nextCharacters;
273 end += 1;
274 }
275​
276 const tokens = highlighter.codeToTokensBase(lines.slice(start, end).join("\n"), {
277 lang,
278 theme,
279 grammarState,
280 });
281 grammarState = highlighter.getLastGrammarState(tokens);
282 highlighted.push(...normalizeTokens(tokens));
283 start = end;
284 if (start < lines.length) await waitForNextFrame();
285 }
286​
287 return signal?.aborted ? [] : highlighted;
288 },
289 };
291​
292async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
293 const nativeEngineModule = await import("react-native-shiki-engine");
294 if (!nativeEngineModule.isNativeEngineAvailable()) {
295 throw new NativeReviewDiffHighlighterUnavailableError();
296 }
297​
298 const highlighter = await createHighlighterCore({
299 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
300 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
301 engine: nativeEngineModule.createNativeEngine(),
302 });
303​
304 return createHighlighterHandle(highlighter, "native");
306​
307async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
308 const highlighter: HighlighterCore = await createHighlighterCore({
309 langs: NATIVE_REVIEW_DIFF_LANGUAGES,
310 themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
311 engine: createJavaScriptRegexEngine(),
312 });
313​
314 return createHighlighterHandle(highlighter, "javascript");
316​
317export async function getNativeReviewDiffHighlighter(
318 engine: NativeReviewDiffHighlightEngine = "native",
319): Promise<NativeReviewDiffHighlighterHandle> {
320 if (engine === "javascript") {
321 try {
322 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
323 return await javascriptHighlighterPromise;
324 } catch (cause) {
325 javascriptHighlighterPromise = null;
326 throw new NativeReviewDiffHighlighterInitializationError({
327 requestedEngine: engine,
328 attemptedEngine: "javascript",
329 cause,
330 });
331 }
332 }
333​
334 nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
335 .catch(async (cause: unknown) => {
336 const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
337 ? cause
338 : new NativeReviewDiffHighlighterInitializationError({
339 requestedEngine: engine,
340 attemptedEngine: "native",
341 cause,
342 });
343 console.warn("[debug-native-diff] native highlighter unavailable", {
344 error: nativeError,
345 });
346 try {
347 javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
348 return await javascriptHighlighterPromise;
349 } catch (fallbackCause) {
350 javascriptHighlighterPromise = null;
351 throw new NativeReviewDiffHighlighterInitializationError({
352 requestedEngine: engine,
353 attemptedEngine: "javascript",
354 cause: new AggregateError(
355 [nativeError, fallbackCause],
356 "Native and JavaScript review diff highlighter initialization failed.",
357 { cause: nativeError },
358 ),
359 });
360 }
361 })
362 .catch((error) => {
363 nativeHighlighterPromise = null;
364 throw error;
365 });
366 return await nativeHighlighterPromise;
368​
369function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
370 return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
372​
373function hasConsecutiveLineNumbers(
374 previous: number | null | undefined,
375 next: number | null | undefined,
376): boolean {
377 return typeof previous === "number" && typeof next === "number" && next === previous + 1;
379​
380function hasOnlyCommentRowsBetween(
381 rows: ReadonlyArray<NativeReviewDiffRow>,
382 previousRowIndex: number,
383 nextRowIndex: number,
384): boolean {
385 for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
386 if (rows[rowIndex]?.kind !== "comment") {
387 return false;
388 }
389 }
390 return true;
392​
393function canShareGrammarContext(
394 previous: IndexedNativeReviewDiffLineRow,
395 next: IndexedNativeReviewDiffLineRow,
396 rows: ReadonlyArray<NativeReviewDiffRow>,
397): boolean {
398 if (
399 next.row.fileId !== previous.row.fileId ||
400 !hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
401 ) {
402 return false;
403 }
404​
405 if (previous.row.change === "delete" || next.row.change === "delete") {
406 return (
407 previous.row.change !== "add" &&
408 next.row.change !== "add" &&
409 hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
410 );
411 }
412​
413 if (previous.row.change === "add" || next.row.change === "add") {
414 return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
415 }
416​
417 return (
418 previous.row.change === "context" &&
419 next.row.change === "context" &&
420 hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
421 hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
422 );
424​
425function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
426 const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
427 for (const row of rows) {
428 if (!isHighlightableLineRow(row)) {
429 continue;
430 }
431​
432 const fileRows = rowsByFileId.get(row.fileId) ?? [];
433 fileRows.push(row);
434 rowsByFileId.set(row.fileId, fileRows);
435 }
436 return rowsByFileId;
438​
439function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
440 return new Map(files.map((file) => [file.id, file]));
442​
443function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
444 if (rows.length === 0) {
445 return 0;
446 }
447​
448 return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
450​
451function makePlainTokenFallback(
452 row: NativeReviewDiffLineRow,
453): ReadonlyArray<NativeReviewDiffToken> {
454 return [{ content: row.content || " ", color: null, fontStyle: null }];
456​
457export async function highlightNativeReviewDiffVisibleRows(
458 input: HighlightNativeReviewDiffVisibleRowsInput,
459): Promise<{
460 readonly engine: NativeReviewDiffHighlightEngine;
461 readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
462 readonly rowCount: number;
463 readonly durationMs: number;
464}> {
465 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
466 if (input.signal?.aborted) {
467 return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
468 }
469​
470 const startedAt = performance.now();
471 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
472 const fileMap = createFileMap(input.files);
473 const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
474 const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
475 const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
476 const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
477 const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
478​
479 for (
480 let rowIndex = startIndex;
481 rowIndex <= endIndex && selectedRows.length < maxRows;
482 rowIndex += 1
483 ) {
484 const row = input.rows[rowIndex];
485 if (
486 row &&
487 isHighlightableLineRow(row) &&
488 !input.alreadyHighlightedRowIds?.has(row.id) &&
489 fileMap.has(row.fileId)
490 ) {
491 selectedRows.push({ row, rowIndex });
492 }
493 }
494​
495 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
496 let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
497 let segmentFile: NativeReviewDiffFile | undefined;
498 let charactersSinceYield = 0;
499​
500 const flushSegment = async () => {
501 if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
502 segmentRows = [];
503 segmentFile = undefined;
504 return;
505 }
506​
507 const code = segmentRows.map(({ row }) => row.content).join("\n");
508 if (
509 charactersSinceYield > 0 &&
510 charactersSinceYield + code.length > NATIVE_REVIEW_DIFF_TOKENIZE_MAX_CHARACTERS
511 ) {
512 await waitForNextFrame();
513 charactersSinceYield = 0;
514 if (input.signal?.aborted) return;
515 }
516 const tokenLines = await highlighter.tokenize(code, {
517 lang: segmentFile.language,
518 theme,
519 signal: input.signal,
520 });
521 charactersSinceYield += code.length;
522 segmentRows.forEach(({ row }, rowIndex) => {
523 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
524 });
525 segmentRows = [];
526 segmentFile = undefined;
527 };
528​
529 for (const selectedRow of selectedRows) {
530 if (input.signal?.aborted) break;
531 const { row } = selectedRow;
532 const file = fileMap.get(row.fileId);
533 if (!file) {
534 continue;
535 }
536​
537 const previousRow = segmentRows.at(-1);
538 if (
539 segmentFile &&
540 (segmentFile.id !== file.id ||
541 (previousRow !== undefined &&
542 !canShareGrammarContext(previousRow, selectedRow, input.rows)))
543 ) {
544 await flushSegment();
545 }
546​
547 segmentFile = file;
548 segmentRows.push(selectedRow);
549 }
550 await flushSegment();
551​
552 if (input.signal?.aborted) {
553 return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
554 }
555​
556 return {
557 engine: highlighter.engine,
558 tokensByRowId,
559 rowCount: selectedRows.length,
560 durationMs: Math.round(performance.now() - startedAt),
561 };
563​
564export async function streamNativeReviewDiffTokens(
565 input: StreamNativeReviewDiffTokenInput,
566): Promise<NativeReviewDiffHighlightEngine> {
567 const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
568 const rowsByFileId = groupLineRowsByFileId(input.rows);
569 const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
570 const chunkSize = input.chunkSize ?? NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE;
571 let chunkIndex = 0;
572​
573 for (const file of input.files) {
574 const fileRows = rowsByFileId.get(file.id) ?? [];
575 for (let startIndex = 0; startIndex < fileRows.length; startIndex += chunkSize) {
576 if (input.signal?.aborted) {
577 return highlighter.engine;
578 }
579​
580 const startedAt = performance.now();
581 const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
582 const code = chunkRows.map((row) => row.content).join("\n");
583 const tokenLines = await highlighter.tokenize(code, {
584 lang: file.language,
585 theme,
586 signal: input.signal,
587 });
588 if (input.signal?.aborted) return highlighter.engine;
589 const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
590​
591 chunkRows.forEach((row, rowIndex) => {
592 tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
593 });
594​
595 input.onChunk({
596 chunkIndex,
597 fileId: file.id,
598 filePath: file.path,
599 language: file.language,
600 lineCount: chunkRows.length,
601 durationMs: Math.round(performance.now() - startedAt),
602 tokensByRowId,
603 });
604​
605 chunkIndex += 1;
606 await waitForNextFrame();
607 }
608 }
609​
610 return highlighter.engine;