diff --git a/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs b/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs index 6ed821cea..26ffd2489 100644 --- a/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs +++ b/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs @@ -63,10 +63,25 @@ const html = ` #diagram svg { display: block; } + /* Keep Mermaid's temporary render container unscaled when the host mounts this frame + at 0x0 or 240x240 before the diagram's own dimensions are known. */ + #staging-clip { + position: fixed; + width: 0; + height: 0; + overflow: hidden; + visibility: hidden; + pointer-events: none; + } + #staging { + width: 16384px; + height: 16384px; + }
+ `; diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts index 25d7db5e3..a7d00d59e 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts @@ -40,6 +40,9 @@ function initializeMermaid(colorScheme: "light" | "dark"): void { ], flowchart: { htmlLabels: false }, class: { htmlLabels: false }, + // A gantt chart takes the width of the element it renders in, which is the oversized staging + // container. Keep it as wide as this frame, which on native is the message column. + gantt: { useWidth: document.body.clientWidth }, }); } @@ -97,7 +100,15 @@ function measureDiagram(host: HTMLElement, svg: SVGSVGElement | null): DiagramSi async function render(message: MermaidRuntimeRenderMessage): Promise { try { initializeMermaid(message.colorScheme); - const { svg } = await mermaid.render(`paseo-mermaid-${message.revision}`, message.source); + const staging = document.getElementById("staging"); + if (!staging) { + throw new Error("Missing Mermaid staging container"); + } + const { svg } = await mermaid.render( + `paseo-mermaid-${message.revision}`, + message.source, + staging, + ); if (message.revision !== latestRevision) { return; } diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts index 608ab2786..082c07321 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts @@ -1,4 +1,4 @@ // Generated by packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs. // Do not edit by hand. -export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n \n \n"; +export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n
\n \n \n"; diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts index 7ffbbc79d..a9727900f 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts @@ -29,9 +29,15 @@ function waitForRuntimeMessage( }); } -async function mountRuntime(size?: { width: number; height: number }): Promise { +async function mountRuntime( + size?: { width: number; height: number }, + options?: { allowSameOrigin?: boolean }, +): Promise { const frame = document.createElement("iframe"); frame.sandbox.add("allow-scripts"); + if (options?.allowSameOrigin) { + frame.sandbox.add("allow-same-origin"); + } if (size) { frame.style.width = `${size.width}px`; frame.style.height = `${size.height}px`; @@ -112,6 +118,103 @@ describe("Mermaid sandbox runtime", () => { expect(renderedSize(narrow)).toEqual(renderedSize(wide)); }); + /** + * MermaidFenceHost renders the first revision inside a 240x240 measuring frame (or 0x0 before + * ResizeObserver settles), then resizes the frame to the reported diagram size without + * re-rendering. Diagrams such as xychart-beta set `width="100%"` and `viewBox="0 0 700 500"` + * before measuring axis text with `getBoundingClientRect()`, so rendering directly in a narrow + * frame shrinks measured glyph boxes and leaves the Y-axis title colliding with tick labels and + * X-axis labels clipped at the bottom edge. + */ + it("preserves unscaled SVG layout when rendered inside a narrow or zero-sized frame", async () => { + const source = [ + "xychart-beta", + ' title "Throughput by Stage (req/s)"', + ' x-axis ["v1-base", "v2-parse", "v3-batch", "v4-cache", "v5-simd", "v6-final"]', + ' y-axis "Throughput (req/s)" 92.5 --> 93.6', + " bar [92.7, 92.8, 93.1, 93.2, 93.3, 93.5]", + ].join("\n"); + const zeroFrame = await mountRuntime({ height: 0, width: 0 }, { allowSameOrigin: true }); + const measuringFrame = await mountRuntime( + { height: 240, width: 240 }, + { allowSameOrigin: true }, + ); + const fullFrame = await mountRuntime({ height: 500, width: 700 }, { allowSameOrigin: true }); + + await render(zeroFrame, { revision: 1, source }); + await render(measuringFrame, { revision: 1, source }); + await render(fullFrame, { revision: 1, source }); + + for (const frame of [zeroFrame, measuringFrame]) { + frame.style.width = "700px"; + frame.style.height = "500px"; + const doc = frame.contentDocument; + if (!doc) { + throw new Error("Expected inspectable runtime document"); + } + const svgRect = doc.querySelector("#diagram svg")?.getBoundingClientRect(); + const yTitleRect = doc.querySelector(".left-axis .title text")?.getBoundingClientRect(); + const yLabels = Array.from(doc.querySelectorAll(".left-axis .label text")); + const xLabels = Array.from(doc.querySelectorAll(".bottom-axis .label text")); + expect(svgRect).not.toBeUndefined(); + expect(yTitleRect).not.toBeUndefined(); + expect(yLabels.length).toBeGreaterThan(0); + expect(xLabels.length).toBeGreaterThan(0); + + for (const label of yLabels) { + expect(yTitleRect!.right).toBeLessThan(label.getBoundingClientRect().left); + } + for (const label of xLabels) { + expect(label.getBoundingClientRect().bottom).toBeLessThanOrEqual(svgRect!.bottom); + } + } + + function axisOrigin(frame: HTMLIFrameElement): { leftAxisX: number; bottomAxisY: number } { + const doc = frame.contentDocument; + const leftPath = doc?.querySelector(".left-axis .axisl-line path")?.getAttribute("d") ?? ""; + const bottomPath = + doc?.querySelector(".bottom-axis .axis-line path")?.getAttribute("d") ?? ""; + const leftMatch = leftPath.match(/^M\s+([\d.]+),/); + const bottomMatch = bottomPath.match(/^M\s+[\d.]+,([\d.]+)/); + if (!leftMatch || !bottomMatch) { + throw new Error(`Unexpected axis paths: ${leftPath} | ${bottomPath}`); + } + return { + leftAxisX: Number.parseFloat(leftMatch[1]), + bottomAxisY: Number.parseFloat(bottomMatch[1]), + }; + } + + const fullOrigin = axisOrigin(fullFrame); + for (const candidate of [measuringFrame, zeroFrame]) { + const origin = axisOrigin(candidate); + expect(origin.leftAxisX).toBeCloseTo(fullOrigin.leftAxisX, 3); + expect(origin.bottomAxisY).toBeCloseTo(fullOrigin.bottomAxisY, 3); + } + }); + + /** + * A gantt chart takes the width of the element Mermaid renders it in. Rendering inside the large + * offscreen container must keep it as wide as the frame, which on native is the message column. + */ + it("renders a gantt chart as wide as the frame the host gives it", async () => { + const source = [ + "gantt", + " title Release plan", + " dateFormat YYYY-MM-DD", + " section Build", + " Design :a1, 2024-01-01, 10d", + " Implement :after a1, 20d", + ].join("\n"); + const widths = []; + for (const width of [240, 350, 900]) { + const frame = await mountRuntime({ height: 240, width }); + widths.push(renderedSize(await render(frame, { revision: 1, source })).width); + } + + expect(widths).toEqual([240, 350, 900]); + }); + it("coalesces queued input and never reports an obsolete result", async () => { const frame = await mountRuntime(); const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;