Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(agents): render mermaid diagrams in agent messages (#1787)

Vadim Lazukd0c3b9ba344b
diff --git a/src/features/agents/Markdown.test.tsx b/src/features/agents/Markdown.test.tsx
index e8cb2638c..d80f270a5 100644
--- a/src/features/agents/Markdown.test.tsx
+++ b/src/features/agents/Markdown.test.tsx
@@ -1,20 +1,41 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
+import { resetMermaidForTests } from "../viewers/markdown/mermaid";
import { Markdown } from "./Markdown";
const { openFile, openExternalUrl } = vi.hoisted(() => ({
openFile: vi.fn().mockResolvedValue(undefined),
openExternalUrl: vi.fn().mockResolvedValue(undefined),
}));
+const copyText = vi.hoisted(() => vi.fn());
const readImage = vi.fn<(path: string) => Promise<string>>();
const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
vi.mock("@/workbench/contributions", () => ({ editorService: () => ({ openFile }) }));
vi.mock("@/platform/openUrl", () => ({ openExternalUrl }));
+vi.mock("@/ui", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/ui")>()), copyText }));
+
+const mermaid = vi.hoisted(() => ({ initialize: vi.fn(), render: vi.fn() }));
+vi.mock("mermaid", () => ({ default: { initialize: mermaid.initialize, render: mermaid.render } }));
+
+const DIAGRAM = "flowchart TD\n A-->B";
+const FENCE = `\`\`\`mermaid\n${DIAGRAM}\n\`\`\`\n`;
beforeEach(() => {
vi.clearAllMocks();
readImage.mockReset().mockResolvedValue(PIXEL);
+ resetMermaidForTests();
+ mermaid.render.mockReset().mockImplementation(async (id: string, text: string) => {
+ // Like mermaid: a measuring node under <body> while rendering.
+ const tmp = document.createElement("div");
+ tmp.id = `d${id}`;
+ document.body.append(tmp);
+ return {
+ svg:
+ `<svg id="${id}"><defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
+ `<path d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
+ };
+ });
mockIPC((cmd, args) => (cmd === "fs_read_image" ? readImage((args as { path: string }).path) : null));
});
afterEach(clearMocks);
@@ -166,3 +187,66 @@ it("reports network or decode failures without leaving a broken source", () => {
expect(screen.getByRole("img")).not.toHaveAttribute("src");
expect(screen.getByRole("img")).toHaveAttribute("alt", "Unable to load image: https://example.com/gone.png");
});
+
+describe("mermaid diagrams in a reply", () => {
+ it("renders the fence as a placeholder holding the source, then draws the diagram", async () => {
+ const { container } = render(
+ <Markdown text={`Before\n\n${FENCE}\n\n\`\`\`ts\nconst a = 1;\n\`\`\``} cwd="/repo" />,
+ );
+ const block = container.querySelector<HTMLElement>("[data-mermaid]")!;
+ expect(block.querySelector("code.language-mermaid")!.textContent).toBe(DIAGRAM);
+ expect(container.querySelector("code.language-ts")).not.toBeNull();
+ await waitFor(() => expect(block).toHaveAttribute("data-mermaid-state", "ok"));
+ expect(block.querySelector(".mermaid-output svg")).not.toBeNull();
+ // Temporary nodes mermaid leaves under <body> are removed.
+ expect(document.body.querySelector(":scope > [id^='d']")).toBeNull();
+ });
+
+ it("draws two equal diagrams with unique SVG ids, so markers of a hidden copy stay live", async () => {
+ const one = render(<Markdown text={FENCE} cwd="/repo" />);
+ await waitFor(() => expect(one.container.querySelector("[data-mermaid-state='ok']")).not.toBeNull());
+ // The second copy (the first now hidden, like a collapsed subagent reply) comes
+ // from the cache — and still gets ids of its own.
+ const two = render(<Markdown text={FENCE} cwd="/repo" />);
+ await waitFor(() => expect(two.container.querySelector("[data-mermaid-state='ok']")).not.toBeNull());
+ expect(mermaid.render).toHaveBeenCalledTimes(1);
+ const idsOf = (root: HTMLElement) =>
+ [...root.querySelectorAll("svg[id], svg [id]")].map((el) => el.getAttribute("id"));
+ const idsOne = idsOf(one.container);
+ const idsTwo = idsOf(two.container);
+ expect(idsOne).toHaveLength(2);
+ expect(idsTwo).toHaveLength(2);
+ expect(idsOne.filter((id) => idsTwo.includes(id))).toEqual([]);
+ // Every marker reference resolves inside its own copy.
+ for (const root of [one.container, two.container]) {
+ const svg = root.querySelector(".mermaid-output svg")!;
+ const ref = svg.querySelector("[marker-end]")!.getAttribute("marker-end")!;
+ expect(new Set(idsOf(root)).has(/url\(#(.+)\)/.exec(ref)![1]!)).toBe(true);
+ }
+ });
+
+ it("keeps the source copyable on the block once the diagram is drawn", async () => {
+ const { container } = render(<Markdown text={FENCE} cwd="/repo" />);
+ const block = container.querySelector<HTMLElement>("[data-mermaid]")!;
+ await waitFor(() => expect(block).toHaveAttribute("data-mermaid-state", "ok"));
+ // The drawn diagram hides the code block (and with it the usual per-pre Copy button):
+ // the block keeps its own, outside what gets hidden.
+ const copy = block.querySelector<HTMLElement>(":scope > button[data-copy]")!;
+ expect(copy.dataset.copy).toBe(DIAGRAM);
+ expect(block.querySelector("pre button[data-copy]")).toBeNull();
+ fireEvent.click(copy);
+ expect(copyText).toHaveBeenCalledWith(DIAGRAM);
+ });
+
+ it("tells the conversation to follow when a diagram draws after the message rendered", async () => {
+ const onDiagramDrawn = vi.fn();
+ const { rerender } = render(<Markdown text={FENCE} cwd="/repo" onDiagramDrawn={onDiagramDrawn} />);
+ expect(onDiagramDrawn).not.toHaveBeenCalled(); // the draw hasn't finished yet
+ await waitFor(() => expect(onDiagramDrawn).toHaveBeenCalledTimes(1));
+ // The next streamed chunk hits the cache: drawn in place before paint, so the
+ // conversation follows it on its own render pass without another callback.
+ rerender(<Markdown text={`${FENCE}\n\nDone.`} cwd="/repo" onDiagramDrawn={onDiagramDrawn} />);
+ await act(async () => {});
+ expect(onDiagramDrawn).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/agents/Markdown.tsx b/src/features/agents/Markdown.tsx
index ccdb630cb..005621f62 100644
--- a/src/features/agents/Markdown.tsx
+++ b/src/features/agents/Markdown.tsx
@@ -1,6 +1,10 @@
/**
* Agent messages: Markdown → sanitized HTML (marked + DOMPurify). Fenced code is
* highlighted and gets a Copy button; inline code naming a file of the task opens it.
+ * Mermaid fences become `[data-mermaid]` placeholders drawn by the Markdown viewer's
+ * shared renderer after each render; the block keeps a Copy button of its own, since
+ * the drawn diagram hides the code block, and `onDiagramDrawn` lets the conversation
+ * follow the end when a diagram draws after the last streamed chunk.
*/
import { useLayoutEffect, useMemo, useRef } from "react";
import { Marked } from "marked";
@@ -12,11 +16,24 @@ import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { copyText } from "@/ui";
import { editorService } from "@/workbench/contributions";
+import { hasMermaid, renderMermaidIn } from "@/features/viewers/markdown/mermaid";
import { fileHref, pathLink, type PathLink } from "./conversation";
import { loadImages } from "./markdownImages";
import styles from "./Session.module.css";
-const marked = new Marked({ gfm: true, breaks: true });
+const escapeHtml = (s: string) =>
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
+
+const marked = new Marked({
+ gfm: true,
+ breaks: true,
+ renderer: {
+ code({ text, lang }) {
+ if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "mermaid") return false;
+ return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
+ },
+ },
+});
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
const rendered = new Map<string, string>();
@@ -62,6 +79,9 @@ function renderHtml(text: string): string {
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
ALLOW_DATA_ATTR: false,
+ // Only the mermaid placeholder written by the renderer above; data attributes
+ // quoted in a reply stay out.
+ ADD_ATTR: ["data-mermaid"],
}) as HTMLElement;
root.querySelectorAll("li").forEach(wrapLooseText);
return root.innerHTML;
@@ -121,7 +141,6 @@ function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<str
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
const text = (code.textContent ?? "").replace(/\n+$/, "");
code.textContent = text;
- void highlightInto(code, text, lang);
const copy = document.createElement("button");
copy.type = "button";
copy.className = styles.codeCopy!;
@@ -130,6 +149,13 @@ function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<str
copy.setAttribute("aria-label", label);
copy.appendChild(iconNode("copy", 14));
copy.dataset.copy = text;
+ if (pre.parentElement?.hasAttribute("data-mermaid")) {
+ // Mermaid source: not highlighted (the diagram draws over it), and the Copy
+ // button sits on the block — the drawn diagram hides the code block itself.
+ pre.parentElement.appendChild(copy);
+ return;
+ }
+ void highlightInto(code, text, lang);
pre.appendChild(copy);
});
root.querySelectorAll<HTMLElement>("code").forEach((code) => {
@@ -151,11 +177,36 @@ function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<str
};
}
-export function Markdown({ text, cwd }: { text: string; cwd: string }) {
+export function Markdown({
+ text,
+ cwd,
+ onDiagramDrawn,
+}: {
+ text: string;
+ cwd: string;
+ /** A diagram drew after the message rendered: the conversation may follow the end. */
+ onDiagramDrawn?: () => void;
+}) {
const html = useMemo(() => markdownHtml(text), [text]);
const ref = useRef<HTMLDivElement>(null);
const images = useRef(new Map<string, Promise<string>>());
+ /** The last drawing of each mermaid block, stood in while a changed one renders. */
+ const diagrams = useRef<Node[]>([]);
useLayoutEffect(() => (ref.current ? enhance(ref.current, cwd, images.current) : undefined), [html, cwd]);
+ // Mermaid diagrams: before paint, so cached ones don't flash their source. Only a
+ // draw that lands after the render needs the follow — cached ones are in place by
+ // the time the conversation's own render pass scrolls.
+ useLayoutEffect(() => {
+ const root = ref.current;
+ if (!root || !hasMermaid(root)) return;
+ const pass = renderMermaidIn(root, diagrams.current);
+ let live = true;
+ if (pass.async) void pass.done.then(() => live && onDiagramDrawn?.());
+ return () => {
+ live = false;
+ pass.cancel();
+ };
+ }, [html, onDiagramDrawn]);
return (
<div
ref={ref}
diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css
index 823347725..bbbb06524 100644
--- a/src/features/agents/Session.module.css
+++ b/src/features/agents/Session.module.css
@@ -301,12 +301,42 @@
opacity: 0;
}
.markdown :global(pre:hover) .codeCopy,
+.markdown :global([data-mermaid]:hover) .codeCopy,
.codeCopy:focus-visible {
opacity: 1;
}
.codeCopy:hover {
background: var(--bg-hover);
}
+/* Mermaid diagrams: the source stays until the diagram is drawn (and next to an
+ error), and the Copy button lives on the block — the drawn diagram hides the
+ code block that would otherwise carry it. */
+.markdown :global([data-mermaid]) {
+ position: relative;
+ margin: 0 0 8px;
+}
+.markdown :global([data-mermaid] > pre) {
+ margin: 0;
+}
+.markdown :global([data-mermaid-state="ok"] > pre) {
+ display: none;
+}
+.markdown :global(.mermaid-output) {
+ overflow: hidden;
+ text-align: center;
+}
+.markdown :global([data-mermaid-state="error"] > .mermaid-output) {
+ margin-top: 6px;
+ padding: 6px 10px;
+ border-left: 3px solid var(--danger);
+ border-radius: var(--radius-small);
+ background: var(--bg-elev);
+ color: var(--danger);
+ font-family: var(--font-mono);
+ font-size: var(--fs-small);
+ text-align: left;
+ white-space: pre-wrap;
+}
.fileLink {
color: var(--link);
cursor: pointer;
diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsx
index b1475948f..cabef1ee3 100644
--- a/src/features/agents/SessionEditor.tsx
+++ b/src/features/agents/SessionEditor.tsx
@@ -447,6 +447,11 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
}, [start]);
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
const visible = useEditorShown();
+ /** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
+ const onDiagramDrawn = useCallback(() => {
+ const el = ref.current;
+ if (el && position.current.stick) el.scrollTop = el.scrollHeight;
+ }, []);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
@@ -508,6 +513,7 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
turn={turns?.get(start + i) ?? null}
turnCount={turns?.size ?? 0}
onOpenSubagent={onOpenSubagent}
+ onDiagramDrawn={onDiagramDrawn}
/>
))
)}
@@ -739,6 +745,7 @@ const Entry = memo(function Entry({
turn,
turnCount,
onOpenSubagent,
+ onDiagramDrawn,
}: {
task: AgentTask;
entry: AgentEntry;
@@ -746,12 +753,13 @@ const Entry = memo(function Entry({
turn: number | null;
turnCount: number;
onOpenSubagent: (id: string) => void;
+ onDiagramDrawn: () => void;
}) {
switch (entry.type) {
case "user":
return <UserMessage task={task} entry={entry} turn={turn} turnCount={turnCount} />;
case "agent":
- return <Markdown text={entry.text} cwd={task.cwd} />;
+ return <Markdown text={entry.text} cwd={task.cwd} onDiagramDrawn={onDiagramDrawn} />;
case "thought":
return (
<div>
@@ -783,7 +791,14 @@ const Entry = memo(function Entry({
</div>
);
case "subagent":
- return <SubagentCard task={task} entry={entry} onOpen={() => onOpenSubagent(entry.id)} />;
+ return (
+ <SubagentCard
+ task={task}
+ entry={entry}
+ onOpen={() => onOpenSubagent(entry.id)}
+ onDiagramDrawn={onDiagramDrawn}
+ />
+ );
case "message":
return entry.incoming ? (
<div className={styles.message}>
@@ -797,7 +812,7 @@ const Entry = memo(function Entry({
<div className={styles.messageFrom}>
<T>Report to the parent agent</T>
</div>
- <Markdown text={entry.text} cwd={task.cwd} />
+ <Markdown text={entry.text} cwd={task.cwd} onDiagramDrawn={onDiagramDrawn} />
</div>
);
case "permission":
@@ -1083,7 +1098,17 @@ function SubagentStatusIcon({ status }: { status: SubagentEntry["status"] }) {
}
/** A subagent in its parent's conversation: what it does, its latest step, what it was asked and answered. */
-function SubagentCard({ task, entry, onOpen }: { task: AgentTask; entry: SubagentEntry; onOpen: () => void }) {
+function SubagentCard({
+ task,
+ entry,
+ onOpen,
+ onDiagramDrawn,
+}: {
+ task: AgentTask;
+ entry: SubagentEntry;
+ onOpen: () => void;
+ onDiagramDrawn: () => void;
+}) {
const tx = useTx();
const working = subagentWorking(entry.status);
const now = useNow(working ? 1000 : 60_000);
@@ -1148,7 +1173,7 @@ function SubagentCard({ task, entry, onOpen }: { task: AgentTask; entry: Subagen
<T>Result</T>
</summary>
<div className={styles.subagentReply}>
- <Markdown text={entry.reply} cwd={task.cwd} />
+ <Markdown text={entry.reply} cwd={task.cwd} onDiagramDrawn={onDiagramDrawn} />
</div>
</details>
)}
diff --git a/src/features/agents/mermaidFollow.test.tsx b/src/features/agents/mermaidFollow.test.tsx
new file mode 100644
index 000000000..f45edaff7
--- /dev/null
+++ b/src/features/agents/mermaidFollow.test.tsx
@@ -0,0 +1,79 @@
+import { act, render, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import type { AgentEntry, AgentTask } from "@/bindings";
+
+const ipc = vi.hoisted(() => ({ entries: vi.fn() }));
+vi.mock("@/platform/ipc", async (original) => ({
+ ...(await original<typeof import("@/platform/ipc")>()),
+ commands: {
+ agentEntries: ipc.entries,
+ agentChanges: async () => ({ status: "ok", data: [] }),
+ vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
+ },
+}));
+vi.mock("@tauri-apps/api/webview", () => ({
+ getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }),
+}));
+
+const mermaid = vi.hoisted(() => ({ initialize: vi.fn(), render: vi.fn() }));
+vi.mock("mermaid", () => ({ default: { initialize: mermaid.initialize, render: mermaid.render } }));
+
+import { SessionEditor } from "./SessionEditor";
+import { resetMermaidForTests } from "../viewers/markdown/mermaid";
+import { useAgents } from "./store";
+
+const entries: AgentEntry[] = [{ type: "agent", text: "```mermaid\nflowchart TD\n A-->B\n```" }];
+
+const task: AgentTask = {
+ id: "mermaid",
+ title: "Test task",
+ provider: "codex",
+ status: "ready",
+ isolation: "local",
+ model: null,
+ cwd: "/project",
+ branch: null,
+ base: null,
+ baseCommit: null,
+ error: null,
+ createdMs: 0,
+ updatedMs: 0,
+ config: [],
+ commands: [],
+ usage: null,
+ queue: [],
+ capabilities: { fork: true, rollback: true, steer: true, images: true },
+};
+
+beforeEach(() => {
+ resetMermaidForTests();
+ ipc.entries.mockReset().mockResolvedValue({ status: "ok", data: entries });
+ useAgents.setState({ tasks: new Map([[task.id, task]]), entries: new Map(), composers: new Map(), focus: null });
+});
+
+it("follows the end when a diagram draws after the last update", async () => {
+ // The diagram is still rendering when the conversation arrives at its end.
+ let draw!: () => void;
+ mermaid.render.mockReset().mockImplementation(
+ (id: string) =>
+ new Promise<{ svg: string }>((resolve) => {
+ draw = () => resolve({ svg: `<svg id="${id}"><text>flowchart TD</text></svg>` });
+ }),
+ );
+ const { container } = render(
+ <SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
+ );
+ const block = await waitFor(() => {
+ const el = container.querySelector("[data-mermaid]");
+ expect(el).not.toBeNull();
+ return el as HTMLElement;
+ });
+ // The stream holds the conversation at the end (the default when no offset was kept).
+ const scroller = block.closest<HTMLElement>("div[tabindex='-1']")!;
+ Object.defineProperty(scroller, "scrollHeight", { value: 1000, configurable: true });
+ expect(scroller.scrollTop).toBe(0);
+ // The draw lands after the last streamed chunk: the viewport must follow it.
+ await act(async () => draw());
+ await waitFor(() => expect(block).toHaveAttribute("data-mermaid-state", "ok"));
+ expect(scroller.scrollTop).toBe(1000);
+});
diff --git a/src/features/viewers/markdown/mermaid.test.ts b/src/features/viewers/markdown/mermaid.test.ts
index 80b8b8bb7..c2584ff32 100644
--- a/src/features/viewers/markdown/mermaid.test.ts
+++ b/src/features/viewers/markdown/mermaid.test.ts
@@ -12,7 +12,11 @@ const m = vi.hoisted(() => ({
tmp.id = `d${id}`;
document.body.append(tmp);
if (text.includes("bad")) throw new Error("Parse error on line 2:\nbad\n^");
- return { svg: `<svg id="${id}"><text>${text.split("\n")[0]}</text></svg>` };
+ return {
+ svg:
+ `<svg id="${id}"><defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
+ `<path d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
+ };
}),
}));
@@ -109,6 +113,32 @@ describe("mermaid in the markdown preview", () => {
expect(ids.size).toBe(2);
});
+ it("applies a cached diagram with fresh SVG ids so copies don't share markers", async () => {
+ const first = preview(SEQ);
+ await renderMermaidIn(first, []).done;
+ // Like the first copy sitting in a hidden host: a closed details, another tab.
+ first.style.display = "none";
+ const second = preview(SEQ);
+ const pass = renderMermaidIn(second, []);
+ expect(pass.async).toBe(false); // drawn from the cache, no new render
+ await pass.done;
+ expect(m.render).toHaveBeenCalledTimes(1);
+ const idsOf = (svg: Element) => [svg, ...svg.querySelectorAll("[id]")].map((el) => el.getAttribute("id"));
+ const a = first.querySelector("svg")!;
+ const b = second.querySelector("svg")!;
+ const idsA = idsOf(a);
+ const idsB = idsOf(b);
+ expect(idsA).toHaveLength(2);
+ expect(idsB).toHaveLength(2);
+ expect(idsA.filter((id) => idsB.includes(id))).toEqual([]);
+ // Every marker reference resolves within its own copy.
+ for (const svg of [a, b]) {
+ const own = new Set(idsOf(svg));
+ const ref = svg.querySelector("[marker-end]")!.getAttribute("marker-end")!;
+ expect(own.has(/url\(#(.+)\)/.exec(ref)![1]!)).toBe(true);
+ }
+ });
+
it("re-renders when switching between built-in palette themes of the same light / dark base", async () => {
const root = document.documentElement;
const previous = root.dataset.colorTheme;
diff --git a/src/features/viewers/markdown/mermaid.ts b/src/features/viewers/markdown/mermaid.ts
index fbd8bd0d2..3d7f9ac91 100644
--- a/src/features/viewers/markdown/mermaid.ts
+++ b/src/features/viewers/markdown/mermaid.ts
@@ -112,12 +112,38 @@ function remember(k: string, r: Result) {
cache.set(k, r);
}
+const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+let applied = 0;
+/**
+ * A fresh render carries unique ids (mermaid draws under a unique root id), but a cache
+ * hit reapplies the first render's SVG string. Two copies in one document — the same
+ * diagram twice, or one drawn again while the first sits hidden (a closed details, an
+ * inactive tab) — collide on their marker ids, and Chromium resolves the `url(#…)`
+ * references against the hidden copy, losing arrowheads. Rewrites every id per
+ * application: longest first, so an id that extends a shorter one moves out of the way.
+ */
+function reid(svg: string): string {
+ const ids = [...new Set([...svg.matchAll(/\bid="([^"]+)"/g)].map((m) => m[1]!))];
+ if (!ids.length) return svg;
+ const suffix = `-c${++applied}`;
+ // References come as `id="…"`, `href="#…"` and `url(#…)`; the lookahead keeps
+ // an id that extends this one untouched.
+ for (const id of ids.sort((a, b) => b.length - a.length)) {
+ svg = svg.replace(
+ new RegExp(`(\\bid="|#|url\\(#)${escapeRegExp(id)}(?="|\\))`, "g"),
+ (_m, prefix: string) => `${prefix}${id}${suffix}`,
+ );
+ }
+ return svg;
+}
+
function show(block: HTMLElement, result: Result | null, stale?: Node) {
block.querySelector(`:scope > .${OUTPUT_CLASS}`)?.remove();
const out = document.createElement("div");
out.className = OUTPUT_CLASS;
if (result && "svg" in result) {
- out.innerHTML = result.svg;
+ out.innerHTML = reid(result.svg);
block.setAttribute(RENDERED_ATTR, "ok");
} else if (result) {
out.setAttribute("role", "alert");