feat: 归档渲染
This commit is contained in:
56
src/lib/highlight.js
Normal file
56
src/lib/highlight.js
Normal file
@@ -0,0 +1,56 @@
|
||||
import {JSDOM} from 'jsdom'
|
||||
import {createHighlighter} from 'shiki'
|
||||
|
||||
const highlighter = await createHighlighter({
|
||||
themes: ['github-dark-dimmed'],
|
||||
langs: ['javascript', 'typescript', 'css', 'tsx', 'less', 'scss', 'text'],
|
||||
})
|
||||
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user