Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
"use client";
/**
* MermaidDiagram — sandboxed Mermaid diagram renderer.
*
* Extracted from `readonly-content.tsx` so the Tiptap CodeBlock NodeView
* (`code-block-view.tsx`) can render the same component when a code block's
* language is `mermaid`. Previously Mermaid only worked in read-only
* markdown surfaces (comment cards) — issue descriptions, which always
* stay in the Tiptap editor, never rendered diagrams.
*
* Theme variables are detected from the host's CSS custom properties so the
* diagram colors match light/dark mode. The SVG is rendered inside a
* sandboxed iframe to keep Mermaid's runtime stylesheet from leaking into
* the page.
*
* This component owns the inline presentation; the full-screen experience
* lives in `MermaidViewer`. Both read the same rendered SVG, so what you
* export or blow up is always what you were looking at.
*
* The inline preview opens fitted — the whole diagram, within the column's
* width and MERMAID_PREVIEW_MAX_HEIGHT_PX — with zoom buttons to step in
* from there (MUL-7766). Browsing a thread reads every diagram in full; the
* viewer is for when the detail matters.
*
* Standalone (the editable code block's preview) it draws its own box,
* toolbar and error state. Inside a DynamicBlock (`frame`, MUL-7649) the frame
* owns all of that: this renders only the diagram, and hands the viewer's open
* state and any render error up to the frame.
*/
import {
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
type CSSProperties,
type RefObject,
} from "react";
import { Frame, Maximize2, Minus, Plus } from "@multica/ui/icons";
import { CopyCheckIcon } from "@multica/ui/components/common/copy-check-icon";
import { copyText } from "@multica/ui/lib/clipboard";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { useT } from "../i18n";
import { DYNAMIC_BLOCK_COLLAPSE_AT_PX, DynamicBlockSkeleton } from "./dynamic-block";
import { useDragToScroll } from "./hooks/use-drag-to-scroll";
import { useInlineZoom, type InlineZoom } from "./hooks/use-inline-zoom";
import { useThemeVersion } from "./hooks/use-theme-version";
import { MermaidViewer } from "./mermaid-viewer";
import { hashSource } from "./utils/source-hash";
import type { Size } from "./utils/zoom-transform";
type MermaidAPI = typeof import("mermaid").default;
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);
}
const FALLBACK_BACKGROUND = "rgb(255, 255, 255)";
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;
const variables = ["--muted", "--primary", "--foreground", "--muted-foreground"]
.map((name) => `${name}: ${styles?.getPropertyValue(name).trim() || "initial"};`)
.join(" ");
// The diagram is drawn in the app's colors, so its document declares the
// app's scheme too. Without it a light document inside a dark page is
// painted on an opaque white canvas, under a diagram colored for dark.
const declared = styles?.colorScheme ?? "";
const scheme = /\bdark\b/.test(declared) && !/\blight\b/.test(declared) ? "dark" : "light";
return `${variables} color-scheme: ${scheme};`;
}
/**
* The host's font for the sandbox body. Mermaid measures label text in this
* page (its font is `inherit`), so the sandbox has to draw with the same font
* or the labels no longer fit the boxes laid out for them.
*/
function getSandboxFontFamily(host: HTMLElement | null): string {
const fontFamily = host ? getComputedStyle(host).fontFamily.trim() : "";
return fontFamily && !/[<>{};]/.test(fontFamily) ? fontFamily : "sans-serif";
}
/**
* Concrete colors for export. An exported file has no host page to inherit
* from, so `var(--muted)` / `font-family: inherit` would resolve to nothing.
*/
function getExportStyle(host: HTMLElement | null): {
background: string;
fontFamily: string;
} {
if (!host) {
return { background: FALLBACK_BACKGROUND, fontFamily: "sans-serif" };
}
return {
background: resolveCssColor(host, "--muted", FALLBACK_BACKGROUND),
fontFamily: getComputedStyle(host).fontFamily || "sans-serif",
};
}
function getMermaidLayout(svg: string): Size | null {
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 null;
}
// Default skeleton height while Mermaid loads + renders for the first time
// in this session. Picked to absorb most issue-detail diagrams without
// excessive empty space; web.dev's CLS guidance recommends reserving any
// such space upfront so async content doesn't shift surrounding layout.
export const MERMAID_SKELETON_HEIGHT_PX = 280;
const MERMAID_LAYOUT_CACHE_PREFIX = "multica:mermaid:layout:";
// `.mermaid-diagram` padding, top plus bottom (1rem each).
const DIAGRAM_PADDING_Y_PX = 32;
/**
* Tallest the inline preview draws a fitted diagram: the frame's collapse
* threshold less the diagram's padding, so a fitted diagram is always whole
* and never folds behind "Show all". Zooming in past it scrolls inside the
* same box rather than growing the page.
*/
export const MERMAID_PREVIEW_MAX_HEIGHT_PX =
DYNAMIC_BLOCK_COLLAPSE_AT_PX - DIAGRAM_PADDING_Y_PX;
/**
* Height a framed diagram's body will take: the fitted height of this exact
* chart plus the container's padding when it already rendered in this
* session, otherwise the skeleton default. Exported so the near-viewport lazy
* shell (rich-content/lazy-rich-block.tsx) reserves the SAME space this
* component would, instead of maintaining a second guess at the size.
*
* NOT safe to call during render: it reads sessionStorage, which does not exist
* on the server, so the value differs between the server frame and the browser's
* hydration frame whenever the cache is warm. Callers must use the skeleton
* default for the first frame and call this from an effect (see
* useReservedHeightPx in rich-content/rich-code-block.tsx).
*/
export function framedMermaidBodyHeightPx(chart: string): number {
const cached = readCachedLayout(chart);
return cached ? previewHeightOf(cached) + DIAGRAM_PADDING_Y_PX : MERMAID_SKELETON_HEIGHT_PX;
}
interface CachedLayout extends Size {
/**
* Height the fitted preview drew at, which depends on the column's width
* and so can only be recorded after the preview has been measured.
*/
previewHeight?: number;
}
/**
* The fitted preview's height, or the best guess without a recorded one: the
* height cap, which assumes the diagram is not wider than its column.
*/
function previewHeightOf(layout: CachedLayout): number {
return layout.previewHeight ?? Math.min(layout.height, MERMAID_PREVIEW_MAX_HEIGHT_PX);
}
function readCachedLayout(chart: string): CachedLayout | null {
if (typeof window === "undefined") return null;
try {
const raw = window.sessionStorage.getItem(
MERMAID_LAYOUT_CACHE_PREFIX + hashSource(chart),
);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (
typeof parsed?.width === "number" &&
typeof parsed?.height === "number" &&
parsed.width > 0 &&
parsed.height > 0
) {
const previewHeight =
typeof parsed.previewHeight === "number" && parsed.previewHeight > 0
? parsed.previewHeight
: undefined;
return { width: parsed.width, height: parsed.height, previewHeight };
}
return null;
} catch {
return null;
}
}
function writeCachedLayout(chart: string, layout: CachedLayout | null): void {
if (typeof window === "undefined") return;
if (!layout) return;
try {
window.sessionStorage.setItem(
MERMAID_LAYOUT_CACHE_PREFIX + hashSource(chart),
JSON.stringify({
width: layout.width,
height: layout.height,
previewHeight: layout.previewHeight,
}),
);
} catch {
// Quota exceeded or storage disabled — degrade silently; we still
// render correctly, just without the zero-shift optimisation.
}
}
/**
* Inline document: the SVG fills the iframe, so the preview zooms by resizing
* the iframe and the diagram is redrawn as vectors at every step. Mermaid
* writes an inline `max-width` onto the SVG, which only `!important` outranks;
* left in place it would stop the diagram from growing past natural size.
*/
function buildSandboxedMermaidDocument(svg: string, host: HTMLElement | null): string {
const cssVariables = getSandboxCssVariables(host);
const fontFamily = getSandboxFontFamily(host);
return `<!doctype html><html><head><style>:root { ${cssVariables} } html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; font-family: ${fontFamily}; } svg { display: block; width: 100%; height: 100%; max-width: none !important; }</style></head><body>${svg}</body></html>`;
}
/**
* Viewer document: the diagram is drawn at natural size and the host applies
* zoom as a CSS transform on the wrapper. Clamping to `max-width: 100%` here
* (as the inline document does) would fight the transform and cap zoom at
* whatever the iframe happens to measure.
*/
function buildViewerMermaidDocument(
svg: string,
host: HTMLElement | null,
layout: Size,
): string {
const cssVariables = getSandboxCssVariables(host);
const fontFamily = getSandboxFontFamily(host);
return `<!doctype html><html><head><style>:root { ${cssVariables} } html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; font-family: ${fontFamily}; } svg { display: block; width: ${layout.width}px; height: ${layout.height}px; max-width: none; }</style></head><body>${svg}</body></html>`;
}
/**
* Tracks which horizontal edges of a scroll container have content beyond
* them, so CSS can fade those edges as an affordance that the diagram
* continues off-screen.
*/
function useHorizontalOverflow(ref: React.RefObject<HTMLElement | null>, deps: unknown[]) {
const [edges, setEdges] = useState<{ start: boolean; end: boolean }>({
start: false,
end: false,
});
useEffect(() => {
const element = ref.current;
if (!element) return;
const measure = () => {
const { scrollLeft, scrollWidth, clientWidth } = element;
const maxScroll = scrollWidth - clientWidth;
setEdges((previous) => {
// 1px tolerance: fractional layout widths otherwise leave a fade
// permanently stuck on at rest.
const start = scrollLeft > 1;
const end = scrollLeft < maxScroll - 1;
return previous.start === start && previous.end === end
? previous
: { start, end };
});
};
measure();
element.addEventListener("scroll", measure, { passive: true });
const observer =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
observer?.observe(element);
return () => {
element.removeEventListener("scroll", measure);
observer?.disconnect();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref, ...deps]);
return edges;
}
// Size to fall back to when the SVG carries no usable viewBox. Mermaid always
// emits one, but the inline zoom and the viewer's transform math both need a
// concrete content size, and rendering nothing at all would be a worse failure
// than an approximate one.
const FALLBACK_LAYOUT: Size = { width: 800, height: MERMAID_SKELETON_HEIGHT_PX };
interface RenderedDiagram {
svg: string;
inlineDocument: string;
viewerDocument: string;
/**
* Natural size. Always concrete — neither the inline zoom nor the viewer can
* lay out against an unknown size.
*/
layout: Size;
exportBackground: string;
exportFontFamily: string;
}
/** What a DynamicBlock needs from the diagram it frames. */
export interface MermaidFrameBinding {
viewerOpen: boolean;
onViewerOpenChange: (open: boolean) => void;
onErrorChange: (error: string | null) => void;
/** The frame's fullscreen button; focus returns there when the viewer closes. */
finalFocusRef: RefObject<HTMLButtonElement | null>;
}
export function MermaidDiagram({
chart,
frame,
}: {
chart: string;
frame?: MermaidFrameBinding;
}) {
const { t } = useT("editor");
const reactId = useId();
const containerRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const expandButtonRef = useRef<HTMLButtonElement>(null);
const diagramId = useMemo(
() => `mermaid-${reactId.replace(/[^a-zA-Z0-9_-]/g, "")}`,
[reactId],
);
const themeVersion = useThemeVersion();
// One object rather than parallel states: a half-applied re-render (new SVG,
// old layout) would size the viewer's iframe against the wrong diagram.
const [rendered, setRendered] = useState<RenderedDiagram | null>(null);
// Lazy initial value: if we've rendered this exact chart already in the
// current session, the cached layout lets us reserve correct space on the
// very first paint — eliminating the 0px → real-height shift that breaks
// deep-link scroll positioning and ambient reading position.
const [skeletonLayout, setSkeletonLayout] = useState<CachedLayout | null>(() =>
readCachedLayout(chart),
);
const [error, setError] = useState<string | null>(null);
const [ownViewerOpen, setOwnViewerOpen] = useState(false);
const viewerOpen = frame ? frame.viewerOpen : ownViewerOpen;
const setViewerOpen = frame ? frame.onViewerOpenChange : setOwnViewerOpen;
const onErrorChange = frame?.onErrorChange;
const [copied, setCopied] = useState(false);
useEffect(() => {
let cancelled = false;
async function renderDiagram() {
try {
setError(null);
// Deliberately NOT clearing `rendered` here. A theme switch re-runs
// this effect, and dropping to null would unmount the open viewer —
// closing it, and with it the user's zoom and position. Keeping the
// previous diagram on screen until the new one is ready also removes
// a flash of the loading skeleton on every theme toggle.
setSkeletonLayout(readCachedLayout(chart));
const mermaid = await getMermaid();
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
theme: "base",
// Render labels as SVG <text> instead of Mermaid's default HTML-in-
// <foreignObject>. Browsers do not rasterize foreignObject when an
// SVG is drawn through an <img> — verified in Chromium, the label
// paints zero pixels AND taints the canvas, so PNG export produces
// nothing at all. SVG text keeps the export self-contained.
htmlLabels: false,
themeVariables: getMermaidThemeVariables(containerRef.current),
// On invalid syntax, make render() throw instead of drawing Mermaid's
// built-in error graphic into the DOM. The catch below then shows our
// own compact error state — no orphaned error SVG, and no extra parse
// pass over valid charts.
suppressErrorRendering: true,
});
const { svg: renderedSvg } = await mermaid.render(diagramId, chart);
if (cancelled) return;
const measured = getMermaidLayout(renderedSvg);
const layout = measured ?? FALLBACK_LAYOUT;
const exportStyle = getExportStyle(containerRef.current);
writeCachedLayout(chart, measured);
setSkeletonLayout(measured);
setRendered({
svg: renderedSvg,
inlineDocument: buildSandboxedMermaidDocument(renderedSvg, containerRef.current),
// Same size the viewer lays out against, so the drawn SVG and the
// transform never disagree about how big the diagram is.
viewerDocument: buildViewerMermaidDocument(
renderedSvg,
containerRef.current,
layout,
),
layout,
exportBackground: exportStyle.background,
exportFontFamily: exportStyle.fontFamily,
});
} catch (err) {
if (!cancelled) {
setRendered(null);
setError(err instanceof Error ? err.message : "Failed to render Mermaid diagram");
}
}
}
void renderDiagram();
return () => {
cancelled = true;
};
}, [chart, diagramId, themeVersion]);
useEffect(() => {
onErrorChange?.(error);
}, [error, onErrorChange]);
const zoom = useInlineZoom({
content: rendered?.layout ?? null,
maxHeight: MERMAID_PREVIEW_MAX_HEIGHT_PX,
scrollRef,
});
// Record the fitted height once the column has been measured, so the next
// mount of this chart reserves exactly the space it will take. `rendered`
// is a dependency because the render effect rewrites the entry without it.
const fittedHeight = zoom.fitted ? zoom.size.height : null;
useEffect(() => {
if (!rendered || fittedHeight === null) return;
writeCachedLayout(chart, { ...rendered.layout, previewHeight: fittedHeight });
}, [chart, rendered, fittedHeight]);
const overflow = useHorizontalOverflow(scrollRef, [
rendered?.inlineDocument,
zoom.size.width,
]);
const openViewer = useCallback(() => setViewerOpen(true), [setViewerOpen]);
const dragToScroll = useDragToScroll({ onTap: openViewer });
const handleCopySource = useCallback(async () => {
if (await copyText(chart)) {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
}, [chart]);
if (error && frame) {
// The frame shows the error panel; keep the host so a theme switch can
// still resolve colors for the next attempt.
return <div ref={containerRef} className="mermaid-diagram" data-framed="" />;
}
if (error) {
return (
<div ref={containerRef} className="mermaid-diagram mermaid-diagram-error">
<div className="mermaid-diagram-error-head">
<p>{t(($) => $.mermaid.render_error)}</p>
<TooltipHint label={t(($) => $.mermaid.copy_source)}>
<button
type="button"
onClick={handleCopySource}
aria-label={t(($) => $.mermaid.copy_source)}
>
<CopyCheckIcon copied={copied} />
</button>
</TooltipHint>
</div>
{/* The parser message is the only clue about which line is wrong;
without it the fallback is just an unexplained code block. */}
<p className="mermaid-diagram-error-detail">{error}</p>
<pre>
<code>{chart}</code>
</pre>
</div>
);
}
// While the iframe is not yet ready, hold the container at the skeleton
// height (cached real height when available, fallback default otherwise).
// Once the iframe renders, drop the min-height — the iframe's own height
// drives layout. If the cache was right, this transition is zero-shift.
const containerStyle: CSSProperties | undefined = rendered
? undefined
: {
minHeight: skeletonLayout
? previewHeightOf(skeletonLayout) + (frame ? DIAGRAM_PADDING_Y_PX : 0)
: MERMAID_SKELETON_HEIGHT_PX,
};
return (
<div
ref={containerRef}
className="mermaid-diagram"
data-framed={frame ? "" : undefined}
aria-label={t(($) => $.mermaid.diagram_label)}
style={containerStyle}
data-overflow-start={overflow.start ? "" : undefined}
data-overflow-end={overflow.end ? "" : undefined}
>
{rendered ? (
<>
{/* The scroll container is a sibling of the toolbar, not its parent:
as an absolutely-positioned child of the scroller the toolbar used
to slide out of view with the diagram on wide charts. */}
{/* Tap opens the viewer, but a drag must not — see useDragToScroll.
The gesture drives this instead of `onClick`, because a click
fires at the end of a drag too and would reopen the viewer over
a user who was only trying to look at the rest of a wide chart. */}
<div
ref={scrollRef}
className="mermaid-diagram-scroll"
style={{ maxHeight: MERMAID_PREVIEW_MAX_HEIGHT_PX }}
{...dragToScroll}
>
<iframe
className="mermaid-diagram-frame"
sandbox=""
srcDoc={rendered.inlineDocument}
style={{
height: `${zoom.size.height}px`,
width: `${zoom.size.width}px`,
}}
title={t(($) => $.mermaid.diagram_label)}
/>
</div>
{/* Framed, the zoom floats on its own: the frame's title bar holds
the other actions. Standalone it joins the toolbar, because two
pills stacked on a short, wide diagram covered most of it. */}
{frame && <MermaidZoomControls zoom={zoom} />}
{!frame && (
<div className="mermaid-diagram-toolbar">
<MermaidZoomControls zoom={zoom} />
<TooltipHint label={t(($) => $.mermaid.copy_source)}>
<button
type="button"
onClick={handleCopySource}
aria-label={t(($) => $.mermaid.copy_source)}
>
<CopyCheckIcon copied={copied} />
</button>
</TooltipHint>
<TooltipHint label={t(($) => $.mermaid.open_viewer)}>
<button
ref={expandButtonRef}
type="button"
onClick={() => setViewerOpen(true)}
aria-label={t(($) => $.mermaid.open_viewer)}
>
<Maximize2 className="size-3.5" />
</button>
</TooltipHint>
</div>
)}
<MermaidViewer
open={viewerOpen}
onOpenChange={setViewerOpen}
chart={chart}
svg={rendered.svg}
viewerDocument={rendered.viewerDocument}
layout={rendered.layout}
exportBackground={rendered.exportBackground}
exportFontFamily={rendered.exportFontFamily}
finalFocusRef={frame ? frame.finalFocusRef : expandButtonRef}
/>
</>
) : frame ? (
<DynamicBlockSkeleton className="absolute inset-0 p-4" />
) : (
<div className="mermaid-diagram-loading">{t(($) => $.mermaid.rendering)}</div>
)}
</div>
);
}
/**
* The preview's zoom buttons. Siblings of the scroll box, never inside it, so
* pressing one is not a tap that opens the viewer.
*/
function MermaidZoomControls({ zoom }: { zoom: InlineZoom }) {
const { t } = useT("editor");
return (
<div className="mermaid-diagram-zoom">
<TooltipHint label={t(($) => $.canvas.zoom_out)}>
<button
type="button"
onClick={zoom.zoomOut}
disabled={!zoom.canZoomOut}
aria-label={t(($) => $.canvas.zoom_out)}
>
<Minus className="size-3.5" />
</button>
</TooltipHint>
{/* Not a live region: a fitted preview's percent follows the column's
width, and every diagram on the page would announce each resize. */}
<span>{zoom.zoomPercent}%</span>
<TooltipHint label={t(($) => $.canvas.zoom_in)}>
<button
type="button"
onClick={zoom.zoomIn}
disabled={!zoom.canZoomIn}
aria-label={t(($) => $.canvas.zoom_in)}
>
<Plus className="size-3.5" />
</button>
</TooltipHint>
<TooltipHint label={t(($) => $.canvas.zoom_fit)}>
<button
type="button"
onClick={zoom.fit}
disabled={zoom.fitted}
aria-label={t(($) => $.canvas.zoom_fit)}
>
<Frame className="size-3.5" />
</button>
</TooltipHint>
</div>
);
}