import { useEffect, useRef, useState } from 'react'; /** Mermaid.js diagram, rendered in the browser; the source is shown until it is ready (and if it fails). */ export default function Mermaid({ code, caption }: { code: string; caption?: string }) { const [svg, setSvg] = useState(''); const [err, setErr] = useState(''); const id = useRef('mmd' + Math.random().toString(36).slice(2)); useEffect(() => { let off = false; (async () => { try { const mermaid = (await import('mermaid')).default; const dark = window.matchMedia('(prefers-color-scheme: dark)').matches; mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: dark ? 'dark' : 'default', flowchart: { htmlLabels: true, curve: 'basis' } }); const out = await mermaid.render(id.current, code); if (!off) setSvg(out.svg); } catch (e) { if (!off) setErr(String((e as Error).message ?? e)); } })(); return () => { off = true; }; }, [code]); return (
{svg ?
:
{code}
} {err &&

Diagram could not be drawn: {err}

} {caption &&
{caption}
}
); }