feat: fix katex and mermaid diagrams

This commit is contained in:
2026-04-25 18:02:29 +02:00
parent 7268933a17
commit 931b7d0d4d
6 changed files with 284 additions and 25 deletions
+2
View File
@@ -2,6 +2,7 @@
import hljs from 'highlight.js'
import { createIcons, icons } from 'lucide'
import { onMounted, onUpdated, nextTick } from 'vue'
import mermaid from 'mermaid'
async function update() {
setTimeout(async () => {
@@ -15,6 +16,7 @@ async function update() {
height: '1.1em',
},
})
mermaid.run()
}, 100)
}
+35 -18
View File
@@ -20,25 +20,41 @@ function parseMetadata(
}
const LATEX_REGEX = /\$\$((?:(?!\$\$)[\s\S])*)\$\$/m
const INLINE_LATEX_REGEX = /\$([^$\n]*)\$/
const MERMAID_REGEX = /<pre>\s*<code class="language-mermaid">([\s\S]*)<\/code>\s*<\/pre>/m
function transformLatexBlocks(srcHtml: string): string {
let outHtml = srcHtml
let match: RegExpExecArray | null = null
do {
match = LATEX_REGEX.exec(outHtml)
if (match && match[1]) {
try {
outHtml = outHtml.replace(match[0], katex.renderToString(match[1]))
} catch (ex) {
outHtml = outHtml.replace(match[0], `<i>katex error: ${ex}</i>`)
}
}
} while (match && match[1])
return outHtml
}
function transformMermaidBlocks(srcHtml: string): string {
let outHtml = srcHtml
let match: RegExpExecArray | null = null
do {
match = MERMAID_REGEX.exec(outHtml)
if (match && match[1]) {
outHtml = outHtml.replace(match[0], `<pre class="mermaid">\n${match[1]}\n</pre>`)
}
} while (match && match[1])
return outHtml
}
function transformHtml(srcHtml: string, pathPrefix: string): string {
let html: string = srcHtml.replaceAll('="./', '="' + pathPrefix + '/')
let match: RegExpExecArray | null
do {
match = LATEX_REGEX.exec(html)
if (match && match[1]) {
console.log(match)
html = html.replace(match[0], katex.renderToString(match[1]))
}
} while (match && match[1])
do {
match = INLINE_LATEX_REGEX.exec(html)
if (match && match[1]) {
html = html.replace(match[0], katex.renderToString(match[1]))
}
} while (match && match[1])
return html
let outHtml: string = srcHtml.replaceAll('="./', '="' + pathPrefix + '/')
outHtml = transformLatexBlocks(outHtml)
outHtml = transformMermaidBlocks(outHtml)
return outHtml
}
export async function loadArticle(date: Date): Promise<Article | null> {
@@ -52,7 +68,8 @@ export async function loadArticle(date: Date): Promise<Article | null> {
metadata: parseMetadata(data.attributes, path, date),
html: transformHtml(data.html, path),
}
} catch {
} catch (ex) {
console.error(ex)
return null
}
}