Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(editor): standard Mermaid viewer with pan/zoom, exports and a real dialog (MUL-4908) (#5564)
Naiyuan Qing17ee59ccc5b5
diff --git a/packages/views/editor/hooks/use-diagram-canvas.ts b/packages/views/editor/hooks/use-diagram-canvas.tsnew file mode 100644index 0000000000..15134226d7--- /dev/null+++ b/packages/views/editor/hooks/use-diagram-canvas.ts@@ -0,0 +1,389 @@+"use client";++/**+ * Pan/zoom controller for a diagram rendered inside an empty-sandbox iframe.+ *+ * The iframe cannot script itself, so every gesture is captured on the host+ * viewport element and applied as a CSS transform on the wrapper around it.+ * That inversion is also what keeps Escape working: the iframe is+ * `pointer-events: none`, so it never takes focus, and key events always stay+ * in the host document where the Dialog can hear them.+ *+ * Transform math lives in `../utils/diagram-transform`; this hook owns only+ * event plumbing and state.+ */++import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+ type KeyboardEvent as ReactKeyboardEvent,+} from "react";+import {+ MAX_SCALE,+ MIN_SCALE,+ PAN_STEP_PX,+ ZOOM_STEP,+ centerTransform,+ clampTransform,+ computeFitTransform,+ distanceBetween,+ midpointOf,+ panBy,+ wheelZoomFactor,+ zoomByAtCenter,+ zoomToAt,+ type DiagramTransform,+ type Point,+ type Size,+} from "../utils/diagram-transform";++interface UseDiagramCanvasOptions {+ /** Natural (unscaled) size of the diagram, or null while it is unknown. */+ content: Size | null;+}++export interface DiagramCanvasApi {+ /**+ * Callback ref for the viewport element. Deliberately not a RefObject: the+ * canvas is portaled by the Dialog and attaches in a later commit than this+ * hook's first layout effect, so an effect keyed on `[]` would find no+ * element, skip measuring, and never observe a resize — leaving the canvas+ * permanently unfitted and inert.+ */+ setViewportNode: (node: HTMLDivElement | null) => void;+ transform: DiagramTransform;+ /** Whole-percent zoom for the toolbar readout. */+ zoomPercent: number;+ canZoomIn: boolean;+ canZoomOut: boolean;+ isPanning: boolean;+ /**+ * True when the last change came from a discrete control (button/keyboard)+ * rather than direct manipulation, so the transform can be eased. Dragging+ * and wheel/pinch must track the input 1:1 and are never animated.+ */+ isAnimated: boolean;+ /** True when the view already matches the default fit — lets Reset disable itself. */+ isFitted: boolean;+ zoomIn: () => void;+ zoomOut: () => void;+ zoomToActualSize: () => void;+ fit: () => void;+ reset: () => void;+ handlePointerDown: (event: ReactPointerEvent<HTMLElement>) => void;+ handlePointerMove: (event: ReactPointerEvent<HTMLElement>) => void;+ handlePointerUp: (event: ReactPointerEvent<HTMLElement>) => void;+ handleKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void;+}++const IDENTITY: DiagramTransform = { scale: 1, x: 0, y: 0 };+const EMPTY_SIZE: Size = { width: 0, height: 0 };++function nearlyEqual(a: number, b: number): boolean {+ return Math.abs(a - b) < 0.5;+}++export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramCanvasApi {+ const [viewportNode, setViewportNode] = useState<HTMLDivElement | null>(null);+ const [viewport, setViewport] = useState<Size>(EMPTY_SIZE);+ const [transform, setTransform] = useState<DiagramTransform>(IDENTITY);+ const [isPanning, setIsPanning] = useState(false);+ const [isAnimated, setIsAnimated] = useState(false);++ // Fit is deferred until both sizes are known; until then any transform we+ // computed would be against a 0x0 viewport and would have to be thrown away.+ const hasFittedRef = useRef(false);+ const activePointersRef = useRef(new Map<number, Point>());+ const panOriginRef = useRef<{ pointer: Point; transform: DiagramTransform } | null>(null);+ const pinchOriginRef = useRef<{ distance: number; scale: number } | null>(null);++ const contentSize = content ?? EMPTY_SIZE;+ const hasContent = contentSize.width > 0 && contentSize.height > 0;+ const hasViewport = viewport.width > 0 && viewport.height > 0;+ const ready = hasContent && hasViewport;++ // Latest-value refs: the native wheel listener below is registered once with+ // `{ passive: false }` and would otherwise close over stale state.+ const stateRef = useRef({ transform, contentSize, viewport, ready });+ stateRef.current = { transform, contentSize, viewport, ready };++ useLayoutEffect(() => {+ const element = viewportNode;+ if (!element) return;++ const measure = () => {+ const rect = element.getBoundingClientRect();+ setViewport((previous) =>+ nearlyEqual(previous.width, rect.width) && nearlyEqual(previous.height, rect.height)+ ? previous+ : { width: rect.width, height: rect.height },+ );+ };++ measure();++ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(measure);+ observer.observe(element);++ return () => observer.disconnect();+ }, [viewportNode]);++ // Fit once, on first open. Deliberately not re-fitting on later viewport+ // changes: a theme switch re-renders the diagram at the same size, and+ // silently snapping the user's zoom back to fit would lose their place.+ useEffect(() => {+ if (!ready || hasFittedRef.current) return;+ hasFittedRef.current = true;+ setTransform(computeFitTransform(contentSize, viewport));+ }, [ready, contentSize, viewport]);++ // A genuinely different diagram (new natural size) starts fresh.+ const contentKey = `${contentSize.width}x${contentSize.height}`;+ const previousContentKeyRef = useRef(contentKey);+ useEffect(() => {+ if (previousContentKeyRef.current === contentKey) return;+ previousContentKeyRef.current = contentKey;+ if (!ready) return;+ setTransform(computeFitTransform(contentSize, viewport));+ }, [contentKey, ready, contentSize, viewport]);++ // Keep the diagram in view when the window/pane is resized under it.+ useEffect(() => {+ if (!ready) return;+ setTransform((current) => clampTransform(current, contentSize, viewport));+ }, [ready, contentSize, viewport]);++ const fit = useCallback(() => {+ const { contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;+ setIsAnimated(true);+ setTransform(computeFitTransform(c, v));+ }, []);++ const zoomToActualSize = useCallback(() => {+ const { contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;+ setIsAnimated(true);+ setTransform(clampTransform(centerTransform(c, v, 1), c, v));+ }, []);++ const zoomBy = useCallback((factor: number) => {+ const { transform: t, contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;+ setIsAnimated(true);+ setTransform(zoomByAtCenter(t, factor, c, v));+ }, []);++ const zoomIn = useCallback(() => zoomBy(ZOOM_STEP), [zoomBy]);+ const zoomOut = useCallback(() => zoomBy(1 / ZOOM_STEP), [zoomBy]);++ // Wheel must be a native non-passive listener: React routes `onWheel` through+ // a passive root listener, where preventDefault is ignored and the page would+ // scroll behind the dialog instead of the diagram zooming.+ useEffect(() => {+ const element = viewportNode;+ if (!element) return;++ const onWheel = (event: WheelEvent) => {+ const { transform: t, contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;+ event.preventDefault();+ setIsAnimated(false);++ const rect = element.getBoundingClientRect();+ const anchor: Point = {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ };+ const factor = wheelZoomFactor(event.deltaY, event.deltaMode);+ setTransform(zoomToAt(t, t.scale * factor, anchor, c, v));+ };++ element.addEventListener("wheel", onWheel, { passive: false });+ return () => element.removeEventListener("wheel", onWheel);+ }, [viewportNode]);++ const localPoint = useCallback(+ (event: ReactPointerEvent<HTMLElement>): Point => {+ const rect = viewportNode?.getBoundingClientRect();+ return {+ x: event.clientX - (rect?.left ?? 0),+ y: event.clientY - (rect?.top ?? 0),+ };+ },+ [viewportNode],+ );++ const handlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLElement>) => {+ if (!stateRef.current.ready) return;+ // Ignore secondary mouse buttons so right-click never starts a pan.+ if (event.pointerType === "mouse" && event.button !== 0) return;++ setIsAnimated(false);+ const point = localPoint(event);+ activePointersRef.current.set(event.pointerId, point);+ event.currentTarget.setPointerCapture?.(event.pointerId);++ const pointers = [...activePointersRef.current.values()];+ if (pointers.length === 1) {+ panOriginRef.current = { pointer: point, transform: stateRef.current.transform };+ pinchOriginRef.current = null;+ setIsPanning(true);+ return;+ }+ if (pointers.length === 2) {+ // Second finger down: hand off from pan to pinch.+ panOriginRef.current = null;+ pinchOriginRef.current = {+ distance: distanceBetween(pointers[0]!, pointers[1]!),+ scale: stateRef.current.transform.scale,+ };+ setIsPanning(false);+ }+ },+ [localPoint],+ );++ const handlePointerMove = useCallback(+ (event: ReactPointerEvent<HTMLElement>) => {+ if (!activePointersRef.current.has(event.pointerId)) return;+ const { contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;++ const point = localPoint(event);+ activePointersRef.current.set(event.pointerId, point);+ const pointers = [...activePointersRef.current.values()];++ if (pointers.length >= 2) {+ const pinchOrigin = pinchOriginRef.current;+ if (!pinchOrigin || pinchOrigin.distance <= 0) return;+ const [first, second] = pointers as [Point, Point];+ const nextScale =+ pinchOrigin.scale * (distanceBetween(first, second) / pinchOrigin.distance);+ setTransform((current) =>+ zoomToAt(current, nextScale, midpointOf(first, second), c, v),+ );+ return;+ }++ const panOrigin = panOriginRef.current;+ if (!panOrigin) return;+ setTransform(+ clampTransform(+ {+ scale: panOrigin.transform.scale,+ x: panOrigin.transform.x + (point.x - panOrigin.pointer.x),+ y: panOrigin.transform.y + (point.y - panOrigin.pointer.y),+ },+ c,+ v,+ ),+ );+ },+ [localPoint],+ );++ const handlePointerUp = useCallback((event: ReactPointerEvent<HTMLElement>) => {+ activePointersRef.current.delete(event.pointerId);+ event.currentTarget.releasePointerCapture?.(event.pointerId);++ const pointers = [...activePointersRef.current.values()];+ if (pointers.length === 1) {+ // Lifting one finger out of a pinch: resume panning from the survivor+ // rather than freezing until the user lifts and re-touches.+ panOriginRef.current = {+ pointer: pointers[0]!,+ transform: stateRef.current.transform,+ };+ pinchOriginRef.current = null;+ setIsPanning(true);+ return;+ }+ if (pointers.length === 0) {+ panOriginRef.current = null;+ pinchOriginRef.current = null;+ setIsPanning(false);+ }+ }, []);++ const handleKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLElement>) => {+ const { contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;++ // Escape is the Dialog's; never swallow it here.+ switch (event.key) {+ case "+":+ case "=":+ event.preventDefault();+ zoomIn();+ return;+ case "-":+ case "_":+ event.preventDefault();+ zoomOut();+ return;+ case "0":+ event.preventDefault();+ fit();+ return;+ case "ArrowLeft":+ case "ArrowRight":+ case "ArrowUp":+ case "ArrowDown": {+ event.preventDefault();+ setIsAnimated(true);+ const step = event.shiftKey ? PAN_STEP_PX * 3 : PAN_STEP_PX;+ const deltaX =+ event.key === "ArrowLeft" ? step : event.key === "ArrowRight" ? -step : 0;+ const deltaY =+ event.key === "ArrowUp" ? step : event.key === "ArrowDown" ? -step : 0;+ setTransform((current) => panBy(current, deltaX, deltaY, c, v));+ return;+ }+ default:+ }+ },+ [zoomIn, zoomOut, fit],+ );++ const isFitted = useMemo(() => {+ if (!ready) return true;+ const fitted = computeFitTransform(contentSize, viewport);+ return (+ Math.abs(fitted.scale - transform.scale) < 0.001 &&+ nearlyEqual(fitted.x, transform.x) &&+ nearlyEqual(fitted.y, transform.y)+ );+ }, [ready, contentSize, viewport, transform]);++ return {+ setViewportNode,+ transform,+ zoomPercent: Math.round(transform.scale * 100),+ canZoomIn: transform.scale < MAX_SCALE - 0.001,+ canZoomOut: transform.scale > MIN_SCALE + 0.001,+ isPanning,+ isAnimated,+ isFitted,+ zoomIn,+ zoomOut,+ zoomToActualSize,+ fit,+ reset: fit,+ handlePointerDown,+ handlePointerMove,+ handlePointerUp,+ handleKeyDown,+ };+}++export type { DiagramTransform, Size };+export { MIN_SCALE, MAX_SCALE };diff --git a/packages/views/editor/hooks/use-drag-to-scroll.ts b/packages/views/editor/hooks/use-drag-to-scroll.tsnew file mode 100644index 0000000000..0b6f71b308--- /dev/null+++ b/packages/views/editor/hooks/use-drag-to-scroll.ts@@ -0,0 +1,125 @@+"use client";++/**+ * Tap-vs-drag gesture for a horizontally 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.+ * 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.+ *+ * The rule (product decision, MUL-4908): once the pointer travels past a small+ * threshold the gesture is a drag for good, and releasing must not tap — even+ * when the element had no room to scroll, so an unscrollable diagram cannot+ * 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.+ */++import { useCallback, useRef, type PointerEvent as ReactPointerEvent } from "react";++// Kim specced 4–6px. 5 sits in the middle: past the jitter of a real click+// (including a shaky trackpad tap) while still well under a deliberate drag.+export const DRAG_THRESHOLD_PX = 5;++interface GestureState {+ pointerId: number;+ pointerType: string;+ startX: number;+ startY: number;+ startScrollLeft: number;+ dragged: boolean;+}++function isTouch(gesture: GestureState): boolean {+ return gesture.pointerType === "touch";+}++export interface DragToScrollHandlers {+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;+ onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;+ onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;+ onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;+}++/**+ * @param onTap Fired on release only when the gesture never became a drag.+ */+export function useDragToScroll({+ onTap,+}: {+ onTap: () => void;+}): DragToScrollHandlers {+ // A ref, not state: a drag updates on every pointermove, and re-rendering the+ // diagram (and its iframe) at that rate would stutter the pan it is driving.+ const gestureRef = useRef<GestureState | null>(null);++ const onPointerDown = useCallback((event: ReactPointerEvent<HTMLElement>) => {+ // Secondary buttons open the context menu; they are not a tap or a drag.+ if (event.pointerType === "mouse" && event.button !== 0) return;++ gestureRef.current = {+ pointerId: event.pointerId,+ pointerType: event.pointerType,+ startX: event.clientX,+ startY: event.clientY,+ startScrollLeft: event.currentTarget.scrollLeft,+ dragged: false,+ };+ }, []);++ const onPointerMove = useCallback((event: ReactPointerEvent<HTMLElement>) => {+ const gesture = gestureRef.current;+ if (!gesture || gesture.pointerId !== event.pointerId) return;++ const deltaX = event.clientX - gesture.startX;+ const deltaY = event.clientY - gesture.startY;++ if (!gesture.dragged) {+ if (Math.hypot(deltaX, deltaY) <= DRAG_THRESHOLD_PX) return;+ gesture.dragged = true;+ // Capture only once it is definitely a drag, and never for touch: taking+ // the pointer at pointerdown would swallow ordinary clicks, and capturing+ // a touch would fight the native scroll this relies on.+ if (!isTouch(gesture)) {+ event.currentTarget.setPointerCapture?.(event.pointerId);+ }+ }++ // Touch scrolls itself; driving scrollLeft 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;+ }, []);++ const onPointerUp = useCallback(+ (event: ReactPointerEvent<HTMLElement>) => {+ const gesture = gestureRef.current;+ gestureRef.current = null;+ if (!gesture || gesture.pointerId !== event.pointerId) return;++ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {+ event.currentTarget.releasePointerCapture?.(event.pointerId);+ }++ if (!gesture.dragged) onTap();+ },+ [onTap],+ );++ // The browser took the gesture over (native touch scroll, or the pointer was+ // otherwise lost). That is a drag by definition, so it must not tap.+ const onPointerCancel = useCallback((event: ReactPointerEvent<HTMLElement>) => {+ const gesture = gestureRef.current;+ if (!gesture || gesture.pointerId !== event.pointerId) return;+ gestureRef.current = null;+ }, []);++ return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel };+}diff --git a/packages/views/editor/mermaid-diagram.test.tsx b/packages/views/editor/mermaid-diagram.test.tsxnew file mode 100644index 0000000000..ab21df2c66--- /dev/null+++ b/packages/views/editor/mermaid-diagram.test.tsx@@ -0,0 +1,422 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { readFileSync } from "node:fs";++vi.mock("../i18n", async () => {+ const editor = (await import("../locales/en/editor.json")).default;+ return {+ useT: () => ({ t: (select: (bundle: typeof editor) => string) => select(editor) }),+ };+});++vi.mock("./code-block-static", () => ({+ CodeBlockStatic: ({ body }: { body: string }) => (+ <pre data-testid="code-block-static">{body}</pre>+ ),+}));++const copyTextMock = vi.hoisted(() => vi.fn().mockResolvedValue(true));+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: copyTextMock }));++const mermaidRenderMock = vi.hoisted(() => vi.fn());+const mermaidInitializeMock = vi.hoisted(() => vi.fn());+vi.mock("mermaid", () => ({+ default: { initialize: mermaidInitializeMock, render: mermaidRenderMock },+}));++const MOCK_SVG = '<svg viewBox="0 0 1000 500"><g><text>mock diagram</text></g></svg>';++import { MermaidDiagram } from "./mermaid-diagram";++const CHART = "graph LR\n A[Start] --> B[Done]";+const VIEWPORT = { width: 800, height: 400 };++// jsdom reports 0x0 for every rect; the canvas needs a real viewport to fit against.+function stubViewportSize() {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({+ bottom: VIEWPORT.height,+ height: VIEWPORT.height,+ left: 0,+ right: VIEWPORT.width,+ top: 0,+ width: VIEWPORT.width,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ });+}++beforeEach(() => {+ stubViewportSize();+ // Full reset, not mockClear: `mock.calls` would otherwise carry over and make+ // a "re-render happened" waitFor pass instantly on a previous test's calls,+ // and an unconsumed *Once implementation would leak into the next test.+ mermaidRenderMock.mockReset();+ mermaidRenderMock.mockResolvedValue({ svg: MOCK_SVG });+ mermaidInitializeMock.mockClear();+ copyTextMock.mockClear();+ Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {+ configurable: true,+ value: () => ({+ fillStyle: "#000",+ fillRect: vi.fn(),+ getImageData: () => ({ data: new Uint8ClampedArray([12, 34, 56, 255]) }),+ }),+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ document.documentElement.className = "";+});++function currentScale(): number {+ const element = document.querySelector<HTMLElement>(".mermaid-viewer-content")!;+ return Number.parseFloat(/scale\(([\d.]+)\)/.exec(element.style.transform)![1]!);+}++async function openViewer() {+ const expand = await screen.findByRole("button", { name: "Open diagram viewer" });+ fireEvent.click(expand);+ await screen.findByRole("application");+}++async function findScroller(): Promise<HTMLElement> {+ return waitFor(() => {+ const found = document.querySelector<HTMLElement>(".mermaid-diagram-scroll");+ expect(found).not.toBeNull();+ return found!;+ });+}++/**+ * A press and release with no movement — the gesture that should open the viewer.+ *+ * Fires the trailing `click` too. jsdom does not synthesize it from pointer+ * events, but a real browser always does, and that click is exactly what used+ * to reopen the viewer at the end of a drag — so a gesture helper that omits it+ * cannot see the bug at all.+ */+function tap(element: HTMLElement, { x, y }: { x: number; y: number }) {+ fireEvent.pointerDown(element, { pointerId: 1, clientX: x, clientY: y });+ fireEvent.pointerUp(element, { pointerId: 1, clientX: x, clientY: y });+ fireEvent.click(element, { clientX: x, clientY: y });+}++/** A press, drag and release, in the event order a real browser produces. */+function drag(+ element: HTMLElement,+ from: { x: number; y: number },+ to: { x: number; y: number },+ { pointerType = "mouse", button = 0 }: { pointerType?: string; button?: number } = {},+) {+ const id = { pointerId: 1, pointerType, button };+ fireEvent.pointerDown(element, { ...id, clientX: from.x, clientY: from.y });+ fireEvent.pointerMove(element, { ...id, clientX: to.x, clientY: to.y });+ fireEvent.pointerUp(element, { ...id, clientX: to.x, clientY: to.y });+ fireEvent.click(element, { clientX: to.x, clientY: to.y });+}++async function expectViewerStaysClosed() {+ // The viewer mounts asynchronously through the Dialog's portal, so assert+ // after a flush — a synchronous check would pass even if it were opening.+ await waitFor(() => {+ expect(mermaidRenderMock).toHaveBeenCalled();+ });+ expect(screen.queryByRole("application")).toBeNull();+}++describe("MermaidDiagram theme changes", () => {+ it("keeps the viewer open and preserves zoom when the theme flips", async () => {+ render(<MermaidDiagram chart={CHART} />);+ await openViewer();++ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));+ const zoomed = currentScale();+ expect(zoomed).toBeGreaterThan(0.8);++ // Flip the theme the way the app does; the component observes documentElement+ // and re-renders the diagram with new theme colors.+ await act(async () => {+ document.documentElement.classList.add("dark");+ // Let the MutationObserver callback and the async re-render settle.+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(mermaidRenderMock.mock.calls.length).toBeGreaterThan(1);+ });++ // The viewer previously unmounted here: the re-render cleared the rendered+ // document to null before the new one arrived, closing the dialog and+ // throwing away the user's zoom and position mid-read.+ expect(screen.getByRole("application")).toBeInTheDocument();+ expect(currentScale()).toBeCloseTo(zoomed, 5);+ });++ it("never blanks the diagram while the themed re-render is still in flight", async () => {+ render(<MermaidDiagram chart={CHART} />);+ await waitFor(() => {+ expect(document.querySelector(".mermaid-diagram-frame")).not.toBeNull();+ });++ // Hold the themed re-render open so the intermediate state is observable.+ // Without this the replacement lands in the same tick and a blanking bug+ // would slip through unseen.+ let releaseRender!: (value: { svg: string }) => void;+ mermaidRenderMock.mockImplementationOnce(+ () =>+ new Promise<{ svg: string }>((resolve) => {+ releaseRender = resolve;+ }),+ );++ await act(async () => {+ document.documentElement.classList.add("dark");+ await Promise.resolve();+ });+ await waitFor(() => {+ expect(mermaidRenderMock.mock.calls.length).toBeGreaterThan(1);+ });++ // Mid-flight: the previous diagram must still be on screen rather than+ // collapsing to the loading skeleton on every theme toggle.+ expect(document.querySelector(".mermaid-diagram-frame")).not.toBeNull();+ expect(screen.queryByText("Rendering diagram…")).toBeNull();++ await act(async () => {+ releaseRender({ svg: '<svg viewBox="0 0 1000 500"><text>themed</text></svg>' });+ });+ expect(document.querySelector(".mermaid-diagram-frame")).not.toBeNull();+ });+});++// Verified in Chromium: dragging a diagram starts a native text selection that+// paints the whole iframe box with the selection highlight (it is a replaced+// element) and runs on into the surrounding comment text. Asserted against the+// stylesheet because jsdom has no layout and cannot reproduce a real selection.+// Deliberately NOT solved by preventDefault-ing pointerdown: that also drops+// the default focus, which silently kills the viewer's keyboard controls.+describe("Mermaid selection suppression", () => {+ const mermaidCss = readFileSync("editor/styles/mermaid.css", "utf8");++ function blockFor(selector: string): string {+ const start = mermaidCss.indexOf(selector);+ expect(start, `${selector} missing from mermaid.css`).toBeGreaterThan(-1);+ return mermaidCss.slice(start, mermaidCss.indexOf("}", start));+ }++ it("stops a drag on the inline diagram from selecting text", () => {+ expect(blockFor(".mermaid-diagram-scroll {")).toContain("user-select: none");+ });++ it("stops a pan that leaves the viewer canvas from selecting text", () => {+ expect(blockFor(".mermaid-viewer-canvas {")).toContain("user-select: none");+ });+});++describe("MermaidDiagram rendering config", () => {+ it("renders labels as SVG text, without which PNG export silently produces nothing", async () => {+ render(<MermaidDiagram chart={CHART} />);++ await waitFor(() => {+ expect(mermaidInitializeMock).toHaveBeenCalled();+ });++ // Verified in Chromium against the real Mermaid build: with Mermaid's+ // default (htmlLabels: true) the labels land in a <foreignObject>, which a+ // browser refuses to rasterize through <img> — it paints zero pixels and+ // taints the canvas, so toBlob throws and "Download PNG" does nothing at+ // all. Keep this false or export is broken.+ expect(mermaidInitializeMock).toHaveBeenCalledWith(+ expect.objectContaining({ htmlLabels: false }),+ );+ // The sandbox iframe is the isolation boundary; strict must stay strict.+ expect(mermaidInitializeMock).toHaveBeenCalledWith(+ expect.objectContaining({ securityLevel: "strict" }),+ );+ });+});++describe("MermaidDiagram inline presentation", () => {+ it("renders the diagram in an empty sandbox at its natural size", async () => {+ render(<MermaidDiagram chart={CHART} />);++ const frame = await waitFor(() => {+ const found = document.querySelector<HTMLIFrameElement>(".mermaid-diagram-frame");+ expect(found).not.toBeNull();+ return found!;+ });++ expect(frame.getAttribute("sandbox")).toBe("");+ expect(frame.style.width).toBe("1000px");+ expect(frame.style.height).toBe("500px");+ });++ it("copies the source straight from the inline toolbar", async () => {+ render(<MermaidDiagram chart={CHART} />);++ fireEvent.click(await screen.findByRole("button", { name: "Copy diagram source" }));++ await waitFor(() => {+ expect(copyTextMock).toHaveBeenCalledWith(CHART);+ });+ });++ it("opens the viewer when the diagram itself is tapped, not just the button", async () => {+ render(<MermaidDiagram chart={CHART} />);+ const scroll = await findScroller();++ tap(scroll, { x: 100, y: 100 });++ expect(await screen.findByRole("application")).toBeInTheDocument();+ });+});++// Kim's acceptance (MUL-4908): a still click opens, a horizontal drag moves a+// wide diagram, and no gesture past the threshold may open the viewer on+// release. Before this, every attempt to drag a wide diagram ended in a click+// and the viewer opened on top of the user.+describe("MermaidDiagram inline tap vs drag", () => {+ async function setupScroller({ scrollable = true }: { scrollable?: boolean } = {}) {+ render(<MermaidDiagram chart={CHART} />);+ const scroll = await findScroller();+ // jsdom has no layout: scrollLeft would clamp to 0 and scrollWidth is+ // always 0, so back them with real values to observe the pan.+ let scrollLeft = 0;+ Object.defineProperty(scroll, "scrollLeft", {+ configurable: true,+ get: () => scrollLeft,+ set: (value: number) => {+ // Mirror the browser's clamping, which is what makes an unscrollable+ // diagram stay put while still counting as a drag.+ const max = scrollable ? 2000 : 0;+ scrollLeft = Math.min(Math.max(value, 0), max);+ },+ });+ return scroll;+ }++ it("opens the viewer on a still click", async () => {+ const scroll = await setupScroller();++ tap(scroll, { x: 100, y: 100 });++ expect(await screen.findByRole("application")).toBeInTheDocument();+ });++ it("still opens the viewer when a click jitters below the threshold", async () => {+ const scroll = await setupScroller();++ // ~3px of shake is a click with an unsteady hand, not a drag. The threshold+ // has to sit above this or trackpad users could never open the viewer.+ drag(scroll, { x: 100, y: 100 }, { x: 102, y: 102 });++ expect(await screen.findByRole("application")).toBeInTheDocument();+ });++ it("does not open the viewer after a horizontal drag", async () => {+ const scroll = await setupScroller();++ drag(scroll, { x: 300, y: 100 }, { x: 200, y: 100 });++ await expectViewerStaysClosed();+ });++ it("pans the scroll container while dragging horizontally", async () => {+ const scroll = await setupScroller();++ fireEvent.pointerDown(scroll, { pointerId: 1, clientX: 300, clientY: 100 });+ fireEvent.pointerMove(scroll, { pointerId: 1, clientX: 200, clientY: 100 });++ // Dragging left by 100px reveals 100px further right.+ expect(scroll.scrollLeft).toBe(100);++ fireEvent.pointerMove(scroll, { pointerId: 1, clientX: 260, clientY: 100 });+ // Tracks the pointer from the gesture's origin, not incrementally.+ expect(scroll.scrollLeft).toBe(40);+ });++ 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.+ const scroll = await setupScroller({ scrollable: false });++ drag(scroll, { x: 300, y: 100 }, { x: 200, y: 100 });++ expect(scroll.scrollLeft).toBe(0);+ await expectViewerStaysClosed();+ });++ it("does not open the viewer when the browser takes over the gesture", async () => {+ // Touch scrolling (horizontal pan or vertical page scroll) is handed to the+ // browser, which signals the takeover with pointercancel.+ const scroll = await setupScroller();++ fireEvent.pointerDown(scroll, { pointerId: 1, pointerType: "touch", clientX: 100, clientY: 300 });+ fireEvent.pointerCancel(scroll, { pointerId: 1, pointerType: "touch" });++ await expectViewerStaysClosed();+ });++ it("leaves touch panning to the browser instead of driving scrollLeft itself", async () => {+ // The container is `overflow-x: auto`, so touch already pans natively and+ // vertical drags belong to the page. Driving scrollLeft here as well would+ // move the diagram at double speed.+ const scroll = await setupScroller();++ fireEvent.pointerDown(scroll, { pointerId: 1, pointerType: "touch", clientX: 300, clientY: 100 });+ fireEvent.pointerMove(scroll, { pointerId: 1, pointerType: "touch", clientX: 200, clientY: 100 });++ expect(scroll.scrollLeft).toBe(0);+ });++ it("pans for a pen drag, which has no native drag-to-scroll either", async () => {+ // Only touch is left to the browser. Keying the pan on `=== "mouse"` would+ // silently leave pen users unable to pan at all.+ const scroll = await setupScroller();++ fireEvent.pointerDown(scroll, { pointerId: 1, pointerType: "pen", clientX: 300, clientY: 100 });+ fireEvent.pointerMove(scroll, { pointerId: 1, pointerType: "pen", clientX: 200, clientY: 100 });++ expect(scroll.scrollLeft).toBe(100);+ });++ it("ignores right-button drags", async () => {+ const scroll = await setupScroller();++ drag(scroll, { x: 300, y: 100 }, { x: 200, y: 100 }, { button: 2 });++ expect(scroll.scrollLeft).toBe(0);+ await expectViewerStaysClosed();+ });++ it("keeps the expand button opening the viewer regardless of the gesture rule", async () => {+ await setupScroller();++ fireEvent.click(screen.getByRole("button", { name: "Open diagram viewer" }));++ expect(await screen.findByRole("application")).toBeInTheDocument();+ });+});++describe("MermaidDiagram error state", () => {+ it("surfaces the parser message and a copy affordance alongside the source fallback", async () => {+ mermaidRenderMock.mockRejectedValueOnce(new Error("Parse error on line 3"));++ render(<MermaidDiagram chart={CHART} />);++ await waitFor(() => {+ expect(document.querySelector(".mermaid-diagram-error")).not.toBeNull();+ });+ // Without the parser message the fallback is an unexplained code block.+ expect(screen.getByText("Parse error on line 3")).toBeInTheDocument();+ expect(screen.getByText("Unable to render Mermaid diagram.")).toBeInTheDocument();+ expect(document.querySelector(".mermaid-diagram-error code")?.textContent).toBe(CHART);++ fireEvent.click(screen.getByRole("button", { name: "Copy diagram source" }));+ await waitFor(() => {+ expect(copyTextMock).toHaveBeenCalledWith(CHART);+ });+ });+});diff --git a/packages/views/editor/mermaid-diagram.tsx b/packages/views/editor/mermaid-diagram.tsxindex 5ac0ff95fe..892f475b8a 100644--- a/packages/views/editor/mermaid-diagram.tsx+++ b/packages/views/editor/mermaid-diagram.tsx@@ -13,20 +13,30 @@* 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.*/-import { useEffect, useId, useMemo, useRef, useState, type CSSProperties } from "react";-import { createPortal } from "react-dom";-import { Maximize2 } from "lucide-react";+import {+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+} from "react";+import { Check, Copy, Maximize2 } from "lucide-react";+import { copyText } from "@multica/ui/lib/clipboard";import { useT } from "../i18n";+import { useDragToScroll } from "./hooks/use-drag-to-scroll";+import { MermaidViewer } from "./mermaid-viewer";+import type { Size } from "./utils/diagram-transform";type MermaidAPI = typeof import("mermaid").default;-type MermaidLayout = {- width?: number;- height?: number;-};-let mermaidPromise: Promise<MermaidAPI> | null = null;function getMermaid(): Promise<MermaidAPI> {@@ -68,6 +78,8 @@ function resolveCssColor(return toLegacyColor(color || fallback, fallback, host.ownerDocument);}+const FALLBACK_BACKGROUND = "rgb(255, 255, 255)";+function getMermaidThemeVariables(host: HTMLElement | null) {if (!host) {return {@@ -95,7 +107,25 @@ function getSandboxCssVariables(host: HTMLElement | null): string {.join(" ");}-function getMermaidLayout(svg: string): MermaidLayout {+/**+ * 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,);@@ -110,7 +140,7 @@ function getMermaidLayout(svg: string): MermaidLayout {};}- return {};+ return null;}// Default skeleton height while Mermaid loads + renders for the first time@@ -131,7 +161,7 @@ function hashChart(chart: string): string {return (hash >>> 0).toString(36);}-function readCachedLayout(chart: string): MermaidLayout | null {+function readCachedLayout(chart: string): Size | null {if (typeof window === "undefined") return null;try {const raw = window.sessionStorage.getItem(@@ -153,9 +183,9 @@ function readCachedLayout(chart: string): MermaidLayout | null {}}-function writeCachedLayout(chart: string, layout: MermaidLayout): void {+function writeCachedLayout(chart: string, layout: Size | null): void {if (typeof window === "undefined") return;- if (!layout.width || !layout.height) return;+ if (!layout) return;try {window.sessionStorage.setItem(MERMAID_LAYOUT_CACHE_PREFIX + hashChart(chart),@@ -173,10 +203,20 @@ function buildSandboxedMermaidDocument(svg: string, host: HTMLElement | null): sreturn `<!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 buildExpandedMermaidDocument(svg: string, host: HTMLElement | null): string {+/**+ * 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);- return `<!doctype html><html><head><style>:root { ${cssVariables} } html, body { width: 100%; height: 100%; } body { margin: 0; display: flex; align-items: center; justify-content: center; background: transparent; } svg { max-width: 100%; max-height: 100%; width: auto; 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; } svg { display: block; width: ${layout.width}px; height: ${layout.height}px; max-width: none; }</style></head><body>${svg}</body></html>`;}function useThemeVersion() {@@ -208,59 +248,94 @@ function useThemeVersion() {return themeVersion;}-function MermaidLightbox({- srcDoc,- onClose,-}: {- srcDoc: string;- onClose: () => void;-}) {+/**+ * 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 handler = (e: KeyboardEvent) => {- if (e.key === "Escape") onClose();+ 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 };+ });};- document.addEventListener("keydown", handler);- return () => document.removeEventListener("keydown", handler);- }, [onClose]);- return createPortal(- <div- className="mermaid-diagram-lightbox"- role="dialog"- aria-modal="true"- aria-label="Mermaid diagram fullscreen view"- onClick={onClose}- >- <iframe- className="mermaid-diagram-lightbox-frame"- sandbox=""- srcDoc={srcDoc}- title="Mermaid diagram fullscreen"- onClick={(e) => e.stopPropagation()}- />- </div>,- document.body,- );+ 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 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 };++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;+ exportBackground: string;+ exportFontFamily: string;}export function MermaidDiagram({ chart }: { chart: string }) {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();- const [sandboxedDocument, setSandboxedDocument] = useState<string | null>(null);- const [expandedDocument, setExpandedDocument] = useState<string | null>(null);+ // 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 [layout, setLayout] = useState<MermaidLayout>(() => readCachedLayout(chart) ?? {});+ const [skeletonLayout, setSkeletonLayout] = useState<Size | null>(() =>+ readCachedLayout(chart),+ );const [error, setError] = useState<string | null>(null);- const [lightboxOpen, setLightboxOpen] = useState(false);+ const [viewerOpen, setViewerOpen] = useState(false);+ const [copied, setCopied] = useState(false);useEffect(() => {let cancelled = false;@@ -268,17 +343,23 @@ export function MermaidDiagram({ chart }: { chart: string }) {async function renderDiagram() {try {setError(null);- setSandboxedDocument(null);- setExpandedDocument(null);- // Seed layout from cache (if any) so the skeleton sizes correctly- // even when `chart` changes after mount — the lazy useState above- // only fires once.- setLayout(readCachedLayout(chart) ?? {});+ // 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@@ -287,19 +368,31 @@ export function MermaidDiagram({ chart }: { chart: string }) {suppressErrorRendering: true,});const { svg: renderedSvg } = await mermaid.render(diagramId, chart);- if (!cancelled) {- const measured = getMermaidLayout(renderedSvg);- setLayout(measured);- writeCachedLayout(chart, measured);- setSandboxedDocument(- buildSandboxedMermaidDocument(renderedSvg, containerRef.current),- );- setExpandedDocument(- buildExpandedMermaidDocument(renderedSvg, containerRef.current),- );- }+ if (cancelled) return;++ const measured = getMermaidLayout(renderedSvg);+ const viewerLayout = measured ?? VIEWER_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,+ viewerLayout,+ ),+ layout: measured,+ viewerLayout,+ exportBackground: exportStyle.background,+ exportFontFamily: exportStyle.fontFamily,+ });} catch (err) {if (!cancelled) {+ setRendered(null);setError(err instanceof Error ? err.message : "Failed to render Mermaid diagram");}}@@ -312,10 +405,34 @@ export function MermaidDiagram({ chart }: { chart: string }) {};}, [chart, diagramId, themeVersion]);+ const overflow = useHorizontalOverflow(scrollRef, [rendered?.inlineDocument]);+ const openViewer = useCallback(() => setViewerOpen(true), []);+ const dragToScroll = useDragToScroll({ onTap: openViewer });++ const handleCopySource = useCallback(async () => {+ if (await copyText(chart)) {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }+ }, [chart]);+if (error) {return (<div ref={containerRef} className="mermaid-diagram mermaid-diagram-error">- <p>{t(($) => $.mermaid.render_error)}</p>+ <div className="mermaid-diagram-error-head">+ <p>{t(($) => $.mermaid.render_error)}</p>+ <button+ type="button"+ onClick={handleCopySource}+ title={t(($) => $.mermaid.copy_source)}+ aria-label={t(($) => $.mermaid.copy_source)}+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </button>+ </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>@@ -327,9 +444,9 @@ export function MermaidDiagram({ chart }: { chart: string }) {// 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 = sandboxedDocument+ const containerStyle: CSSProperties | undefined = rendered? undefined- : { minHeight: layout.height ?? MERMAID_SKELETON_HEIGHT_PX };+ : { minHeight: skeletonLayout?.height ?? MERMAID_SKELETON_HEIGHT_PX };return (<div@@ -337,35 +454,64 @@ export function MermaidDiagram({ chart }: { chart: string }) {className="mermaid-diagram"aria-label="Mermaid diagram"style={containerStyle}+ data-overflow-start={overflow.start ? "" : undefined}+ data-overflow-end={overflow.end ? "" : undefined}>- {sandboxedDocument ? (+ {rendered ? (<>- <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"- />+ {/* 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"+ {...dragToScroll}+ >+ <iframe+ className="mermaid-diagram-frame"+ sandbox=""+ srcDoc={rendered.inlineDocument}+ style={{+ height: rendered.layout ? `${rendered.layout.height}px` : undefined,+ width: rendered.layout ? `${rendered.layout.width}px` : undefined,+ }}+ title="Mermaid diagram"+ />+ </div><div className="mermaid-diagram-toolbar"><buttontype="button"- onClick={() => setLightboxOpen(true)}- title="Open fullscreen"- aria-label="Open Mermaid diagram fullscreen"+ onClick={handleCopySource}+ title={t(($) => $.mermaid.copy_source)}+ aria-label={t(($) => $.mermaid.copy_source)}+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </button>+ <button+ ref={expandButtonRef}+ type="button"+ onClick={() => setViewerOpen(true)}+ title={t(($) => $.mermaid.open_viewer)}+ aria-label={t(($) => $.mermaid.open_viewer)}><Maximize2 className="size-3.5" /></button></div>- {lightboxOpen && expandedDocument && (- <MermaidLightbox- srcDoc={expandedDocument}- onClose={() => setLightboxOpen(false)}- />- )}+ <MermaidViewer+ open={viewerOpen}+ onOpenChange={setViewerOpen}+ chart={chart}+ svg={rendered.svg}+ viewerDocument={rendered.viewerDocument}+ layout={rendered.viewerLayout}+ exportBackground={rendered.exportBackground}+ exportFontFamily={rendered.exportFontFamily}+ finalFocusRef={expandButtonRef}+ /></>) : (<div className="mermaid-diagram-loading">{t(($) => $.mermaid.rendering)}</div>diff --git a/packages/views/editor/mermaid-viewer.test.tsx b/packages/views/editor/mermaid-viewer.test.tsxnew file mode 100644index 0000000000..ef5a1833d2--- /dev/null+++ b/packages/views/editor/mermaid-viewer.test.tsx@@ -0,0 +1,491 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useState } from "react";++// Resolve against the real EN bundle rather than a hand-written stub: the+// accessible names below are then the strings that actually ship, and a+// missing/renamed key fails here instead of silently rendering "".+vi.mock("../i18n", async () => {+ const editor = (await import("../locales/en/editor.json")).default;+ return {+ useT: () => ({ t: (select: (bundle: typeof editor) => string) => select(editor) }),+ };+});++// CodeBlockStatic pulls in lowlight, which has a heavy import surface and a+// jsdom-incompatible path. The source view's wiring is what matters here.+vi.mock("./code-block-static", () => ({+ CodeBlockStatic: ({ body }: { body: string }) => (+ <pre data-testid="code-block-static">{body}</pre>+ ),+}));++const copyTextMock = vi.hoisted(() => vi.fn().mockResolvedValue(true));+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: copyTextMock }));++import { MermaidViewer } from "./mermaid-viewer";++const CHART = "graph LR\n A[Start] --> B[Done]";+const SVG = '<svg viewBox="0 0 1000 500"><text>mock diagram</text></svg>';+const VIEWER_DOC = "<!doctype html><html><body>mock</body></html>";+const LAYOUT = { width: 1000, height: 500 };++// The canvas measures itself with getBoundingClientRect, which jsdom always+// reports as 0x0. Without a real viewport the transform math has nothing to+// fit against and every gesture is a no-op, so pin a deterministic size.+const VIEWPORT = { width: 800, height: 400 };++function stubViewportSize() {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({+ bottom: VIEWPORT.height,+ height: VIEWPORT.height,+ left: 0,+ right: VIEWPORT.width,+ top: 0,+ width: VIEWPORT.width,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ });+}++function Harness({ initialOpen = true }: { initialOpen?: boolean }) {+ const [open, setOpen] = useState(initialOpen);+ return (+ <>+ <button type="button" data-testid="opener" onClick={() => setOpen(true)}>+ open+ </button>+ <MermaidViewer+ open={open}+ onOpenChange={setOpen}+ chart={CHART}+ svg={SVG}+ viewerDocument={VIEWER_DOC}+ layout={LAYOUT}+ exportBackground="rgb(240, 240, 240)"+ exportFontFamily="Inter, sans-serif"+ />+ </>+ );+}++function canvas(): HTMLElement {+ return screen.getByRole("application");+}++function content(): HTMLElement {+ return document.querySelector<HTMLElement>(".mermaid-viewer-content")!;+}++/** Reads the applied scale back out of the inline transform. */+function currentScale(): number {+ const match = /scale\(([\d.]+)\)/.exec(content().style.transform);+ return Number.parseFloat(match![1]!);+}++function currentTranslate(): { x: number; y: number } {+ const match = /translate\(([-\d.]+)px, ([-\d.]+)px\)/.exec(content().style.transform);+ return { x: Number.parseFloat(match![1]!), y: Number.parseFloat(match![2]!) };+}++beforeEach(() => {+ stubViewportSize();+ copyTextMock.mockClear();+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("MermaidViewer closing", () => {+ it("closes via the explicit X button", async () => {+ render(<Harness />);+ expect(canvas()).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Close" }));++ await waitFor(() => {+ expect(screen.queryByRole("application")).toBeNull();+ });+ });++ it("closes on Escape after the canvas has been clicked and focused", async () => {+ // The regression this pins: the old lightbox put the diagram in an iframe+ // that took focus on click, stranding keydown inside a document the host+ // could not hear — so Escape silently stopped working and the overlay had+ // no visible close button. Interaction now lives in the host document.+ render(<Harness />);++ fireEvent.pointerDown(canvas(), { pointerId: 1, clientX: 100, clientY: 100 });+ fireEvent.pointerUp(canvas(), { pointerId: 1, clientX: 100, clientY: 100 });+ canvas().focus();+ expect(document.activeElement).toBe(canvas());++ fireEvent.keyDown(document.activeElement!, { key: "Escape" });++ await waitFor(() => {+ expect(screen.queryByRole("application")).toBeNull();+ });+ });++ it("keeps the diagram inside an empty sandbox, so it can never steal focus or run scripts", () => {+ render(<Harness />);++ const frame = document.querySelector<HTMLIFrameElement>(".mermaid-viewer-frame");+ expect(frame).not.toBeNull();+ // An empty sandbox is what makes host-side pan/zoom necessary; if this ever+ // loosens, the isolation the whole design protects is gone.+ expect(frame?.getAttribute("sandbox")).toBe("");+ expect(frame?.srcdoc).toBe(VIEWER_DOC);+ });++ it("returns focus to the element that opened it", async () => {+ function FocusHarness() {+ const [open, setOpen] = useState(false);+ const ref = { current: null as HTMLButtonElement | null };+ return (+ <>+ <button+ type="button"+ data-testid="opener"+ ref={(node) => {+ ref.current = node;+ }}+ onClick={() => setOpen(true)}+ >+ open+ </button>+ <MermaidViewer+ open={open}+ onOpenChange={setOpen}+ chart={CHART}+ svg={SVG}+ viewerDocument={VIEWER_DOC}+ layout={LAYOUT}+ exportBackground="rgb(240, 240, 240)"+ exportFontFamily="Inter, sans-serif"+ finalFocusRef={ref}+ />+ </>+ );+ }++ render(<FocusHarness />);+ const opener = screen.getByTestId("opener");+ opener.focus();+ fireEvent.click(opener);++ await screen.findByRole("application");+ fireEvent.click(screen.getByRole("button", { name: "Close" }));++ await waitFor(() => {+ expect(document.activeElement).toBe(opener);+ });+ });++ it("locks background scroll while open and restores it on close", async () => {+ render(<Harness />);++ // Base UI marks the scroll-locked root; without the lock the page behind+ // drifts and reopening lands the reader somewhere else.+ await waitFor(() => {+ expect(document.documentElement).toHaveAttribute("data-base-ui-scroll-locked");+ });++ fireEvent.click(screen.getByRole("button", { name: "Close" }));++ await waitFor(() => {+ expect(document.documentElement).not.toHaveAttribute("data-base-ui-scroll-locked");+ });+ });+});++describe("MermaidViewer zoom controls", () => {+ it("opens fitted to the viewport rather than squashed to a fixed size", () => {+ render(<Harness />);++ // 1000x500 content in an 800x400 viewport → limited by width: 0.8.+ expect(currentScale()).toBeCloseTo(0.8, 5);+ expect(screen.getByText("80%")).toBeInTheDocument();+ });++ it("zooms in and out from the toolbar", () => {+ render(<Harness />);+ const initial = currentScale();++ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));+ expect(currentScale()).toBeGreaterThan(initial);++ fireEvent.click(screen.getByRole("button", { name: "Zoom out" }));+ expect(currentScale()).toBeCloseTo(initial, 5);+ });++ it("jumps to natural size with Actual size", () => {+ render(<Harness />);++ fireEvent.click(screen.getByRole("button", { name: "Actual size" }));++ expect(currentScale()).toBe(1);+ expect(screen.getByText("100%")).toBeInTheDocument();+ });++ it("restores the fitted view with Reset after panning away", () => {+ render(<Harness />);+ const fitted = currentTranslate();++ fireEvent.pointerDown(canvas(), { pointerId: 1, clientX: 400, clientY: 200 });+ fireEvent.pointerMove(canvas(), { pointerId: 1, clientX: 200, clientY: 120 });+ fireEvent.pointerUp(canvas(), { pointerId: 1, clientX: 200, clientY: 120 });+ expect(currentTranslate()).not.toEqual(fitted);++ fireEvent.click(screen.getByRole("button", { name: "Reset view" }));++ expect(currentTranslate().x).toBeCloseTo(fitted.x, 5);+ expect(currentTranslate().y).toBeCloseTo(fitted.y, 5);+ });++ it("disables Reset when the view is already fitted, and enables it once moved", () => {+ render(<Harness />);+ expect(screen.getByRole("button", { name: "Reset view" })).toBeDisabled();++ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));++ expect(screen.getByRole("button", { name: "Reset view" })).toBeEnabled();+ });++ it("stops at 400% and disables Zoom in at the ceiling", () => {+ render(<Harness />);++ for (let i = 0; i < 20; i++) {+ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));+ }++ expect(currentScale()).toBe(4);+ expect(screen.getByText("400%")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Zoom in" })).toBeDisabled();+ });++ it("re-fits on reopen instead of inheriting the previous session's zoom", async () => {+ render(<Harness initialOpen={false} />);+ fireEvent.click(screen.getByTestId("opener"));+ await screen.findByRole("application");+ const fitted = currentScale();++ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));+ expect(currentScale()).toBeGreaterThan(fitted);++ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ await waitFor(() => expect(screen.queryByRole("application")).toBeNull());++ fireEvent.click(screen.getByTestId("opener"));+ await screen.findByRole("application");++ // Reopening is a fresh read; carrying a stale zoom over would drop the+ // reader somewhere in the middle of a diagram they just reopened.+ expect(currentScale()).toBeCloseTo(fitted, 5);+ });++ it("reopens showing the diagram even if it was left on the source view", async () => {+ render(<Harness initialOpen={false} />);+ fireEvent.click(screen.getByTestId("opener"));+ await screen.findByRole("application");++ fireEvent.click(screen.getByRole("button", { name: "Show source" }));+ expect(screen.queryByRole("application")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ await waitFor(() => expect(screen.queryByTestId("code-block-static")).toBeNull());++ fireEvent.click(screen.getByTestId("opener"));++ expect(await screen.findByRole("application")).toBeInTheDocument();+ });++ it("stops at 25% and disables Zoom out at the floor", () => {+ render(<Harness />);++ for (let i = 0; i < 20; i++) {+ fireEvent.click(screen.getByRole("button", { name: "Zoom out" }));+ }++ expect(currentScale()).toBe(0.25);+ expect(screen.getByText("25%")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Zoom out" })).toBeDisabled();+ });+});++describe("MermaidViewer canvas interaction", () => {+ it("pans with a mouse drag", () => {+ render(<Harness />);+ const before = currentTranslate();++ fireEvent.pointerDown(canvas(), { pointerId: 1, clientX: 300, clientY: 200 });+ fireEvent.pointerMove(canvas(), { pointerId: 1, clientX: 350, clientY: 230 });++ const after = currentTranslate();+ expect(after.x).toBeCloseTo(before.x + 50, 5);+ expect(after.y).toBeCloseTo(before.y + 30, 5);+ });++ it("ignores right-button drags so context-menu clicks do not shift the diagram", () => {+ render(<Harness />);+ const before = currentTranslate();++ fireEvent.pointerDown(canvas(), {+ pointerId: 1,+ button: 2,+ pointerType: "mouse",+ clientX: 300,+ clientY: 200,+ });+ fireEvent.pointerMove(canvas(), { pointerId: 1, clientX: 350, clientY: 230 });++ expect(currentTranslate()).toEqual(before);+ });++ it("zooms on wheel, anchored so the point under the cursor stays put", () => {+ render(<Harness />);+ const before = { scale: currentScale(), ...currentTranslate() };+ const anchor = { x: 200, y: 150 };++ fireEvent.wheel(canvas(), { deltaY: -100, clientX: anchor.x, clientY: anchor.y });++ const after = { scale: currentScale(), ...currentTranslate() };+ expect(after.scale).toBeGreaterThan(before.scale);+ // Same content coordinate under the cursor before and after.+ expect((anchor.x - after.x) / after.scale).toBeCloseTo(+ (anchor.x - before.x) / before.scale,+ 3,+ );+ });++ it("zooms out on the opposite wheel direction", () => {+ render(<Harness />);+ const before = currentScale();++ fireEvent.wheel(canvas(), { deltaY: 100, clientX: 200, clientY: 150 });++ expect(currentScale()).toBeLessThan(before);+ });++ it("pinch-zooms with two touch pointers", () => {+ render(<Harness />);+ const before = currentScale();++ fireEvent.pointerDown(canvas(), {+ pointerId: 1,+ pointerType: "touch",+ clientX: 300,+ clientY: 200,+ });+ fireEvent.pointerDown(canvas(), {+ pointerId: 2,+ pointerType: "touch",+ clientX: 400,+ clientY: 200,+ });+ // Fingers spread from 100px apart to 200px apart → ~2x.+ fireEvent.pointerMove(canvas(), {+ pointerId: 2,+ pointerType: "touch",+ clientX: 500,+ clientY: 200,+ });++ expect(currentScale()).toBeCloseTo(before * 2, 2);+ });++ it("zooms with the +/- keys and refits with 0", () => {+ render(<Harness />);+ const fitted = currentScale();++ fireEvent.keyDown(canvas(), { key: "+" });+ expect(currentScale()).toBeGreaterThan(fitted);++ fireEvent.keyDown(canvas(), { key: "-" });+ expect(currentScale()).toBeCloseTo(fitted, 5);++ fireEvent.keyDown(canvas(), { key: "+" });+ fireEvent.keyDown(canvas(), { key: "0" });+ expect(currentScale()).toBeCloseTo(fitted, 5);+ });++ it("pans with the arrow keys", () => {+ render(<Harness />);+ const before = currentTranslate();++ fireEvent.keyDown(canvas(), { key: "ArrowRight" });++ // ArrowRight moves the viewport right, i.e. the content left.+ expect(currentTranslate().x).toBeLessThan(before.x);+ });++ it("never lets the diagram be panned entirely out of view", () => {+ render(<Harness />);++ fireEvent.pointerDown(canvas(), { pointerId: 1, clientX: 400, clientY: 200 });+ fireEvent.pointerMove(canvas(), { pointerId: 1, clientX: -100000, clientY: -100000 });++ const { x, y } = currentTranslate();+ const scale = currentScale();+ // At least a sliver of content still overlaps the viewport.+ expect(x + LAYOUT.width * scale).toBeGreaterThan(0);+ expect(y + LAYOUT.height * scale).toBeGreaterThan(0);+ });+});++describe("MermaidViewer source and export", () => {+ it("copies the Mermaid source", async () => {+ render(<Harness />);++ fireEvent.click(screen.getByRole("button", { name: "Copy diagram source" }));++ await waitFor(() => {+ expect(copyTextMock).toHaveBeenCalledWith(CHART);+ });+ });++ it("toggles to the source view and back, because Issue/Comment is where agent output gets audited", async () => {+ render(<Harness />);++ fireEvent.click(screen.getByRole("button", { name: "Show source" }));++ expect(screen.queryByRole("application")).toBeNull();+ expect(screen.getByText(/graph LR/)).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Show diagram" }));+ expect(screen.getByRole("application")).toBeInTheDocument();+ });++ it("offers PNG, SVG and .mmd exports", async () => {+ render(<Harness />);++ fireEvent.click(screen.getByRole("button", { name: "Export" }));++ expect(await screen.findByText("Download PNG")).toBeInTheDocument();+ expect(screen.getByText("Download SVG")).toBeInTheDocument();+ expect(screen.getByText("Download .mmd")).toBeInTheDocument();+ });++ it("downloads an .mmd file containing the original source", async () => {+ const createObjectURL = vi.fn((_blob: Blob) => "blob:mock");+ const revokeObjectURL = vi.fn((_url: string) => {});+ vi.stubGlobal("URL", { ...URL, createObjectURL, revokeObjectURL });+ const clickSpy = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(() => {});++ render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "Export" }));+ fireEvent.click(await screen.findByText("Download .mmd"));++ await waitFor(() => {+ expect(clickSpy).toHaveBeenCalled();+ });+ const blob = createObjectURL.mock.calls[0]![0];+ await expect(blob.text()).resolves.toBe(CHART);++ vi.unstubAllGlobals();+ });+});diff --git a/packages/views/editor/mermaid-viewer.tsx b/packages/views/editor/mermaid-viewer.tsxnew file mode 100644index 0000000000..bf54b705a3--- /dev/null+++ b/packages/views/editor/mermaid-viewer.tsx@@ -0,0 +1,357 @@+"use client";++/**+ * MermaidViewer — full-screen diagram viewer.+ *+ * Built on the shared `Dialog` (Base UI) rather than a bespoke portal, so it+ * inherits the behaviors the old Mermaid lightbox was missing: a real backdrop,+ * focus trap, background scroll lock, focus restore, and Escape-to-close.+ *+ * The diagram stays inside an `sandbox=""` iframe — the isolation boundary is+ * not relaxed to buy interactivity. Instead the iframe is `pointer-events:+ * none` and pan/zoom is applied from this document as a transform on the+ * wrapper (see `useDiagramCanvas`). A side effect worth keeping: because the+ * iframe never takes focus, key events cannot get stranded in a document the+ * dialog can't hear, which is why Escape used to stop working after a click.+ */++import { useCallback, useMemo, useRef, useState } from "react";+import {+ Check,+ Code as CodeIcon,+ Copy,+ Download,+ Frame,+ Image as ImageIcon,+ Maximize,+ Minus,+ Plus,+ RotateCcw,+ X,+} from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import { copyText } from "@multica/ui/lib/clipboard";+import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { useT } from "../i18n";+import { CodeBlockStatic } from "./code-block-static";+import { useDiagramCanvas } from "./hooks/use-diagram-canvas";+import {+ buildExportSvg,+ diagramFilenameStem,+ downloadBlob,+ renderSvgToPngBlob,+} from "./utils/mermaid-export";+import type { Size } from "./utils/diagram-transform";++const COPY_FEEDBACK_MS = 2000;++interface MermaidViewerContentProps {+ /** Mermaid source, for the source view and `.mmd` export. */+ chart: string;+ /** Rendered SVG markup, for export. */+ svg: string | null;+ /** Sandboxed document that draws the diagram at natural size. */+ viewerDocument: string | null;+ /** Natural size of the diagram. */+ layout: Size;+ /** Colors resolved from the host theme, so exports match what is on screen. */+ exportBackground: string;+ exportFontFamily: string;+}++export interface MermaidViewerProps extends MermaidViewerContentProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Focus returns here on close — the button that opened the viewer. */+ finalFocusRef?: React.RefObject<HTMLElement | null>;+}++function ToolbarButton({+ onClick,+ disabled,+ label,+ children,+}: {+ onClick: () => void;+ disabled?: boolean;+ label: string;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ title={label}+ aria-label={label}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:pointer-events-none disabled:opacity-40"+ >+ {children}+ </button>+ );+}++export function MermaidViewer({+ open,+ onOpenChange,+ finalFocusRef,+ ...content+}: MermaidViewerProps) {+ const { t } = useT("editor");+ const canvasRef = useRef<HTMLDivElement>(null);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ initialFocus={canvasRef}+ finalFocus={finalFocusRef}+ // Dynamic viewport units: on mobile Safari and in narrow Electron+ // panes `vh` includes retracted browser chrome, which would push the+ // toolbar off-screen — the exact "can't find the close button"+ // failure this viewer exists to remove.+ className="!max-w-[calc(100vw-2rem)] !h-[min(90dvh,calc(100dvh-2rem))] !w-[calc(100vw-2rem)] flex flex-col gap-0 overflow-hidden p-0 xl:!max-w-[80rem]"+ aria-label={t(($) => $.mermaid.viewer_title)}+ >+ {/* Body state (zoom, pan, source toggle) deliberately lives below the+ portal boundary so it is destroyed on close. Each open is a fresh+ read that re-fits, rather than restoring a stale zoom from the last+ time this diagram happened to be opened. */}+ <MermaidViewerContent+ {...content}+ canvasRef={canvasRef}+ onClose={() => onOpenChange(false)}+ />+ </DialogContent>+ </Dialog>+ );+}++function MermaidViewerContent({+ chart,+ svg,+ viewerDocument,+ layout,+ exportBackground,+ exportFontFamily,+ canvasRef,+ onClose,+}: MermaidViewerContentProps & {+ canvasRef: React.RefObject<HTMLDivElement | null>;+ onClose: () => void;+}) {+ const { t } = useT("editor");+ const [showSource, setShowSource] = useState(false);+ const [copied, setCopied] = useState(false);+ const canvas = useDiagramCanvas({ content: layout });++ const handleCopySource = useCallback(async () => {+ if (await copyText(chart)) {+ setCopied(true);+ setTimeout(() => setCopied(false), COPY_FEEDBACK_MS);+ }+ }, [chart]);++ const standaloneSvg = useMemo(() => {+ if (!svg) return null;+ return buildExportSvg(svg, {+ background: exportBackground,+ fontFamily: exportFontFamily,+ width: layout.width,+ height: layout.height,+ });+ }, [svg, layout, exportBackground, exportFontFamily]);++ const filenameStem = useMemo(() => diagramFilenameStem(chart), [chart]);++ const handleDownloadSource = useCallback(() => {+ downloadBlob(+ new Blob([chart], { type: "text/vnd.mermaid;charset=utf-8" }),+ `${filenameStem}.mmd`,+ );+ }, [chart, filenameStem]);++ const handleDownloadSvg = useCallback(() => {+ if (!standaloneSvg) return;+ downloadBlob(+ new Blob([standaloneSvg], { type: "image/svg+xml;charset=utf-8" }),+ `${filenameStem}.svg`,+ );+ }, [standaloneSvg, filenameStem]);++ const handleDownloadPng = useCallback(async () => {+ if (!standaloneSvg) return;+ try {+ const blob = await renderSvgToPngBlob(standaloneSvg, layout);+ downloadBlob(blob, `${filenameStem}.png`);+ } catch {+ // Rasterization is best-effort: `.svg` and `.mmd` remain available, and+ // failing loudly here would put an error dialog over the diagram the+ // user is reading.+ }+ }, [standaloneSvg, layout, filenameStem]);++ const canExportImage = standaloneSvg !== null;++ return (+ <>+ {/* Sibling of the scrolling canvas, never inside it: the toolbar must+ stay put no matter how far the diagram is panned or zoomed. */}+ <header className="flex shrink-0 items-center gap-1 border-b border-border bg-muted/30 px-3 py-2">+ <DialogTitle className="mr-1 truncate text-sm font-medium">+ {t(($) => $.mermaid.viewer_title)}+ </DialogTitle>++ <div className="flex items-center gap-0.5">+ <ToolbarButton+ onClick={canvas.zoomOut}+ disabled={!canvas.canZoomOut || showSource}+ label={t(($) => $.mermaid.zoom_out)}+ >+ <Minus className="size-4" />+ </ToolbarButton>+ {/* Fixed width so the toolbar doesn't jitter as digits change. */}+ <span+ className="w-12 select-none text-center text-xs tabular-nums text-muted-foreground"+ aria-live="polite"+ >+ {canvas.zoomPercent}%+ </span>+ <ToolbarButton+ onClick={canvas.zoomIn}+ disabled={!canvas.canZoomIn || showSource}+ label={t(($) => $.mermaid.zoom_in)}+ >+ <Plus className="size-4" />+ </ToolbarButton>+ <ToolbarButton+ onClick={canvas.fit}+ disabled={showSource}+ label={t(($) => $.mermaid.zoom_fit)}+ >+ <Frame className="size-4" />+ </ToolbarButton>+ <ToolbarButton+ onClick={canvas.zoomToActualSize}+ disabled={showSource}+ label={t(($) => $.mermaid.zoom_actual)}+ >+ <Maximize className="size-4" />+ </ToolbarButton>+ <ToolbarButton+ onClick={canvas.reset}+ disabled={showSource || canvas.isFitted}+ label={t(($) => $.mermaid.reset_view)}+ >+ <RotateCcw className="size-4" />+ </ToolbarButton>+ </div>++ <div className="ml-auto flex items-center gap-0.5">+ <ToolbarButton+ onClick={() => setShowSource((value) => !value)}+ label={+ showSource+ ? t(($) => $.mermaid.show_diagram)+ : t(($) => $.mermaid.show_source)+ }+ >+ <CodeIcon className={cn("size-4", showSource && "text-foreground")} />+ </ToolbarButton>+ <ToolbarButton+ onClick={handleCopySource}+ label={t(($) => $.mermaid.copy_source)}+ >+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}+ </ToolbarButton>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ title={t(($) => $.mermaid.export)}+ aria-label={t(($) => $.mermaid.export)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ >+ <Download className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleDownloadPng} disabled={!canExportImage}>+ <ImageIcon className="size-4" />+ {t(($) => $.mermaid.export_png)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={handleDownloadSvg} disabled={!canExportImage}>+ <ImageIcon className="size-4" />+ {t(($) => $.mermaid.export_svg)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={handleDownloadSource}>+ <CodeIcon className="size-4" />+ {t(($) => $.mermaid.export_source)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <ToolbarButton+ onClick={onClose}+ label={t(($) => $.mermaid.close_viewer)}+ >+ <X className="size-4" />+ </ToolbarButton>+ </div>+ </header>++ {showSource ? (+ <div className="min-h-0 flex-1 overflow-auto bg-background p-3">+ <CodeBlockStatic language="mermaid" body={chart} />+ </div>+ ) : (+ <div+ ref={(node) => {+ canvasRef.current = node;+ canvas.setViewportNode(node);+ }}+ className={cn("mermaid-viewer-canvas", canvas.isPanning && "is-panning")}+ // `application` tells screen readers to pass arrow keys through to+ // the canvas instead of using them for their own navigation.+ role="application"+ aria-label={t(($) => $.mermaid.canvas_label)}+ tabIndex={0}+ onPointerDown={canvas.handlePointerDown}+ onPointerMove={canvas.handlePointerMove}+ onPointerUp={canvas.handlePointerUp}+ onPointerCancel={canvas.handlePointerUp}+ onKeyDown={canvas.handleKeyDown}+ >+ {viewerDocument && (+ <div+ className={cn(+ "mermaid-viewer-content",+ canvas.isAnimated && "is-animated",+ )}+ style={{+ width: `${layout.width}px`,+ height: `${layout.height}px`,+ transform: `translate(${canvas.transform.x}px, ${canvas.transform.y}px) scale(${canvas.transform.scale})`,+ }}+ >+ <iframe+ className="mermaid-viewer-frame"+ sandbox=""+ srcDoc={viewerDocument}+ title={t(($) => $.mermaid.viewer_title)}+ style={{ width: `${layout.width}px`, height: `${layout.height}px` }}+ />+ </div>+ )}+ </div>+ )}+ </>+ );+}diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex a6fb492308..883396c72b 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -16,6 +16,17 @@ vi.mock("../issues/hooks", () => ({resolveIssueIdentifierMock(identifier),}));+// i18next is not initialized in this suite, so `t()` would resolve every label+// to "". Resolve against the real EN bundle instead — the editor tree only ever+// uses the `editor` namespace — so tests can select controls by accessible name.+vi.mock("../i18n", async () => {+ const editor = (await import("../locales/en/editor.json")).default;+ return {+ useT: () => ({ t: (select: (bundle: typeof editor) => string) => select(editor) }),+ useTimeAgo: () => "just now",+ };+});+vi.mock("@multica/core/api", () => ({api: { getAttachmentTextContent: getAttachmentTextContentMock },PreviewTooLargeError: class extends Error {},@@ -406,39 +417,62 @@ describe("ReadonlyContent Mermaid rendering", () => {expect(container.querySelector("pre")).toBeNull();});- it("opens a fullscreen lightbox when the toolbar button is clicked", async () => {+ it("opens the fullscreen viewer from the toolbar and closes it with Escape", async () => {const { container } = render(<ReadonlyContentcontent={["```mermaid", "graph LR", " A[Start] --> B[Done]", "```"].join("\n")}/>,);- const button = await waitFor(() => {+ const expandButton = await waitFor(() => {const found = container.querySelector<HTMLButtonElement>(- ".mermaid-diagram-toolbar button",+ '.mermaid-diagram-toolbar button[aria-label="Open diagram viewer"]',);expect(found).not.toBeNull();return found!;});- expect(document.querySelector(".mermaid-diagram-lightbox")).toBeNull();+ expect(document.querySelector(".mermaid-viewer-canvas")).toBeNull();- fireEvent.click(button);+ fireEvent.click(expandButton);- const lightboxFrame = document.querySelector<HTMLIFrameElement>(- ".mermaid-diagram-lightbox-frame",- );- expect(lightboxFrame).not.toBeNull();- expect(lightboxFrame?.getAttribute("sandbox")).toBe("");- expect(lightboxFrame?.srcdoc).toContain("mock diagram");- expect(lightboxFrame?.srcdoc).toContain("max-height: 100%");+ const viewerFrame = await waitFor(() => {+ const found = document.querySelector<HTMLIFrameElement>(".mermaid-viewer-frame");+ expect(found).not.toBeNull();+ return found!;+ });+ expect(viewerFrame.getAttribute("sandbox")).toBe("");+ expect(viewerFrame.srcdoc).toContain("mock diagram");+ // The viewer draws at natural size and lets the host transform handle zoom;+ // an inline-style max-width clamp here would cap how far it can scale.+ expect(viewerFrame.srcdoc).toContain("width: 123px");+ expect(viewerFrame.srcdoc).toContain("max-width: none");fireEvent.keyDown(document, { key: "Escape" });await waitFor(() => {- expect(document.querySelector(".mermaid-diagram-lightbox")).toBeNull();+ expect(document.querySelector(".mermaid-viewer-canvas")).toBeNull();});});+ it("keeps the inline toolbar outside the scroll container so wide diagrams stay openable", async () => {+ const { container } = render(+ <ReadonlyContent+ content={["```mermaid", "graph LR", " A[Start] --> B[Done]", "```"].join("\n")}+ />,+ );++ await waitFor(() => {+ expect(container.querySelector(".mermaid-diagram-toolbar")).not.toBeNull();+ });++ // Previously the toolbar was an absolutely-positioned child of the+ // horizontally-scrolling element, so on a wide diagram it scrolled out of+ // view along with the content and left no way to open or copy it.+ const scroller = container.querySelector(".mermaid-diagram-scroll");+ expect(scroller).not.toBeNull();+ expect(scroller?.querySelector(".mermaid-diagram-toolbar")).toBeNull();+ });+it("shows the compact error state instead of embedding Mermaid's parser error SVG", async () => {// With suppressErrorRendering enabled, invalid syntax makes render() reject// instead of emitting Mermaid's built-in error graphic.diff --git a/packages/views/editor/styles/mermaid.css b/packages/views/editor/styles/mermaid.cssindex a9386f931e..3f14275f5d 100644--- a/packages/views/editor/styles/mermaid.css+++ b/packages/views/editor/styles/mermaid.css@@ -1,19 +1,78 @@/* Mermaid diagrams */++/* The outer container does NOT scroll — `.mermaid-diagram-scroll` inside it+ does. That split is what keeps the toolbar pinned: when the container itself+ was the scroller, the absolutely-positioned toolbar scrolled away with wide+ diagrams and left no visible way to open or copy them. */.rich-text-editor .mermaid-diagram {background: var(--muted);border: 1px solid var(--border);border-radius: var(--radius);margin: 0.75rem 0;- overflow-x: auto;+ overflow: hidden;padding: 1rem;position: relative;}+.rich-text-editor .mermaid-diagram-scroll {+ display: flex;+ /* Small diagrams sit centered at natural size; only oversized ones scroll.+ Upscaling a small diagram to fill the column would just coarsen it. */+ justify-content: center;+ overflow-x: auto;+ overflow-y: hidden;+ 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+ the selection highlight, and the drag runs on into the surrounding+ comment text. Selecting prose *through* the diagram still works — this+ only stops a selection from starting on the diagram itself. */+ user-select: none;+}+.rich-text-editor .mermaid-diagram-frame {border: 0;display: block;- height: auto;- width: 100%;+ /* 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. */+ flex: none;+ /* The iframe cannot forward clicks to this document, so it would swallow+ the click-to-open gesture. Disabling pointer events hands wheel, click,+ and drag to the scroll container instead. */+ pointer-events: none;+}++/* Edge fades: a hint that the diagram continues past the container. Driven by+ data attributes the component sets from scroll position, so a diagram that+ fits shows no fade, and a scrolled-to-the-end one fades only on the left. */+.rich-text-editor .mermaid-diagram::before,+.rich-text-editor .mermaid-diagram::after {+ content: "";+ position: absolute;+ top: 0;+ bottom: 0;+ width: 2rem;+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.15s;+ z-index: 1;+}++.rich-text-editor .mermaid-diagram::before {+ left: 0;+ background: linear-gradient(to right, var(--muted), transparent);+}++.rich-text-editor .mermaid-diagram::after {+ right: 0;+ background: linear-gradient(to left, var(--muted), transparent);+}++.rich-text-editor .mermaid-diagram[data-overflow-start]::before,+.rich-text-editor .mermaid-diagram[data-overflow-end]::after {+ opacity: 1;}.rich-text-editor .mermaid-diagram-loading,@@ -23,11 +82,45 @@margin: 0;}+.rich-text-editor .mermaid-diagram-error-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+}++.rich-text-editor .mermaid-diagram-error-head 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);+ flex: none;+}++.rich-text-editor .mermaid-diagram-error-head button:hover {+ background: var(--secondary);+ color: var(--foreground);+}++.rich-text-editor .mermaid-diagram-error-detail {+ font-family: var(--font-mono, monospace);+ font-size: 0.75rem;+ margin: 0.375rem 0 0;+ white-space: pre-wrap;+ word-break: break-word;+}++/* The error state has no inner scroller, and the container clips; without its+ own overflow a long source line would be cut off with no way to read it. */.rich-text-editor .mermaid-diagram-error pre {margin-bottom: 0;+ overflow-x: auto;}-/* Mermaid toolbar — dark pill, top-right corner, appears on hover */+/* Mermaid toolbar — dark pill, top-right corner */.rich-text-editor .mermaid-diagram-toolbar {position: absolute;top: 0.5rem;@@ -38,14 +131,22 @@background: color-mix(in srgb, black 75%, transparent);backdrop-filter: blur(8px);border-radius: var(--radius);- opacity: 0;transition: opacity 0.15s;- z-index: 1;+ z-index: 2;}-.rich-text-editor .mermaid-diagram:hover .mermaid-diagram-toolbar,-.rich-text-editor .mermaid-diagram-toolbar:focus-within {- opacity: 1;+/* Reveal-on-hover only where hovering exists. On touch there is no hover+ state to enter, so the toolbar would have been permanently invisible and+ the diagram effectively un-openable. */+@media (hover: hover) {+ .rich-text-editor .mermaid-diagram-toolbar {+ opacity: 0;+ }++ .rich-text-editor .mermaid-diagram:hover .mermaid-diagram-toolbar,+ .rich-text-editor .mermaid-diagram-toolbar:focus-within {+ opacity: 1;+ }}.rich-text-editor .mermaid-diagram-toolbar button {@@ -63,22 +164,66 @@background: color-mix(in srgb, white 15%, transparent);}-/* Mermaid lightbox — full-screen preview (ESC or click backdrop to close) */-.mermaid-diagram-lightbox {- position: fixed;- inset: 0;- z-index: 50;- display: flex;- align-items: center;- justify-content: center;- background: color-mix(in srgb, black 80%, transparent);- cursor: zoom-out;+/* Full-screen viewer canvas. Not scoped to .rich-text-editor: the viewer is+ portaled to document.body by the Dialog and never renders inside the editor+ subtree. */+.mermaid-viewer-canvas {+ position: relative;+ width: 100%;+ /* Flex owns the height: the header is shrink-0 and the canvas takes the rest.+ `min-height: 0` is what allows it to shrink below content size instead of+ pushing the toolbar out of the dialog. */+ flex: 1 1 auto;+ min-height: 0;+ overflow: hidden;+ background: var(--muted);+ cursor: grab;+ /* Claim every touch gesture: browser pan/pinch would otherwise scroll or+ zoom the page underneath instead of moving the diagram. */+ touch-action: none;+ /* A pan that leaves the canvas would otherwise start a native text selection+ and highlight the toolbar text plus the whole iframe box. Done in CSS+ rather than by preventDefault-ing pointerdown, which would also suppress+ the default focus and silently kill the keyboard controls. */+ user-select: none;+ outline: none;+}++.mermaid-viewer-canvas:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: -2px;+}++.mermaid-viewer-canvas.is-panning {+ cursor: grabbing;}-.mermaid-diagram-lightbox-frame {+.mermaid-viewer-content {+ position: absolute;+ top: 0;+ left: 0;+ transform-origin: 0 0;+ will-change: transform;+}++/* Only discrete controls (toolbar buttons, +/-/0, arrow keys) ease between+ states. Drag and wheel/pinch set `is-animated` off so the diagram tracks the+ input exactly — easing direct manipulation reads as lag, not polish. */+.mermaid-viewer-content.is-animated {+ transition: transform 150ms ease-out;+}++@media (prefers-reduced-motion: reduce) {+ .mermaid-viewer-content.is-animated {+ transition: none;+ }+}++.mermaid-viewer-frame {border: 0;- width: 90vw;- height: 90vh;+ display: block;background: transparent;- cursor: default;+ /* Same reason as the inline frame: interaction is owned by the canvas in+ this document, so the sandbox never has to be relaxed to allow zooming. */+ pointer-events: none;}diff --git a/packages/views/editor/utils/diagram-transform.test.ts b/packages/views/editor/utils/diagram-transform.test.tsnew file mode 100644index 0000000000..699513294e--- /dev/null+++ b/packages/views/editor/utils/diagram-transform.test.ts@@ -0,0 +1,200 @@+import { describe, expect, it } from "vitest";+import {+ MAX_SCALE,+ MIN_SCALE,+ centerTransform,+ clampScale,+ clampTransform,+ computeFitScale,+ computeFitTransform,+ distanceBetween,+ midpointOf,+ panBy,+ wheelZoomFactor,+ zoomByAtCenter,+ zoomToAt,+ type DiagramTransform,+} from "./diagram-transform";++const VIEWPORT = { width: 1000, height: 600 };++describe("clampScale", () => {+ it("holds zoom inside the 25%–400% product range", () => {+ expect(clampScale(0.01)).toBe(MIN_SCALE);+ expect(clampScale(99)).toBe(MAX_SCALE);+ expect(clampScale(1.5)).toBe(1.5);+ });++ it("falls back to 1 for non-finite input rather than propagating NaN into the transform", () => {+ // NaN/Infinity can only reach here from a degenerate measurement; a safe+ // default beats poisoning every later transform with NaN.+ expect(clampScale(Number.NaN)).toBe(1);+ expect(clampScale(Number.POSITIVE_INFINITY)).toBe(1);+ });+});++describe("computeFitScale", () => {+ it("shrinks an oversized diagram to the tighter axis", () => {+ // Width needs 0.5, height needs 0.6 — the diagram only fits at 0.5.+ expect(computeFitScale({ width: 2000, height: 1000 }, VIEWPORT)).toBe(0.5);+ });++ it("leaves a small diagram at natural size instead of magnifying it", () => {+ expect(computeFitScale({ width: 100, height: 80 }, VIEWPORT)).toBe(1);+ });++ it("clamps a diagram too large for even the minimum zoom", () => {+ expect(computeFitScale({ width: 100000, height: 100000 }, VIEWPORT)).toBe(MIN_SCALE);+ });++ it("returns 1 when either size is unknown, so a 0x0 measure never divides by zero", () => {+ expect(computeFitScale({ width: 0, height: 0 }, VIEWPORT)).toBe(1);+ expect(computeFitScale({ width: 100, height: 100 }, { width: 0, height: 0 })).toBe(1);+ });+});++describe("computeFitTransform", () => {+ it("centers the fitted diagram", () => {+ const transform = computeFitTransform({ width: 2000, height: 1000 }, VIEWPORT);++ expect(transform.scale).toBe(0.5);+ // 2000*0.5 = 1000 wide → exactly fills, no horizontal offset.+ expect(transform.x).toBe(0);+ // 1000*0.5 = 500 tall in a 600 viewport → 50px of slack each side.+ expect(transform.y).toBe(50);+ });+});++describe("clampTransform", () => {+ const content = { width: 400, height: 300 };++ it("keeps the diagram reachable when panned far off the left edge", () => {+ const clamped = clampTransform({ scale: 1, x: -5000, y: 0 }, content, VIEWPORT);++ // At least 48px of the 400px-wide diagram stays on screen.+ expect(clamped.x).toBe(48 - 400);+ expect(clamped.x + content.width).toBe(48);+ });++ it("keeps the diagram reachable when panned far off the right edge", () => {+ const clamped = clampTransform({ scale: 1, x: 9999, y: 0 }, content, VIEWPORT);++ expect(clamped.x).toBe(VIEWPORT.width - 48);+ });++ it("requires a diagram smaller than the margin to stay fully visible", () => {+ // A 20px-wide diagram must not be allowed to hide 48px off-screen —+ // that would leave nothing at all on the canvas.+ const clamped = clampTransform({ scale: 1, x: -9999, y: 0 }, { width: 20, height: 20 }, VIEWPORT);++ expect(clamped.x).toBe(0);+ });++ it("leaves an in-bounds transform untouched", () => {+ const transform: DiagramTransform = { scale: 1, x: 100, y: 50 };++ expect(clampTransform(transform, content, VIEWPORT)).toEqual(transform);+ });+});++describe("zoomToAt", () => {+ const content = { width: 1000, height: 1000 };++ it("pins the content point under the anchor so zoom tracks the cursor", () => {+ const start: DiagramTransform = { scale: 1, x: 0, y: 0 };+ const anchor = { x: 200, y: 100 };++ const zoomed = zoomToAt(start, 2, anchor, content, VIEWPORT);++ // The content coordinate under the anchor before and after must match.+ const contentXBefore = (anchor.x - start.x) / start.scale;+ const contentXAfter = (anchor.x - zoomed.x) / zoomed.scale;+ expect(contentXAfter).toBeCloseTo(contentXBefore, 5);++ const contentYBefore = (anchor.y - start.y) / start.scale;+ const contentYAfter = (anchor.y - zoomed.y) / zoomed.scale;+ expect(contentYAfter).toBeCloseTo(contentYBefore, 5);+ });++ it("clamps to the max zoom rather than overshooting", () => {+ const zoomed = zoomToAt({ scale: 1, x: 0, y: 0 }, 50, { x: 0, y: 0 }, content, VIEWPORT);++ expect(zoomed.scale).toBe(MAX_SCALE);+ });++ it("clamps to the min zoom rather than undershooting", () => {+ const zoomed = zoomToAt({ scale: 1, x: 0, y: 0 }, 0.001, { x: 0, y: 0 }, content, VIEWPORT);++ expect(zoomed.scale).toBe(MIN_SCALE);+ });++ it("is a no-op once already at the limit, so held keys/wheel do not drift the diagram", () => {+ const atMax: DiagramTransform = { scale: MAX_SCALE, x: 10, y: 20 };++ expect(zoomToAt(atMax, MAX_SCALE * 2, { x: 100, y: 100 }, content, VIEWPORT)).toBe(atMax);+ });+});++describe("zoomByAtCenter", () => {+ it("zooms about the viewport center for button/keyboard input", () => {+ const start: DiagramTransform = { scale: 1, x: 0, y: 0 };+ const center = { x: VIEWPORT.width / 2, y: VIEWPORT.height / 2 };++ const zoomed = zoomByAtCenter(start, 2, { width: 1000, height: 1000 }, VIEWPORT);++ expect(zoomed.scale).toBe(2);+ expect((center.x - zoomed.x) / zoomed.scale).toBeCloseTo(center.x - start.x, 5);+ });+});++describe("panBy", () => {+ it("moves by the delta and re-clamps", () => {+ const panned = panBy({ scale: 1, x: 0, y: 0 }, 50, -20, { width: 400, height: 300 }, VIEWPORT);++ expect(panned).toEqual({ scale: 1, x: 50, y: -20 });+ });++ it("cannot pan the diagram out of sight", () => {+ const panned = panBy({ scale: 1, x: 0, y: 0 }, -100000, 0, { width: 400, height: 300 }, VIEWPORT);++ expect(panned.x + 400).toBe(48);+ });+});++describe("centerTransform", () => {+ it("centers content at an explicit scale", () => {+ expect(centerTransform({ width: 400, height: 200 }, VIEWPORT, 1)).toEqual({+ scale: 1,+ x: 300,+ y: 200,+ });+ });+});++describe("wheelZoomFactor", () => {+ it("zooms in when scrolling up and out when scrolling down", () => {+ expect(wheelZoomFactor(-100, 0)).toBeGreaterThan(1);+ expect(wheelZoomFactor(100, 0)).toBeLessThan(1);+ });++ it("is symmetric, so equal opposite scrolls return to the original scale", () => {+ expect(wheelZoomFactor(-100, 0) * wheelZoomFactor(100, 0)).toBeCloseTo(1, 10);+ });++ it("normalizes line and page delta modes so a mouse wheel is not 16x weaker than a trackpad", () => {+ // deltaMode 1 (lines) — one line is treated as 16 pixels.+ expect(wheelZoomFactor(1, 1)).toBeCloseTo(wheelZoomFactor(16, 0), 10);+ // deltaMode 2 (pages) — one page is treated as 100 pixels.+ expect(wheelZoomFactor(1, 2)).toBeCloseTo(wheelZoomFactor(100, 0), 10);+ });+});++describe("pinch helpers", () => {+ it("measures distance between two pointers", () => {+ expect(distanceBetween({ x: 0, y: 0 }, { x: 3, y: 4 })).toBe(5);+ });++ it("finds the midpoint used as the pinch anchor", () => {+ expect(midpointOf({ x: 0, y: 0 }, { x: 10, y: 20 })).toEqual({ x: 5, y: 10 });+ });+});diff --git a/packages/views/editor/utils/diagram-transform.ts b/packages/views/editor/utils/diagram-transform.tsnew file mode 100644index 0000000000..e2bcbb9580--- /dev/null+++ b/packages/views/editor/utils/diagram-transform.ts@@ -0,0 +1,211 @@+/**+ * Pan/zoom math for the Mermaid diagram viewer.+ *+ * The diagram itself lives inside an empty-sandbox iframe, which cannot run+ * scripts and therefore cannot implement its own pan/zoom. All interaction is+ * driven from the host document by transforming the wrapper around that+ * iframe, so this module stays pure DOM-free math: it is the single place+ * where "where is the diagram and how big is it" is decided.+ *+ * Coordinate model: the content wrapper has `transform-origin: 0 0` and is+ * positioned at the viewport's top-left, so a transform is applied as+ * `translate(x, y) scale(scale)`. `x`/`y` are viewport-space pixels of the+ * content's top-left corner; `scale` is the natural-size multiplier.+ */++export interface Size {+ width: number;+ height: number;+}++export interface Point {+ x: number;+ y: number;+}++export interface DiagramTransform {+ scale: number;+ x: number;+ y: number;+}++export const MIN_SCALE = 0.25;+export const MAX_SCALE = 4;++// How much of the diagram must stay inside the viewport. Panning is clamped so+// the user can never fling the canvas out of sight and be left staring at an+// empty viewport with no way back other than Reset.+const MIN_VISIBLE_PX = 48;++// Keyboard/button zoom step. 1.2 gives ~4 presses per doubling, which feels+// responsive without skipping past the scale the user wanted.+export const ZOOM_STEP = 1.2;++// Keyboard pan step, in viewport pixels per arrow-key press.+export const PAN_STEP_PX = 48;++export function clampScale(scale: number): number {+ if (!Number.isFinite(scale)) return 1;+ return Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale));+}++function hasArea(size: Size): boolean {+ return (+ Number.isFinite(size.width) &&+ Number.isFinite(size.height) &&+ size.width > 0 &&+ size.height > 0+ );+}++/**+ * Scale that makes the content fit the viewport, never magnifying past natural+ * size. A small diagram opened in a large viewer should read at 100%, not be+ * blown up until its strokes look broken — same convention as macOS Preview.+ */+export function computeFitScale(content: Size, viewport: Size): number {+ if (!hasArea(content) || !hasArea(viewport)) return 1;++ return clampScale(+ Math.min(1, viewport.width / content.width, viewport.height / content.height),+ );+}++/** Centers `content` at `scale` inside `viewport`. */+export function centerTransform(+ content: Size,+ viewport: Size,+ scale: number,+): DiagramTransform {+ return {+ scale,+ x: (viewport.width - content.width * scale) / 2,+ y: (viewport.height - content.height * scale) / 2,+ };+}++/** Default view: fit to viewport, centered. */+export function computeFitTransform(content: Size, viewport: Size): DiagramTransform {+ return centerTransform(content, viewport, computeFitScale(content, viewport));+}++/**+ * Keeps at least `MIN_VISIBLE_PX` of the diagram inside the viewport (or all of+ * it, when the diagram is smaller than that margin), so the canvas can never be+ * panned into nothing.+ */+export function clampTransform(+ transform: DiagramTransform,+ content: Size,+ viewport: Size,+): DiagramTransform {+ if (!hasArea(content) || !hasArea(viewport)) return transform;++ const scale = clampScale(transform.scale);+ const scaledWidth = content.width * scale;+ const scaledHeight = content.height * scale;+ const marginX = Math.min(MIN_VISIBLE_PX, scaledWidth);+ const marginY = Math.min(MIN_VISIBLE_PX, scaledHeight);++ return {+ scale,+ x: Math.min(+ Math.max(transform.x, marginX - scaledWidth),+ viewport.width - marginX,+ ),+ y: Math.min(+ Math.max(transform.y, marginY - scaledHeight),+ viewport.height - marginY,+ ),+ };+}++/**+ * Zooms to `nextScale` while pinning the content point under `anchor` (in+ * viewport coordinates) to that same spot. This is what makes wheel and pinch+ * zoom track the cursor/fingers instead of drifting toward a corner.+ */+export function zoomToAt(+ transform: DiagramTransform,+ nextScale: number,+ anchor: Point,+ content: Size,+ viewport: Size,+): DiagramTransform {+ const scale = clampScale(nextScale);+ if (scale === transform.scale) return transform;++ const ratio = scale / transform.scale;++ return clampTransform(+ {+ scale,+ x: anchor.x - (anchor.x - transform.x) * ratio,+ y: anchor.y - (anchor.y - transform.y) * ratio,+ },+ content,+ viewport,+ );+}++/** Multiplicative zoom (wheel notch, +/- key, toolbar button) about `anchor`. */+export function zoomByAt(+ transform: DiagramTransform,+ factor: number,+ anchor: Point,+ content: Size,+ viewport: Size,+): DiagramTransform {+ return zoomToAt(transform, transform.scale * factor, anchor, content, viewport);+}++/** Zoom about the viewport center — the anchor to use for keyboard/buttons. */+export function zoomByAtCenter(+ transform: DiagramTransform,+ factor: number,+ content: Size,+ viewport: Size,+): DiagramTransform {+ return zoomByAt(+ transform,+ factor,+ { x: viewport.width / 2, y: viewport.height / 2 },+ content,+ viewport,+ );+}++export function panBy(+ transform: DiagramTransform,+ deltaX: number,+ deltaY: number,+ content: Size,+ viewport: Size,+): DiagramTransform {+ return clampTransform(+ { scale: transform.scale, x: transform.x + deltaX, y: transform.y + deltaY },+ content,+ viewport,+ );+}++/** Distance between two active pointers — the pinch gesture's scale signal. */+export function distanceBetween(a: Point, b: Point): number {+ return Math.hypot(a.x - b.x, a.y - b.y);+}++export function midpointOf(a: Point, b: Point): Point {+ return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };+}++/**+ * Converts a wheel notch into a zoom factor. `deltaMode` matters: mice report+ * lines (1) or pages (2) while trackpads report pixels (0), so a raw `deltaY`+ * comparison would make one of the two unusable.+ */+export function wheelZoomFactor(deltaY: number, deltaMode: number): number {+ const pixels = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 100 : deltaY;+ // Exponential mapping keeps zooming symmetric: equal and opposite scrolls+ // return to the original scale. The 400 divisor tunes trackpad sensitivity.+ return Math.exp(-pixels / 400);+}diff --git a/packages/views/editor/utils/mermaid-export.test.ts b/packages/views/editor/utils/mermaid-export.test.tsnew file mode 100644index 0000000000..c5033a3812--- /dev/null+++ b/packages/views/editor/utils/mermaid-export.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import { buildExportSvg, diagramFilenameStem } from "./mermaid-export";++const BASE_OPTIONS = {+ background: "rgb(240, 240, 240)",+ fontFamily: "Inter, sans-serif",+ width: 800,+ height: 600,+};++function parse(markup: string): SVGElement {+ const doc = new DOMParser().parseFromString(markup, "image/svg+xml");+ return doc.documentElement as unknown as SVGElement;+}++describe("buildExportSvg", () => {+ it("replaces Mermaid's percentage width with concrete pixels an <img> can size against", () => {+ // Mermaid renders for embedding: width="100%" has no basis in a file, and+ // the PNG path's <img> would have no intrinsic size to draw.+ const result = buildExportSvg(+ '<svg width="100%" viewBox="0 0 800 600"><g/></svg>',+ BASE_OPTIONS,+ );++ const root = parse(result!);+ expect(root.getAttribute("width")).toBe("800");+ expect(root.getAttribute("height")).toBe("600");+ });++ it("drops the host-tuned max-width so the export is not clipped to the old container", () => {+ const result = buildExportSvg(+ '<svg style="max-width: 320px;" viewBox="0 0 800 600"><g/></svg>',+ BASE_OPTIONS,+ );++ expect(result).not.toContain("max-width");+ });++ it("paints an opaque background so the export is not transparent-on-transparent", () => {+ const result = buildExportSvg('<svg viewBox="0 0 800 600"><g/></svg>', BASE_OPTIONS);++ const root = parse(result!);+ const rect = root.firstElementChild;+ expect(rect?.tagName.toLowerCase()).toBe("rect");+ expect(rect?.getAttribute("fill")).toBe("rgb(240, 240, 240)");+ });++ it("covers a negative-origin viewBox, so padded diagrams do not export with transparent margins", () => {+ // Mermaid emits negative viewBox origins for diagrams with padding; a+ // 0,0-anchored background rect would leave those margins unpainted.+ const result = buildExportSvg('<svg viewBox="-8 -12 800 600"><g/></svg>', BASE_OPTIONS);++ const rect = parse(result!).firstElementChild;+ expect(rect?.getAttribute("x")).toBe("-8");+ expect(rect?.getAttribute("y")).toBe("-12");+ expect(rect?.getAttribute("width")).toBe("800");+ expect(rect?.getAttribute("height")).toBe("600");+ });++ it("falls back to the given size when the viewBox is missing or malformed", () => {+ const rect = parse(buildExportSvg("<svg><g/></svg>", BASE_OPTIONS)!).firstElementChild;+ expect(rect?.getAttribute("width")).toBe("800");+ expect(rect?.getAttribute("height")).toBe("600");++ const bad = parse(buildExportSvg('<svg viewBox="nonsense"><g/></svg>', BASE_OPTIONS)!);+ expect(bad.firstElementChild?.getAttribute("width")).toBe("800");+ });++ it("resolves font-family, which has nothing to inherit from in a standalone file", () => {+ const result = buildExportSvg('<svg viewBox="0 0 800 600"><g/></svg>', BASE_OPTIONS);++ expect(result).toContain("Inter, sans-serif");+ });++ it("declares the SVG namespace so the file opens outside a browser document", () => {+ const result = buildExportSvg('<svg viewBox="0 0 800 600"><g/></svg>', BASE_OPTIONS);++ expect(result).toContain("http://www.w3.org/2000/svg");+ });++ it("preserves the diagram content", () => {+ const result = buildExportSvg(+ '<svg viewBox="0 0 800 600"><text>Start</text></svg>',+ BASE_OPTIONS,+ );++ expect(result).toContain("Start");+ });++ it("returns null on unparseable markup instead of emitting a corrupt file", () => {+ expect(buildExportSvg("<svg><unclosed>", BASE_OPTIONS)).toBeNull();+ });++ it("returns null when the root is not an <svg>", () => {+ expect(buildExportSvg("<div>not a diagram</div>", BASE_OPTIONS)).toBeNull();+ });+});++describe("diagramFilenameStem", () => {+ it("derives the stem from the first meaningful line", () => {+ expect(diagramFilenameStem("graph LR\n A --> B")).toBe("graph-lr");+ });++ it("skips %% comments and blank lines to reach the real declaration", () => {+ expect(diagramFilenameStem("\n%% title: ignored\n\nsequenceDiagram\n A->>B: hi")).toBe(+ "sequencediagram",+ );+ });++ it("falls back to 'diagram' when nothing usable survives slugification", () => {+ expect(diagramFilenameStem("")).toBe("diagram");+ expect(diagramFilenameStem("%%%%")).toBe("diagram");+ expect(diagramFilenameStem("中文标题")).toBe("diagram");+ });++ it("caps length and leaves no trailing separator for the extension to butt against", () => {+ const stem = diagramFilenameStem("graph LR with an extremely long trailing description here");++ expect(stem.length).toBeLessThanOrEqual(40);+ expect(stem.endsWith("-")).toBe(false);+ });+});diff --git a/packages/views/editor/utils/mermaid-export.ts b/packages/views/editor/utils/mermaid-export.tsnew file mode 100644index 0000000000..3cd05b8768--- /dev/null+++ b/packages/views/editor/utils/mermaid-export.ts@@ -0,0 +1,208 @@+/**+ * Export helpers for Mermaid diagrams (`.mmd` source, `.svg`, `.png`).+ *+ * Export runs in the host document against the SVG markup Mermaid returned —+ * never by reaching into the preview iframe, which is `sandbox=""` and+ * deliberately unreachable. The markup therefore has to be made standalone+ * first: Mermaid renders for embedding, so it emits a transparent background,+ * a `max-width` style tuned to the host container, and `font-family: inherit`,+ * none of which survive being opened as a file on their own.+ */++const SVG_NAMESPACE = "http://www.w3.org/2000/svg";++// Rasterize above CSS pixels so PNGs stay legible when zoomed or pasted into a+// doc. 2 matches a typical HiDPI screen without producing huge files.+const PNG_PIXEL_RATIO = 2;++export interface ExportSvgOptions {+ /** Opaque page color, so an exported file is not transparent-on-transparent. */+ background: string;+ /** Concrete stack to replace Mermaid's `inherit`, which has nothing to inherit from in a file. */+ fontFamily: string;+ width: number;+ height: number;+}++interface ViewBox {+ minX: number;+ minY: number;+ width: number;+ height: number;+}++function readViewBox(root: SVGElement, fallback: Size): ViewBox {+ const parts = (root.getAttribute("viewBox") ?? "")+ .split(/[\s,]+/)+ .map((value) => Number.parseFloat(value));++ if (parts.length === 4 && parts.every((value) => Number.isFinite(value))) {+ const [minX, minY, width, height] = parts as [number, number, number, number];+ if (width > 0 && height > 0) return { minX, minY, width, height };+ }++ return { minX: 0, minY: 0, width: fallback.width, height: fallback.height };+}++interface Size {+ width: number;+ height: number;+}++/**+ * Rewrites a `style` attribute's declarations.+ *+ * Done at the attribute level rather than through the `.style` CSSStyleDeclaration+ * API: an SVG root parsed out of an XML document does not reliably expose that+ * API (jsdom does not implement it at all), so touching `.style` here would+ * throw outside a real browser.+ */+function mergeStyleAttribute(+ existing: string | null,+ overrides: Record<string, string>,+ remove: string[],+): string {+ const declarations = new Map<string, string>();++ for (const part of (existing ?? "").split(";")) {+ const separator = part.indexOf(":");+ if (separator === -1) continue;+ const property = part.slice(0, separator).trim().toLowerCase();+ if (property) declarations.set(property, part.slice(separator + 1).trim());+ }++ for (const property of remove) declarations.delete(property);+ for (const [property, value] of Object.entries(overrides)) {+ declarations.set(property, value);+ }++ return [...declarations]+ .map(([property, value]) => `${property}: ${value}`)+ .join("; ");+}++/**+ * Rewrites embedded Mermaid SVG markup into a standalone document.+ *+ * @returns serialized SVG, or `null` when the markup does not parse.+ */+export function buildExportSvg(+ svgMarkup: string,+ { background, fontFamily, width, height }: ExportSvgOptions,+): string | null {+ const parsed = new DOMParser().parseFromString(svgMarkup, "image/svg+xml");+ if (parsed.querySelector("parsererror")) return null;++ const root = parsed.documentElement as unknown as SVGElement;+ if (root.nodeName.toLowerCase() !== "svg") return null;++ root.setAttribute("xmlns", SVG_NAMESPACE);+ // Concrete pixel dimensions: `width="100%"` (Mermaid's default) has no+ // percentage basis in a standalone file, and an <img> loading it for the PNG+ // path would have no intrinsic size to draw.+ root.setAttribute("width", String(width));+ root.setAttribute("height", String(height));+ root.setAttribute(+ "style",+ mergeStyleAttribute(+ root.getAttribute("style"),+ { "background-color": background, "font-family": fontFamily },+ // Mermaid sizes the embedded SVG to the host container; kept, it would+ // clip the export to whatever width the page happened to have.+ ["max-width"],+ ),+ );++ const viewBox = readViewBox(root, { width, height });+ const backgroundRect = parsed.createElementNS(SVG_NAMESPACE, "rect");+ // Cover the viewBox rather than 0,0 100%x100%: Mermaid emits negative+ // viewBox origins for diagrams with padding, and a 0,0-anchored rect would+ // leave those margins transparent.+ backgroundRect.setAttribute("x", String(viewBox.minX));+ backgroundRect.setAttribute("y", String(viewBox.minY));+ backgroundRect.setAttribute("width", String(viewBox.width));+ backgroundRect.setAttribute("height", String(viewBox.height));+ backgroundRect.setAttribute("fill", background);+ root.insertBefore(backgroundRect, root.firstChild);++ return new XMLSerializer().serializeToString(root);+}++function loadImage(url: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => resolve(image);+ image.onerror = () => reject(new Error("Failed to load SVG for PNG export"));+ image.src = url;+ });+}++/**+ * Rasterizes standalone SVG markup to a PNG blob.+ *+ * The blob URL is same-origin and the markup carries no external references+ * (fonts are resolved to a concrete stack by `buildExportSvg`), so the canvas+ * stays untainted and `toBlob` is allowed to read it back.+ */+export async function renderSvgToPngBlob(+ standaloneSvg: string,+ { width, height }: Size,+ pixelRatio: number = PNG_PIXEL_RATIO,+): Promise<Blob> {+ const svgBlob = new Blob([standaloneSvg], { type: "image/svg+xml;charset=utf-8" });+ const url = URL.createObjectURL(svgBlob);++ try {+ const image = await loadImage(url);+ const canvas = document.createElement("canvas");+ canvas.width = Math.max(1, Math.round(width * pixelRatio));+ canvas.height = Math.max(1, Math.round(height * pixelRatio));++ const context = canvas.getContext("2d");+ if (!context) throw new Error("Canvas 2D context unavailable for PNG export");+ context.drawImage(image, 0, 0, canvas.width, canvas.height);++ const blob = await new Promise<Blob | null>((resolve) =>+ canvas.toBlob(resolve, "image/png"),+ );+ if (!blob) throw new Error("Failed to encode PNG");++ return blob;+ } finally {+ URL.revokeObjectURL(url);+ }+}++export function downloadBlob(blob: Blob, filename: string): void {+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ anchor.rel = "noopener";+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ // Revoke on the next task: Safari aborts the download if the URL dies while+ // the click is still being processed synchronously.+ setTimeout(() => URL.revokeObjectURL(url), 0);+}++/**+ * Filename stem derived from the diagram's first meaningful line, so a folder+ * of exports is scannable instead of being `diagram (3).png` all the way down.+ */+export function diagramFilenameStem(chart: string): string {+ const firstLine = chart+ .split("\n")+ .map((line) => line.trim())+ .find((line) => line.length > 0 && !line.startsWith("%%"));++ const slug = (firstLine ?? "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 40)+ .replace(/-+$/g, "");++ return slug || "diagram";+}diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex e25d82e24e..06e44dcab2 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -88,6 +88,22 @@},"mermaid": {"render_error": "Unable to render Mermaid diagram.",- "rendering": "Rendering diagram…"+ "rendering": "Rendering diagram…",+ "viewer_title": "Diagram",+ "canvas_label": "Diagram canvas. Drag to pan, scroll to zoom.",+ "open_viewer": "Open diagram viewer",+ "close_viewer": "Close",+ "copy_source": "Copy diagram source",+ "show_source": "Show source",+ "show_diagram": "Show diagram",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "zoom_fit": "Fit to view",+ "zoom_actual": "Actual size",+ "reset_view": "Reset view",+ "export": "Export",+ "export_png": "Download PNG",+ "export_svg": "Download SVG",+ "export_source": "Download .mmd"}}diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 1ae355a7a3..d861e064dd 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -81,7 +81,23 @@},"mermaid": {"render_error": "Mermaid ダイアグラムを描画できません。",- "rendering": "ダイアグラムを描画中…"+ "rendering": "ダイアグラムを描画中…",+ "viewer_title": "ダイアグラム",+ "canvas_label": "ダイアグラムキャンバス。ドラッグで移動、スクロールで拡大縮小できます。",+ "open_viewer": "ダイアグラムビューアを開く",+ "close_viewer": "閉じる",+ "copy_source": "ダイアグラムのソースをコピー",+ "show_source": "ソースを表示",+ "show_diagram": "ダイアグラムを表示",+ "zoom_in": "拡大",+ "zoom_out": "縮小",+ "zoom_fit": "画面に合わせる",+ "zoom_actual": "実際のサイズ",+ "reset_view": "表示をリセット",+ "export": "エクスポート",+ "export_png": "PNG をダウンロード",+ "export_svg": "SVG をダウンロード",+ "export_source": ".mmd をダウンロード"},"slash_command": {"no_skills_configured": "設定済みスキルなし",diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 8a41f65bc1..35610a16d3 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -81,7 +81,23 @@},"mermaid": {"render_error": "Mermaid 다이어그램을 렌더링할 수 없습니다.",- "rendering": "다이어그램 렌더링 중..."+ "rendering": "다이어그램 렌더링 중...",+ "viewer_title": "다이어그램",+ "canvas_label": "다이어그램 캔버스. 드래그하여 이동, 스크롤하여 확대/축소할 수 있습니다.",+ "open_viewer": "다이어그램 뷰어 열기",+ "close_viewer": "닫기",+ "copy_source": "다이어그램 소스 복사",+ "show_source": "소스 표시",+ "show_diagram": "다이어그램 표시",+ "zoom_in": "확대",+ "zoom_out": "축소",+ "zoom_fit": "화면에 맞추기",+ "zoom_actual": "실제 크기",+ "reset_view": "보기 초기화",+ "export": "내보내기",+ "export_png": "PNG 다운로드",+ "export_svg": "SVG 다운로드",+ "export_source": ".mmd 다운로드"},"slash_command": {"no_skills_configured": "구성된 스킬 없음",diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 7c6c8ca7a6..ab5a6bd47f 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -88,6 +88,22 @@},"mermaid": {"render_error": "无法渲染 Mermaid 图。",- "rendering": "渲染中…"+ "rendering": "渲染中…",+ "viewer_title": "图表",+ "canvas_label": "图表画布,拖动可平移,滚动可缩放。",+ "open_viewer": "打开图表查看器",+ "close_viewer": "关闭",+ "copy_source": "复制图表源码",+ "show_source": "显示源码",+ "show_diagram": "显示图表",+ "zoom_in": "放大",+ "zoom_out": "缩小",+ "zoom_fit": "适应窗口",+ "zoom_actual": "实际大小",+ "reset_view": "重置视图",+ "export": "导出",+ "export_png": "下载 PNG",+ "export_svg": "下载 SVG",+ "export_source": "下载 .mmd"}}