UNPKG

@theguild/remark-mermaid

Version:

Remark plugin for replacing ```mermaid code blocks with react `<Mermaid />` component

45 lines (44 loc) 1.51 kB
"use client"; import { jsx } from "react/jsx-runtime"; import { useEffect, useId, useRef, useState } from "react"; function Mermaid({ chart }) { const id = useId(); const [svg, setSvg] = useState(""); const containerRef = useRef(null); useEffect(() => { const htmlElement = document.documentElement; const mutationObserver = new MutationObserver(renderChart); mutationObserver.observe(htmlElement, { attributes: true }); renderChart(); return () => { mutationObserver.disconnect(); }; async function renderChart() { const isDarkTheme = htmlElement.classList.contains("dark") || htmlElement.attributes.getNamedItem("data-theme")?.value === "dark"; const mermaidConfig = { startOnLoad: false, securityLevel: "loose", fontFamily: "inherit", themeCSS: "margin: 1.5rem auto 0;", theme: isDarkTheme ? "dark" : "default" }; const { default: mermaid } = await import("mermaid"); try { mermaid.initialize(mermaidConfig); const { svg: svg2 } = await mermaid.render( // strip invalid characters for `id` attribute id.replaceAll(":", ""), chart, containerRef.current || void 0 ); setSvg(svg2); } catch (error) { console.error("Error while rendering mermaid", error); } } }, [chart]); return /* @__PURE__ */ jsx("div", { ref: containerRef, dangerouslySetInnerHTML: { __html: svg } }); } export { Mermaid };