| 19 | |
| 20 | useLayoutEffect(() => { |
| 21 | const renderDiagram = async () => { |
| 22 | try { |
| 23 | setIsLoading(true) |
| 24 | setError(null) |
| 25 | |
| 26 | // Dynamically import mermaid only on client side |
| 27 | if (!mermaidPromise) { |
| 28 | mermaidPromise = import('mermaid') |
| 29 | } |
| 30 | |
| 31 | const mermaidModule = await mermaidPromise |
| 32 | const mermaid = mermaidModule.default |
| 33 | |
| 34 | // Initialize mermaid only once globally |
| 35 | if (!isInitialized) { |
| 36 | mermaid.initialize({ |
| 37 | startOnLoad: false, |
| 38 | theme: 'default', |
| 39 | securityLevel: 'loose', |
| 40 | fontFamily: 'inherit', |
| 41 | }) |
| 42 | isInitialized = true |
| 43 | } |
| 44 | |
| 45 | // Clear any existing content |
| 46 | if (containerRef.current) { |
| 47 | containerRef.current.innerHTML = '' |
| 48 | } |
| 49 | |
| 50 | // Render the diagram with a unique ID each time |
| 51 | const uniqueId = `${mermaidId}-${Date.now()}` |
| 52 | const { svg } = await mermaid.render(uniqueId, code) |
| 53 | |
| 54 | if (containerRef.current) { |
| 55 | containerRef.current.innerHTML = svg |
| 56 | } |
| 57 | } catch (err) { |
| 58 | console.error('Mermaid rendering error:', err) |
| 59 | setError( |
| 60 | err instanceof Error ? err.message : 'Failed to render diagram', |
| 61 | ) |
| 62 | } finally { |
| 63 | setIsLoading(false) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Small delay to ensure DOM is ready |
| 68 | const timer = setTimeout(renderDiagram, 50) |