|
| 1 | +import { transformerNotationDiff } from '@shikijs/transformers' |
| 2 | +import { unified } from 'unified' |
| 3 | +import rehypeParse from 'rehype-parse' |
| 4 | +import { visit } from 'unist-util-visit' |
| 5 | +import type { Element, Root } from 'hast' |
| 6 | +import { createHighlighter } from 'shiki' |
| 7 | +import type { HighlighterGeneric, Lang, ThemeInput } from 'shiki' |
| 8 | + |
| 9 | +const DEFAULT_THEMES: ThemeInput[] = ['github-light', 'tokyo-night'] |
| 10 | +const DEFAULT_LANGS: Lang[] = [ |
| 11 | + 'typescript', |
| 12 | + 'javascript', |
| 13 | + 'tsx', |
| 14 | + 'jsx', |
| 15 | + 'bash', |
| 16 | + 'json', |
| 17 | + 'html', |
| 18 | + 'css', |
| 19 | + 'markdown', |
| 20 | + 'plaintext', |
| 21 | +] |
| 22 | + |
| 23 | +const LANG_ALIASES: Record<string, Lang> = { |
| 24 | + ts: 'typescript', |
| 25 | + js: 'javascript', |
| 26 | + sh: 'bash', |
| 27 | + shell: 'bash', |
| 28 | + console: 'bash', |
| 29 | + zsh: 'bash', |
| 30 | + md: 'markdown', |
| 31 | + txt: 'plaintext', |
| 32 | + text: 'plaintext', |
| 33 | +} |
| 34 | + |
| 35 | +let highlighterPromise: Promise<HighlighterGeneric<any, any>> | null = null |
| 36 | +const fragmentParser = unified().use(rehypeParse, { fragment: true }) |
| 37 | + |
| 38 | +async function getHighlighter() { |
| 39 | + if (!highlighterPromise) { |
| 40 | + highlighterPromise = createHighlighter({ |
| 41 | + langs: DEFAULT_LANGS, |
| 42 | + themes: DEFAULT_THEMES, |
| 43 | + }) |
| 44 | + } |
| 45 | + return highlighterPromise |
| 46 | +} |
| 47 | + |
| 48 | +async function renderMermaid(code: string): Promise<string> { |
| 49 | + const mermaid = await import('mermaid') |
| 50 | + const { svg } = await mermaid.default.render(`mermaid-${Math.random()}`, code) |
| 51 | + return svg |
| 52 | +} |
| 53 | + |
| 54 | +export const rehypeShikiHighlight = () => { |
| 55 | + return async (tree: Root) => { |
| 56 | + const highlighter = await getHighlighter() |
| 57 | + |
| 58 | + const highlightTasks: Array<Promise<void>> = [] |
| 59 | + |
| 60 | + visit(tree, 'element', (node: Element) => { |
| 61 | + if (node.tagName !== 'pre') return |
| 62 | + const codeNode = node.children?.[0] |
| 63 | + if (!codeNode || codeNode.type !== 'element' || codeNode.tagName !== 'code') { |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + const classNames = codeNode.properties?.className |
| 68 | + const className = Array.isArray(classNames) |
| 69 | + ? classNames.find((cls) => cls.startsWith('language-')) |
| 70 | + : typeof classNames === 'string' |
| 71 | + ? classNames |
| 72 | + : undefined |
| 73 | + |
| 74 | + const langRaw = className?.replace('language-', '') ?? 'plaintext' |
| 75 | + const codeText = codeNode.children?.[0]?.value |
| 76 | + if (typeof codeText !== 'string') { |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + highlightTasks.push( |
| 81 | + (async () => { |
| 82 | + const normalizedLang = LANG_ALIASES[langRaw] ?? (langRaw as Lang) |
| 83 | + const effectiveLang = normalizedLang === 'mermaid' ? 'plaintext' : normalizedLang |
| 84 | + |
| 85 | + if ( |
| 86 | + !highlighter |
| 87 | + .getLoadedLanguages() |
| 88 | + .includes(effectiveLang as unknown as Lang) |
| 89 | + ) { |
| 90 | + try { |
| 91 | + await highlighter.loadLanguage(effectiveLang as unknown as Lang) |
| 92 | + } catch { |
| 93 | + // stick with plaintext fallback |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + const htmlFragments = await Promise.all( |
| 98 | + DEFAULT_THEMES.map((theme) => |
| 99 | + highlighter.codeToHtml(codeText, { |
| 100 | + lang: effectiveLang, |
| 101 | + theme, |
| 102 | + transformers: [transformerNotationDiff()], |
| 103 | + }), |
| 104 | + ), |
| 105 | + ) |
| 106 | + |
| 107 | + node.tagName = 'div' |
| 108 | + node.properties = { |
| 109 | + ...node.properties, |
| 110 | + className: [ |
| 111 | + ...(Array.isArray(node.properties?.className) |
| 112 | + ? (node.properties?.className as string[]) |
| 113 | + : []), |
| 114 | + 'shiki-wrapper', |
| 115 | + ], |
| 116 | + 'data-language': normalizedLang, |
| 117 | + } |
| 118 | + |
| 119 | + if (normalizedLang === 'mermaid') { |
| 120 | + const svg = await renderMermaid(codeText) |
| 121 | + const mermaidTree = fragmentParser.parse( |
| 122 | + `<div class="mermaid-diagram py-4 bg-neutral-50 dark:bg-gray-900">${svg}</div>`, |
| 123 | + ) as Root |
| 124 | + |
| 125 | + node.children = mermaidTree.children |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + const fragmentTrees = htmlFragments.map((fragment) => |
| 130 | + fragmentParser.parse(fragment) as Root, |
| 131 | + ) |
| 132 | + |
| 133 | + node.children = fragmentTrees.flatMap((fragmentTree) => fragmentTree.children) |
| 134 | + })(), |
| 135 | + ) |
| 136 | + }) |
| 137 | + |
| 138 | + await Promise.all(highlightTasks) |
| 139 | + } |
| 140 | +} |
0 commit comments