Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7766: feat(editor): fit Mermaid previews to show the whole diagram, with inline zoom (#8898)

Jiayuan Zhangf76cde8e609e
diff --git a/packages/views/editor/hooks/use-drag-to-scroll.ts b/packages/views/editor/hooks/use-drag-to-scroll.ts
index 0b6f71b308..5a10dc7e81 100644
--- a/packages/views/editor/hooks/use-drag-to-scroll.ts
+++ b/packages/views/editor/hooks/use-drag-to-scroll.ts
@@ -1,10 +1,10 @@
"use client";
/**
- * Tap-vs-drag gesture for a horizontally scrollable element.
+ * Tap-vs-drag gesture for a scrollable element.
*
* Solves a specific collision: the inline Mermaid diagram opens the viewer when
- * clicked, but a wide diagram also invites dragging to see the rest of it.
+ * clicked, but a zoomed-in diagram also invites dragging to see the rest of it.
* Without an intent test every drag ends in a `click` and the viewer opens on
* top of the user, which reads as the diagram fighting back.
*
@@ -14,10 +14,10 @@
* surprise the user by opening on release either.
*
* Touch is the one pointer type the browser already drag-scrolls by itself on
- * an `overflow-x: auto` element, and whose vertical drags belong to the page —
- * so touch is left alone here and only watched for intent, with the browser
- * announcing its takeover via `pointercancel`. Every other pointer (mouse, pen)
- * has no native drag-to-scroll and is panned below.
+ * an `overflow: auto` element, handing the drag on to the page once the
+ * element runs out of room — so touch is left alone here and only watched for
+ * intent, with the browser announcing its takeover via `pointercancel`. Every
+ * other pointer (mouse, pen) has no native drag-to-scroll and is panned below.
*/
import { useCallback, useRef, type PointerEvent as ReactPointerEvent } from "react";
@@ -32,6 +32,7 @@ interface GestureState {
startX: number;
startY: number;
startScrollLeft: number;
+ startScrollTop: number;
dragged: boolean;
}
@@ -68,6 +69,7 @@ export function useDragToScroll({
startX: event.clientX,
startY: event.clientY,
startScrollLeft: event.currentTarget.scrollLeft,
+ startScrollTop: event.currentTarget.scrollTop,
dragged: false,
};
}, []);
@@ -90,12 +92,13 @@ export function useDragToScroll({
}
}
- // Touch scrolls itself; driving scrollLeft here too would double the speed.
+ // Touch scrolls itself; driving the scroll here too would double the speed.
if (isTouch(gesture)) return;
// Assigning past either end is clamped by the browser, so an unscrollable
// diagram simply stays put — the gesture is still a drag, and still
// suppresses the tap below.
event.currentTarget.scrollLeft = gesture.startScrollLeft - deltaX;
+ event.currentTarget.scrollTop = gesture.startScrollTop - deltaY;
}, []);
const onPointerUp = useCallback(
diff --git a/packages/views/editor/hooks/use-inline-zoom.ts b/packages/views/editor/hooks/use-inline-zoom.ts
new file mode 100644
index 0000000000..df32f236b6
--- /dev/null
+++ b/packages/views/editor/hooks/use-inline-zoom.ts
@@ -0,0 +1,184 @@
+"use client";
+
+/**
+ * Zoom for the inline Mermaid preview (MUL-7766).
+ *
+ * The preview opens fitted — the whole diagram inside the column's width and
+ * at most `maxHeight` tall — so a reader browsing a thread sees every diagram
+ * in full without opening anything. The zoom buttons step from there, and the
+ * preview box scrolls natively once the diagram outgrows it.
+ *
+ * Deliberately not `useZoomCanvas`. That hook owns the wheel and every touch
+ * gesture, which is right for a full-screen viewer and wrong inside a
+ * document, where those belong to the page. It also zooms with a transform;
+ * here the diagram is an SVG that fills its iframe, so zooming is just a
+ * bigger iframe, and every step is redrawn as vectors instead of scaling a
+ * bitmap.
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
+import {
+ MAX_SCALE,
+ ZOOM_STEP,
+ computeFitScale,
+ type Point,
+ type Size,
+} from "../utils/zoom-transform";
+
+export interface InlineZoom {
+ scale: number;
+ /** Drawn size of the diagram at `scale`, in whole pixels. */
+ size: Size;
+ /** True while the preview shows the whole diagram, following the column's width. */
+ fitted: boolean;
+ /** Whole-percent zoom for the readout. */
+ zoomPercent: number;
+ canZoomIn: boolean;
+ canZoomOut: boolean;
+ zoomIn: () => void;
+ zoomOut: () => void;
+ fit: () => void;
+}
+
+/**
+ * One zoom step from `scale`, landing on 100% on the way past it: natural size
+ * is the one stop worth hitting exactly, and 1.2 steps from an arbitrary fit
+ * scale would otherwise skip over it.
+ */
+export function stepScale(scale: number, factor: number): number {
+ const next = scale * factor;
+ if ((scale < 1 && next > 1) || (scale > 1 && next < 1)) return 1;
+ return next;
+}
+
+export function useInlineZoom({
+ content,
+ maxHeight,
+ scrollRef,
+}: {
+ /** Natural size of the diagram, or null before it has rendered. */
+ content: Size | null;
+ /** Tallest the fitted diagram may be drawn. */
+ maxHeight: number;
+ /** The preview's scroll box: measured for the fit, scrolled to keep zoom centered. */
+ scrollRef: RefObject<HTMLElement | null>;
+}): InlineZoom {
+ const [availableWidth, setAvailableWidth] = useState(0);
+ // null = fitted. Stored apart from the scale so a fitted preview keeps
+ // fitting as the column resizes, instead of freezing at the old width's fit.
+ const [zoom, setZoom] = useState<number | null>(null);
+ const hasContent = content !== null;
+
+ // Layout effect: the first painted frame must already be fitted, not a
+ // natural-size diagram that then snaps down.
+ useLayoutEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+
+ // offsetWidth, not clientWidth: it includes a vertical scrollbar, so the
+ // fit does not change when zooming in makes one appear. Zero means hidden
+ // (a frame showing its source view), not a zero-wide column; keep the
+ // last real width rather than refit against nothing.
+ const measure = () => {
+ const width = element.offsetWidth;
+ if (width > 0) setAvailableWidth(width);
+ };
+ measure();
+
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [scrollRef, hasContent]);
+
+ // A different diagram starts fitted again; a re-render of the same one (a
+ // theme switch) keeps the reader's zoom.
+ useEffect(() => {
+ setZoom(null);
+ }, [content?.width, content?.height]);
+
+ const natural = content ?? { width: 1, height: 1 };
+ const fitScale = computeFitScale(natural, {
+ // Unmeasured (no layout, e.g. jsdom) constrains the height only.
+ width: availableWidth > 0 ? availableWidth : natural.width,
+ height: maxHeight,
+ });
+ const scale = zoom === null ? fitScale : Math.max(fitScale, zoom);
+ const fitted = scale <= fitScale + 0.001;
+ const size: Size = {
+ width: Math.max(1, Math.floor(natural.width * scale)),
+ height: Math.max(1, Math.floor(natural.height * scale)),
+ };
+
+ // Latest-value ref so the button callbacks stay stable.
+ const stateRef = useRef({ scale, fitScale, size });
+ stateRef.current = { scale, fitScale, size };
+ // Content point at the center of the box, carried across a zoom step.
+ const anchorRef = useRef<Point | null>(null);
+
+ const zoomTo = useCallback(
+ (next: number | null) => {
+ const element = scrollRef.current;
+ const { scale: current, fitScale: fitAt, size: currentSize } = stateRef.current;
+ const target = next === null ? fitAt : Math.max(fitAt, next);
+ // Only a real step carries an anchor: one left behind by a no-op would
+ // fire on the next resize and scroll the box on its own.
+ if (element && Math.abs(target - current) > 0.0005) {
+ // A diagram narrower than the box is centered by auto margins.
+ const offsetX = Math.max(0, (element.clientWidth - currentSize.width) / 2);
+ anchorRef.current = {
+ x: (element.scrollLeft + element.clientWidth / 2 - offsetX) / current,
+ y: (element.scrollTop + element.clientHeight / 2) / current,
+ };
+ }
+ setZoom(next);
+ },
+ [scrollRef],
+ );
+
+ // Buttons zoom about the middle of what is on screen, so a step never
+ // throws the reader back to the diagram's top-left corner.
+ useLayoutEffect(() => {
+ const anchor = anchorRef.current;
+ anchorRef.current = null;
+ const element = scrollRef.current;
+ if (!anchor || !element) return;
+
+ const offsetX = Math.max(0, (element.clientWidth - size.width) / 2);
+ element.scrollLeft = anchor.x * scale + offsetX - element.clientWidth / 2;
+ element.scrollTop = anchor.y * scale - element.clientHeight / 2;
+ }, [scrollRef, scale, size.width]);
+
+ const zoomIn = useCallback(() => {
+ const { scale: current } = stateRef.current;
+ zoomTo(Math.min(MAX_SCALE, stepScale(current, ZOOM_STEP)));
+ }, [zoomTo]);
+
+ const zoomOut = useCallback(() => {
+ const { scale: current, fitScale: fitAt } = stateRef.current;
+ const next = stepScale(current, 1 / ZOOM_STEP);
+ // Nothing below the fit: it already shows the whole diagram.
+ zoomTo(next <= fitAt + 0.001 ? null : next);
+ }, [zoomTo]);
+
+ const fit = useCallback(() => zoomTo(null), [zoomTo]);
+
+ return {
+ scale,
+ size,
+ fitted,
+ zoomPercent: Math.round(scale * 100),
+ canZoomIn: scale < MAX_SCALE - 0.001,
+ canZoomOut: !fitted,
+ zoomIn,
+ zoomOut,
+ fit,
+ };
+}
diff --git a/packages/views/editor/mermaid-diagram.test.tsx b/packages/views/editor/mermaid-diagram.test.tsx
index 24e61b682d..5164d36be4 100644
--- a/packages/views/editor/mermaid-diagram.test.tsx
+++ b/packages/views/editor/mermaid-diagram.test.tsx
@@ -82,6 +82,19 @@ async function openViewer() {
await screen.findByRole("application");
}
+/** jsdom has no layout; give the preview a column to fit against. */
+function stubColumnWidth(width: number) {
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(width);
+}
+
+async function findFrame(): Promise<HTMLIFrameElement> {
+ return waitFor(() => {
+ const found = document.querySelector<HTMLIFrameElement>(".mermaid-diagram-frame");
+ expect(found).not.toBeNull();
+ return found!;
+ });
+}
+
async function findScroller(): Promise<HTMLElement> {
return waitFor(() => {
const found = document.querySelector<HTMLElement>(".mermaid-diagram-scroll");
@@ -268,21 +281,100 @@ describe("MermaidDiagram rendering config", () => {
});
describe("MermaidDiagram inline presentation", () => {
- it("renders the diagram in an empty sandbox at its natural size", async () => {
+ it("renders the diagram in an empty sandbox, fitted to the column", async () => {
+ stubColumnWidth(800);
render(<MermaidDiagram chart={CHART} />);
expect(screen.getByLabelText("Mermaid diagram")).toBeInTheDocument();
- const frame = await waitFor(() => {
- const found = document.querySelector<HTMLIFrameElement>(".mermaid-diagram-frame");
- expect(found).not.toBeNull();
- return found!;
- });
+ const frame = await findFrame();
expect(frame.getAttribute("sandbox")).toBe("");
+ // 1000x500 in an 800px column: the whole diagram, at 80%.
+ expect(frame.style.width).toBe("800px");
+ expect(frame.style.height).toBe("400px");
+ expect(frame.title).toBe("Mermaid diagram");
+ // The SVG fills the iframe, so resizing the iframe is what zooms it.
+ expect(frame.srcdoc).toContain("width: 100%; height: 100%; max-width: none !important");
+ expect(screen.getByText("80%")).toBeInTheDocument();
+ });
+
+ it("fits a tall diagram to the preview's height cap", async () => {
+ mermaidRenderMock.mockResolvedValue({
+ svg: '<svg viewBox="0 0 400 1792"><g><text>tall</text></g></svg>',
+ });
+ stubColumnWidth(800);
+ render(<MermaidDiagram chart={CHART} />);
+
+ const frame = await findFrame();
+
+ // Capped at 448px tall, so the preview never grows past the frame's
+ // collapse threshold and always shows the whole diagram.
+ expect(frame.style.width).toBe("100px");
+ expect(frame.style.height).toBe("448px");
+ });
+
+ it("never upscales a diagram that already fits", async () => {
+ mermaidRenderMock.mockResolvedValue({
+ svg: '<svg viewBox="0 0 300 120"><g><text>small</text></g></svg>',
+ });
+ stubColumnWidth(800);
+ render(<MermaidDiagram chart={CHART} />);
+
+ const frame = await findFrame();
+
+ expect(frame.style.width).toBe("300px");
+ expect(frame.style.height).toBe("120px");
+ expect(screen.getByRole("button", { name: "Zoom out" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Fit to view" })).toBeDisabled();
+ });
+
+ it("zooms in and back out from the fit with the preview's buttons", async () => {
+ stubColumnWidth(800);
+ render(<MermaidDiagram chart={CHART} />);
+ const frame = await findFrame();
+
+ const zoomIn = screen.getByRole("button", { name: "Zoom in" });
+ const zoomOut = screen.getByRole("button", { name: "Zoom out" });
+ const fit = screen.getByRole("button", { name: "Fit to view" });
+ expect(zoomOut).toBeDisabled();
+ expect(fit).toBeDisabled();
+
+ fireEvent.click(zoomIn);
+ // 80% x 1.2 = 96%.
+ expect(frame.style.width).toBe("960px");
+ expect(screen.getByText("96%")).toBeInTheDocument();
+ expect(zoomOut).toBeEnabled();
+ expect(fit).toBeEnabled();
+
+ // The next step would pass 100%, so it lands there exactly.
+ fireEvent.click(zoomIn);
expect(frame.style.width).toBe("1000px");
expect(frame.style.height).toBe("500px");
- expect(frame.title).toBe("Mermaid diagram");
+
+ fireEvent.click(zoomOut);
+ expect(frame.style.width).toBe("833px");
+
+ // Stepping below the fit stops at the fit: it already shows everything.
+ fireEvent.click(zoomOut);
+ expect(frame.style.width).toBe("800px");
+ expect(zoomOut).toBeDisabled();
+
+ fireEvent.click(zoomIn);
+ fireEvent.click(zoomIn);
+ fireEvent.click(fit);
+ expect(frame.style.width).toBe("800px");
+ expect(fit).toBeDisabled();
+ });
+
+ it("does not open the viewer when a zoom button is pressed", async () => {
+ stubColumnWidth(800);
+ render(<MermaidDiagram chart={CHART} />);
+ await findFrame();
+
+ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
+
+ await expectViewerStaysClosed();
});
it("copies the source straight from the inline toolbar", async () => {
@@ -369,6 +461,23 @@ describe("MermaidDiagram inline tap vs drag", () => {
expect(scroll.scrollLeft).toBe(40);
});
+ it("pans vertically too, for a zoomed-in diagram taller than the preview", async () => {
+ const scroll = await setupScroller();
+ let scrollTop = 0;
+ Object.defineProperty(scroll, "scrollTop", {
+ configurable: true,
+ get: () => scrollTop,
+ set: (value: number) => {
+ scrollTop = Math.min(Math.max(value, 0), 2000);
+ },
+ });
+
+ fireEvent.pointerDown(scroll, { pointerId: 1, clientX: 300, clientY: 300 });
+ fireEvent.pointerMove(scroll, { pointerId: 1, clientX: 300, clientY: 180 });
+
+ expect(scroll.scrollTop).toBe(120);
+ });
+
it("does not open the viewer after dragging a diagram that cannot scroll", async () => {
// Nothing to pan, so the drag has no visible effect — releasing must still
// not open the viewer, or the gesture reads as an accidental jump.
diff --git a/packages/views/editor/mermaid-diagram.tsx b/packages/views/editor/mermaid-diagram.tsx
index 443e500397..40cfb65b0a 100644
--- a/packages/views/editor/mermaid-diagram.tsx
+++ b/packages/views/editor/mermaid-diagram.tsx
@@ -18,6 +18,11 @@
* 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
@@ -34,11 +39,12 @@ import {
type CSSProperties,
type RefObject,
} from "react";
-import { Check, Copy, Maximize2 } from "lucide-react";
+import { Check, Copy, Frame, Maximize2, Minus, Plus } from "lucide-react";
import { copyText } from "@multica/ui/lib/clipboard";
import { useT } from "../i18n";
-import { DynamicBlockSkeleton } from "./dynamic-block";
+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";
@@ -179,7 +185,16 @@ const MERMAID_LAYOUT_CACHE_PREFIX = "multica:mermaid:layout:";
const DIAGRAM_PADDING_Y_PX = 32;
/**
- * Height a framed diagram's body will take: the drawn height of this exact
+ * 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
@@ -193,10 +208,26 @@ const DIAGRAM_PADDING_Y_PX = 32;
*/
export function framedMermaidBodyHeightPx(chart: string): number {
const cached = readCachedLayout(chart);
- return cached ? cached.height + DIAGRAM_PADDING_Y_PX : MERMAID_SKELETON_HEIGHT_PX;
+ 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;
}
-function readCachedLayout(chart: string): Size | null {
+/**
+ * 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(
@@ -210,7 +241,11 @@ function readCachedLayout(chart: string): Size | null {
parsed.width > 0 &&
parsed.height > 0
) {
- return { width: parsed.width, height: parsed.height };
+ const previewHeight =
+ typeof parsed.previewHeight === "number" && parsed.previewHeight > 0
+ ? parsed.previewHeight
+ : undefined;
+ return { width: parsed.width, height: parsed.height, previewHeight };
}
return null;
} catch {
@@ -218,13 +253,17 @@ function readCachedLayout(chart: string): Size | null {
}
}
-function writeCachedLayout(chart: string, layout: Size | null): void {
+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 }),
+ JSON.stringify({
+ width: layout.width,
+ height: layout.height,
+ previewHeight: layout.previewHeight,
+ }),
);
} catch {
// Quota exceeded or storage disabled — degrade silently; we still
@@ -232,12 +271,18 @@ function writeCachedLayout(chart: string, layout: Size | null): void {
}
}
+/**
+ * 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} } body { margin: 0; display: flex; justify-content: center; background: transparent; font-family: ${fontFamily}; } svg { max-width: 100%; height: auto; }</style></head><body>${svg}</body></html>`;
+ 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>`;
}
/**
@@ -304,20 +349,21 @@ function useHorizontalOverflow(ref: React.RefObject<HTMLElement | null>, deps: u
return edges;
}
-// Size the viewer falls back to when the SVG carries no usable viewBox. Mermaid
-// always emits one, but the viewer's transform math needs a concrete content
-// size, and rendering nothing at all would be a worse failure than an
-// approximate one.
-const VIEWER_FALLBACK_LAYOUT: Size = { width: 800, height: MERMAID_SKELETON_HEIGHT_PX };
+// 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, or null when the viewBox was unreadable. Sizes the inline iframe. */
- layout: Size | null;
- /** Always concrete — the viewer cannot lay out against an unknown size. */
- viewerLayout: Size;
+ /**
+ * Natural size. Always concrete — neither the inline zoom nor the viewer can
+ * lay out against an unknown size.
+ */
+ layout: Size;
exportBackground: string;
exportFontFamily: string;
}
@@ -355,7 +401,7 @@ export function MermaidDiagram({
// 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<Size | null>(() =>
+ const [skeletonLayout, setSkeletonLayout] = useState<CachedLayout | null>(() =>
readCachedLayout(chart),
);
const [error, setError] = useState<string | null>(null);
@@ -399,7 +445,7 @@ export function MermaidDiagram({
if (cancelled) return;
const measured = getMermaidLayout(renderedSvg);
- const viewerLayout = measured ?? VIEWER_FALLBACK_LAYOUT;
+ const layout = measured ?? FALLBACK_LAYOUT;
const exportStyle = getExportStyle(containerRef.current);
writeCachedLayout(chart, measured);
setSkeletonLayout(measured);
@@ -411,10 +457,9 @@ export function MermaidDiagram({
viewerDocument: buildViewerMermaidDocument(
renderedSvg,
containerRef.current,
- viewerLayout,
+ layout,
),
- layout: measured,
- viewerLayout,
+ layout,
exportBackground: exportStyle.background,
exportFontFamily: exportStyle.fontFamily,
});
@@ -437,7 +482,25 @@ export function MermaidDiagram({
onErrorChange?.(error);
}, [error, onErrorChange]);
- const overflow = useHorizontalOverflow(scrollRef, [rendered?.inlineDocument]);
+ 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 });
@@ -486,7 +549,7 @@ export function MermaidDiagram({
? undefined
: {
minHeight: skeletonLayout
- ? skeletonLayout.height + (frame ? DIAGRAM_PADDING_Y_PX : 0)
+ ? previewHeightOf(skeletonLayout) + (frame ? DIAGRAM_PADDING_Y_PX : 0)
: MERMAID_SKELETON_HEIGHT_PX,
};
@@ -512,6 +575,7 @@ export function MermaidDiagram({
<div
ref={scrollRef}
className="mermaid-diagram-scroll"
+ style={{ maxHeight: MERMAID_PREVIEW_MAX_HEIGHT_PX }}
{...dragToScroll}
>
<iframe
@@ -519,14 +583,19 @@ export function MermaidDiagram({
sandbox=""
srcDoc={rendered.inlineDocument}
style={{
- height: rendered.layout ? `${rendered.layout.height}px` : undefined,
- width: rendered.layout ? `${rendered.layout.width}px` : undefined,
+ 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} />
<button
type="button"
onClick={handleCopySource}
@@ -552,7 +621,7 @@ export function MermaidDiagram({
chart={chart}
svg={rendered.svg}
viewerDocument={rendered.viewerDocument}
- layout={rendered.viewerLayout}
+ layout={rendered.layout}
exportBackground={rendered.exportBackground}
exportFontFamily={rendered.exportFontFamily}
finalFocusRef={frame ? frame.finalFocusRef : expandButtonRef}
@@ -566,3 +635,46 @@ export function MermaidDiagram({
</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">
+ <button
+ type="button"
+ onClick={zoom.zoomOut}
+ disabled={!zoom.canZoomOut}
+ title={t(($) => $.canvas.zoom_out)}
+ aria-label={t(($) => $.canvas.zoom_out)}
+ >
+ <Minus className="size-3.5" />
+ </button>
+ {/* 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>
+ <button
+ type="button"
+ onClick={zoom.zoomIn}
+ disabled={!zoom.canZoomIn}
+ title={t(($) => $.canvas.zoom_in)}
+ aria-label={t(($) => $.canvas.zoom_in)}
+ >
+ <Plus className="size-3.5" />
+ </button>
+ <button
+ type="button"
+ onClick={zoom.fit}
+ disabled={zoom.fitted}
+ title={t(($) => $.canvas.zoom_fit)}
+ aria-label={t(($) => $.canvas.zoom_fit)}
+ >
+ <Frame className="size-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/packages/views/editor/styles/mermaid.css b/packages/views/editor/styles/mermaid.css
index 1b9d2f3855..038df77332 100644
--- a/packages/views/editor/styles/mermaid.css
+++ b/packages/views/editor/styles/mermaid.css
@@ -14,10 +14,13 @@
position: relative;
}
+/* Fitted, the diagram fits this box and nothing scrolls. Zoomed in, it
+ scrolls both ways inside it; the height cap (inline style, from
+ MERMAID_PREVIEW_MAX_HEIGHT_PX) keeps a zoomed diagram from pushing the
+ rest of the page down. */
.rich-text-editor .mermaid-diagram-scroll {
display: flex;
- overflow-x: auto;
- overflow-y: hidden;
+ overflow: auto;
cursor: zoom-in;
/* Dragging a diagram would otherwise start a native text selection: the
iframe is a replaced element, so the whole diagram box gets painted with
@@ -30,13 +33,12 @@
.rich-text-editor .mermaid-diagram-frame {
border: 0;
display: block;
- /* Natural width, never shrunk to the column: a wide diagram must keep a
- readable font size and scroll sideways instead of being squashed until the
- labels are unreadable. `flex: none` stops the flex parent from shrinking
- it; a `max-width` here would defeat the scroll entirely. */
+ /* The size is the zoom (MUL-7766): the component sets it, and the flex
+ parent must not shrink it back to the column, or zooming in would squash
+ the diagram instead of scrolling it. */
flex: none;
- /* Small diagrams sit centered at natural size; only oversized ones scroll.
- Upscaling a small diagram to fill the column would just coarsen it.
+ /* Diagrams narrower than the column sit centered; the fit never upscales
+ past natural size, which would only coarsen a small diagram.
Centered with auto margins, not `justify-content: center` on the
scroller: that pushes an oversized diagram's left part past the scroll
origin, where it is cut off and cannot be scrolled to (MUL-7733). Auto
@@ -185,6 +187,92 @@
background: color-mix(in srgb, white 15%, transparent);
}
+/* Zoom pill — bottom-right, over a framed diagram, in the frame's light
+ chrome. The standalone preview puts the same controls in its dark toolbar
+ instead (below). */
+.rich-text-editor .mermaid-diagram-zoom {
+ position: absolute;
+ right: 0.5rem;
+ bottom: 0.5rem;
+ display: flex;
+ align-items: center;
+ gap: 1px;
+ padding: 0.125rem;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ box-shadow: var(--surface-shadow);
+ transition: opacity 0.15s;
+ z-index: 2;
+}
+
+/* Same reveal rule as the toolbar: on hover where hovering exists, always on
+ touch, and whenever a button inside holds focus. */
+@media (hover: hover) {
+ .rich-text-editor .mermaid-diagram-zoom {
+ opacity: 0;
+ }
+
+ .rich-text-editor .mermaid-diagram:hover .mermaid-diagram-zoom,
+ .rich-text-editor .mermaid-diagram-zoom:focus-within {
+ opacity: 1;
+ }
+}
+
+.rich-text-editor .mermaid-diagram-zoom button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 1.75rem;
+ height: 1.75rem;
+ border-radius: calc(var(--radius) - 2px);
+ color: var(--muted-foreground);
+ transition: background 0.15s, color 0.15s;
+}
+
+.rich-text-editor .mermaid-diagram-zoom button:hover {
+ background: var(--secondary);
+ color: var(--foreground);
+}
+
+.rich-text-editor .mermaid-diagram-zoom button:disabled {
+ opacity: 0.4;
+ pointer-events: none;
+}
+
+/* Fixed width so the pill doesn't jitter as the digits change. */
+.rich-text-editor .mermaid-diagram-zoom span {
+ width: 2.75rem;
+ color: var(--muted-foreground);
+ font-size: var(--text-caption);
+ font-variant-numeric: tabular-nums;
+ text-align: center;
+ user-select: none;
+}
+
+/* Inside the standalone toolbar: a plain group, separated from copy/expand
+ by a hairline. The toolbar owns the pill, the reveal and the hover. */
+.rich-text-editor .mermaid-diagram-toolbar .mermaid-diagram-zoom {
+ position: static;
+ padding: 0 0.25rem 0 0;
+ margin-right: 0.25rem;
+ background: none;
+ border: 0;
+ border-right: 1px solid color-mix(in srgb, white 20%, transparent);
+ border-radius: 0;
+ box-shadow: none;
+ opacity: 1;
+}
+
+.rich-text-editor .mermaid-diagram-toolbar .mermaid-diagram-zoom button,
+.rich-text-editor .mermaid-diagram-toolbar .mermaid-diagram-zoom span {
+ color: white;
+}
+
+.rich-text-editor .mermaid-diagram-toolbar .mermaid-diagram-zoom button:hover {
+ background: color-mix(in srgb, white 15%, transparent);
+}
+
/* Full-screen viewer frame. The canvas that pans/zooms it is shared with the
image preview and lives in ./zoom-canvas.css. */
.mermaid-viewer-frame {