|
| 1 | +import mermaid from 'mermaid' |
| 2 | +import CryptoJs from 'crypto-js' |
| 3 | + |
| 4 | +export const processMermaid = { |
| 5 | + fn: () => {} |
| 6 | +} |
| 7 | + |
| 8 | +const computeHash = (str) => { |
| 9 | + return CryptoJs.SHA256(str).toString(CryptoJs.enc.Hex) |
| 10 | +} |
| 11 | + |
| 12 | +const verifyMermaid = (content: string) => { |
| 13 | + return new Promise<{ isValid: boolean; }>((resolve) => { |
| 14 | + mermaid.parse(content) |
| 15 | + .then(() => { |
| 16 | + resolve({ |
| 17 | + isValid: true |
| 18 | + }) |
| 19 | + }).catch((err) => { |
| 20 | + resolve({ |
| 21 | + isValid: false |
| 22 | + }) |
| 23 | + }) |
| 24 | + }) |
| 25 | +} |
| 26 | + |
| 27 | +export const mermaidPlugin = (md, options = {}) => { |
| 28 | + // 缓存渲染结果 |
| 29 | + const cache = new Map() |
| 30 | + // 记录正在渲染中的图表 |
| 31 | + const pendingQueue = new Map() |
| 32 | + |
| 33 | + const defaultFence = md.renderer.rules.fence |
| 34 | + md.renderer.rules.fence = (tokens, idx, opts, env, self) => { |
| 35 | + const token = tokens[idx] |
| 36 | + |
| 37 | + if (token.info.trim() !== 'mermaid') { |
| 38 | + return defaultFence(tokens, idx, opts, env, self) |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + const content = token.content |
| 43 | + const hash = computeHash(content) |
| 44 | + const encodedContent = encodeURIComponent(content) |
| 45 | + |
| 46 | + |
| 47 | + if (cache.has(hash)) { |
| 48 | + return `<div data-mermaid-hash="${ hash }">${ cache.get(hash) }</div>` |
| 49 | + } |
| 50 | + |
| 51 | + return ` |
| 52 | + <div data-mermaid-hash="${ hash }" |
| 53 | + data-mermaid-content="${ encodedContent }" |
| 54 | + data-mermaid-status="pending"> |
| 55 | + <pre>${ md.utils.escapeHtml(content) }</pre> |
| 56 | + </div> |
| 57 | + ` |
| 58 | + } |
| 59 | + |
| 60 | + // 后处理渲染 mermaid |
| 61 | + const renderMermaid = async (container) => { |
| 62 | + const encodedContent = container.dataset.mermaidContent |
| 63 | + const content = decodeURIComponent(encodedContent) |
| 64 | + const hash = container.dataset.mermaidHash |
| 65 | + |
| 66 | + |
| 67 | + // 如果已经在渲染队列中,则直接返回 |
| 68 | + if (pendingQueue.has(hash)) return |
| 69 | + |
| 70 | + try { |
| 71 | + pendingQueue.set(hash, true) |
| 72 | + let svg |
| 73 | + |
| 74 | + // 检查缓存 |
| 75 | + if (cache.has(hash)) { |
| 76 | + svg = cache.get(hash) |
| 77 | + } else { |
| 78 | + const { isValid } = await verifyMermaid(content) |
| 79 | + |
| 80 | + if (!isValid) { |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + // 使用唯一 ID 渲染(避免图表冲突) |
| 85 | + const { svg: renderedSvg } = await mermaid.render(`mermaid-${ hash }`, content) |
| 86 | + svg = renderedSvg |
| 87 | + cache.set(hash, svg) |
| 88 | + } |
| 89 | + |
| 90 | + const fragment = document.createDocumentFragment() |
| 91 | + const wrapper = document.createElement('div') |
| 92 | + wrapper.innerHTML = svg |
| 93 | + fragment.appendChild(wrapper) |
| 94 | + |
| 95 | + container.replaceWith(fragment) |
| 96 | + } catch (err) { |
| 97 | + // console.error('Mermaid 渲染失败:', err) |
| 98 | + container.dataset.mermaidStatus = 'error' |
| 99 | + } finally { |
| 100 | + pendingQueue.delete(hash) |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + // 全局渲染控制器 |
| 105 | + const processContainers = () => { |
| 106 | + const containers = document.querySelectorAll(` |
| 107 | + div[data-mermaid-status="pending"], |
| 108 | + div[data-mermaid-hash]:not([data-mermaid-status]) |
| 109 | + `) as NodeListOf<HTMLElement> |
| 110 | + |
| 111 | + |
| 112 | + containers.forEach(container => { |
| 113 | + if (!document.body.contains(container)) { |
| 114 | + return |
| 115 | + } |
| 116 | + |
| 117 | + if (container.dataset.mermaidStatus !== 'pending') { |
| 118 | + container.dataset.mermaidStatus = 'pending' |
| 119 | + } |
| 120 | + renderMermaid(container) |
| 121 | + }) |
| 122 | + } |
| 123 | + |
| 124 | + // 初始化 Mermaid |
| 125 | + mermaid.initialize({ |
| 126 | + startOnLoad: false, |
| 127 | + securityLevel: 'antiscript', |
| 128 | + markdownAutoWrap: true, |
| 129 | + suppressErrorRendering: true, |
| 130 | + ...options |
| 131 | + }) |
| 132 | + |
| 133 | + // 触发 Mermaid 图表渲染 export |
| 134 | + processMermaid.fn = () => { |
| 135 | + requestAnimationFrame(processContainers) |
| 136 | + } |
| 137 | +} |
| 138 | + |
0 commit comments