|
| 1 | +import React, { useEffect, useRef } from 'react'; |
| 2 | + |
| 3 | +export default function MermaidRenderer() { |
| 4 | + const isMounted = useRef(true); |
| 5 | + const observerRef = useRef<MutationObserver | null>(null); |
| 6 | + const isRenderingRef = useRef(false); |
| 7 | + const initializedRef = useRef(false); |
| 8 | + |
| 9 | + // Initialize Mermaid once with neutral theme for compatibility with both light and dark modes |
| 10 | + useEffect(() => { |
| 11 | + const initializeMermaid = async () => { |
| 12 | + if (initializedRef.current) return; |
| 13 | + |
| 14 | + try { |
| 15 | + const mermaid = await import('mermaid'); |
| 16 | + |
| 17 | + if (!isMounted.current) return; |
| 18 | + |
| 19 | + // Use 'neutral' theme - works best with both light and dark page themes |
| 20 | + mermaid.default.initialize({ |
| 21 | + startOnLoad: false, |
| 22 | + theme: 'neutral', // Fixed neutral theme for visual harmony |
| 23 | + securityLevel: 'loose', |
| 24 | + fontFamily: 'monospace', |
| 25 | + flowchart: { |
| 26 | + useMaxWidth: true, |
| 27 | + htmlLabels: true, |
| 28 | + curve: 'basis', |
| 29 | + }, |
| 30 | + }); |
| 31 | + |
| 32 | + function renderMermaidDiagrams() { |
| 33 | + // Only look for blocks that haven't been processed yet |
| 34 | + const unprocessedCodeBlocks = document.querySelectorAll( |
| 35 | + 'pre:not([data-mermaid-processed]) code', |
| 36 | + ); |
| 37 | + let foundCount = 0; |
| 38 | + |
| 39 | + // Cache the mermaid patterns for better performance |
| 40 | + const mermaidPatterns = [ |
| 41 | + 'graph', |
| 42 | + 'flowchart', |
| 43 | + 'stateDiagram', |
| 44 | + 'sequenceDiagram', |
| 45 | + 'classDiagram', |
| 46 | + 'gantt', |
| 47 | + 'pie', |
| 48 | + 'gitGraph', |
| 49 | + 'erDiagram', |
| 50 | + 'journey', |
| 51 | + 'mindmap', |
| 52 | + ]; |
| 53 | + |
| 54 | + unprocessedCodeBlocks.forEach((codeElement) => { |
| 55 | + const preElement = codeElement.parentElement; |
| 56 | + if (!preElement) return; |
| 57 | + |
| 58 | + const code = codeElement.textContent || ''; |
| 59 | + const trimmedCode = code.trim(); |
| 60 | + |
| 61 | + // Check if it's mermaid code - optimized checks |
| 62 | + const isMermaid = |
| 63 | + codeElement.className.includes('mermaid') || |
| 64 | + preElement.className.includes('mermaid') || |
| 65 | + mermaidPatterns.some((pattern) => |
| 66 | + trimmedCode.startsWith(pattern), |
| 67 | + ) || |
| 68 | + trimmedCode.includes('stateDiagram-v2'); |
| 69 | + |
| 70 | + if (isMermaid) { |
| 71 | + foundCount++; |
| 72 | + |
| 73 | + // Create a div with class mermaid |
| 74 | + const mermaidDiv = document.createElement('div'); |
| 75 | + mermaidDiv.className = 'mermaid'; |
| 76 | + mermaidDiv.textContent = trimmedCode; |
| 77 | + |
| 78 | + // Mark as processed before replacing |
| 79 | + preElement.setAttribute('data-mermaid-processed', 'true'); |
| 80 | + // Replace pre element |
| 81 | + preElement.replaceWith(mermaidDiv); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + return foundCount; |
| 86 | + } |
| 87 | + |
| 88 | + // Wait for DOM to be completely ready |
| 89 | + setTimeout(async () => { |
| 90 | + if (!isMounted.current || isRenderingRef.current) return; |
| 91 | + |
| 92 | + isRenderingRef.current = true; |
| 93 | + try { |
| 94 | + const newBlocks = renderMermaidDiagrams(); |
| 95 | + if (newBlocks > 0 && isMounted.current) { |
| 96 | + try { |
| 97 | + await mermaid.default.run(); |
| 98 | + } catch (error) { |
| 99 | + console.error('Failed to render mermaid diagrams:', error); |
| 100 | + } |
| 101 | + } |
| 102 | + } finally { |
| 103 | + isRenderingRef.current = false; |
| 104 | + initializedRef.current = true; |
| 105 | + } |
| 106 | + }, 500); |
| 107 | + } catch (err) { |
| 108 | + console.error('Failed to initialize mermaid:', err); |
| 109 | + } |
| 110 | + }; |
| 111 | + |
| 112 | + initializeMermaid(); |
| 113 | + }, []); // Initialize only once |
| 114 | + |
| 115 | + // Cleanup and MutationObserver setup |
| 116 | + useEffect(() => { |
| 117 | + // Set up MutationObserver for dynamic content |
| 118 | + observerRef.current = new MutationObserver((mutations) => { |
| 119 | + const hasNewMermaid = mutations.some((mutation) => |
| 120 | + Array.from(mutation.addedNodes).some( |
| 121 | + (node) => |
| 122 | + node.nodeType === Node.ELEMENT_NODE && |
| 123 | + ((node as Element).tagName === 'PRE' || |
| 124 | + (node as Element).querySelector?.('pre') || |
| 125 | + (node as Element).classList?.contains('mermaid')), |
| 126 | + ), |
| 127 | + ); |
| 128 | + |
| 129 | + if (hasNewMermaid && isMounted.current && !isRenderingRef.current) { |
| 130 | + // Debounce to prevent rapid successive calls |
| 131 | + setTimeout(async () => { |
| 132 | + if (!isMounted.current || isRenderingRef.current) return; |
| 133 | + |
| 134 | + isRenderingRef.current = true; |
| 135 | + try { |
| 136 | + const mermaid = await import('mermaid'); |
| 137 | + if (isMounted.current) { |
| 138 | + try { |
| 139 | + await mermaid.default.run(); |
| 140 | + } catch (error) { |
| 141 | + console.error( |
| 142 | + 'Failed to render mermaid diagrams from mutation:', |
| 143 | + error, |
| 144 | + ); |
| 145 | + } |
| 146 | + } |
| 147 | + } catch (error) { |
| 148 | + console.error('Failed to import mermaid:', error); |
| 149 | + } finally { |
| 150 | + isRenderingRef.current = false; |
| 151 | + } |
| 152 | + }, 100); // Small debounce delay |
| 153 | + } |
| 154 | + }); |
| 155 | + |
| 156 | + // Start observing the document body |
| 157 | + observerRef.current.observe(document.body, { |
| 158 | + childList: true, |
| 159 | + subtree: true, |
| 160 | + }); |
| 161 | + |
| 162 | + return () => { |
| 163 | + isMounted.current = false; |
| 164 | + isRenderingRef.current = false; |
| 165 | + initializedRef.current = false; |
| 166 | + |
| 167 | + if (observerRef.current) { |
| 168 | + observerRef.current.disconnect(); |
| 169 | + observerRef.current = null; |
| 170 | + } |
| 171 | + |
| 172 | + // Clean up existing Mermaid diagrams |
| 173 | + const mermaidElements = document.querySelectorAll('.mermaid'); |
| 174 | + mermaidElements.forEach((element) => { |
| 175 | + element.innerHTML = ''; |
| 176 | + }); |
| 177 | + }; |
| 178 | + }, []); |
| 179 | + |
| 180 | + return null; // No visual output, just side effects |
| 181 | +} |
0 commit comments