Skip to content
refs
History
28 lines · 1.5 KBRaw
1import { DEFAULT_THEMES, getFiletypeFromFileName, getSharedHighlighter } from "@pierre/diffs";
2
3/** One coloured run of a line. A colour is absent when the token takes the text colour. */
4export interface CodeToken {
5 readonly text: string;
6 readonly light?: string;
7 readonly dark?: string;
8}
9
10/** Past these sizes a file stays plain, so highlighting never freezes the page. */
11const MAX_LINES = 5000;
12const MAX_CHARACTERS = 300_000;
13const MAX_LINE_LENGTH = 1000;
14
15/**
16 * Colours a file's lines with the highlighter and the themes of the diff view, so code looks the same in both.
17 * It resolves to null when the language is unknown or the file is too large; the caller keeps the plain text.
18 */
19export async function highlightLines(name: string, lines: readonly string[]): Promise<CodeToken[][] | null> {
20 const lang = getFiletypeFromFileName(name);
21 if (lang === "text" || lines.length > MAX_LINES) return null;
22 const code = lines.join("\n");
23 if (code.length > MAX_CHARACTERS) return null;
24 const highlighter = await getSharedHighlighter({ themes: [DEFAULT_THEMES.dark, DEFAULT_THEMES.light], langs: [lang], preferredHighlighter: "shiki-js" });
25 const { tokens } = highlighter.codeToTokens(code, { lang, themes: DEFAULT_THEMES, defaultColor: false, tokenizeMaxLineLength: MAX_LINE_LENGTH });
26 if (tokens.length !== lines.length) return null;
27 return tokens.map((line) => line.map((token) => ({ text: token.content, light: token.htmlStyle?.["--shiki-light"], dark: token.htmlStyle?.["--shiki-dark"] })));
28}