import { NodeViewProps } from "@tiptap/react"; import { useEffect, useState } from "react"; import mermaid from "mermaid"; import { v4 as uuidv4 } from "uuid"; import classes from "./code-block.module.css"; import { useTranslation } from "react-i18next"; import { useComputedColorScheme } from "@mantine/core"; interface MermaidViewProps { props: NodeViewProps; } export default function MermaidView({ props }: MermaidViewProps) { const { t } = useTranslation(); const computedColorScheme = useComputedColorScheme(); const { node } = props; const [preview, setPreview] = useState(""); // Update Mermaid config when theme changes. useEffect(() => { mermaid.initialize({ startOnLoad: false, suppressErrorRendering: true, theme: computedColorScheme === "light" ? "default" : "dark", }); }, [computedColorScheme]); // Re-render the diagram whenever the node content or theme changes. useEffect(() => { const id = `mermaid-${uuidv4()}`; if (node.textContent.length > 0) { mermaid .render(id, node.textContent) .then((item) => { setPreview(item.svg); }) .catch((err) => { if (props.editor.isEditable) { setPreview( `
${t("Mermaid diagram error:")} ${err}
`, ); } else { setPreview( `
${t("Invalid Mermaid diagram")}
`, ); } }); } }, [node.textContent, computedColorScheme]); return (
); }