import { DEFAULT_THEMES, getFiletypeFromFileName, getSharedHighlighter } from "@pierre/diffs"; /** One coloured run of a line. A colour is absent when the token takes the text colour. */ export interface CodeToken { readonly text: string; readonly light?: string; readonly dark?: string; } /** Past these sizes a file stays plain, so highlighting never freezes the page. */ const MAX_LINES = 5000; const MAX_CHARACTERS = 300_000; const MAX_LINE_LENGTH = 1000; /** * Colours a file's lines with the highlighter and the themes of the diff view, so code looks the same in both. * It resolves to null when the language is unknown or the file is too large; the caller keeps the plain text. */ export async function highlightLines(name: string, lines: readonly string[]): Promise { const lang = getFiletypeFromFileName(name); if (lang === "text" || lines.length > MAX_LINES) return null; const code = lines.join("\n"); if (code.length > MAX_CHARACTERS) return null; const highlighter = await getSharedHighlighter({ themes: [DEFAULT_THEMES.dark, DEFAULT_THEMES.light], langs: [lang], preferredHighlighter: "shiki-js" }); const { tokens } = highlighter.codeToTokens(code, { lang, themes: DEFAULT_THEMES, defaultColor: false, tokenizeMaxLineLength: MAX_LINE_LENGTH }); if (tokens.length !== lines.length) return null; return tokens.map((line) => line.map((token) => ({ text: token.content, light: token.htmlStyle?.["--shiki-light"], dark: token.htmlStyle?.["--shiki-dark"] }))); }