All files / src/components MermaidDiagram.tsx

96.55% Statements 28/29
68.75% Branches 11/16
100% Functions 5/5
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 1172x                                         1x 1x 1x 1x 1x               10x 10x 10x 10x   10x 6x   6x 6x 6x 6x                                                         6x 6x 4x 1x     3x     6x 6x 6x       10x 3x                       7x                              
"use client";
 
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useT } from "@/lib/i18n/translate";
 
interface MermaidDiagramProps {
  chart: string;
  /** Text, or a translated sentence with links to its sources. */
  caption?: ReactNode;
  /** Changes the rendered SVG before it is shown, e.g. to make parts of it
   *  links. Mermaid stays at its default strict security level, so its own
   *  `click` lines do nothing; a caller adds interaction here instead. It runs
   *  on the SVG before it is stored, so a re-render keeps the change. */
  transform?: (svg: SVGSVGElement) => void;
}
 
/** The SVG markup after `transform` has changed its parsed form. */
function transformed(
  markup: string,
  transform: (svg: SVGSVGElement) => void,
): string {
  const doc = new DOMParser().parseFromString(markup, "image/svg+xml");
  const root = doc.documentElement;
  Iif (!(root instanceof SVGSVGElement)) return markup;
  transform(root);
  return new XMLSerializer().serializeToString(root);
}
 
export default function MermaidDiagram({
  chart,
  caption,
  transform,
}: MermaidDiagramProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const t = useT("common");
  const [svg, setSvg] = useState<string>("");
  const [error, setError] = useState<string>("");
 
  useEffect(() => {
    let cancelled = false;
    async function render() {
      try {
        const mermaid = (await import("mermaid")).default;
        const isDark = document.documentElement.classList.contains("dark");
        mermaid.initialize({
          startOnLoad: false,
          theme: isDark ? "dark" : "default",
          themeVariables: isDark
            ? {
                darkMode: true,
                background: "#1a1a2e",
                primaryColor: "#6366f1",
                primaryTextColor: "#e2e8f0",
                primaryBorderColor: "#818cf8",
                lineColor: "#e2e8f0",
                secondaryColor: "#1e293b",
                tertiaryColor: "#0f172a",
                edgeLabelBackground: "#1e293b",
                fontFamily: "ui-sans-serif, system-ui, sans-serif",
              }
            : {
                darkMode: false,
                background: "#ffffff",
                primaryColor: "#4f46e5",
                primaryTextColor: "#1e293b",
                primaryBorderColor: "#6366f1",
                lineColor: "#334155",
                secondaryColor: "#f1f5f9",
                tertiaryColor: "#e2e8f0",
                edgeLabelBackground: "#f8fafc",
                fontFamily: "ui-sans-serif, system-ui, sans-serif",
              },
        });
        const id = `mermaid-${Math.random().toString(36).slice(2, 9)}`;
        const { svg: rendered } = await mermaid.render(id, chart.trim());
        if (!cancelled) {
          setSvg(transform ? transformed(rendered, transform) : rendered);
        }
      } catch (err: unknown) {
        Eif (!cancelled) setError(String(err));
      }
    }
    render();
    return () => {
      cancelled = true;
    };
  }, [chart, transform]);
 
  if (error) {
    return (
      <div className="border border-red-700 rounded-lg p-4 my-4">
        <p className="text-red-400 text-sm">
          {t("Diagram render error: {error}", { error })}
        </p>
        <pre className="text-xs text-(--text-secondary) mt-2 overflow-x-auto">
          {chart}
        </pre>
      </div>
    );
  }
 
  return (
    <figure className="my-6">
      <div
        ref={containerRef}
        className="bg-(--surface)/50 border border-(--border) rounded-lg p-4 overflow-x-auto flex justify-center"
        dangerouslySetInnerHTML={{ __html: svg }}
      />
      {caption && (
        <figcaption className="text-center text-sm text-(--text-secondary) mt-2 italic">
          {caption}
        </figcaption>
      )}
    </figure>
  );
}