aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/packages/docs/app/components/mermaid.tsx
blob: fe153eceba38a81f7cb4383b1caa64cea4da9164 (plain) (blame)
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
"use client";

import mermaid from "mermaid";
import { useEffect, useRef } from "react";

mermaid.initialize({
  startOnLoad: false,
  theme: "default",
  securityLevel: "strict",
});

export function Mermaid({ chart }: { chart: string }) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let current = true;
    const id = `mermaid-${Math.random().toString(36).slice(2, 9)}`;
    mermaid
      .render(id, chart)
      .then(({ svg }) => {
        if (!current) return;
        const parser = new DOMParser();
        const doc = parser.parseFromString(svg, "image/svg+xml");
        const svgEl = doc.querySelector("svg");
        if (ref.current && svgEl) {
          ref.current.replaceChildren(svgEl);
        }
      })
      .catch(() => {
        if (current) ref.current?.replaceChildren();
      });
    return () => {
      current = false;
    };
  }, [chart]);

  return (
    <div className="not-prose my-6">
      <div ref={ref} className="mermaid" />
    </div>
  );
}