|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useRef, useState } from 'react'; |
| 4 | + |
| 5 | +type MermaidModule = typeof import('@mermanjs/web'); |
| 6 | + |
| 7 | +type UseMermaidOptions = { |
| 8 | + /** The Mermaid diagram source. */ |
| 9 | + source: string; |
| 10 | + /** The host appearance used for the rendered diagram. */ |
| 11 | + theme?: 'light' | 'dark'; |
| 12 | + /** Injectable module loader, so unit tests can stub the WASM renderer. */ |
| 13 | + loader?: () => Promise<MermaidModule>; |
| 14 | +}; |
| 15 | + |
| 16 | +const defaultLoader: () => Promise<MermaidModule> = () => |
| 17 | + import('@mermanjs/web'); |
| 18 | + |
| 19 | +/** |
| 20 | + * Renders a Mermaid diagram through the Merman WASM renderer into the |
| 21 | + * returned container ref. Rendering happens lazily on the client, so the |
| 22 | + * WASM module is only loaded when a diagram is actually on the page. |
| 23 | + */ |
| 24 | +export const useMermaid = ({ |
| 25 | + source, |
| 26 | + theme = 'light', |
| 27 | + loader = defaultLoader, |
| 28 | +}: UseMermaidOptions) => { |
| 29 | + const containerRef = useRef<HTMLDivElement>(null); |
| 30 | + const [error, setError] = useState<Error | null>(null); |
| 31 | + |
| 32 | + useEffect(() => { |
| 33 | + let cancelled = false; |
| 34 | + |
| 35 | + const renderDiagram = async () => { |
| 36 | + try { |
| 37 | + const merman = await loader(); |
| 38 | + await merman.initMerman(); |
| 39 | + |
| 40 | + if (!cancelled && containerRef.current) { |
| 41 | + merman.renderSvgToElement(containerRef.current, source.trim(), { |
| 42 | + host_theme: { appearance: theme }, |
| 43 | + }); |
| 44 | + setError(null); |
| 45 | + } |
| 46 | + } catch (renderError) { |
| 47 | + if (!cancelled) { |
| 48 | + setError(renderError as Error); |
| 49 | + } |
| 50 | + } |
| 51 | + }; |
| 52 | + |
| 53 | + renderDiagram(); |
| 54 | + |
| 55 | + return () => { |
| 56 | + cancelled = true; |
| 57 | + }; |
| 58 | + }, [source, theme, loader]); |
| 59 | + |
| 60 | + return { containerRef, error }; |
| 61 | +}; |
| 62 | + |
| 63 | +export default useMermaid; |
0 commit comments