|
1 | 1 | "use client"; |
2 | 2 |
|
3 | | -import { useEffect, useState } from "react"; |
| 3 | +import { useEffect, useId, useState } from "react"; |
4 | 4 | import type { Components } from "react-markdown"; |
5 | 5 | import type { BundledLanguage } from "shiki"; |
6 | 6 |
|
| 7 | +function MermaidBlock({ children }: { children: string }) { |
| 8 | + const id = useId().replace(/:/g, "m"); |
| 9 | + const [svg, setSvg] = useState<string | null>(null); |
| 10 | + const [error, setError] = useState<string | null>(null); |
| 11 | + |
| 12 | + useEffect(() => { |
| 13 | + let cancelled = false; |
| 14 | + |
| 15 | + import("mermaid").then(({ default: mermaid }) => { |
| 16 | + if (cancelled) return; |
| 17 | + mermaid.initialize({ |
| 18 | + startOnLoad: false, |
| 19 | + theme: "neutral", |
| 20 | + securityLevel: "loose", |
| 21 | + }); |
| 22 | + mermaid |
| 23 | + .render(`mermaid-${id}`, children.replace(/\n$/, "")) |
| 24 | + .then(({ svg: renderedSvg }: { svg: string }) => { |
| 25 | + if (!cancelled) setSvg(renderedSvg); |
| 26 | + }) |
| 27 | + .catch((err: unknown) => { |
| 28 | + if (!cancelled) setError(String(err)); |
| 29 | + }); |
| 30 | + }); |
| 31 | + |
| 32 | + return () => { |
| 33 | + cancelled = true; |
| 34 | + }; |
| 35 | + }, [children, id]); |
| 36 | + |
| 37 | + if (error) { |
| 38 | + return ( |
| 39 | + <pre className="mb-5 rounded-lg border border-red-300 bg-red-50 text-red-700 p-4 text-sm"> |
| 40 | + <code>{error}</code> |
| 41 | + </pre> |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + if (svg) { |
| 46 | + return ( |
| 47 | + <div |
| 48 | + className="mb-5 flex justify-center rounded-lg border border-zinc-200 bg-white p-4 [&_svg]:max-w-full" |
| 49 | + dangerouslySetInnerHTML={{ __html: svg }} |
| 50 | + /> |
| 51 | + ); |
| 52 | + } |
| 53 | + |
| 54 | + return ( |
| 55 | + <div className="mb-5 flex justify-center rounded-lg border border-zinc-200 bg-zinc-50 p-8 text-zinc-400 text-sm"> |
| 56 | + Rendering diagram… |
| 57 | + </div> |
| 58 | + ); |
| 59 | +} |
| 60 | + |
7 | 61 | function CodeBlock({ |
8 | 62 | language, |
9 | 63 | children, |
@@ -77,6 +131,9 @@ export const markdownComponents: Components = { |
77 | 131 | code: ({ children, className }) => { |
78 | 132 | const match = className?.match(/language-(\w+)/); |
79 | 133 | if (match) { |
| 134 | + if (match[1] === "mermaid") { |
| 135 | + return <MermaidBlock>{String(children)}</MermaidBlock>; |
| 136 | + } |
80 | 137 | return <CodeBlock language={match[1]} children={String(children)} />; |
81 | 138 | } |
82 | 139 | // Block code without a language (inside <pre>) |
|
0 commit comments