|
| 1 | +import { useEffect, useId, useRef, useState } from "react"; |
| 2 | +import mermaid, { type MermaidConfig } from "mermaid"; |
| 3 | + |
| 4 | +interface MermaidProps { |
| 5 | + code: string; |
| 6 | + config?: MermaidConfig; |
| 7 | +} |
| 8 | + |
| 9 | +let mermaidInitialized = false; |
| 10 | +let mermaidInitPromise: Promise<void> | null = null; |
| 11 | + |
| 12 | +const ensureMermaidInitialized = () => { |
| 13 | + if (mermaidInitialized) return mermaidInitPromise as Promise<void>; |
| 14 | + |
| 15 | + mermaidInitialized = true; |
| 16 | + mermaidInitPromise = Promise.resolve().then(() => |
| 17 | + mermaid.initialize({ startOnLoad: false, securityLevel: "loose" }) |
| 18 | + ); |
| 19 | + |
| 20 | + return mermaidInitPromise; |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * Renders a Mermaid diagram from fenced code blocks. |
| 25 | + * |
| 26 | + * @example |
| 27 | + * <Mermaid code="graph TD; A-->B;" /> |
| 28 | + */ |
| 29 | +export default function Mermaid({ code, config }: MermaidProps) { |
| 30 | + const [svg, setSvg] = useState(""); |
| 31 | + const [hasError, setHasError] = useState(false); |
| 32 | + const id = useId().replace(/:/g, ""); |
| 33 | + const renderRequestRef = useRef(0); |
| 34 | + |
| 35 | + useEffect(() => { |
| 36 | + ensureMermaidInitialized(); |
| 37 | + }, []); |
| 38 | + |
| 39 | + useEffect(() => { |
| 40 | + const theme = document.documentElement.classList.contains("dark") |
| 41 | + ? "dark" |
| 42 | + : "default"; |
| 43 | + |
| 44 | + const mergedConfig: MermaidConfig = { |
| 45 | + startOnLoad: false, |
| 46 | + securityLevel: "loose", |
| 47 | + theme, |
| 48 | + ...config, |
| 49 | + }; |
| 50 | + |
| 51 | + const definition = `%%{init: ${JSON.stringify(mergedConfig)}}%%\n${code}`; |
| 52 | + let isCancelled = false; |
| 53 | + const renderId = renderRequestRef.current + 1; |
| 54 | + renderRequestRef.current = renderId; |
| 55 | + |
| 56 | + ensureMermaidInitialized() |
| 57 | + ?.then(() => mermaid.render(id, definition)) |
| 58 | + .then(({ svg }) => { |
| 59 | + if (isCancelled || renderId !== renderRequestRef.current) return; |
| 60 | + |
| 61 | + setSvg(svg); |
| 62 | + setHasError(false); |
| 63 | + }) |
| 64 | + .catch(() => { |
| 65 | + if (isCancelled || renderId !== renderRequestRef.current) return; |
| 66 | + |
| 67 | + setHasError(true); |
| 68 | + }); |
| 69 | + |
| 70 | + return () => { |
| 71 | + isCancelled = true; |
| 72 | + }; |
| 73 | + }, [code, config, id]); |
| 74 | + |
| 75 | + if (hasError) { |
| 76 | + return null; |
| 77 | + } |
| 78 | + |
| 79 | + return <div dangerouslySetInnerHTML={{ __html: svg }} />; |
| 80 | +} |
0 commit comments