返回 slidev
mermaid.ts
根目录 / packages / client / modules / mermaid.ts
1 import { clearUndefined } from '@antfu/utils'
2 import lz from 'lz-string'
3 import mermaid from 'mermaid/dist/mermaid.esm.mjs'
4 import mermaidRenderers from '#slidev/setups/mermaid-renderer'
5 import { makeId } from '../logic/utils'
6 import setupMermaid from '../setup/mermaid'
7
8 mermaid.startOnLoad = false
9 mermaid.initialize({ startOnLoad: false })
10
11 const cache = new Map<string, string>()
12 let containerElement: Element | undefined
13
14 export async function renderMermaid(lzEncoded: string, options: any) {
15 containerElement ??= document.getElementById('mermaid-rendering-container')!
16 const key = lzEncoded + JSON.stringify(options)
17 const _cache = cache.get(key)
18 if (_cache)
19 return _cache
20
21 const code = lz.decompressFromBase64(lzEncoded)
22
23 // custom renderer
24 for (const setup of mermaidRenderers) {
25 const renderer = await setup()
26 if (renderer) {
27 const svg = await renderer(code, options)
28 cache.set(key, svg)
29 return svg
30 }
31 }
32
33 // fallback: existing mermaid
34 mermaid.initialize({
35 startOnLoad: false,
36 ...clearUndefined(await setupMermaid() || {}),
37 ...clearUndefined(options),
38 })
39 const id = makeId()
40 const { svg } = await mermaid.render(id, code, containerElement)
41 cache.set(key, svg)
42 return svg
43 }
44
44 lines TYPESCRIPT