Skip to content

Commit 4c2a6ec

Browse files
authored
fix: isolate Mermaid diagram rendering (#1455)
1 parent 32cc46c commit 4c2a6ec

2 files changed

Lines changed: 263 additions & 9 deletions

File tree

‎src/components/markdown/MermaidBlock.tsx‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { twMerge } from 'tailwind-merge'
33
import { CodeBlockView } from './CodeBlockView'
44
import { buildPlainCodeBlockHtml } from './codeBlock.shared'
55

6+
// Mermaid shares configuration and a temporary DOM across renders.
7+
let mermaidRenderQueue = Promise.resolve()
8+
let mermaidRenderId = 0
9+
610
type MermaidRenderState =
711
| {
812
status: 'loading'
@@ -56,31 +60,38 @@ export function MermaidBlock({
5660
title?: string
5761
}) {
5862
const isDark = useIsDarkMode()
59-
const reactId = React.useId()
60-
const mermaidId = React.useMemo(
61-
() => `mermaid-${reactId.replace(/[^a-zA-Z0-9_-]/g, '')}`,
62-
[reactId],
63-
)
6463
const [renderState, setRenderState] = React.useState<MermaidRenderState>({
6564
status: 'loading',
6665
})
6766

6867
React.useEffect(() => {
6968
let cancelled = false
7069

70+
setRenderState({ status: 'loading' })
71+
7172
async function renderMermaid() {
72-
setRenderState({ status: 'loading' })
73+
if (cancelled) return
74+
75+
const container = document.createElement('div')
76+
container.style.visibility = 'hidden'
77+
container.style.position = 'absolute'
78+
document.body.append(container)
7379

7480
try {
7581
const mermaid = (await import('mermaid')).default
82+
if (cancelled) return
7683

7784
mermaid.initialize({
7885
securityLevel: 'strict',
7986
startOnLoad: false,
8087
theme: isDark ? 'dark' : 'default',
8188
})
8289

83-
const { svg } = await mermaid.render(mermaidId, code)
90+
const { svg } = await mermaid.render(
91+
`mermaid-${++mermaidRenderId}`,
92+
code,
93+
container,
94+
)
8495

8596
if (!cancelled) {
8697
setRenderState({ status: 'rendered', svg })
@@ -89,15 +100,17 @@ export function MermaidBlock({
89100
if (!cancelled) {
90101
setRenderState({ status: 'error' })
91102
}
103+
} finally {
104+
container.remove()
92105
}
93106
}
94107

95-
void renderMermaid()
108+
mermaidRenderQueue = mermaidRenderQueue.then(renderMermaid)
96109

97110
return () => {
98111
cancelled = true
99112
}
100-
}, [code, isDark, mermaidId])
113+
}, [code, isDark])
101114

102115
if (renderState.status !== 'rendered') {
103116
return (

‎tests/mermaid-rendering.test.ts‎

Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
import assert from 'node:assert/strict'
2+
import { existsSync, readFileSync } from 'node:fs'
3+
import path from 'node:path'
4+
import test from 'node:test'
5+
import { build } from 'esbuild'
6+
import { chromium } from 'playwright-core'
7+
8+
const repoRoot = path.resolve(import.meta.dirname, '..')
9+
const chromePath = [
10+
process.env.CHROME_BIN,
11+
process.env.CHROME_PATH,
12+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
13+
'/usr/bin/google-chrome',
14+
'/usr/bin/chromium',
15+
chromium.executablePath(),
16+
].find((candidate) => candidate && existsSync(candidate))
17+
const post = readFileSync(
18+
path.join(
19+
repoRoot,
20+
'src/blog/tanstack-db-1.0-rc1-going-all-in-on-oracles.md',
21+
),
22+
'utf8',
23+
)
24+
const diagram = post.match(/```mermaid\n([\s\S]*?)```/)?.[1]
25+
assert.ok(diagram)
26+
27+
test(
28+
'Mermaid isolates asynchronous renders, theme changes, errors, and unmounts',
29+
{ skip: chromePath ? false : 'Chrome is not installed', timeout: 60_000 },
30+
async () => {
31+
const bundle = await build({
32+
stdin: {
33+
contents: `
34+
import React from 'react'
35+
import { createRoot } from 'react-dom/client'
36+
import { MermaidBlock } from './src/components/markdown/MermaidBlock'
37+
38+
const root = createRoot(document.getElementById('root'))
39+
window.mermaidTest = { active: 0, configRaces: 0, visibleScratch: 0 }
40+
window.holdRender = () => {
41+
window.mermaidTest.gate = new Promise(resolve => {
42+
window.releaseRender = () => {
43+
window.mermaidTest.gate = undefined
44+
resolve()
45+
}
46+
})
47+
}
48+
window.setDiagrams = codes => root.render(
49+
React.createElement(React.StrictMode, null,
50+
codes.map((code, index) => React.createElement(MermaidBlock, { key: index, code }))
51+
)
52+
)
53+
new MutationObserver(() => {
54+
for (const svg of document.querySelectorAll('body svg')) {
55+
if (!svg.closest('#root') && getComputedStyle(svg).visibility !== 'hidden') {
56+
window.mermaidTest.visibleScratch++
57+
}
58+
}
59+
}).observe(document.body, { childList: true, subtree: true })
60+
`,
61+
loader: 'tsx',
62+
resolveDir: repoRoot,
63+
},
64+
plugins: [
65+
{
66+
name: 'mermaid-render-harness',
67+
setup(build) {
68+
// Isolate the renderer from the fallback's unrelated toast providers.
69+
build.onResolve({ filter: /^\.\/CodeBlockView$/ }, () => ({
70+
path: 'fallback',
71+
namespace: 'mermaid-test',
72+
}))
73+
build.onResolve({ filter: /^mermaid$/ }, () => ({
74+
path: 'mermaid',
75+
namespace: 'mermaid-test',
76+
}))
77+
build.onLoad(
78+
{ filter: /.*/, namespace: 'mermaid-test' },
79+
(args) => ({
80+
contents:
81+
args.path === 'fallback'
82+
? `import React from 'react'
83+
export function CodeBlockView({ copyText }) {
84+
return React.createElement('pre', null, copyText)
85+
}`
86+
: `import mermaid from ${JSON.stringify(path.join(repoRoot, 'node_modules/mermaid/dist/mermaid.core.mjs'))}
87+
export default {
88+
initialize(config) {
89+
if (window.mermaidTest.active) window.mermaidTest.configRaces++
90+
mermaid.initialize(config)
91+
},
92+
async render(...args) {
93+
window.mermaidTest.active++
94+
try {
95+
await window.mermaidTest.gate
96+
return await mermaid.render(...args)
97+
} finally {
98+
window.mermaidTest.active--
99+
}
100+
}
101+
}`,
102+
loader: 'jsx',
103+
resolveDir: repoRoot,
104+
}),
105+
)
106+
},
107+
},
108+
],
109+
bundle: true,
110+
format: 'iife',
111+
platform: 'browser',
112+
write: false,
113+
})
114+
const browser = await chromium.launch({
115+
executablePath: chromePath,
116+
headless: true,
117+
})
118+
try {
119+
const page = await browser.newPage()
120+
const errors: string[] = []
121+
page.on('pageerror', (error) => errors.push(error.message))
122+
await page.setContent(
123+
'<html class="dark"><body><div id="root"></div></body></html>',
124+
)
125+
await page.addScriptTag({ content: bundle.outputFiles[0].text })
126+
const run = (source: string) => page.evaluate(source)
127+
await run('window.holdRender()')
128+
await run(`window.setDiagrams([${JSON.stringify(diagram)}])`)
129+
await page.waitForFunction('window.mermaidTest.active > 0')
130+
await run(
131+
`window.setDiagrams([${JSON.stringify(diagram)}, 'flowchart TD; A[Second diagram] --> B[Result]'])`,
132+
)
133+
// Flush React effects while the first render is deliberately held.
134+
await page.waitForFunction(
135+
() => document.querySelectorAll('#root pre').length === 2,
136+
)
137+
await run('window.releaseRender()')
138+
await page.waitForFunction(
139+
() =>
140+
document.querySelectorAll('#root .mermaid-block svg').length === 2,
141+
)
142+
143+
const assertDiagrams = async (count: number) => {
144+
await page.waitForFunction(
145+
(count) =>
146+
document.querySelectorAll('#root .mermaid-block svg').length ===
147+
count,
148+
count,
149+
)
150+
await page.waitForFunction('window.mermaidTest.active === 0')
151+
assert.equal(await page.locator('body > div:not(#root)').count(), 0)
152+
assert.deepEqual(
153+
await page
154+
.locator('.mermaid-block')
155+
.first()
156+
.locator('.nodeLabel')
157+
.allTextContents(),
158+
[
159+
'Explicit design',
160+
'Generate permitted changes',
161+
'Independent model',
162+
'Compare promised public behavior',
163+
'Real DB',
164+
],
165+
)
166+
assert.equal(
167+
await run('window.mermaidTest.configRaces'),
168+
0,
169+
'Mermaid configuration must stay fixed during a render',
170+
)
171+
assert.equal(
172+
await run('window.mermaidTest.visibleScratch'),
173+
0,
174+
'Temporary diagrams must never be visible outside their blocks',
175+
)
176+
assert.deepEqual(errors, [])
177+
}
178+
await assertDiagrams(2)
179+
const initialId = await page
180+
.locator('.mermaid-block svg')
181+
.first()
182+
.getAttribute('id')
183+
for (const dark of [false, true]) {
184+
const previousId = await page
185+
.locator('.mermaid-block svg')
186+
.first()
187+
.getAttribute('id')
188+
await page.evaluate(
189+
(dark) => document.documentElement.classList.toggle('dark', dark),
190+
dark,
191+
)
192+
await page.waitForFunction(
193+
(id) => document.querySelector('.mermaid-block svg')?.id !== id,
194+
previousId,
195+
)
196+
await assertDiagrams(2)
197+
assert.equal(
198+
await page
199+
.locator('.mermaid-block .node rect')
200+
.first()
201+
.evaluate((rect) => getComputedStyle(rect).fill),
202+
dark ? 'rgb(31, 32, 32)' : 'rgb(236, 236, 255)',
203+
)
204+
}
205+
assert.notEqual(
206+
await page.locator('.mermaid-block svg').first().getAttribute('id'),
207+
initialId,
208+
)
209+
210+
await run(
211+
`window.setDiagrams([${JSON.stringify(diagram)}, 'not a diagram'])`,
212+
)
213+
await page.waitForFunction(
214+
() => document.querySelectorAll('#root pre').length === 1,
215+
)
216+
await page.waitForFunction('window.mermaidTest.active === 0')
217+
await assertDiagrams(1)
218+
await run(
219+
`window.setDiagrams([${JSON.stringify(diagram)}, 'flowchart TD; A[Recovered] --> B[Result]'])`,
220+
)
221+
await assertDiagrams(2)
222+
223+
await run('window.holdRender()')
224+
await run(
225+
`window.setDiagrams([${JSON.stringify(diagram + '\n%% updated')}])`,
226+
)
227+
await page.waitForFunction('window.mermaidTest.active > 0')
228+
await run('window.setDiagrams([])')
229+
await page.waitForFunction(
230+
() => document.querySelector('#root')?.childElementCount === 0,
231+
)
232+
await run('window.releaseRender()')
233+
await page.waitForFunction('window.mermaidTest.active === 0')
234+
assert.equal(await page.locator('body svg').count(), 0)
235+
assert.equal(await page.locator('body > div:not(#root)').count(), 0)
236+
assert.deepEqual(errors, [])
237+
} finally {
238+
await browser.close()
239+
}
240+
},
241+
)

0 commit comments

Comments
 (0)