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

syntaxHighlighting.ts

41 lines1.7 KB

1import type { DiffsHighlighter, HighlighterTypes, SupportedLanguages } from "@pierre/diffs";
2​
3import { resolveDiffThemeName } from "./diffRendering";
4​
5/**
6 * Always highlight with the Oniguruma WASM engine — the JS regex engine can
7 * backtrack catastrophically and hang the tokenizing thread. The shared
8 * highlighter is a first-caller-wins singleton, so every creation site must
9 * pass this value.
10 */
11export const PREFERRED_HIGHLIGHTER: HighlighterTypes = "shiki-wasm";
12​
13const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
14​
15export function getSyntaxHighlighterPromise(language: string): Promise<DiffsHighlighter> {
16 const cached = highlighterPromiseCache.get(language);
17 if (cached) return cached;
18​
19 // Shiki and its engines load with the first highlight, not with the app.
20 const promise = import("./sharedHighlighter")
21 .then(({ getSharedHighlighter }) =>
22 getSharedHighlighter({
23 themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
24 langs: [language as SupportedLanguages],
25 preferredHighlighter: PREFERRED_HIGHLIGHTER,
26 }),
27 )
28 .catch((error) => {
29 if (language === "text") {
30 // "text" itself failed — Shiki cannot initialize at all, surface the error
31 throw error;
32 }
33 // Language not supported by Shiki — fall back to "text"
34 return getSyntaxHighlighterPromise("text");
35 });
36 // A failure stays cached too. Callers pass this promise to React `use()`, which needs the
37 // same promise on every render to reach the error boundary's plain-text fallback, and
38 // Chromium caches a failed dynamic import, so a retry of the same chunk cannot succeed.
39 highlighterPromiseCache.set(language, promise);
40 return promise;