Skip to content

fix(mermaid): use XMLSerializer to produce valid SVG/XML on download#517

Open
sleitor wants to merge 1 commit into
vercel:mainfrom
sleitor:fix-516
Open

fix(mermaid): use XMLSerializer to produce valid SVG/XML on download#517
sleitor wants to merge 1 commit into
vercel:mainfrom
sleitor:fix-516

Conversation

@sleitor
Copy link
Copy Markdown
Contributor

@sleitor sleitor commented Apr 30, 2026

Problem

Mermaid renders diagrams via innerHTML, which allows the browser to normalize elements like <br /> to their HTML void form (<br>). Saving that raw string as an SVG file fails because SVG/XML parsers reject the non-self-closing element, and PNG conversion via canvas also fails since the <img> cannot load invalid XML SVG.

Reported in #516.

Fix

Add sanitizeSvgForExport() in lib/mermaid/utils.ts that:

  1. Parses the raw SVG string into the DOM via a temporary <div>.innerHTML
  2. Re-serializes the <svg> element with XMLSerializer.serializeToString(), producing a well-formed XML document
  3. Falls back to the original string if running outside a browser or if parsing fails

Both the SVG download path and the PNG conversion path in download-button.tsx now sanitize the SVG string before use.

Tests

  • Updated existing SVG/PNG download tests to accept XMLSerializer output (which adds the XML namespace attribute)
  • Added new tests for the <br> element case in both mermaid-download.test.tsx and mermaid-utils.test.ts
  • All 988 tests pass

Fixes #516

Mermaid renders diagrams via innerHTML which causes the browser to
normalize elements like <br /> to their HTML void form (<br>), making
the raw SVG string invalid XML.  Saving that string as .svg or
converting it to PNG via an <img>/canvas both fail on that input.

Add sanitizeSvgForExport() which re-parses the SVG through a temporary
DOM node and re-serializes with XMLSerializer.serializeToString(),
producing a well-formed XML document.  Both the SVG download path and
the PNG conversion path now sanitize before use.

Fixes vercel#516
@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Apr 30, 2026

@sleitor is attempting to deploy a commit to the Vercel Team on Vercel.

A member of the Team first needs to authorize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mermaid download produces invalid SVG / fails for PNG when chart contains <br />

1 participant