be57821457
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
31 lines
1.3 KiB
TypeScript
31 lines
1.3 KiB
TypeScript
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 (
|
|
<figure className="mermaid-fig">
|
|
{svg ? <div className="mermaid-svg" dangerouslySetInnerHTML={{ __html: svg }} /> : <pre className="mermaid-src">{code}</pre>}
|
|
{err && <p className="sub" style={{ fontSize: 12 }}>Diagram could not be drawn: {err}</p>}
|
|
{caption && <figcaption>{caption}</figcaption>}
|
|
</figure>
|
|
);
|
|
}
|