pr_01m47d24b0e6n91zwymwxg0vpx/apps/web/app/lib/highlight.server.ts
| 1 | import { THEME, getHighlighter, languageOf, linesToHtml } from "./shiki"; |
| 2 | |
| 3 | const MAX_HIGHLIGHT_CHARS = 200_000; |
| 4 | |
| 5 | /** |
| 6 | * Highlighted HTML for a file, or null when its language is unknown or it |
| 7 | * is too large, in which case the caller shows plain text. |
| 8 | */ |
| 9 | export async function highlight(path: string, text: string): Promise<string | null> { |
| 10 | const lang = languageOf(path); |
| 11 | if (!lang || text.length > MAX_HIGHLIGHT_CHARS) return null; |
| 12 | try { |
| 13 | return (await getHighlighter()).codeToHtml(text.replace(/\n$/, ""), { lang, theme: THEME }); |
| 14 | } catch { |
| 15 | return null; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * A file's lines as highlighted HTML, one string per line, or null when its |
| 21 | * language is unknown or it is too large. |
| 22 | */ |
| 23 | export async function highlightLines(path: string, text: string): Promise<string[] | null> { |
| 24 | const lang = languageOf(path); |
| 25 | if (!lang || text.length > MAX_HIGHLIGHT_CHARS) return null; |
| 26 | try { |
| 27 | return linesToHtml(await getHighlighter(), text.replace(/\n$/, ""), lang); |
| 28 | } catch { |
| 29 | return null; |
| 30 | } |
| 31 | } |