From 5ad582ec3eeb957e6acf857298826f9f9fa85dd3 Mon Sep 17 00:00:00 2001 From: Amit Haridas Date: Fri, 5 Jun 2026 13:03:32 +0530 Subject: [PATCH] feat(renderer): MarkdownRenderer with mermaid code re-extraction from source --- .../components/preview/MarkdownRenderer.tsx | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/renderer/components/preview/MarkdownRenderer.tsx diff --git a/src/renderer/components/preview/MarkdownRenderer.tsx b/src/renderer/components/preview/MarkdownRenderer.tsx new file mode 100644 index 0000000..b149e68 --- /dev/null +++ b/src/renderer/components/preview/MarkdownRenderer.tsx @@ -0,0 +1,44 @@ +import { useEffect, useRef, useState } from 'react'; +import { renderMarkdown } from '@/lib/markdown'; +import { MermaidLazy } from './MermaidLazy'; + +interface Props { + source: string; +} + +const MERMAID_RE = /```mermaid\n([\s\S]*?)```/g; + +function extractMermaidCodes(source: string): string[] { + const codes: string[] = []; + let match: RegExpExecArray | null; + while ((match = MERMAID_RE.exec(source)) !== null) { + codes.push(match[1].trim()); + } + return codes; +} + +export function MarkdownRenderer({ source }: Props) { + const html = renderMarkdown(source); + const containerRef = useRef(null); + const [mermaidCodes, setMermaidCodes] = useState([]); + + // Re-derive mermaid codes from the original source. The renderMarkdown function + // replaces mermaid blocks with placeholders (data-mermaid-source="${idx}"), but + // it does not return the actual codes. Rather than thread them through the API, + // we re-extract from the source. Source is small (single buffer content) so this + // cost is negligible. + useEffect(() => { + setMermaidCodes(extractMermaidCodes(source)); + }, [source]); + + return ( +
+
+ {mermaidCodes.map((code, i) => ( +
+ +
+ ))} +
+ ); +}