Skip to content

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

fix(mermaid): preserve compact subgraph rendering with upstream patches

tianma-if83f603b974e8
diff --git a/apps/web/src/lib/mermaid-renderer.test.mjs b/apps/web/src/lib/mermaid-renderer.test.mjs
index da227020..03f4dd60 100644
--- a/apps/web/src/lib/mermaid-renderer.test.mjs
+++ b/apps/web/src/lib/mermaid-renderer.test.mjs
@@ -10,7 +10,7 @@ const GANTT_SOURCE = `gantt
Compatibility fallback :fallback, 2026-07-30, 1d`;
describe("Mermaid renderer fallback", () => {
- test("routes the reported subgraph to Mermaid even when the compact renderer would succeed", async () => {
+ test("keeps the reported Chinese subgraph on the compact renderer", async () => {
const source = `flowchart LR
subgraph 日志开启建议
A[生产环境] -->|不开启| B[查询日志]
@@ -31,12 +31,12 @@ describe("Mermaid renderer fallback", () => {
source,
renderBeautiful: () => {
compactRenderCount += 1;
- return renderMermaidSVG(source);
+ return compactRender.stdout;
},
renderOfficial: () => '<svg data-renderer="mermaid"></svg>',
});
- expect(compactRenderCount).toBe(0);
- expect(svg).toContain('data-renderer="mermaid"');
+ expect(compactRenderCount).toBe(1);
+ expect(svg).toBe(compactRender.stdout);
});
test("does not route a comment mentioning subgraphs to the official renderer", async () => {
diff --git a/apps/web/src/lib/mermaid-renderer.ts b/apps/web/src/lib/mermaid-renderer.ts
index 3c266bf6..3bca663a 100644
--- a/apps/web/src/lib/mermaid-renderer.ts
+++ b/apps/web/src/lib/mermaid-renderer.ts
@@ -9,14 +9,9 @@ interface MermaidRenderFallbackOptions {
}
export const renderMermaidWithFallback = async ({
- source = "",
renderBeautiful,
renderOfficial,
}: MermaidRenderFallbackOptions) => {
- // The compact renderer offsets subgraph nodes without moving their edge endpoints.
- // It can return a valid SVG with disconnected arrows, so exceptions are insufficient.
- if (/^\s*subgraph\b/m.test(source)) return renderOfficial();
-
try {
return await renderBeautiful();
} catch {
@@ -40,6 +35,8 @@ export const renderThemedMermaidSvg = (
) => renderMermaidWithFallback({
source,
renderBeautiful: async () => {
+ // Repository dependency patches preserve CJK group IDs and ELK edge offsets
+ // (upstream PRs #132 and #152). Keep supported subgraphs on this renderer.
const { renderMermaidSVG, THEMES } = await (compactModule ??= import("beautiful-mermaid"));
return scaleMermaidSvg(renderMermaidSVG(source, {
...THEMES[theme], ...palette, transparent: true, font, padding,
diff --git a/apps/web/src/lib/mermaid-subgraph.test.mjs b/apps/web/src/lib/mermaid-subgraph.test.mjs
new file mode 100644
index 00000000..11e022e5
--- /dev/null
+++ b/apps/web/src/lib/mermaid-subgraph.test.mjs
@@ -0,0 +1,50 @@
+import { expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+
+test("patched compact renderer preserves Chinese groups and cross-container edge geometry in source and browser bundles", () => {
+ // ELK must initialize without the partial window globals installed by other suites.
+ const result = spawnSync(process.execPath, ["--eval", `
+ import assert from "node:assert/strict";
+ import { readFileSync } from "node:fs";
+ import { parseMermaid, renderMermaidSVG } from "beautiful-mermaid";
+ const entry = import.meta.resolve("beautiful-mermaid");
+ const { layoutGraphSync } = await import(new URL("./layout.ts", entry).href);
+ const browser = await import(new URL("../dist/index.js", entry).href);
+ const onBoundary = (p, n) => {
+ const near = (a, b) => Math.abs(a - b) < 1.5;
+ return ((near(p.x, n.x) || near(p.x, n.x + n.width)) && p.y >= n.y - 1.5 && p.y <= n.y + n.height + 1.5)
+ || ((near(p.y, n.y) || near(p.y, n.y + n.height)) && p.x >= n.x - 1.5 && p.x <= n.x + n.width + 1.5);
+ };
+ for (const direction of ["LR", "RL", "TD", "BT"]) {
+ for (const body of [
+ 'subgraph 日志开启建议\\nA[生产环境] -->|不开启| B[查询日志]\\nC[开发测试] -->|按需开启| B\\nE[审计场景] -->|按需开启| B\\nend',
+ 'subgraph outer["Outer"]\\na[A]\\nsubgraph inner["Inner"]\\nb[B]\\nend\\nend\\na -->|yes| b',
+ 'subgraph 外层["外层分组"]\\na[A]\\nsubgraph 内层["内层分组"]\\nb[B]\\nend\\nend\\na -->|yes| b',
+ 'a[A] -->|yes| b[B]',
+ ]) {
+ const source = 'flowchart ' + direction + '\\n' + body;
+ const graph = parseMermaid(source);
+ for (const group of graph.subgraphs) assert(group.id, 'empty Chinese group id');
+ const positioned = layoutGraphSync(graph);
+ const nodes = new Map(positioned.nodes.map(n => [n.id, n]));
+ for (const edge of positioned.edges) {
+ assert(onBoundary(edge.points[0], nodes.get(edge.source)), direction + ': detached start');
+ assert(onBoundary(edge.points.at(-1), nodes.get(edge.target)), direction + ': detached end');
+ }
+ assert.equal(renderMermaidSVG(source), browser.renderMermaidSVG(source), 'Bun and browser patches differ');
+ }
+ }
+ // Exercise the actual demo without rewriting its topology or saved content.
+ const seed = readFileSync(new URL('../../../api/src/demo-seed-data.ts', import.meta.url), 'utf8');
+ const start = seed.indexOf('flowchart TD', seed.indexOf('## 2. 全景架构与生态联动'));
+ const source = seed.slice(start, seed.indexOf('\\n' + String.fromCharCode(92, 96).repeat(3), start));
+ const svg = renderMermaidSVG(source);
+ assert.equal(svg, browser.renderMermaidSVG(source));
+ assert(svg.includes('全端客户端矩阵'));
+ assert(svg.includes('AI 智能体与外部生态'));
+ console.log('geometry and source/browser parity passed');
+ `], { cwd: import.meta.dir, encoding: "utf8", timeout: 30_000 });
+ expect(result.stderr).toBe("");
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("geometry and source/browser parity passed");
+});
diff --git a/bun.lock b/bun.lock
index f271b729..1da2672f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -337,12 +337,13 @@
},
},
"patchedDependencies": {
"@joplin/[email protected]": "patches/@joplin%[email protected]",
},
"overrides": {
"dompurify": "3.4.17",
diff --git a/package.json b/package.json
index 8f43e338..55331175 100644
--- a/package.json
+++ b/package.json
@@ -234,6 +234,7 @@
"@joplin/[email protected]": "patches/@joplin%[email protected]",
}
}
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000..6880abb4
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,290 @@
+diff --git a/dist/index.js b/dist/index.js
+index e7e087bcb6f29d0d8f36cd558e0183bc0f162fcb..0fff240f51bd750a1f2f231ed8d322ef25f0b11a 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -347,6 +347,13 @@ function parseMermaid(text) {
+ }
+ return parseFlowchart(lines);
+ }
++function stripWrappingQuotes(s) {
++ const t = s.trim();
++ if (t.length >= 2 && (t[0] === '"' && t[t.length - 1] === '"' || t[0] === "'" && t[t.length - 1] === "'")) {
++ return t.slice(1, -1);
++ }
++ return t;
++}
+ function parseFlowchart(lines) {
+ const headerMatch = lines[0].match(/^(?:graph|flowchart)\s+(TD|TB|LR|BT|RL)\s*$/i);
+ if (!headerMatch) {
+@@ -416,15 +423,15 @@ function parseFlowchart(lines) {
+ const subgraphMatch = line.match(/^subgraph\s+(.+)$/);
+ if (subgraphMatch) {
+ const rest = subgraphMatch[1].trim();
+- const bracketMatch = rest.match(/^([\w-]+)\s*\[(.+)\]$/);
++ const bracketMatch = rest.match(/^([^\s[]+)\s*\[(.+)\]$/);
+ let id;
+ let label;
+ if (bracketMatch) {
+ id = bracketMatch[1];
+- label = normalizeBrTags(bracketMatch[2]);
++ label = normalizeBrTags(stripWrappingQuotes(bracketMatch[2]));
+ } else {
+- label = normalizeBrTags(rest);
+- id = rest.replace(/\s+/g, "_").replace(/[^\w]/g, "");
++ label = normalizeBrTags(stripWrappingQuotes(rest));
++ id = label.replace(/\s+/g, "_").replace(/[^\p{L}\p{N}_-]/gu, "");
+ }
+ const sg = { id, label, nodeIds: [], children: [] };
+ subgraphStack.push(sg);
+@@ -6485,7 +6492,9 @@ function calculatePathMidpoint(points) {
+ }
+ function extractEdgesRecursively(elkNode, graph, edges, offsetX, offsetY, margins) {
+ const segments = /* @__PURE__ */ new Map();
+- collectEdgeSegments(elkNode, segments, 0, 0);
++ const containerOffsets = new Map();
++ collectContainerOffsets(elkNode, containerOffsets, 0, 0);
++ collectEdgeSegments(elkNode, segments, 0, 0, containerOffsets);
+ let marginEdgeIndex = 0;
+ for (const [edgeIndex, seg] of segments) {
+ const originalEdge = graph.edges[edgeIndex];
+@@ -6569,27 +6578,42 @@ function orthogonalizeEdgePoints(points, margins, edgeIndex = 0) {
+ }
+ return result;
+ }
+-function collectEdgeSegments(elkNode, segments, offsetX, offsetY) {
++function collectContainerOffsets(elkNode, offsets, offsetX, offsetY) {
++ offsets.set(elkNode.id, { x: offsetX, y: offsetY });
++ for (const child of elkNode.children ?? []) {
++ collectContainerOffsets(
++ child,
++ offsets,
++ offsetX + (child.x ?? 0),
++ offsetY + (child.y ?? 0)
++ );
++ }
++}
++function collectEdgeSegments(elkNode, segments, offsetX, offsetY, containerOffsets) {
+ if (elkNode.edges) {
+ for (const elkEdge of elkNode.edges) {
+ const isInternal = elkEdge.id.endsWith("_internal");
+ const edgeIndex = parseInt(elkEdge.id.substring(1), 10);
+ if (isNaN(edgeIndex)) continue;
++ const container = elkEdge.container;
++ const containerOffset = container ? containerOffsets.get(container) : void 0;
++ const edgeOffsetX = containerOffset?.x ?? offsetX;
++ const edgeOffsetY = containerOffset?.y ?? offsetY;
+ const points = [];
+ if (elkEdge.sections && elkEdge.sections.length > 0) {
+ const section = elkEdge.sections[0];
+ points.push({
+- x: section.startPoint.x + offsetX,
+- y: section.startPoint.y + offsetY
++ x: section.startPoint.x + edgeOffsetX,
++ y: section.startPoint.y + edgeOffsetY
+ });
+ if (section.bendPoints) {
+ for (const bp of section.bendPoints) {
+- points.push({ x: bp.x + offsetX, y: bp.y + offsetY });
++ points.push({ x: bp.x + edgeOffsetX, y: bp.y + edgeOffsetY });
+ }
+ }
+ points.push({
+- x: section.endPoint.x + offsetX,
+- y: section.endPoint.y + offsetY
++ x: section.endPoint.x + edgeOffsetX,
++ y: section.endPoint.y + edgeOffsetY
+ });
+ }
+ let labelPosition;
+@@ -6597,8 +6621,8 @@ function collectEdgeSegments(elkNode, segments, offsetX, offsetY) {
+ const label = elkEdge.labels[0];
+ if (label.x != null && label.y != null) {
+ labelPosition = {
+- x: label.x + (label.width ?? 0) / 2 + offsetX,
+- y: label.y + (label.height ?? 0) / 2 + offsetY
++ x: label.x + (label.width ?? 0) / 2 + edgeOffsetX,
++ y: label.y + (label.height ?? 0) / 2 + edgeOffsetY
+ };
+ }
+ }
+@@ -6623,7 +6647,13 @@ function collectEdgeSegments(elkNode, segments, offsetX, offsetY) {
+ }
+ if (elkNode.children) {
+ for (const child of elkNode.children) {
+- collectEdgeSegments(child, segments, offsetX + (child.x ?? 0), offsetY + (child.y ?? 0));
++ collectEdgeSegments(
++ child,
++ segments,
++ offsetX + (child.x ?? 0),
++ offsetY + (child.y ?? 0),
++ containerOffsets
++ );
+ }
+ }
+ }
+diff --git a/src/layout-engine.ts b/src/layout-engine.ts
+index 8557308223e16670db3d126d9c55673b6e946598..8b0cb71f26e674922e425bd23c49659de751f375 100644
+--- a/src/layout-engine.ts
++++ b/src/layout-engine.ts
+@@ -710,7 +710,9 @@ function extractEdgesRecursively(
+ ): void {
+ // First pass: collect all edge segments
+ const segments = new Map<number, { external?: EdgeSegment; incoming?: EdgeSegment; outgoing?: EdgeSegment }>()
+- collectEdgeSegments(elkNode, segments, 0, 0)
++ const containerOffsets = new Map<string, Point>()
++ collectContainerOffsets(elkNode, containerOffsets, 0, 0)
++ collectEdgeSegments(elkNode, segments, 0, 0, containerOffsets)
+
+ // Track margin-routed edge count for spacing offsets
+ let marginEdgeIndex = 0
+@@ -789,6 +791,24 @@ function extractEdgesRecursively(
+ }
+ }
+
++/** Build absolute root-coordinate offsets for every ELK container. */
++function collectContainerOffsets(
++ elkNode: ElkNode,
++ offsets: Map<string, Point>,
++ offsetX: number,
++ offsetY: number
++): void {
++ offsets.set(elkNode.id, { x: offsetX, y: offsetY })
++ for (const child of elkNode.children ?? []) {
++ collectContainerOffsets(
++ child,
++ offsets,
++ offsetX + (child.x ?? 0),
++ offsetY + (child.y ?? 0),
++ )
++ }
++}
++
+ /**
+ * Post-process edge points to ensure all segments are purely orthogonal.
+ *
+@@ -863,7 +883,8 @@ function collectEdgeSegments(
+ elkNode: ElkNode,
+ segments: Map<number, { external?: EdgeSegment; incoming?: EdgeSegment; outgoing?: EdgeSegment }>,
+ offsetX: number,
+- offsetY: number
++ offsetY: number,
++ containerOffsets: Map<string, Point>
+ ): void {
+ if (elkNode.edges) {
+ for (const elkEdge of elkNode.edges) {
+@@ -872,22 +893,31 @@ function collectEdgeSegments(
+ const edgeIndex = parseInt(elkEdge.id.substring(1), 10)
+ if (isNaN(edgeIndex)) continue
+
++ // ELK may retain a cross-hierarchy edge in an ancestor's `edges` array
++ // while reporting sections and labels in the coordinate space named by
++ // `edge.container`. Prefer that container's accumulated root offset;
++ // edges without a container retain the owning-array behavior.
++ const container = (elkEdge as ElkExtendedEdge & { container?: string }).container
++ const containerOffset = container ? containerOffsets.get(container) : undefined
++ const edgeOffsetX = containerOffset?.x ?? offsetX
++ const edgeOffsetY = containerOffset?.y ?? offsetY
++
+ // Extract points
+ const points: Point[] = []
+ if (elkEdge.sections && elkEdge.sections.length > 0) {
+ const section = elkEdge.sections[0]!
+ points.push({
+- x: section.startPoint.x + offsetX,
+- y: section.startPoint.y + offsetY,
++ x: section.startPoint.x + edgeOffsetX,
++ y: section.startPoint.y + edgeOffsetY,
+ })
+ if (section.bendPoints) {
+ for (const bp of section.bendPoints) {
+- points.push({ x: bp.x + offsetX, y: bp.y + offsetY })
++ points.push({ x: bp.x + edgeOffsetX, y: bp.y + edgeOffsetY })
+ }
+ }
+ points.push({
+- x: section.endPoint.x + offsetX,
+- y: section.endPoint.y + offsetY,
++ x: section.endPoint.x + edgeOffsetX,
++ y: section.endPoint.y + edgeOffsetY,
+ })
+ }
+
+@@ -897,8 +927,8 @@ function collectEdgeSegments(
+ const label = elkEdge.labels[0]!
+ if (label.x != null && label.y != null) {
+ labelPosition = {
+- x: label.x + (label.width ?? 0) / 2 + offsetX,
+- y: label.y + (label.height ?? 0) / 2 + offsetY,
++ x: label.x + (label.width ?? 0) / 2 + edgeOffsetX,
++ y: label.y + (label.height ?? 0) / 2 + edgeOffsetY,
+ }
+ }
+ }
+@@ -933,7 +963,13 @@ function collectEdgeSegments(
+ // Recurse into children with accumulated offset
+ if (elkNode.children) {
+ for (const child of elkNode.children) {
+- collectEdgeSegments(child, segments, offsetX + (child.x ?? 0), offsetY + (child.y ?? 0))
++ collectEdgeSegments(
++ child,
++ segments,
++ offsetX + (child.x ?? 0),
++ offsetY + (child.y ?? 0),
++ containerOffsets,
++ )
+ }
+ }
+ }
+diff --git a/src/parser.ts b/src/parser.ts
+index 685835e3f1a9a480370ec8e1ff40b7356a3ed3c1..defc40d3f2ebf56ea097efe058a2ef26fba7a767 100644
+--- a/src/parser.ts
++++ b/src/parser.ts
+@@ -1,6 +1,18 @@
+ import type { MermaidGraph, MermaidNode, MermaidEdge, MermaidSubgraph, Direction, NodeShape, EdgeStyle } from './types.ts'
+ import { normalizeBrTags } from './multiline-utils.ts'
+
++/** Remove a single layer of matching wrapping quotes (`"…"` or `'…'`). */
++function stripWrappingQuotes(s: string): string {
++ const t = s.trim()
++ if (
++ t.length >= 2 &&
++ ((t[0] === '"' && t[t.length - 1] === '"') || (t[0] === "'" && t[t.length - 1] === "'"))
++ ) {
++ return t.slice(1, -1)
++ }
++ return t
++}
++
+ // ============================================================================
+ // Mermaid parser — flowcharts and state diagrams
+ //
+@@ -126,18 +138,22 @@ function parseFlowchart(lines: string[]): MermaidGraph {
+ const subgraphMatch = line.match(/^subgraph\s+(.+)$/)
+ if (subgraphMatch) {
+ const rest = subgraphMatch[1]!.trim()
+- // Check for "subgraph id [Label]" form
+- // ID can contain hyphens (e.g. "us-east"), so use [\w-]+ not \w+
+- const bracketMatch = rest.match(/^([\w-]+)\s*\[(.+)\]$/)
++ // Check for `subgraph id [Label]` / `subgraph id ["Label"]` form. The id
++ // may contain non-ASCII chars (e.g. CJK), so match any run of non-space,
++ // non-`[` chars rather than ASCII [\w-]; strip optional quotes wrapping
++ // the title.
++ const bracketMatch = rest.match(/^([^\s[]+)\s*\[(.+)\]$/)
+ let id: string
+ let label: string
+ if (bracketMatch) {
+ id = bracketMatch[1]!
+- label = normalizeBrTags(bracketMatch[2]!)
++ label = normalizeBrTags(stripWrappingQuotes(bracketMatch[2]!))
+ } else {
+- // Use the label text as id (slugified)
+- label = normalizeBrTags(rest)
+- id = rest.replace(/\s+/g, '_').replace(/[^\w]/g, '')
++ // `subgraph Label` (optionally quoted): the label doubles as the id,
++ // slugified — but preserve unicode letters/numbers so a CJK-only title
++ // doesn't collapse to an empty id (which broke nested layout).
++ label = normalizeBrTags(stripWrappingQuotes(rest))
++ id = label.replace(/\s+/g, '_').replace(/[^\p{L}\p{N}_-]/gu, '')
+ }
+ const sg: MermaidSubgraph = { id, label, nodeIds: [], children: [] }
+ subgraphStack.push(sg)
diff --git a/tests/e2e/fixtures/mermaid-viewer.js b/tests/e2e/fixtures/mermaid-viewer.js
index 9cfafd7b..d190b568 100644
--- a/tests/e2e/fixtures/mermaid-viewer.js
+++ b/tests/e2e/fixtures/mermaid-viewer.js
@@ -4,6 +4,10 @@ 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";
+import demoSeed from "../../../apps/api/src/demo-seed-data.ts?raw";
+
+const demoStart = demoSeed.indexOf("flowchart TD", demoSeed.indexOf("## 2. 全景架构与生态联动"));
+const demoSource = demoSeed.slice(demoStart).split("\\`\\`\\`")[0].trim();
const reportedSource = `---
config:
@@ -36,6 +40,8 @@ const cases = [
{ 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: "Demo architecture with compact subgraphs", source: demoSource, theme: "github-light", label: "全端客户端矩阵" },
+ { name: "Chinese subgraph edge alignment", source: "flowchart LR\nsubgraph 日志开启建议\nA[生产环境] -->|不开启| B[查询日志]\nC[开发测试] -->|按需开启| B\nE[审计场景] -->|按需开启| B\nend", 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标签" },
];
diff --git a/tests/e2e/mermaid-viewer.spec.ts b/tests/e2e/mermaid-viewer.spec.ts
index 051cd31c..01489878 100644
--- a/tests/e2e/mermaid-viewer.spec.ts
+++ b/tests/e2e/mermaid-viewer.spec.ts
@@ -7,7 +7,7 @@ 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 expect(page.locator("#cases img")).toHaveCount(7);
await page.getByRole("button", { name: "Open reported diagram", exact: true }).click();
const image = page.locator(".yarl__slide_image");
await expect(image).toBeVisible();