85 lines
1.8 KiB
JavaScript
85 lines
1.8 KiB
JavaScript
import {JSDOM} from 'jsdom'
|
|
import {createHighlighter} from 'shiki'
|
|
|
|
const highlighter = await createHighlighter({
|
|
themes: ['github-dark-dimmed'],
|
|
langs: [
|
|
"bash",
|
|
"json",
|
|
"yaml",
|
|
"xml",
|
|
"html",
|
|
"css",
|
|
"scss",
|
|
"javascript",
|
|
"typescript",
|
|
"jsx",
|
|
"tsx",
|
|
"vue",
|
|
"markdown",
|
|
"sql",
|
|
"graphql",
|
|
"python",
|
|
"java",
|
|
"go",
|
|
"rust",
|
|
"c",
|
|
"cpp",
|
|
"csharp",
|
|
"php",
|
|
"ruby",
|
|
"kotlin",
|
|
"swift",
|
|
"dockerfile",
|
|
"nginx"
|
|
]
|
|
})
|
|
|
|
const resolveLang = (lang) => {
|
|
const supported = highlighter.getLoadedLanguages?.() || []
|
|
if (!lang) return 'text'
|
|
if (supported.includes(lang)) return lang
|
|
return 'text'
|
|
}
|
|
|
|
export const highlightHtmlWithJsdom = async (rawHtml) => {
|
|
const dom = new JSDOM(rawHtml)
|
|
const document = dom.window.document
|
|
|
|
const codeElements = document.querySelectorAll('pre code')
|
|
|
|
for (const codeEl of codeElements) {
|
|
const preEl = codeEl.parentElement
|
|
if (!preEl || preEl.tagName !== 'PRE') continue
|
|
|
|
const codeContent = codeEl.textContent?.trim() || ''
|
|
|
|
// 提取语言
|
|
let lang = 'text'
|
|
for (const cls of codeEl.classList) {
|
|
if (cls.startsWith('language-')) {
|
|
lang = cls.slice('language-'.length)
|
|
break
|
|
}
|
|
}
|
|
|
|
lang = resolveLang(lang)
|
|
|
|
// 生成高亮 HTML
|
|
const highlighted = highlighter.codeToHtml(codeContent, {
|
|
lang,
|
|
theme: 'github-dark-dimmed',
|
|
})
|
|
|
|
// 替换 DOM
|
|
const wrapper = document.createElement('div')
|
|
wrapper.innerHTML = highlighted.trim()
|
|
|
|
const newNode = wrapper.firstChild
|
|
if (newNode && preEl.parentNode) {
|
|
preEl.parentNode.replaceChild(newNode, preEl)
|
|
}
|
|
}
|
|
|
|
return dom.serialize()
|
|
} |