Render mermaid diagrams

Mermaid code blocks showed up as code. Mermaid is loaded lazily, and
diagrams are redrawn when the app theme changes. DOMPurify's config
moves from a global `setConfig` to each call site, because the global
one stripped mermaid's SVG output.

Co-authored-by: Rūdolfs Ošiņš <rudolfs@osins.org>
This commit is contained in:
Brandon Oxendine
2026-10-07 16:56:58 +02:00
committed by Rūdolfs Ošiņš
co-authored by Rūdolfs Ošiņš
parent ab8300e09a
commit dc1a067396
9 changed files with 1541 additions and 10 deletions
+1189 -3
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -85,6 +85,7 @@
"marked-katex-extension": "^5.1.10",
"marked-linkify-it": "^4.0.0",
"md5": "^2.3.0",
"mermaid": "^11.16.0",
"playwright": "1.61.1",
"prettier": "^3.9.5",
"prettier-plugin-svelte": "^4.1.1",
+3 -1
View File
@@ -2,6 +2,8 @@
import dompurify from "dompurify";
import escape from "lodash/escape";
import { sanitizeConfig } from "@app/lib/markdown";
interface Props {
content: string;
fontSize?: "tiny" | "small" | "regular" | "medium" | "large";
@@ -32,5 +34,5 @@
class:txt-body-l-regular={fontSize === "regular"}
class:txt-body-m-regular={fontSize === "small"}
class:txt-body-s-regular={fontSize === "tiny"}>
{@html dompurify.sanitize(formatInlineTitle(escape(content)))}
{@html dompurify.sanitize(formatInlineTitle(escape(content)), sanitizeConfig)}
</span>
+53
View File
@@ -23,6 +23,7 @@
toggleTask,
} from "@app/lib/markdown";
import { parseEntityHref } from "@app/lib/mentions";
import { renderMermaidBlocks } from "@app/lib/mermaid";
import { isOid } from "@app/lib/radUri";
import { enhanceRepoImages, RepoImages } from "@app/lib/repoImages";
import { scrollIntoView, twemoji } from "@app/lib/utils";
@@ -30,6 +31,7 @@
import Icon from "@app/components/Icon.svelte";
import Mention from "@app/components/Mention.svelte";
import ReferenceLink from "@app/components/ReferenceLink.svelte";
import { theme } from "@app/components/ThemeSwitch.svelte";
interface Props {
rid?: string;
@@ -79,6 +81,18 @@
const images = new RepoImages();
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- imperative warning→icon lookup, never rendered reactively
const diagramWarningIcons = new Map<HTMLElement, ReturnType<typeof mount>>();
function unmountDiagramWarningIcons(all: boolean) {
for (const [warning, icon] of diagramWarningIcons) {
if (all || !warning.isConnected) {
void unmount(icon);
diagramWarningIcons.delete(warning);
}
}
}
let destroyed = false;
$effect(() => () => {
@@ -88,6 +102,7 @@
}
embedPreviews.clear();
images.dispose();
unmountDiagramWarningIcons(true);
});
// The revision and path of a document can change while its text stays the
@@ -104,6 +119,27 @@
});
});
$effect(() => {
const diagramTheme = $theme;
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
content;
void tick().then(async () => {
if (!container) {
return;
}
unmountDiagramWarningIcons(false);
await renderMermaidBlocks(container, diagramTheme, {
decorateWarning: warning => {
diagramWarningIcons.set(
warning,
mount(Icon, { target: warning, props: { name: "warning" } }),
);
},
});
});
});
function createEmbedPreview(
mimeType: string | undefined,
url: string,
@@ -741,6 +777,23 @@
.markdown :global(.alert-caution) {
--alert-color: var(--color-feedback-error-text);
}
.markdown :global(.mermaid-diagram) {
margin: 1rem 0;
text-align: center;
}
.markdown :global(.mermaid-diagram svg) {
max-width: 100%;
height: auto;
}
.markdown :global(.mermaid-error) {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-feedback-warning-text);
font: var(--txt-body-s-regular);
margin: 1rem 0 0.25rem;
}
</style>
{#if frontMatter && frontMatter.length > 0}
+3 -3
View File
@@ -4,9 +4,9 @@ import dompurify from "dompurify";
import { invoke } from "@app/lib/invoke";
// `markdown.ts` pins the shared DOMPurify singleton to the markdown allowlist
// via `setConfig`, which makes per-call configs no-ops. AsciiDoc output needs a
// wider allowlist, so it gets its own instance.
// AsciiDoc output needs a wider allowlist than markdown's, and `setConfig`
// on the shared DOMPurify singleton would leak into every other consumer of
// it, so it gets its own instance.
const purify = dompurify(window);
purify.setConfig({
+11 -2
View File
@@ -1,3 +1,4 @@
import type { Config } from "dompurify";
import type {
MarkedExtension,
RendererExtension,
@@ -26,7 +27,14 @@ import { bareReferenceStart, matchBareReference } from "@app/lib/mentions";
const allowedUriSchemes =
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix|rad|did):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/i;
dompurify.setConfig({
/**
* DOMPurify configuration for sanitizing markdown-derived HTML. Pass this as
* the second argument to `dompurify.sanitize` at each call site instead of
* setting it globally. A global config leaks into every other consumer of the
* DOMPurify singleton, including mermaid's internal strict-mode sanitization,
* which would then strip the SVG output of valid diagrams.
*/
export const sanitizeConfig: Config = {
/* eslint-disable @typescript-eslint/naming-convention */
ALLOWED_URI_REGEXP: allowedUriSchemes,
ALLOWED_ATTR: [
@@ -78,7 +86,7 @@ dompurify.setConfig({
"ul",
],
/* eslint-enable @typescript-eslint/naming-convention */
});
};
// Converts self closing anchor tags into empty anchor tags, to avoid erratic wrapping behaviour
// e.g. <a name="test"/> -> <a name="test"></a>
@@ -247,6 +255,7 @@ export function renderMarkdown(content: string, breaks = false): string {
renderer: new Renderer(),
breaks,
}) as string,
sanitizeConfig,
);
}
+122
View File
@@ -0,0 +1,122 @@
export type DiagramTheme = "dark" | "light";
export type RenderDiagram = (
source: string,
theme: DiagramTheme,
) => Promise<string>;
// Mermaid is heavy and `initialize` mutates a process wide singleton, so load
// it lazily and share the one instance across every document.
let mermaidPromise: Promise<typeof import("mermaid").default> | undefined;
let mermaidTheme: DiagramTheme | undefined;
async function loadMermaid(theme: DiagramTheme) {
mermaidPromise ??= import("mermaid").then(
({ default: mermaid }) => mermaid,
error => {
// Forget the failed import, so that the next diagram tries again.
mermaidPromise = undefined;
throw error;
},
);
const mermaid = await mermaidPromise;
// `initialize` replaces the entire site config, so it is passed in full and
// only re-run when the app theme changed since the last diagram.
if (mermaidTheme !== theme) {
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
// Render our own warning instead of letting mermaid append its
// "Syntax error" graphic to the document.
suppressErrorRendering: true,
theme: theme === "dark" ? "dark" : "default",
});
mermaidTheme = theme;
}
return mermaid;
}
export const renderDiagram: RenderDiagram = async (source, theme) => {
const mermaid = await loadMermaid(theme);
const { svg } = await mermaid.render(
`mermaid-${crypto.randomUUID()}`,
source,
);
return svg;
};
/**
* Replaces the mermaid code blocks in `container` with diagrams, and redraws
* the diagrams drawn for another theme. A block that can't be drawn stays as
* code, under a warning that `decorateWarning` can add to.
*/
export async function renderMermaidBlocks(
container: HTMLElement,
theme: DiagramTheme,
{
render = renderDiagram,
decorateWarning,
}: {
render?: RenderDiagram;
decorateWarning?: (warning: HTMLElement) => void;
} = {},
) {
for (const code of container.querySelectorAll("pre code.language-mermaid")) {
if (code.closest(".mermaid-block")) {
continue;
}
const pre = code.parentElement as HTMLElement;
const target = pre.closest(".pre-wrapper") ?? pre;
const block = document.createElement("div");
block.classList.add("mermaid-block");
block.dataset.source = code.textContent ?? "";
target.replaceWith(block);
block.appendChild(target);
}
const pending: Promise<void>[] = [];
for (const block of container.querySelectorAll<HTMLElement>(
".mermaid-block",
)) {
if (block.dataset.theme === theme) {
continue;
}
block.dataset.theme = theme;
pending.push(renderBlock(block, theme, render, decorateWarning));
}
await Promise.all(pending);
}
async function renderBlock(
block: HTMLElement,
theme: DiagramTheme,
render: RenderDiagram,
decorateWarning: ((warning: HTMLElement) => void) | undefined,
) {
try {
const svg = await render(block.dataset.source ?? "", theme);
// Another theme may have been asked for while this one was drawn.
if (block.dataset.theme !== theme) {
return;
}
const diagram = document.createElement("div");
diagram.classList.add("mermaid-diagram");
diagram.innerHTML = svg;
block.replaceChildren(diagram);
} catch (error) {
console.warn("Not able to render mermaid diagram", error);
// A diagram drawn for the previous theme is still better than code.
if (block.querySelector(".mermaid-diagram, .mermaid-error")) {
return;
}
const warning = document.createElement("div");
warning.classList.add("mermaid-error");
decorateWarning?.(warning);
const message = document.createElement("span");
message.textContent = "Couldn't render diagram";
warning.appendChild(message);
block.prepend(warning);
}
}
+23 -1
View File
@@ -65,6 +65,10 @@ async function createRichRepo(peer: RadiclePeer) {
"",
"![Screenshot](./images/shot.png)",
"",
"```mermaid",
"graph TD; Start-->Finish",
"```",
"",
].join("\n"),
);
await Fs.writeFile(
@@ -77,7 +81,7 @@ async function createRichRepo(peer: RadiclePeer) {
return { rid };
}
test("render alerts and repository images in a readme", async ({
test("render alerts, diagrams and repository images in a readme", async ({
page,
peer,
}) => {
@@ -88,6 +92,8 @@ test("render alerts and repository images in a readme", async ({
await expect(
readme.locator(".alert-note").getByText("Read the guide first."),
).toBeVisible();
await expect(readme.locator(".mermaid-diagram svg")).toBeVisible();
await expect(readme.locator(".mermaid-diagram")).toContainText("Finish");
const logoImage = readme.getByRole("img", { name: "Logo" });
await expect(logoImage).toHaveAttribute("src", /^blob:/);
@@ -106,6 +112,22 @@ test("render alerts and repository images in a readme", async ({
.toBe(32);
});
test("redraw a diagram when the theme changes", async ({ page, peer }) => {
const { rid } = await createRichRepo(peer);
await page.goto(`/repos/${rid}/home`);
const diagram = page.locator(".mermaid-diagram svg");
await expect(diagram).toBeVisible();
const darkId = await diagram.getAttribute("id");
await page.getByRole("button", { name: "Settings" }).click();
await page.getByRole("button", { name: "Light", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
await expect(diagram).not.toHaveAttribute("id", darkId ?? "");
await expect(page.locator(".mermaid-diagram")).toHaveCount(1);
});
test("show repository images in an AsciiDoc file", async ({ page, peer }) => {
const { rid } = await createRichRepo(peer);
await page.goto(`/repos/${rid}/home`);
+136
View File
@@ -0,0 +1,136 @@
import { describe, expect, test, vi } from "vitest";
import { renderMermaidBlocks } from "@app/lib/mermaid";
function documentWith(html: string): HTMLElement {
const container = document.createElement("div");
container.innerHTML = html;
return container;
}
const diagram =
'<pre><code class="language-mermaid">graph TD; A--&gt;B</code></pre>';
function fakeRender() {
return vi.fn(
async (source: string, theme: string) =>
`<svg data-theme="${theme}">${source}</svg>`,
);
}
describe("renderMermaidBlocks", () => {
test("replaces a mermaid block with its diagram", async () => {
const render = fakeRender();
const container = documentWith(
`${diagram}<pre><code class="language-rust">fn main() {}</code></pre>`,
);
await renderMermaidBlocks(container, "dark", { render });
expect(render).toHaveBeenCalledExactlyOnceWith("graph TD; A-->B", "dark");
expect(container.querySelector(".mermaid-diagram svg")).not.toBeNull();
expect(container.querySelector("code.language-mermaid")).toBeNull();
expect(container.querySelector("code.language-rust")).not.toBeNull();
});
test("replaces the copy button wrapper along with the code", async () => {
const container = documentWith(
`<div class="pre-wrapper">${diagram}<radicle-clipboard></radicle-clipboard></div>`,
);
await renderMermaidBlocks(container, "dark", { render: fakeRender() });
expect(container.querySelector(".pre-wrapper")).toBeNull();
expect(container.querySelector(".mermaid-diagram")).not.toBeNull();
});
test("redraws diagrams only when the theme changes", async () => {
const render = fakeRender();
const container = documentWith(diagram);
await renderMermaidBlocks(container, "dark", { render });
await renderMermaidBlocks(container, "dark", { render });
await renderMermaidBlocks(container, "light", { render });
expect(render.mock.calls.map(([, theme]) => theme)).toEqual([
"dark",
"light",
]);
expect(render.mock.calls[1][0]).toBe("graph TD; A-->B");
expect(container.querySelectorAll(".mermaid-diagram")).toHaveLength(1);
expect(container.querySelector("svg")?.getAttribute("data-theme")).toBe(
"light",
);
});
test("keeps a diagram that fails to draw as code under one warning", async () => {
const render = vi.fn().mockRejectedValue(new Error("Parse error"));
const decorateWarning = vi.fn();
const container = documentWith(diagram);
vi.spyOn(console, "warn").mockReturnValue(undefined);
await renderMermaidBlocks(container, "dark", { render, decorateWarning });
await renderMermaidBlocks(container, "light", { render, decorateWarning });
expect(container.querySelector("code.language-mermaid")).not.toBeNull();
expect(container.querySelectorAll(".mermaid-error")).toHaveLength(1);
expect(decorateWarning).toHaveBeenCalledOnce();
});
test("keeps the last diagram when redrawing it fails", async () => {
const render = vi
.fn()
.mockResolvedValueOnce("<svg></svg>")
.mockRejectedValue(new Error("Not able to load mermaid"));
const container = documentWith(diagram);
vi.spyOn(console, "warn").mockReturnValue(undefined);
await renderMermaidBlocks(container, "dark", { render });
await renderMermaidBlocks(container, "light", { render });
expect(container.querySelector(".mermaid-diagram svg")).not.toBeNull();
expect(container.querySelector(".mermaid-error")).toBeNull();
});
test("a theme asked for later wins over one still drawing", async () => {
let finishDark!: (svg: string) => void;
const render = vi
.fn()
.mockReturnValueOnce(new Promise(resolve => (finishDark = resolve)))
.mockResolvedValueOnce('<svg data-theme="light"></svg>');
const container = documentWith(diagram);
const dark = renderMermaidBlocks(container, "dark", { render });
await renderMermaidBlocks(container, "light", { render });
finishDark('<svg data-theme="dark"></svg>');
await dark;
expect(container.querySelector("svg")?.getAttribute("data-theme")).toBe(
"light",
);
});
});
describe("renderDiagram", () => {
test("tries loading mermaid again after a failed load", async () => {
vi.resetModules();
vi.doMock("mermaid", () => {
throw new Error("Failed to fetch dynamically imported module");
});
const { renderDiagram } = await import("@app/lib/mermaid");
await expect(renderDiagram("graph TD; A-->B", "dark")).rejects.toThrow();
vi.doMock("mermaid", () => ({
default: {
initialize: vi.fn(),
render: vi.fn(async () => ({ svg: "<svg></svg>" })),
},
}));
await expect(renderDiagram("graph TD; A-->B", "dark")).resolves.toBe(
"<svg></svg>",
);
vi.doUnmock("mermaid");
});
});