From c5b4dadb836178e2c0655da3b50965082d0e1c9c Mon Sep 17 00:00:00 2001 From: Enrico Ros Date: Mon, 30 Dec 2024 17:27:29 -0800 Subject: [PATCH] Mermaid: stick errors --- .../code/code-renderers/RenderCodeMermaid.tsx | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/modules/blocks/code/code-renderers/RenderCodeMermaid.tsx b/src/modules/blocks/code/code-renderers/RenderCodeMermaid.tsx index 0ae0e8264..c1a58d71b 100644 --- a/src/modules/blocks/code/code-renderers/RenderCodeMermaid.tsx +++ b/src/modules/blocks/code/code-renderers/RenderCodeMermaid.tsx @@ -20,7 +20,6 @@ import { patchSvgString } from './RenderCodeSVG'; * options are updated accordingly. */ const MERMAID_CDN_FILE: string = 'https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.min.js'; -const MERMAID_ERROR_PREFIX: string = '[Mermaid]'; interface MermaidAPI { initialize: (config: any) => void; @@ -117,6 +116,10 @@ function useMermaidLoader() { return { mermaidAPI, isSuccess: !!mermaidAPI, hasStartedLoading: loadingStarted, error: loadingError }; } +type MermaidResult = + | { success: true; svg: string } + | { success: false; error: string }; + export function RenderCodeMermaid(props: { mermaidCode: string, fitScreen: boolean }) { @@ -127,16 +130,16 @@ export function RenderCodeMermaid(props: { mermaidCode: string, fitScreen: boole const { mermaidAPI, error: mermaidLoadError } = useMermaidLoader(); // [effect] re-render on code changes - const { data } = useQuery({ + const { data } = useQuery({ enabled: !!mermaidAPI && !!props.mermaidCode, queryKey: ['mermaid', props.mermaidCode], - queryFn: async () => { + queryFn: async (): Promise => { try { const elementId = `mermaid-${Math.random().toString(36).substring(2, 9)}`; const { svg } = await mermaidAPI!.render(elementId, props.mermaidCode, mermaidContainerRef.current!); - return svg ? svg : MERMAID_ERROR_PREFIX + ' no SVG.'; + return svg ? { success: true, svg } : { success: false, error: 'No SVG returned.' }; } catch (error: any) { - return MERMAID_ERROR_PREFIX + ' ' + (error?.message || 'invalid.'); + return { success: false, error: error?.message ?? error?.toString() ?? 'unknown error' }; } }, staleTime: 1000 * 60 * 60 * 24, // 1 day @@ -144,11 +147,10 @@ export function RenderCodeMermaid(props: { mermaidCode: string, fitScreen: boole // derived const hasMermaidLoadError = !!mermaidLoadError; - const hasSvgError = data?.startsWith(MERMAID_ERROR_PREFIX); return ( - {hasSvgError && ( + {data?.success === false && ( Unable to display diagram. Issue with the generated Mermaid code. @@ -156,8 +158,13 @@ export function RenderCodeMermaid(props: { mermaidCode: string, fitScreen: boole );