Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mermaid-stable-svg-html.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"streamdown": patch
---

perf: stop re-parsing a Mermaid diagram's SVG every time it re-renders with the same chart
15 changes: 15 additions & 0 deletions packages/streamdown/__tests__/mermaid-component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,21 @@ describe("Mermaid Component", () => {
});
});

it("should keep the rendered SVG node when re-rendering the same chart", async () => {
const { container, rerender } = renderWithContext(
<Mermaid chart={simpleChart} />
);

await waitFor(() => {
expect(container.querySelector('[role="img"] svg')).toBeTruthy();
});
const svg = container.querySelector('[role="img"] svg');

rerender(<Mermaid chart={simpleChart} />);

expect(container.querySelector('[role="img"] svg')).toBe(svg);
});

it("should generate unique IDs for multiple charts", async () => {
const mockRender = vi.fn().mockResolvedValue({
svg: "<svg><text>Chart</text></svg>",
Expand Down
12 changes: 7 additions & 5 deletions packages/streamdown/lib/mermaid/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useEffect, useRef, useState } from "react";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useDeferredRender } from "../../hooks/use-deferred-render";
import { StreamdownContext } from "../../index";
import { useIsCodeFenceIncomplete } from "../block-incomplete-context";
Expand Down Expand Up @@ -210,6 +210,11 @@ export const Mermaid = ({
renderLatest();
}, [chart, config, retryCount, shouldRender, mermaidPlugin]);

// Always render the SVG if we have content (either current or last valid)
const displaySvg = svgContent || lastValidSvg;
// react-dom 19.2 rewrites innerHTML whenever this object's identity changes
const svgHtml = useMemo(() => ({ __html: displaySvg }), [displaySvg]);

// Show placeholder when not scheduled to render
if (!(shouldRender || svgContent || lastValidSvg)) {
return (
Expand Down Expand Up @@ -275,9 +280,6 @@ export const Mermaid = ({
);
}

// Always render the SVG if we have content (either current or last valid)
const displaySvg = svgContent || lastValidSvg;

return (
<div
className={cn(
Expand Down Expand Up @@ -310,7 +312,7 @@ export const Mermaid = ({
fullscreen ? "size-full items-center" : null
)}
// biome-ignore lint/security/noDangerouslySetInnerHtml: "Required for Mermaid"
dangerouslySetInnerHTML={{ __html: displaySvg }}
dangerouslySetInnerHTML={svgHtml}
role="img"
/>
</PanZoom>
Expand Down
Loading