app-shiki-highlighter.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import path from "node:path";
  2. import { bundledLanguages, createHighlighter, type BundledLanguage, type BundledTheme } from "shiki";
  3. import type { TuiThemeMode } from "./theme/index.js";
  4. const SHIKI_DARK_THEME = "github-dark";
  5. const SHIKI_LIGHT_THEME = "github-light";
  6. const SHIKI_THEMES = [SHIKI_DARK_THEME, SHIKI_LIGHT_THEME] as const;
  7. const HIGHLIGHT_TIMEOUT_MS = 2_500;
  8. const LANGUAGE_BY_FILENAME: Record<string, BundledLanguage> = {
  9. dockerfile: "dockerfile",
  10. makefile: "makefile",
  11. };
  12. const LANGUAGE_BY_EXTENSION: Record<string, BundledLanguage> = {
  13. cjs: "javascript",
  14. cts: "typescript",
  15. h: "c",
  16. hpp: "cpp",
  17. htm: "html",
  18. mjs: "javascript",
  19. mts: "typescript",
  20. psm1: "powershell",
  21. tsx: "tsx",
  22. jsx: "jsx",
  23. swift: "swift",
  24. };
  25. export type ShikiHighlightSegment = {
  26. color?: string;
  27. fontStyle?: number;
  28. text: string;
  29. };
  30. type ShikiHighlighter = Awaited<ReturnType<typeof createHighlighter>>;
  31. let highlighterPromise: Promise<ShikiHighlighter> | undefined;
  32. const loadedLanguages = new Set<BundledLanguage>();
  33. const highlightCache = new Map<string, ShikiHighlightSegment[][] | undefined>();
  34. export function inferShikiLanguage(filePath: string | undefined): BundledLanguage | undefined {
  35. if (!filePath) return undefined;
  36. const basename = path.basename(filePath).toLowerCase();
  37. const filenameMatch = LANGUAGE_BY_FILENAME[basename];
  38. if (filenameMatch) return filenameMatch;
  39. const extension = path.extname(basename).replace(/^\./u, "");
  40. if (!extension) return undefined;
  41. const mapped = LANGUAGE_BY_EXTENSION[extension] ?? extension;
  42. return isBundledLanguage(mapped) ? mapped : undefined;
  43. }
  44. export async function highlightShikiCodeLines(input: {
  45. filePath: string | undefined;
  46. lines: string[];
  47. mode: TuiThemeMode;
  48. }): Promise<ShikiHighlightSegment[][] | undefined> {
  49. const language = inferShikiLanguage(input.filePath);
  50. if (!language) return undefined;
  51. const theme = shikiThemeForMode(input.mode);
  52. const cacheKey = `${theme}\0${language}\0${input.lines.join("\n")}`;
  53. if (highlightCache.has(cacheKey)) return highlightCache.get(cacheKey);
  54. const highlighted = await withTimeout(
  55. tokenizeLines({
  56. language,
  57. lines: input.lines,
  58. theme,
  59. }),
  60. HIGHLIGHT_TIMEOUT_MS,
  61. );
  62. highlightCache.set(cacheKey, highlighted);
  63. return highlighted;
  64. }
  65. export function resetShikiHighlighterForTest(): void {
  66. highlighterPromise = undefined;
  67. loadedLanguages.clear();
  68. highlightCache.clear();
  69. }
  70. async function tokenizeLines(input: {
  71. language: BundledLanguage;
  72. lines: string[];
  73. theme: BundledTheme;
  74. }): Promise<ShikiHighlightSegment[][] | undefined> {
  75. try {
  76. const highlighter = await getHighlighter();
  77. if (!loadedLanguages.has(input.language)) {
  78. await highlighter.loadLanguage(input.language);
  79. loadedLanguages.add(input.language);
  80. }
  81. const result = highlighter.codeToTokens(input.lines.join("\n"), {
  82. lang: input.language,
  83. theme: input.theme,
  84. });
  85. return padTokenLines(
  86. result.tokens.map((line) =>
  87. line.map((token) => ({
  88. color: token.color,
  89. fontStyle: token.fontStyle,
  90. text: token.content,
  91. })),
  92. ),
  93. input.lines.length,
  94. );
  95. } catch {
  96. return undefined;
  97. }
  98. }
  99. function getHighlighter(): Promise<ShikiHighlighter> {
  100. highlighterPromise ??= createHighlighter({
  101. langs: [],
  102. themes: [...SHIKI_THEMES],
  103. });
  104. return highlighterPromise;
  105. }
  106. function isBundledLanguage(language: string): language is BundledLanguage {
  107. return Object.prototype.hasOwnProperty.call(bundledLanguages, language);
  108. }
  109. function shikiThemeForMode(mode: TuiThemeMode): BundledTheme {
  110. return mode === "light" ? SHIKI_LIGHT_THEME : SHIKI_DARK_THEME;
  111. }
  112. function padTokenLines(
  113. lines: ShikiHighlightSegment[][],
  114. expectedLength: number,
  115. ): ShikiHighlightSegment[][] {
  116. if (lines.length >= expectedLength) return lines.slice(0, expectedLength);
  117. return [...lines, ...Array.from({ length: expectedLength - lines.length }, () => [])];
  118. }
  119. async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
  120. let timeout: ReturnType<typeof setTimeout> | undefined;
  121. try {
  122. return await Promise.race([
  123. promise,
  124. new Promise<undefined>((resolve) => {
  125. timeout = setTimeout(() => resolve(undefined), timeoutMs);
  126. }),
  127. ]);
  128. } finally {
  129. if (timeout) clearTimeout(timeout);
  130. }
  131. }