45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
|
|
import "./mermaid.css";
|
|
|
|
/**
|
|
* 静态流程图组件(基于 Mermaid):传入 Mermaid 文本(flowchart TD / sequenceDiagram 等)
|
|
* 渲染为 SVG,适合报告、方案图等快速生成的场景;需要拖拽交互的流程图请用 FlowCanvas。
|
|
*/
|
|
export default function MermaidBlock({ source }: { source: string }) {
|
|
const containerRef = useRef<HTMLDivElement | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
const render = async () => {
|
|
try {
|
|
const mermaid = (await import("mermaid")).default;
|
|
mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "neutral" });
|
|
const { svg } = await mermaid.render(`mermaid-${Math.random().toString(36).slice(2)}`, source);
|
|
if (!cancelled && containerRef.current) {
|
|
containerRef.current.innerHTML = svg;
|
|
setError(null);
|
|
}
|
|
} catch (err) {
|
|
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
|
}
|
|
};
|
|
void render();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [source]);
|
|
|
|
if (error) {
|
|
return (
|
|
<div className="mermaid-error">
|
|
<p>Mermaid 图渲染失败</p>
|
|
<pre>{source}</pre>
|
|
<p className="muted">{error}</p>
|
|
</div>
|
|
);
|
|
}
|
|
return <div ref={containerRef} className="mermaid-block" />;
|
|
}
|