Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(markdown): render mermaid diagrams (#1888)
Prince Pala28312c0b490
diff --git a/packages/views/editor/content-editor.css b/packages/views/editor/content-editor.cssindex 6380da8f40..86f467e883 100644--- a/packages/views/editor/content-editor.css+++ b/packages/views/editor/content-editor.css@@ -200,6 +200,34 @@line-height: 1.6;}+/* Mermaid diagrams */+.rich-text-editor .mermaid-diagram {+ background: var(--muted);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ margin: 0.75rem 0;+ overflow-x: auto;+ padding: 1rem;+}++.rich-text-editor .mermaid-diagram-frame {+ border: 0;+ display: block;+ height: auto;+ width: 100%;+}++.rich-text-editor .mermaid-diagram-loading,+.rich-text-editor .mermaid-diagram-error p {+ color: var(--muted-foreground);+ font-size: 0.8125rem;+ margin: 0;+}++.rich-text-editor .mermaid-diagram-error pre {+ margin-bottom: 0;+}+/* Syntax highlighting — lowlight (hljs) */.rich-text-editor .hljs-keyword,.rich-text-editor .hljs-selector-tag,@@ -529,4 +557,3 @@max-width: min(360px, calc(100vw - 2rem));white-space: nowrap;}-diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex 523d4a81aa..cd36c9f066 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -1,5 +1,5 @@-import { describe, expect, it, vi } from "vitest";-import { render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { render, waitFor } from "@testing-library/react";vi.mock("@multica/core/paths", () => ({useWorkspacePaths: () => ({@@ -32,8 +32,34 @@ vi.mock("./utils/link-handler", () => ({isMentionHref: (href?: string) => Boolean(href?.startsWith("mention://")),}));+vi.mock("mermaid", () => ({+ default: {+ initialize: vi.fn(),+ render: vi.fn().mockResolvedValue({+ svg: '<svg viewBox="0 0 123 45"><g><text>mock diagram</text></g></svg>',+ }),+ },+}));++Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {+ value: () => ({+ fillStyle: "#000",+ fillRect: vi.fn(),+ getImageData: () => ({ data: new Uint8ClampedArray([12, 34, 56, 255]) }),+ }),+});++import mermaid from "mermaid";import { ReadonlyContent } from "./readonly-content";+beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.restoreAllMocks();+});+describe("ReadonlyContent math rendering", () => {it("renders inline and block LaTeX with KaTeX markup", () => {const { container } = render(@@ -72,3 +98,44 @@ describe("ReadonlyContent line breaks", () => {expect(container.querySelectorAll("p").length).toBeGreaterThanOrEqual(2);});});++describe("ReadonlyContent Mermaid rendering", () => {+ it("renders mermaid code fences in a sized sandbox iframe with legacy rgb colors", async () => {+ const originalGetComputedStyle = window.getComputedStyle;+ vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElt) => {+ if (element instanceof HTMLElement && element.style.color.startsWith("var(")) {+ return { color: "oklch(60% 0.2 120)" } as CSSStyleDeclaration;+ }+ return originalGetComputedStyle.call(window, element, pseudoElt);+ });++ const { container } = render(+ <ReadonlyContent+ content={["```mermaid", "graph LR", " A[Start] --> B[Done]", "```"].join("\n")}+ />,+ );++ expect(container.querySelector(".mermaid-diagram")).not.toBeNull();+ expect(container.querySelector("pre code.language-mermaid")).toBeNull();++ await waitFor(() => {+ const iframe = container.querySelector<HTMLIFrameElement>(".mermaid-diagram-frame");+ expect(iframe).not.toBeNull();+ expect(iframe?.getAttribute("sandbox")).toBe("");+ expect(iframe?.srcdoc).toContain("mock diagram");+ expect(iframe?.style.width).toBe("123px");+ expect(iframe?.style.height).toBe("45px");+ });++ expect(mermaid.initialize).toHaveBeenCalledWith(+ expect.objectContaining({+ themeVariables: expect.objectContaining({+ lineColor: "rgb(12, 34, 56)",+ primaryBorderColor: "rgb(12, 34, 56)",+ primaryColor: "rgb(12, 34, 56)",+ primaryTextColor: "rgb(12, 34, 56)",+ }),+ }),+ );+ });+});diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsxindex e1b9f6047a..bb62747e60 100644--- a/packages/views/editor/readonly-content.tsx+++ b/packages/views/editor/readonly-content.tsx@@ -16,7 +16,7 @@* - Rendering mentions with the same IssueMentionCard component and .mention class*/-import { useMemo, useRef, useState } from "react";+import { isValidElement, useEffect, useId, useMemo, useRef, useState } from "react";import ReactMarkdown, {defaultUrlTransform,type Components,@@ -49,6 +49,134 @@ import "./content-editor.css";const lowlight = createLowlight(common);+type MermaidAPI = typeof import("mermaid").default;++type MermaidLayout = {+ width?: number;+ height?: number;+};++let mermaidPromise: Promise<MermaidAPI> | null = null;++function getMermaid(): Promise<MermaidAPI> {+ mermaidPromise ??= import("mermaid").then(({ default: mermaid }) => mermaid);++ return mermaidPromise;+}++function toLegacyColor(color: string, fallback: string, ownerDocument: Document): string {+ const canvas = ownerDocument.createElement("canvas");+ canvas.width = 1;+ canvas.height = 1;+ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) return fallback;++ // Mermaid's color parser only supports legacy color syntax. Canvas can parse+ // modern CSS Color 4 values such as oklch(), then getImageData gives concrete+ // 8-bit sRGB bytes that Mermaid can consume safely.+ context.fillStyle = "#000";+ context.fillStyle = color || fallback;+ context.fillRect(0, 0, 1, 1);+ const [red, green, blue] = context.getImageData(0, 0, 1, 1).data;++ return `rgb(${red}, ${green}, ${blue})`;+}++function resolveCssColor(+ host: HTMLElement,+ variableName: string,+ fallback: string,+): string {+ const probe = host.ownerDocument.createElement("span");+ probe.style.color = `var(${variableName})`;+ probe.style.display = "none";+ host.appendChild(probe);+ const color = getComputedStyle(probe).color;+ probe.remove();++ return toLegacyColor(color || fallback, fallback, host.ownerDocument);+}++function getMermaidThemeVariables(host: HTMLElement | null) {+ if (!host) {+ return {+ primaryColor: "rgb(245, 245, 245)",+ primaryBorderColor: "rgb(59, 130, 246)",+ primaryTextColor: "rgb(17, 24, 39)",+ lineColor: "rgb(107, 114, 128)",+ fontFamily: "inherit",+ };+ }++ return {+ primaryColor: resolveCssColor(host, "--muted", "rgb(245, 245, 245)"),+ primaryBorderColor: resolveCssColor(host, "--primary", "rgb(59, 130, 246)"),+ primaryTextColor: resolveCssColor(host, "--foreground", "rgb(17, 24, 39)"),+ lineColor: resolveCssColor(host, "--muted-foreground", "rgb(107, 114, 128)"),+ fontFamily: "inherit",+ };+}++function getSandboxCssVariables(host: HTMLElement | null): string {+ const styles = host ? getComputedStyle(host) : null;+ return ["--muted", "--primary", "--foreground", "--muted-foreground"]+ .map((name) => `${name}: ${styles?.getPropertyValue(name).trim() || "initial"};`)+ .join(" ");+}++function getMermaidLayout(svg: string): MermaidLayout {+ const viewBoxMatch = svg.match(+ /viewBox=["']\s*([\d.-]+)\s+([\d.-]+)\s+([\d.-]+)\s+([\d.-]+)\s*["']/i,+ );+ const [, , , widthValue, heightValue] = viewBoxMatch ?? [];+ const width = widthValue ? Number.parseFloat(widthValue) : undefined;+ const height = heightValue ? Number.parseFloat(heightValue) : undefined;++ if (width && height && width > 0 && height > 0) {+ return {+ width: Math.ceil(width),+ height: Math.ceil(height),+ };+ }++ return {};+}++function buildSandboxedMermaidDocument(svg: string, host: HTMLElement | null): string {+ const cssVariables = getSandboxCssVariables(host);++ return `<!doctype html><html><head><style>:root { ${cssVariables} } body { margin: 0; display: flex; justify-content: center; background: transparent; } svg { max-width: 100%; height: auto; }</style></head><body>${svg}</body></html>`;+}++function useThemeVersion() {+ const [themeVersion, setThemeVersion] = useState(0);++ useEffect(() => {+ const bumpThemeVersion = () => setThemeVersion((version) => version + 1);+ const observer = new MutationObserver(bumpThemeVersion);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "style", "data-theme"],+ });+ if (document.body) {+ observer.observe(document.body, {+ attributes: true,+ attributeFilter: ["class", "style", "data-theme"],+ });+ }++ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");+ mediaQuery.addEventListener("change", bumpThemeVersion);++ return () => {+ observer.disconnect();+ mediaQuery.removeEventListener("change", bumpThemeVersion);+ };+ }, []);++ return themeVersion;+}+// ---------------------------------------------------------------------------// Sanitization schema — extends GitHub defaults to allow file-card data attrs// ---------------------------------------------------------------------------@@ -158,6 +286,85 @@ function ReadonlyLink({);}+function MermaidDiagram({ chart }: { chart: string }) {+ const reactId = useId();+ const containerRef = useRef<HTMLDivElement>(null);+ const diagramId = useMemo(+ () => `mermaid-${reactId.replace(/[^a-zA-Z0-9_-]/g, "")}`,+ [reactId],+ );+ const themeVersion = useThemeVersion();+ const [sandboxedDocument, setSandboxedDocument] = useState<string | null>(null);+ const [layout, setLayout] = useState<MermaidLayout>({});+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ async function renderDiagram() {+ try {+ setError(null);+ setSandboxedDocument(null);+ setLayout({});+ const mermaid = await getMermaid();+ mermaid.initialize({+ startOnLoad: false,+ securityLevel: "strict",+ theme: "base",+ themeVariables: getMermaidThemeVariables(containerRef.current),+ });+ const { svg: renderedSvg } = await mermaid.render(diagramId, chart);+ if (!cancelled) {+ setLayout(getMermaidLayout(renderedSvg));+ setSandboxedDocument(+ buildSandboxedMermaidDocument(renderedSvg, containerRef.current),+ );+ }+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : "Failed to render Mermaid diagram");+ }+ }+ }++ void renderDiagram();++ return () => {+ cancelled = true;+ };+ }, [chart, diagramId, themeVersion]);++ if (error) {+ return (+ <div ref={containerRef} className="mermaid-diagram mermaid-diagram-error">+ <p>Unable to render Mermaid diagram.</p>+ <pre>+ <code>{chart}</code>+ </pre>+ </div>+ );+ }++ return (+ <div ref={containerRef} className="mermaid-diagram" aria-label="Mermaid diagram">+ {sandboxedDocument ? (+ <iframe+ className="mermaid-diagram-frame"+ sandbox=""+ srcDoc={sandboxedDocument}+ style={{+ height: layout.height ? `${layout.height}px` : undefined,+ width: layout.width ? `${layout.width}px` : undefined,+ }}+ title="Mermaid diagram"+ />+ ) : (+ <div className="mermaid-diagram-loading">Rendering diagram…</div>+ )}+ </div>+ );+}+const components: Partial<Components> = {// Links — route mention:// to mention components, others show preview carda: ReadonlyLink,@@ -251,6 +458,10 @@ const components: Partial<Components> = {node?.position &&node.position.start.line !== node.position.end.line;+ if (isBlock && lang === "mermaid") {+ return <MermaidDiagram chart={String(children).replace(/\n$/, "")} />;+ }+if (!isBlock && !lang) {// Inline code — CSS handles styling via .rich-text-editor codereturn <code {...props}>{children}</code>;@@ -279,7 +490,12 @@ const components: Partial<Components> = {},// Pre — pass through (CSS handles styling via .rich-text-editor pre)- pre: ({ children }) => <pre>{children}</pre>,+ pre: ({ children }) => {+ if (isValidElement(children) && children.type === MermaidDiagram) {+ return <>{children}</>;+ }+ return <pre>{children}</pre>;+ },};// ---------------------------------------------------------------------------diff --git a/packages/views/package.json b/packages/views/package.jsonindex 159fd0623e..a5d5d2e882 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -47,7 +47,6 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@floating-ui/dom": "^1.7.6",-"@multica/core": "workspace:*","@multica/ui": "workspace:*","@tiptap/core": "^3.22.1",@@ -73,6 +72,7 @@"hast-util-to-html": "^4.0.1","katex": "catalog:","lowlight": "^3.3.0",+ "mermaid": "catalog:","react-markdown": "^10.1.0","react-resizable-panels": "^4.7.5","recharts": "3.8.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9b6e32d963..c2093ae613 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -45,6 +45,9 @@ catalogs:lucide-react:specifier: ^1.0.1version: 1.0.1+ mermaid:+ specifier: ^11.14.0+ version: 11.14.0posthog-js:specifier: ^1.176.1version: 1.369.3@@ -739,6 +742,9 @@ importers:lucide-react:specifier: 'catalog:'version: 1.0.1([email protected])+ mermaid:+ specifier: 'catalog:'+ version: 11.14.0react:specifier: 'catalog:'version: 19.2.3diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex a3327bef39..08efb358aa 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -28,6 +28,7 @@ catalog:katex: "^0.16.45"rehype-katex: "^7.0.1"remark-math: "^6.0.0"+ mermaid: "^11.14.0"# Iconslucide-react: "^1.0.1"