|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useTheme } from 'next-themes'; |
| 4 | +import { use, useEffect, useId, useState } from 'react'; |
| 5 | + |
| 6 | +export function Mermaid({ chart }: { chart: string }) { |
| 7 | + const [mounted, setMounted] = useState(false); |
| 8 | + |
| 9 | + useEffect(() => { |
| 10 | + setMounted(true); |
| 11 | + }, []); |
| 12 | + |
| 13 | + if (!mounted) return; |
| 14 | + return <MermaidContent chart={chart} />; |
| 15 | +} |
| 16 | + |
| 17 | +const cache = new Map<string, Promise<unknown>>(); |
| 18 | + |
| 19 | +function cachePromise<T>( |
| 20 | + key: string, |
| 21 | + setPromise: () => Promise<T> |
| 22 | +): Promise<T> { |
| 23 | + const cached = cache.get(key); |
| 24 | + if (cached) return cached as Promise<T>; |
| 25 | + |
| 26 | + const promise = setPromise(); |
| 27 | + cache.set(key, promise); |
| 28 | + return promise; |
| 29 | +} |
| 30 | + |
| 31 | +function MermaidContent({ chart }: { chart: string }) { |
| 32 | + const id = useId(); |
| 33 | + const { resolvedTheme } = useTheme(); |
| 34 | + const { default: mermaid } = use( |
| 35 | + cachePromise('mermaid', () => import('mermaid')) |
| 36 | + ); |
| 37 | + |
| 38 | + mermaid.initialize({ |
| 39 | + startOnLoad: false, |
| 40 | + securityLevel: 'loose', |
| 41 | + fontFamily: 'inherit', |
| 42 | + themeCSS: 'margin: 1.5rem auto 0;', |
| 43 | + theme: resolvedTheme === 'dark' ? 'dark' : 'default', |
| 44 | + }); |
| 45 | + |
| 46 | + const { svg, bindFunctions } = use( |
| 47 | + cachePromise(`${chart}-${resolvedTheme}`, () => { |
| 48 | + return mermaid.render(id, chart.replaceAll('\\n', '\n')); |
| 49 | + }) |
| 50 | + ); |
| 51 | + |
| 52 | + return ( |
| 53 | + <div |
| 54 | + ref={(container) => { |
| 55 | + if (container) bindFunctions?.(container); |
| 56 | + }} |
| 57 | + // biome-ignore lint/security/noDangerouslySetInnerHtml: Matching fumadocs + is only running trusted input from mdx files |
| 58 | + dangerouslySetInnerHTML={{ __html: svg }} |
| 59 | + /> |
| 60 | + ); |
| 61 | +} |
0 commit comments