"use client"; import React, { useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; interface MermaidProps { chart: string; className?: string; } let mermaidLoader: Promise<(typeof import("mermaid"))["default"]> | null = null; async function loadMermaid() { if (!mermaidLoader) { mermaidLoader = import("mermaid").then((module) => { const mermaid = module.default; mermaid.initialize({ startOnLoad: false, theme: "neutral", securityLevel: "strict", fontFamily: "ui-sans-serif, system-ui, sans-serif", flowchart: { useMaxWidth: true, htmlLabels: false, curve: "basis", }, themeVariables: { primaryColor: "#6366f1", primaryTextColor: "#1e293b", primaryBorderColor: "#c7d2fe", lineColor: "#94a3b8", secondaryColor: "#f1f5f9", tertiaryColor: "#f8fafc", }, }); return mermaid; }); } return mermaidLoader; } function cleanupMermaidOrphans(id: string) { try { document.getElementById(id)?.remove(); document.getElementById(`d${id}`)?.remove(); } catch { /* ignore */ } } let mermaidIdCounter = 0; const DEBOUNCE_MS = 600; export const Mermaid: React.FC = ({ chart, className = "" }) => { const { t } = useTranslation(); const containerRef = useRef(null); const [svg, setSvg] = useState(""); const [error, setError] = useState(null); const [stable, setStable] = useState(false); const [id] = useState(() => `mermaid-${++mermaidIdCounter}`); const lastChartRef = useRef(chart); useEffect(() => { lastChartRef.current = chart; setStable(false); const timer = window.setTimeout(() => { if (lastChartRef.current === chart) setStable(true); }, DEBOUNCE_MS); return () => window.clearTimeout(timer); }, [chart]); useEffect(() => { if (!stable) return; let cancelled = false; const renderChart = async () => { if (!chart.trim() || !containerRef.current) return; try { const mermaid = await loadMermaid(); cleanupMermaidOrphans(id); const { svg: renderedSvg } = await mermaid.render(id, chart.trim()); if (!cancelled) { setSvg(renderedSvg); setError(null); } } catch (err) { cleanupMermaidOrphans(id); if (!cancelled) { setError( err instanceof Error ? err.message : t("Failed to render diagram"), ); } } }; void renderChart(); return () => { cancelled = true; }; }, [stable, chart, id, t]); if (error) { return (

{t("Diagram rendering error")}

{error}
{t("Show source")}
            {chart}
          
); } if (!stable && !svg) { return (
{t("Rendering diagram...")}
); } return (
); }; export default Mermaid;