mermaid.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use client';
  2. import { useEffect, useId, useState } from 'react';
  3. import { useTheme } from 'next-themes';
  4. // Client-side, theme-aware Mermaid renderer. Mermaid is imported dynamically so
  5. // it stays out of the initial bundle and only loads on pages that use a diagram.
  6. export function Mermaid({ chart }: { chart: string }) {
  7. const rawId = useId();
  8. const id = `mmd-${rawId.replace(/[^a-zA-Z0-9]/g, '')}`;
  9. const { resolvedTheme } = useTheme();
  10. const [svg, setSvg] = useState('');
  11. useEffect(() => {
  12. let active = true;
  13. void (async () => {
  14. const mermaid = (await import('mermaid')).default;
  15. mermaid.initialize({
  16. startOnLoad: false,
  17. securityLevel: 'strict',
  18. theme: resolvedTheme === 'dark' ? 'dark' : 'default',
  19. fontFamily: 'inherit',
  20. });
  21. try {
  22. const { svg } = await mermaid.render(id, chart.trim());
  23. if (active) setSvg(svg);
  24. } catch {
  25. if (active) setSvg('');
  26. }
  27. })();
  28. return () => {
  29. active = false;
  30. };
  31. }, [chart, resolvedTheme, id]);
  32. return (
  33. <div
  34. className="my-6 flex justify-center overflow-x-auto rounded-xl border bg-fd-card p-4 [&_svg]:max-w-full"
  35. role="img"
  36. aria-label="Architecture diagram"
  37. dangerouslySetInnerHTML={{ __html: svg }}
  38. />
  39. );
  40. }