({ coreOptions = {}, highlighterOptions = {} })
| 42 | * @returns {SyntaxHighlighter} |
| 43 | */ |
| 44 | const createHighlighter = ({ coreOptions = {}, highlighterOptions = {} }) => { |
| 45 | const options = { |
| 46 | themes: [DEFAULT_THEME], |
| 47 | ...coreOptions, |
| 48 | }; |
| 49 | const shiki = createHighlighterCoreSync(options); |
| 50 | const theme = options.themes[0]; |
| 51 | |
| 52 | const loadedLanguages = new Set( |
| 53 | shiki.getLoadedLanguages().map(lang => lang.toLowerCase()) |
| 54 | ); |
| 55 | |
| 56 | /** |
| 57 | * Resolves a language id to one this highlighter can handle. |
| 58 | * Falls back to plain text for unknown/unloaded languages so |
| 59 | * highlighting never throws on unrecognized code fences. |
| 60 | * |
| 61 | * @param {string} [languageId] |
| 62 | * @returns {string} |
| 63 | */ |
| 64 | const resolveLanguage = languageId => { |
| 65 | const normalized = languageId?.toLowerCase(); |
| 66 | |
| 67 | if ( |
| 68 | normalized && |
| 69 | (isSpecialLang(normalized) || loadedLanguages.has(normalized)) |
| 70 | ) { |
| 71 | return languageId; |
| 72 | } |
| 73 | |
| 74 | return FALLBACK_LANGUAGE; |
| 75 | }; |
| 76 | |
| 77 | /** |
| 78 | * Highlights code and returns the inner HTML inside the <code> tag |
| 79 | * |
| 80 | * @param {string} code - The code to highlight |
| 81 | * @param {string} lang - The programming language to use for highlighting |
| 82 | * @param {Record<string, any>} meta - Metadata |
| 83 | * @returns {string} The inner HTML of the highlighted code |
| 84 | */ |
| 85 | const highlightToHtml = (code, lang, meta = {}) => |
| 86 | shiki |
| 87 | .codeToHtml(code, { |
| 88 | lang: resolveLanguage(lang), |
| 89 | theme, |
| 90 | meta, |
| 91 | ...highlighterOptions, |
| 92 | }) |
| 93 | // Shiki will always return the Highlighted code encapsulated in a <pre> and <code> tag |
| 94 | // since our own CodeBox component handles the <code> tag, we just want to extract |
| 95 | // the inner highlighted code to the CodeBox |
| 96 | .match(/<code>(.+?)<\/code>/s)[1]; |
| 97 | |
| 98 | /** |
| 99 | * Highlights code and returns a HAST tree |
| 100 | * |
| 101 | * @param {string} code - The code to highlight |
no outgoing calls
no test coverage detected