|
|
@ -16,9 +16,42 @@ marked.use( |
|
|
}) |
|
|
}) |
|
|
) |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
function highlightHtmlCode(html: string): string { |
|
|
|
|
|
const doc = new DOMParser().parseFromString(html, 'text/html') |
|
|
|
|
|
const blocks = Array.from(doc.querySelectorAll<HTMLElement>('pre')) |
|
|
|
|
|
for (const pre of blocks) { |
|
|
|
|
|
const container = pre.closest<HTMLElement>('.ql-code-block-container') |
|
|
|
|
|
const codeEl = pre.querySelector<HTMLElement>('code') |
|
|
|
|
|
let lang = container?.getAttribute('data-language') ?? '' |
|
|
|
|
|
if (!lang && codeEl) { |
|
|
|
|
|
const m = (codeEl.className || '').match(/language-([\w-]+)/) |
|
|
|
|
|
if (m) lang = m[1] |
|
|
|
|
|
} |
|
|
|
|
|
const text = codeEl ? codeEl.textContent ?? '' : pre.textContent ?? '' |
|
|
|
|
|
let highlighted: string |
|
|
|
|
|
if (lang && hljs.getLanguage(lang)) { |
|
|
|
|
|
highlighted = hljs.highlight(text, { language: lang }).value |
|
|
|
|
|
} else { |
|
|
|
|
|
highlighted = hljs.highlightAuto(text).value |
|
|
|
|
|
} |
|
|
|
|
|
if (codeEl) { |
|
|
|
|
|
codeEl.innerHTML = highlighted |
|
|
|
|
|
codeEl.classList.add('hljs') |
|
|
|
|
|
} else { |
|
|
|
|
|
const newCode = doc.createElement('code') |
|
|
|
|
|
newCode.className = 'hljs' |
|
|
|
|
|
newCode.innerHTML = highlighted |
|
|
|
|
|
pre.innerHTML = '' |
|
|
|
|
|
pre.appendChild(newCode) |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
return doc.body.innerHTML |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
export function renderArticle(content: string): string { |
|
|
export function renderArticle(content: string): string { |
|
|
if (content.trimStart().startsWith('<')) { |
|
|
if (content.trimStart().startsWith('<')) { |
|
|
return DOMPurify.sanitize(content) |
|
|
|
|
|
|
|
|
const safe = DOMPurify.sanitize(content) |
|
|
|
|
|
return highlightHtmlCode(safe) |
|
|
} |
|
|
} |
|
|
const rawHtml = marked.parse(content, { async: false }) as string |
|
|
const rawHtml = marked.parse(content, { async: false }) as string |
|
|
return DOMPurify.sanitize(rawHtml) |
|
|
return DOMPurify.sanitize(rawHtml) |