Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(web): normalize Mermaid HTML labels for diagram viewer (#704)

tianma-ifb84968067de7
diff --git a/apps/web/src/lib/mermaid-svg.ts b/apps/web/src/lib/mermaid-svg.ts
index 8be156ef..73c2da9b 100644
--- a/apps/web/src/lib/mermaid-svg.ts
+++ b/apps/web/src/lib/mermaid-svg.ts
@@ -127,12 +127,21 @@ export const normalizeMermaidSvgForViewer = (
) => {
if (typeof DOMParser === "undefined" || typeof XMLSerializer === "undefined") return svg;
- const document = new DOMParser().parseFromString(svg, "image/svg+xml");
- const root = document.documentElement;
- if (root.tagName.toLowerCase() !== "svg" || document.querySelector("parsererror")) return svg;
+ const parser = new DOMParser();
+ const document = parser.parseFromString(svg, "image/svg+xml");
+ let root: Element | null = document.documentElement;
+ if (document.querySelector("parsererror")) {
+ // Official Mermaid labels can contain HTML void tags such as <br>. Inline
+ // SVG accepts them, but a standalone SVG image requires well-formed XML.
+ // Parse in an inert HTML document, then serialize the SVG with XHTML
+ // namespaces and closed void tags before handing it to the image viewer.
+ root = parser.parseFromString(svg, "text/html").body.firstElementChild;
+ if (root?.namespaceURI !== "http://www.w3.org/2000/svg") return svg;
+ }
+ if (root?.tagName.toLowerCase() !== "svg") return svg;
// Mermaid emits width="100%", which gives Blob-backed images incorrect intrinsic dimensions.
root.setAttribute("width", String(presentation.width));
root.setAttribute("height", String(presentation.height));
- return new XMLSerializer().serializeToString(document);
+ return new XMLSerializer().serializeToString(root);
};
diff --git a/tests/e2e/fixtures/mermaid-viewer.html b/tests/e2e/fixtures/mermaid-viewer.html
new file mode 100644
index 00000000..a7ea2769
--- /dev/null
+++ b/tests/e2e/fixtures/mermaid-viewer.html
@@ -0,0 +1,18 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Mermaid viewer regression #704</title>
+<style>body { font: 14px system-ui; } section { margin: 24px 0; } img { max-width: 100%; }</style>
+<h1>Mermaid viewer regression #704</h1>
+<pre id="result" data-state="running">Running</pre>
+<button id="open-viewer" disabled>Open reported diagram</button>
+<div id="viewer"></div>
+<div id="cases"></div>
+<script type="module">
+ // /@fs fixtures bypass Vite's HTML transform, so initialize React refresh.
+ import RefreshRuntime from "/@react-refresh";
+ RefreshRuntime.injectIntoGlobalHook(window);
+ window.$RefreshReg$ = () => {};
+ window.$RefreshSig$ = () => (type) => type;
+ window.__vite_plugin_react_preamble_installed__ = true;
+</script>
+<script type="module" src="./mermaid-viewer.js"></script>
diff --git a/tests/e2e/fixtures/mermaid-viewer.js b/tests/e2e/fixtures/mermaid-viewer.js
new file mode 100644
index 00000000..9cfafd7b
--- /dev/null
+++ b/tests/e2e/fixtures/mermaid-viewer.js
@@ -0,0 +1,102 @@
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { MermaidViewer } from "/src/components/MermaidViewer.tsx";
+import { renderThemedMermaidSvg } from "/src/lib/mermaid-renderer.ts";
+import { normalizeMermaidSvgForViewer } from "/src/lib/mermaid-svg.ts";
+import { MERMAID_THEME_PALETTES } from "/src/components/ThemeProvider.tsx";
+
+const reportedSource = `---
+config:
+ layout: dagre
+---
+flowchart LR
+ subgraph Ansible_Work[Ansible 工作模式]
+ direction LR
+ ADHOC[命令行模式 Ad-Hoc<br>临时、单次操作]
+ PLAYBOOK[剧本模式 Playbook<br>复杂、批量自动化]
+ end
+ subgraph Module_Test[基础模块测试]
+ M1[命令与软件管理]
+ M2[文件与服务操作]
+ M3[系统配置与安全]
+ end
+ subgraph WP_Deploy[WordPress 剧本部署实战]
+ S1[环境准备与初始化]
+ S2[底层服务 NFS / LNMP / DB]
+ S3[前端负载均衡与 SSL]
+ S4[项目代码发布]
+ end
+ ADHOC --> Module_Test
+ PLAYBOOK --> WP_Deploy`;
+
+const assert = (condition, message) => { if (!condition) throw new Error(message); };
+const parser = new DOMParser();
+const cases = [
+ { name: "Reported diagram, light", source: reportedSource, theme: "github-light", label: "临时、单次操作" },
+ { name: "Reported diagram, dark", source: reportedSource, theme: "github-dark", label: "临时、单次操作" },
+ { name: "Self-closing breaks", source: reportedSource.replaceAll("<br>", "<br/>"), theme: "github-light", label: "临时、单次操作" },
+ { name: "Compact renderer", source: "flowchart LR\nA[开始] --> B[结束]", theme: "github-light", label: "开始" },
+ { name: "HTML entities and formatting", svg: '<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 240 80"><foreignObject width="240" height="80"><div xmlns="http://www.w3.org/1999/xhtml" style="color:rgb(20, 30, 40)"><b>中文 &amp; English</b><br>第二行&nbsp;标签</div></foreignObject></svg>', label: "第二行\u00a0标签" },
+];
+
+try {
+ for (const item of cases) {
+ const original = item.svg ?? await renderThemedMermaidSvg(item.source, {
+ theme: item.theme, palette: MERMAID_THEME_PALETTES[item.theme], font: "sans-serif", padding: 24,
+ });
+ if (item === cases[0]) {
+ const viewer = createRoot(document.querySelector("#viewer"));
+ const renderViewer = (open) => viewer.render(React.createElement(MermaidViewer, {
+ open, svg: original, fallbackBackgroundColor: "#ffffff",
+ closeLabel: "Close", resetZoomLabel: "Reset zoom", viewerLabel: "Reported diagram",
+ zoomInLabel: "Zoom in", zoomOutLabel: "Zoom out", onClose: () => renderViewer(false),
+ }));
+ renderViewer(false);
+ document.querySelector("#open-viewer").disabled = false;
+ document.querySelector("#open-viewer").onclick = () => renderViewer(true);
+ }
+ const section = document.createElement("section");
+ const heading = document.createElement("h2");
+ heading.textContent = item.name;
+ section.append(heading);
+ document.querySelector("#cases").append(section);
+ const normalized = normalizeMermaidSvgForViewer(original);
+ const parsed = parser.parseFromString(normalized, "image/svg+xml");
+ assert(!parsed.querySelector("parsererror"), `${item.name}: invalid XML`);
+ const root = parsed.documentElement;
+ assert(root.namespaceURI === "http://www.w3.org/2000/svg", `${item.name}: SVG namespace`);
+ assert(root.textContent.includes(item.label), `${item.name}: missing label`);
+ for (const br of root.querySelectorAll("foreignObject br")) {
+ assert(br.namespaceURI === "http://www.w3.org/1999/xhtml", `${item.name}: XHTML namespace`);
+ }
+ if (item.svg) {
+ assert(root.querySelector("b")?.textContent === "中文 & English", "Lost formatting or entities");
+ assert(root.querySelector("div")?.getAttribute("style") === "color:rgb(20, 30, 40)", "Lost label style");
+ }
+ const viewBox = root.getAttribute("viewBox").trim().split(/[\s,]+/).map(Number);
+ assert(Number(root.getAttribute("width")) === viewBox[2], `${item.name}: width`);
+ assert(Number(root.getAttribute("height")) === viewBox[3], `${item.name}: height`);
+ const url = URL.createObjectURL(new Blob([normalized], { type: "image/svg+xml;charset=utf-8" }));
+ const image = new Image();
+ image.alt = item.name;
+ section.style.background = item.theme ? MERMAID_THEME_PALETTES[item.theme].bg : "white";
+ try {
+ await new Promise((resolve, reject) => {
+ image.onload = resolve;
+ image.onerror = () => reject(new Error(`${item.name}: image failed to load`));
+ image.src = url;
+ section.append(image);
+ });
+ assert(image.naturalWidth > 0 && image.naturalHeight > 0, `${item.name}: empty image`);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ }
+ const invalid = "<p>Not an SVG</p>";
+ assert(normalizeMermaidSvgForViewer(invalid) === invalid, "Non-SVG input changed");
+ document.querySelector("#result").textContent = `${cases.length} cases passed: XML, namespaces, labels, dimensions and Blob image loading`;
+ document.querySelector("#result").dataset.state = "passed";
+} catch (error) {
+ document.querySelector("#result").textContent = String(error);
+ document.querySelector("#result").dataset.state = "failed";
+}
diff --git a/tests/e2e/mermaid-viewer.spec.ts b/tests/e2e/mermaid-viewer.spec.ts
new file mode 100644
index 00000000..051cd31c
--- /dev/null
+++ b/tests/e2e/mermaid-viewer.spec.ts
@@ -0,0 +1,21 @@
+import { expect, test } from "@playwright/test";
+import { fileURLToPath } from "node:url";
+
+// Exercise real browser HTML/XML parsers and Blob-backed image decoding (#704).
+// This fixture also runs directly in the built-in browser for visual checks.
+test("Mermaid viewer loads HTML labels and preserves valid SVGs", async ({ page }) => {
+ const fixturePath = fileURLToPath(new URL("./fixtures/mermaid-viewer.html", import.meta.url));
+ await page.goto(`/@fs${fixturePath}`);
+ await expect(page.locator("#result")).toHaveAttribute("data-state", "passed");
+ await expect(page.locator("#cases img")).toHaveCount(5);
+ await page.getByRole("button", { name: "Open reported diagram", exact: true }).click();
+ const image = page.locator(".yarl__slide_image");
+ await expect(image).toBeVisible();
+ await expect.poll(() => image.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBeGreaterThan(0);
+ await page.getByRole("button", { name: "Zoom in", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Reset zoom", exact: true })).toBeEnabled();
+ await page.getByRole("button", { name: "Reset zoom", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Reset zoom", exact: true })).toBeDisabled();
+ await page.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(image).toHaveCount(0);
+});