Open History to see the last commit
1import { requireOptionalNativeModule } from "expo";
2
3import { highlightLanguageId } from "./highlightLanguage";
4import { HIGHLIGHTS_THEME_STYLES } from "./highlights.generated";
5
6export type HighlightScheme = "light" | "dark";
7
8export interface HighlightedToken {
9 readonly content: string;
10 readonly color: string | null;
11 readonly fontStyle: number | null;
12}
13
14export type HighlightedLines = ReadonlyArray<ReadonlyArray<HighlightedToken>>;
15
16const LINE_END = 0xffffffff;
17// Longer lines stay one plain token so a minified line does not become
18// thousands of native text runs.
19const MAX_HIGHLIGHTED_LINE_LENGTH = 1_000;
20
21// @pierre/highlights compiled to native code (modules/t3-highlights). Missing
22// from binaries built before it shipped, where code renders as plain text.
23const nativeHighlights = requireOptionalNativeModule<{
24 tokenize(source: string, language: number): ArrayBuffer | null;
25}>("T3Highlights");
26
27function plainLines(code: string): HighlightedLines {
28 return code
29 .split(/\r?\n/u)
30 .map((line) => (line ? [{ content: line, color: null, fontStyle: null }] : []));
31}
32
33/**
34 * Tokenizes `code` synchronously, one token array per line. Lines split at LF
35 * and CRLF, and a trailing line break yields a final empty line.
36 */
37export function highlightCode(
38 code: string,
39 language: string,
40 scheme: HighlightScheme,
41): HighlightedLines {
42 const id = highlightLanguageId(language);
43 const buffer = id === 0 ? null : (nativeHighlights?.tokenize(code, id) ?? null);
44 if (!buffer) return plainLines(code);
45
46 // `(endUtf16, tokenId)` pairs. A LINE_END token ID ends a line, and its end
47 // is where the next line starts. Mirrors @pierre/highlights' lineRecordsToTokens.
48 const records = new Uint32Array(buffer);
49 const styles = HIGHLIGHTS_THEME_STYLES[scheme];
50 const lines: HighlightedToken[][] = [];
51 let start = 0;
52 for (let record = 0; ; record += 2) {
53 const first = record;
54 while (record < records.length && records[record + 1] !== LINE_END) record += 2;
55 const end = record === first ? start : records[record - 2]!;
56 if (end - start > MAX_HIGHLIGHTED_LINE_LENGTH) {
57 lines.push([{ content: code.slice(start, end), color: null, fontStyle: null }]);
58 } else {
59 const line: HighlightedToken[] = [];
60 for (let at = first; at < record; at += 2) {
61 const tokenEnd = records[at]!;
62 if (tokenEnd <= start) continue;
63 const [color, fontStyle] = styles[records[at + 1]!] ?? styles[0]!;
64 line.push({ content: code.slice(start, tokenEnd), color, fontStyle });
65 start = tokenEnd;
66 }
67 lines.push(line);
68 }
69 if (record >= records.length) break;
70 start = records[record]!;
71 }
72 return lines;
73}