From 4e31c53439154864db0f26d4b5fcf0431a688a0e Mon Sep 17 00:00:00 2001 From: Shirasawa <764798966@qq.com> Date: Wed, 15 Apr 2026 01:42:40 +0800 Subject: [PATCH] fix: clean up Mermaid temporary DOM nodes after render failures --- src/lib/utils/index.ts | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index ecaeefab04..f0feb807e9 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -1713,13 +1713,29 @@ export const initMermaid = async () => { return mermaid; }; -export const renderMermaidDiagram = async (mermaid, code: string) => { - const parseResult = await mermaid.parse(code, { suppressErrors: false }); - if (parseResult) { - const { svg } = await mermaid.render(`mermaid-${uuidv4()}`, code); - return svg; +const cleanupMermaidTempElements = (id: string) => { + if (typeof document === 'undefined') { + return; + } + + document.getElementById(id)?.remove(); + document.getElementById(`d${id}`)?.remove(); + document.getElementById(`i${id}`)?.remove(); +}; + +export const renderMermaidDiagram = async (mermaid: typeof import('mermaid').default, code: string, renderId?: string) => { + const id = renderId ?? `mermaid-${uuidv4()}`; + try { + const parseResult = await mermaid.parse(code, { suppressErrors: false }); + if (parseResult) { + const { svg } = await mermaid.render(id, code); + return svg; + } + return ''; + } finally { + // Mermaid can leave temporary d*/i* wrappers on error paths. + cleanupMermaidTempElements(id); } - return ''; }; export const renderVegaVisualization = async (spec: string, i18n?: any) => {