Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(editor): pan/zoom the image attachment preview (MUL-5316) (#5971)
Naiyuan Qinga964c5229d16
diff --git a/packages/ui/components/ui/kbd.tsx b/packages/ui/components/ui/kbd.tsxindex 27f1475a65..860888b090 100644--- a/packages/ui/components/ui/kbd.tsx+++ b/packages/ui/components/ui/kbd.tsx@@ -5,7 +5,10 @@ function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {<kbddata-slot="kbd"className={cn(- "pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3",+ // No in-tooltip color overrides: upstream shadcn inverts its tooltip+ // (dark surface in light mode), but our TooltipContent keeps the+ // popover surface, so the regular muted keycap colors stay readable.+ "pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none [&_svg:not([class*='size-'])]:size-3",className)}{...props}diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex fee7c881b9..3d6c417a0f 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -100,7 +100,16 @@ vi.mock("../i18n", () => ({useT: () => ({t: (sel: (s: Record<string, Record<string, string>>) => string) =>sel({- image: { download: "Download" },+ image: {+ download: "Download",+ canvas_label: "Image canvas",+ },+ canvas: {+ zoom_in: "Zoom in",+ zoom_out: "Zoom out",+ zoom_fit: "Fit to view",+ zoom_actual: "Actual size",+ },attachment: {preview: "Preview",preview_loading: "Loading preview…",@@ -705,3 +714,282 @@ describe("useAttachmentPreview — tryOpen gate", () => {expect(opened).toBe(false);});});++// ---------------------------------------------------------------------------+// Image zoom canvas+// ---------------------------------------------------------------------------++// jsdom has no layout and never decodes images, so both inputs the canvas+// needs — its own size and the image's intrinsic size — have to be pinned.+const CANVAS_VIEWPORT = { width: 800, height: 400 };++function stubCanvasViewport() {+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(+ CANVAS_VIEWPORT.width,+ );+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(+ CANVAS_VIEWPORT.height,+ );+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({+ bottom: CANVAS_VIEWPORT.height,+ height: CANVAS_VIEWPORT.height,+ left: 0,+ right: CANVAS_VIEWPORT.width,+ top: 0,+ width: CANVAS_VIEWPORT.width,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ });+}++function stubNaturalSize(size: { width: number; height: number }) {+ vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get").mockReturnValue(+ size.width,+ );+ vi.spyOn(HTMLImageElement.prototype, "naturalHeight", "get").mockReturnValue(+ size.height,+ );+}++function imageAttachment(): Attachment {+ return makeAttachment({ filename: "shot.png", content_type: "image/png" });+}++function zoomCanvas(): HTMLElement {+ return screen.getByRole("application");+}++function canvasContent(): HTMLElement {+ return document.querySelector<HTMLElement>(".zoom-canvas-content")!;+}++function currentScale(): number {+ const match = /scale\(([\d.]+)\)/.exec(canvasContent().style.transform);+ return Number.parseFloat(match![1]!);+}++function renderImagePreview(attachment: Attachment = imageAttachment()) {+ return render(+ <AttachmentPreviewModal+ source={{ kind: "full", attachment }}+ open+ onClose={() => {}}+ />,+ );+}++describe("AttachmentPreviewModal — image zoom", () => {+ beforeEach(() => {+ stubCanvasViewport();+ });++ it("fits an oversized image to the canvas on open", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ // 1600x800 in an 800x400 canvas fits at exactly 50%.+ expect(currentScale()).toBeCloseTo(0.5, 5);+ expect(screen.getByText("50%")).toBeInTheDocument();+ });++ it("opens a small image at 100% instead of magnifying it", () => {+ stubNaturalSize({ width: 200, height: 100 });+ renderImagePreview();++ expect(currentScale()).toBe(1);+ });++ it("shows a long screenshot in full, below the 25% floor", () => {+ // The regression this pins: with a hard MIN_SCALE floor the fit snapped+ // back up to 25% and a full-page screenshot opened cropped, with no zoom+ // level that showed all of it.+ stubNaturalSize({ width: 1600, height: 8000 });+ renderImagePreview();++ const scale = currentScale();+ expect(scale).toBeLessThan(0.25);+ expect(8000 * scale).toBeLessThanOrEqual(CANVAS_VIEWPORT.height + 0.001);+ });++ it("zooms in and out from the toolbar", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));+ expect(currentScale()).toBeCloseTo(0.5 * 1.2, 5);++ fireEvent.click(screen.getByRole("button", { name: "Zoom out" }));+ expect(currentScale()).toBeCloseTo(0.5, 5);+ });++ it("jumps to natural size and back to fit", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ fireEvent.click(screen.getByRole("button", { name: "Actual size" }));+ expect(currentScale()).toBe(1);++ fireEvent.click(screen.getByRole("button", { name: "Fit to view" }));+ expect(currentScale()).toBeCloseTo(0.5, 5);+ });++ it("zooms on wheel without scrolling the page behind the modal", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ const wheel = new WheelEvent("wheel", {+ deltaY: -100,+ clientX: 400,+ clientY: 200,+ bubbles: true,+ cancelable: true,+ });+ // Dispatched raw rather than via fireEvent.wheel so the test can assert+ // preventDefault — the thing that stops the page behind from scrolling.+ act(() => {+ zoomCanvas().dispatchEvent(wheel);+ });++ expect(currentScale()).toBeGreaterThan(0.5);+ expect(wheel.defaultPrevented).toBe(true);+ });++ it("pans on drag", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();+ const before = canvasContent().style.transform;++ fireEvent.pointerDown(zoomCanvas(), { pointerId: 1, clientX: 400, clientY: 200 });+ fireEvent.pointerMove(zoomCanvas(), { pointerId: 1, clientX: 340, clientY: 170 });+ fireEvent.pointerUp(zoomCanvas(), { pointerId: 1 });++ expect(canvasContent().style.transform).not.toBe(before);+ });++ it("toggles between fit and 100% on double-click", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ fireEvent.doubleClick(zoomCanvas(), { clientX: 400, clientY: 200 });+ expect(currentScale()).toBe(1);++ fireEvent.doubleClick(zoomCanvas(), { clientX: 400, clientY: 200 });+ expect(currentScale()).toBeCloseTo(0.5, 5);+ });++ it("focuses the canvas on open so the keyboard controls work without a click first", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ expect(document.activeElement).toBe(zoomCanvas());++ fireEvent.keyDown(zoomCanvas(), { key: "+" });+ expect(currentScale()).toBeCloseTo(0.5 * 1.2, 5);+ });++ it("re-fits on reopen instead of restoring the previous zoom", async () => {+ stubNaturalSize({ width: 1600, height: 800 });+ const att = imageAttachment();+ render(<ClosablePreview attachment={att} />);++ fireEvent.click(screen.getByRole("button", { name: "Actual size" }));+ expect(currentScale()).toBe(1);++ fireEvent.click(screen.getByTitle("Close"));+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ renderImagePreview(att);+ expect(currentScale()).toBeCloseTo(0.5, 5);+ });++ it("letterboxes an image with no intrinsic size and hides the zoom controls", () => {+ // An SVG that declares only a viewBox has no intrinsic size in Chromium,+ // so there is nothing to build a transform against. It must still render.+ stubNaturalSize({ width: 0, height: 0 });+ renderImagePreview(+ makeAttachment({ filename: "chart.svg", content_type: "image/svg+xml" }),+ );++ expect(document.querySelector(".zoom-canvas-content")).toBeNull();+ expect(document.querySelector(".zoom-canvas-fit")).not.toBeNull();+ expect(document.querySelector("img")?.className).toContain("object-contain");+ expect(screen.queryByRole("button", { name: "Zoom in" })).toBeNull();+ });++ it("keeps a pan that ends over the backdrop from closing the modal", () => {+ stubNaturalSize({ width: 1600, height: 800 });+ const onClose = vi.fn();+ render(+ <AttachmentPreviewModal+ source={{ kind: "full", attachment: imageAttachment() }}+ open+ onClose={onClose}+ />,+ );++ // A drag released outside the panel bubbles its click to the backdrop.+ fireEvent.click(zoomCanvas());+ expect(onClose).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("dialog"));+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("gives the canvas a flex-column parent so it can claim the modal body height", () => {+ // jsdom has no layout, so this is asserted structurally: `.zoom-canvas`+ // sizes itself with `flex: 1 1 auto` and positions its content+ // absolutely. In a plain block parent it collapses to zero height and the+ // image disappears entirely.+ stubNaturalSize({ width: 1600, height: 800 });+ renderImagePreview();++ const body = zoomCanvas().parentElement!;+ expect(body.className).toContain("flex-col");+ expect(body.className).toContain("flex-1");+ expect(body.className).toContain("overflow-hidden");+ });++ it("keeps the scrolling block body for non-image kinds", () => {+ render(+ <AttachmentPreviewModal+ source={{+ kind: "full",+ attachment: makeAttachment({+ filename: "notes.md",+ content_type: "text/markdown",+ }),+ }}+ open+ onClose={() => {}}+ />,+ );++ // A flex column here would let a tall markdown preview shrink to fit+ // instead of scrolling.+ const body = document.querySelector(".min-h-0.flex-1")!;+ expect(body.className).toContain("overflow-auto");+ expect(body.className).not.toContain("flex-col");+ });++ it("shows no zoom controls for non-image kinds", () => {+ render(+ <AttachmentPreviewModal+ source={{+ kind: "full",+ attachment: makeAttachment({+ filename: "manual.pdf",+ content_type: "application/pdf",+ }),+ }}+ open+ onClose={() => {}}+ />,+ );++ expect(screen.queryByRole("button", { name: "Zoom in" })).toBeNull();+ expect(screen.queryByRole("application")).toBeNull();+ });+});diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex 1b1d06a6f2..c97e7c9f07 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -5,8 +5,10 @@** Single modal for every previewable kind. Handles 7 PreviewKinds:*- * - image : <img className="object-contain"> centered in the modal frame.- * Replaces the previous standalone ImageLightbox.+ * - image : <img> on the shared ZoomCanvas — fit on open, then wheel /+ * drag / pinch / double-click / keyboard zoom, same controls as+ * the Mermaid viewer. Replaces the previous standalone+ * ImageLightbox.* - pdf : <iframe src={download_url}> — relies on Chromium's PDFium* plugin. On desktop, requires webPreferences.plugins=true* (see apps/desktop/src/main/index.ts).@@ -46,6 +48,7 @@ import {import { Download, ExternalLink, FileText, Loader2, X } from "lucide-react";import type { Attachment } from "@multica/core/types";import { paths, useWorkspaceSlug } from "@multica/core/paths";+import { cn } from "@multica/ui/lib/utils";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import {UI_EASE_OUT,@@ -62,6 +65,9 @@ import {} from "./utils/preview";import { useDownloadAttachment } from "./use-download-attachment";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";+import { useZoomCanvas, type ZoomCanvasApi } from "./hooks/use-zoom-canvas";+import { ZoomCanvas, ZoomControls } from "./zoom-canvas";+import type { Size } from "./utils/zoom-transform";import { HtmlPreviewBody } from "./html-preview-body";import { CodeBlockStatic } from "./code-block-static";@@ -210,7 +216,6 @@ export function AttachmentPreviewModal({onClose,onExitComplete,}: AttachmentPreviewModalProps & { onExitComplete?: () => void }) {- const { t } = useT("editor");const download = useDownloadAttachment();const shouldReduceMotion = useReducedMotion() ?? false;const state = normalize(source);@@ -268,7 +273,13 @@ export function AttachmentPreviewModal({{open && (<motion.divclassName="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"- onClick={onClose}+ // Only a click that lands on the backdrop itself closes. A pan that+ // starts on the zoom canvas and releases out here retargets its+ // click through pointer capture, but this makes the intent explicit+ // instead of relying on that.+ onClick={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}role="dialog"aria-modal="true"aria-label={state.filename}@@ -316,57 +327,206 @@ export function AttachmentPreviewModal({},}}>- <div className="flex items-center gap-2 border-b border-border bg-muted/30 px-4 py-2">- <FileText className="size-4 shrink-0 text-muted-foreground" />- <p className="truncate text-sm font-medium">{state.filename}</p>- <span className="ml-1 shrink-0 text-xs text-muted-foreground">- {state.contentType || "—"}- </span>- <div className="ml-auto flex items-center gap-1">- {canOpenInNewTab && (- <button- type="button"- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- title={t(($) => $.attachment.open_in_new_tab)}- aria-label={t(($) => $.attachment.open_in_new_tab)}- onClick={handleOpenInNewTab}- >- <ExternalLink className="size-4" />- </button>- )}- <button- type="button"- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- title={t(($) => $.image.download)}- aria-label={t(($) => $.image.download)}- onClick={handleDownload}- >- <Download className="size-4" />- </button>+ {/* Below the `open &&` gate on purpose: the panel's zoom state is+ destroyed on close, so every open re-fits instead of restoring+ a stale zoom from the last time this image was viewed. */}+ <PreviewPanel+ kind={kind}+ source={source}+ state={state}+ onClose={onClose}+ onDownload={handleDownload}+ onOpenInNewTab={canOpenInNewTab ? handleOpenInNewTab : undefined}+ />+ </motion.div>+ </motion.div>+ )}+ </AnimatePresence>,+ document.body,+ );+}++// ---------------------------------------------------------------------------+// Panel — header + content area+// ---------------------------------------------------------------------------++// Header chrome and the content area live together because the image kind's+// zoom controls sit in the header while the canvas they drive is the body:+// one owner for that shared state, mounted and destroyed with the open modal.+function PreviewPanel({+ kind,+ source,+ state,+ onClose,+ onDownload,+ onOpenInNewTab,+}: {+ kind: PreviewKind | null;+ source: PreviewSource;+ state: PreviewState;+ onClose: () => void;+ onDownload: () => void;+ onOpenInNewTab?: () => void;+}) {+ const { t } = useT("editor");++ // Natural size is carried with the URL it was measured from, so a panel+ // reused for a different attachment can never fit the new image against the+ // old one's dimensions.+ const [measured, setMeasured] = useState<{ url: string; size: Size } | null>(+ null,+ );+ const natural =+ kind === "image" && measured?.url === state.mediaUrl ? measured.size : null;+ const canvas = useZoomCanvas({ content: natural });++ const handleNaturalSize = useCallback(+ (url: string, size: Size) => {+ setMeasured((previous) =>+ previous?.url === url &&+ previous.size.width === size.width &&+ previous.size.height === size.height+ ? previous+ : { url, size },+ );+ },+ [],+ );++ return (+ <>+ <div className="flex items-center gap-2 border-b border-border bg-muted/30 px-4 py-2">+ <FileText className="size-4 shrink-0 text-muted-foreground" />+ <p className="truncate text-sm font-medium">{state.filename}</p>+ <span className="ml-1 shrink-0 text-xs text-muted-foreground">+ {state.contentType || "—"}+ </span>+ <div className="ml-auto flex items-center gap-1">+ {/* Only once the image has been measured: without a natural size+ there is no canvas behind these buttons to drive. */}+ {natural && <ZoomControls canvas={canvas} className="mr-1" />}+ {onOpenInNewTab && (<buttontype="button"className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- title={t(($) => $.attachment.close)}- aria-label={t(($) => $.attachment.close)}- onClick={onClose}+ title={t(($) => $.attachment.open_in_new_tab)}+ aria-label={t(($) => $.attachment.open_in_new_tab)}+ onClick={onOpenInNewTab}>- <X className="size-4" />+ <ExternalLink className="size-4" /></button>- </div>+ )}+ <button+ type="button"+ className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ title={t(($) => $.image.download)}+ aria-label={t(($) => $.image.download)}+ onClick={onDownload}+ >+ <Download className="size-4" />+ </button>+ <button+ type="button"+ className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ title={t(($) => $.attachment.close)}+ aria-label={t(($) => $.attachment.close)}+ onClick={onClose}+ >+ <X className="size-4" />+ </button></div>- <div className="min-h-0 flex-1 overflow-auto bg-background">- <PreviewContent- kind={kind}- source={source}- state={state}- onDownload={handleDownload}- />- </div>- </motion.div>- </motion.div>- )}- </AnimatePresence>,- document.body,+ </div>+ {/* Image gets a flex column: the canvas sizes itself with `flex: 1 1+ auto` and its content is absolutely positioned, so in a plain block+ parent it would collapse to zero height and show nothing. It also+ clips and handles its own wheel events — letting this wrapper scroll+ too would fight the pan. Every other kind keeps the block scroller;+ making them flex items would let tall text previews shrink to fit+ instead of scrolling. */}+ <div+ className={cn(+ "min-h-0 flex-1 bg-background",+ kind === "image" ? "flex flex-col overflow-hidden" : "overflow-auto",+ )}+ >+ {kind === "image" ? (+ <ImagePreview+ state={state}+ canvas={canvas}+ natural={natural}+ onNaturalSize={handleNaturalSize}+ />+ ) : (+ <PreviewContent+ kind={kind}+ source={source}+ state={state}+ onDownload={onDownload}+ />+ )}+ </div>+ </>+ );+}++// ---------------------------------------------------------------------------+// Image — zoom canvas+// ---------------------------------------------------------------------------++function ImagePreview({+ state,+ canvas,+ natural,+ onNaturalSize,+}: {+ state: PreviewState;+ canvas: ZoomCanvasApi;+ natural: Size | null;+ onNaturalSize: (url: string, size: Size) => void;+}) {+ const { t } = useT("editor");+ const url = state.mediaUrl;++ const readNaturalSize = useCallback(+ (image: HTMLImageElement | null) => {+ // naturalWidth is 0 for an image that hasn't decoded yet, and also for+ // an SVG that declares only a viewBox — Chromium gives those no+ // intrinsic size at all. Both fall back to the letterboxed branch;+ // the first recovers on load, the second stays there.+ if (!image || image.naturalWidth <= 0 || image.naturalHeight <= 0) return;+ onNaturalSize(url, {+ width: image.naturalWidth,+ height: image.naturalHeight,+ });+ },+ [onNaturalSize, url],+ );++ return (+ <ZoomCanvas+ canvas={canvas}+ content={natural}+ label={t(($) => $.image.canvas_label)}+ className="bg-black/40"+ autoFocus+ >+ <img+ // A cached image is already `complete` before React attaches onLoad,+ // so that event never fires — measure from the ref as well.+ ref={readNaturalSize}+ onLoad={(e) => readNaturalSize(e.currentTarget)}+ src={url}+ alt={state.filename}+ className={cn(+ "select-none",+ natural+ ? "block size-full"+ : "max-h-full max-w-full rounded-lg object-contain",+ )}+ // Native image dragging would hijack the pan gesture.+ draggable={false}+ />+ </ZoomCanvas>);}@@ -376,14 +536,15 @@ export function AttachmentPreviewModal({// Dispatch on PreviewKind. New cases go here; remember that the modal frame// (header, close, Download CTA, ESC handling) is shared — sub-renderers only-// own the content area.+// own the content area. `image` is handled by PreviewPanel itself because its+// toolbar and canvas share zoom state.function PreviewContent({kind,source,state,onDownload,}: {- kind: PreviewKind | null;+ kind: Exclude<PreviewKind, "image"> | null;source: PreviewSource;state: PreviewState;onDownload: () => void;@@ -417,16 +578,6 @@ function PreviewContent({}switch (kind) {- case "image":- return (- <div className="flex h-full w-full items-center justify-center bg-black/40 p-4">- <img- src={state.mediaUrl}- alt={state.filename}- className="h-full w-full rounded-lg object-contain"- />- </div>- );case "pdf":return (<iframediff --git a/packages/views/editor/hooks/use-diagram-canvas.ts b/packages/views/editor/hooks/use-zoom-canvas.tssimilarity index 75%rename from packages/views/editor/hooks/use-diagram-canvas.tsrename to packages/views/editor/hooks/use-zoom-canvas.tsindex 15134226d7..dabaf6cf7d 100644--- a/packages/views/editor/hooks/use-diagram-canvas.ts+++ b/packages/views/editor/hooks/use-zoom-canvas.ts@@ -1,15 +1,16 @@"use client";/**- * Pan/zoom controller for a diagram rendered inside an empty-sandbox iframe.+ * Pan/zoom controller for content that cannot zoom itself — a Mermaid diagram+ * in an empty-sandbox iframe, or an image in the attachment preview.*- * 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.+ * Every gesture is captured on the host viewport element and applied as a CSS+ * transform on the wrapper around the content. For the Mermaid case 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+ * Transform math lives in `../utils/zoom-transform`; this hook owns only* event plumbing and state.*/@@ -17,37 +18,38 @@ import {useCallback,useEffect,useLayoutEffect,- useMemo,useRef,useState,type PointerEvent as ReactPointerEvent,type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent as ReactMouseEvent,} from "react";import {MAX_SCALE,- MIN_SCALE,PAN_STEP_PX,ZOOM_STEP,centerTransform,clampTransform,+ computeFitScale,computeFitTransform,+ computeMinScale,distanceBetween,midpointOf,panBy,wheelZoomFactor,zoomByAtCenter,zoomToAt,- type DiagramTransform,type Point,type Size,-} from "../utils/diagram-transform";+ type ZoomTransform,+} from "../utils/zoom-transform";-interface UseDiagramCanvasOptions {- /** Natural (unscaled) size of the diagram, or null while it is unknown. */+interface UseZoomCanvasOptions {+ /** Natural (unscaled) size of the content, or null while it is unknown. */content: Size | null;}-export interface DiagramCanvasApi {+export interface ZoomCanvasApi {/*** 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@@ -56,7 +58,7 @@ export interface DiagramCanvasApi {* permanently unfitted and inert.*/setViewportNode: (node: HTMLDivElement | null) => void;- transform: DiagramTransform;+ transform: ZoomTransform;/** Whole-percent zoom for the toolbar readout. */zoomPercent: number;canZoomIn: boolean;@@ -68,30 +70,29 @@ export interface DiagramCanvasApi {* 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;+ /** Double-click / double-tap toggles between the default fit and 100%. */+ handleDoubleClick: (event: ReactMouseEvent<HTMLElement>) => void;}-const IDENTITY: DiagramTransform = { scale: 1, x: 0, y: 0 };+const IDENTITY: ZoomTransform = { 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 {+export function useZoomCanvas({ content }: UseZoomCanvasOptions): ZoomCanvasApi {const [viewportNode, setViewportNode] = useState<HTMLDivElement | null>(null);const [viewport, setViewport] = useState<Size>(EMPTY_SIZE);- const [transform, setTransform] = useState<DiagramTransform>(IDENTITY);+ const [transform, setTransform] = useState<ZoomTransform>(IDENTITY);const [isPanning, setIsPanning] = useState(false);const [isAnimated, setIsAnimated] = useState(false);@@ -99,7 +100,7 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramC// 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 panOriginRef = useRef<{ pointer: Point; transform: ZoomTransform } | null>(null);const pinchOriginRef = useRef<{ distance: number; scale: number } | null>(null);const contentSize = content ?? EMPTY_SIZE;@@ -116,12 +117,20 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramCconst element = viewportNode;if (!element) return;+ // offsetWidth/offsetHeight, NOT getBoundingClientRect: both viewers open+ // inside a container that scales in (`zoom-in-95` on the shared Dialog,+ // motion's scale(0.95) on the attachment modal). A client rect is+ // transform-scaled, so measuring mid-animation would fit the content+ // against a viewport a few percent too small — and because ResizeObserver+ // reports the untransformed layout box, it never fires when the animation+ // lands, leaving that mis-fit on screen for the whole session.const measure = () => {- const rect = element.getBoundingClientRect();+ const width = element.offsetWidth;+ const height = element.offsetHeight;setViewport((previous) =>- nearlyEqual(previous.width, rect.width) && nearlyEqual(previous.height, rect.height)+ nearlyEqual(previous.width, width) && nearlyEqual(previous.height, height)? previous- : { width: rect.width, height: rect.height },+ : { width, height },);};@@ -135,7 +144,7 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramC}, [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+ // changes: a theme switch re-renders the content at the same size, and// silently snapping the user's zoom back to fit would lose their place.useEffect(() => {if (!ready || hasFittedRef.current) return;@@ -143,7 +152,7 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramCsetTransform(computeFitTransform(contentSize, viewport));}, [ready, contentSize, viewport]);- // A genuinely different diagram (new natural size) starts fresh.+ // Genuinely different content (new natural size) starts fresh.const contentKey = `${contentSize.width}x${contentSize.height}`;const previousContentKeyRef = useRef(contentKey);useEffect(() => {@@ -153,7 +162,7 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramCsetTransform(computeFitTransform(contentSize, viewport));}, [contentKey, ready, contentSize, viewport]);- // Keep the diagram in view when the window/pane is resized under it.+ // Keep the content in view when the window/pane is resized under it.useEffect(() => {if (!ready) return;setTransform((current) => clampTransform(current, contentSize, viewport));@@ -210,7 +219,7 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramC}, [viewportNode]);const localPoint = useCallback(- (event: ReactPointerEvent<HTMLElement>): Point => {+ (event: { clientX: number; clientY: number }): Point => {const rect = viewportNode?.getBoundingClientRect();return {x: event.clientX - (rect?.left ?? 0),@@ -354,36 +363,48 @@ export function useDiagramCanvas({ content }: UseDiagramCanvasOptions): DiagramC[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]);+ // Double-click toggles fit <-> 100%, anchored under the cursor on the way in.+ // The universal image-viewer gesture (macOS Preview, browsers): one gesture+ // gets from "the whole thing" to "readable detail" and back.+ const handleDoubleClick = useCallback(+ (event: ReactMouseEvent<HTMLElement>) => {+ const { transform: t, contentSize: c, viewport: v, ready: r } = stateRef.current;+ if (!r) return;++ setIsAnimated(true);+ const fitScale = computeFitScale(c, v);+ if (Math.abs(t.scale - fitScale) >= 0.001) {+ setTransform(computeFitTransform(c, v));+ return;+ }+ // Already fitted. Go to 100% — or to 200% when fit already is 100%, so a+ // small image still has somewhere to go instead of ignoring the gesture.+ setTransform(zoomToAt(t, fitScale < 0.999 ? 1 : 2, localPoint(event), c, v));+ },+ [localPoint],+ );return {setViewportNode,transform,zoomPercent: Math.round(transform.scale * 100),canZoomIn: transform.scale < MAX_SCALE - 0.001,- canZoomOut: transform.scale > MIN_SCALE + 0.001,+ // Against the dynamic floor, not MIN_SCALE: for content that only fits+ // below 25% the button must stay live all the way down to that fit scale.+ canZoomOut: transform.scale > computeMinScale(contentSize, viewport) + 0.001,isPanning,isAnimated,- isFitted,zoomIn,zoomOut,zoomToActualSize,fit,- reset: fit,handlePointerDown,handlePointerMove,handlePointerUp,handleKeyDown,+ handleDoubleClick,};}-export type { DiagramTransform, Size };-export { MIN_SCALE, MAX_SCALE };+export type { Size, ZoomTransform };+export { MAX_SCALE };diff --git a/packages/views/editor/mermaid-diagram.test.tsx b/packages/views/editor/mermaid-diagram.test.tsxindex f8093ede8b..39bc5c7ec3 100644--- a/packages/views/editor/mermaid-diagram.test.tsx+++ b/packages/views/editor/mermaid-diagram.test.tsx@@ -71,7 +71,7 @@ afterEach(() => {});function currentScale(): number {- const element = document.querySelector<HTMLElement>(".mermaid-viewer-content")!;+ const element = document.querySelector<HTMLElement>(".zoom-canvas-content")!;return Number.parseFloat(/scale\(([\d.]+)\)/.exec(element.style.transform)![1]!);}@@ -205,20 +205,26 @@ describe("MermaidDiagram theme changes", () => {// 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));+ function blockFor(css: string, selector: string): string {+ const start = css.indexOf(selector);+ expect(start, `${selector} missing from stylesheet`).toBeGreaterThan(-1);+ return css.slice(start, css.indexOf("}", start));}it("stops a drag on the inline diagram from selecting text", () => {- expect(blockFor(".mermaid-diagram-scroll {")).toContain("user-select: none");+ const mermaidCss = readFileSync("editor/styles/mermaid.css", "utf8");++ expect(blockFor(mermaidCss, ".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");+ // The canvas moved to the shared stylesheet when the image preview started+ // using it; the rule still has to be there.+ const zoomCss = readFileSync("editor/styles/zoom-canvas.css", "utf8");++ expect(blockFor(zoomCss, ".zoom-canvas {")).toContain("user-select: none");});});diff --git a/packages/views/editor/mermaid-diagram.tsx b/packages/views/editor/mermaid-diagram.tsxindex 3f14b69dec..66a6fede92 100644--- a/packages/views/editor/mermaid-diagram.tsx+++ b/packages/views/editor/mermaid-diagram.tsx@@ -33,7 +33,7 @@ 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";+import type { Size } from "./utils/zoom-transform";type MermaidAPI = typeof import("mermaid").default;diff --git a/packages/views/editor/mermaid-viewer.test.tsx b/packages/views/editor/mermaid-viewer.test.tsxindex ef5a1833d2..f4aa7843fe 100644--- a/packages/views/editor/mermaid-viewer.test.tsx+++ b/packages/views/editor/mermaid-viewer.test.tsx@@ -30,12 +30,15 @@ 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.+// The canvas measures itself from its layout box and converts pointer+// coordinates through its client rect; jsdom reports both as 0. Without a real+// viewport the transform math has nothing to fit against and every gesture is+// a no-op, so pin a deterministic size for both.const VIEWPORT = { width: 800, height: 400 };function stubViewportSize() {+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(VIEWPORT.width);+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(VIEWPORT.height);vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({bottom: VIEWPORT.height,height: VIEWPORT.height,@@ -75,7 +78,7 @@ function canvas(): HTMLElement {}function content(): HTMLElement {- return document.querySelector<HTMLElement>(".mermaid-viewer-content")!;+ return document.querySelector<HTMLElement>(".zoom-canvas-content")!;}/** Reads the applied scale back out of the inline transform. */@@ -230,7 +233,7 @@ describe("MermaidViewer zoom controls", () => {expect(screen.getByText("100%")).toBeInTheDocument();});- it("restores the fitted view with Reset after panning away", () => {+ it("restores the fitted view with Fit to view after panning away", () => {render(<Harness />);const fitted = currentTranslate();@@ -239,21 +242,12 @@ describe("MermaidViewer zoom controls", () => {fireEvent.pointerUp(canvas(), { pointerId: 1, clientX: 200, clientY: 120 });expect(currentTranslate()).not.toEqual(fitted);- fireEvent.click(screen.getByRole("button", { name: "Reset view" }));+ fireEvent.click(screen.getByRole("button", { name: "Fit to 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 />);diff --git a/packages/views/editor/mermaid-viewer.tsx b/packages/views/editor/mermaid-viewer.tsxindex bf54b705a3..e8a1d05747 100644--- a/packages/views/editor/mermaid-viewer.tsx+++ b/packages/views/editor/mermaid-viewer.tsx@@ -21,12 +21,7 @@ import {Code as CodeIcon,Copy,Download,- Frame,Image as ImageIcon,- Maximize,- Minus,- Plus,- RotateCcw,X,} from "lucide-react";import { cn } from "@multica/ui/lib/utils";@@ -40,14 +35,15 @@ import {} 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 { useZoomCanvas } from "./hooks/use-zoom-canvas";+import { ZoomCanvas, ZoomControls } from "./zoom-canvas";import {buildExportSvg,diagramFilenameStem,downloadBlob,renderSvgToPngBlob,} from "./utils/mermaid-export";-import type { Size } from "./utils/diagram-transform";+import type { Size } from "./utils/zoom-transform";const COPY_FEEDBACK_MS = 2000;@@ -72,6 +68,8 @@ export interface MermaidViewerProps extends MermaidViewerContentProps {finalFocusRef?: React.RefObject<HTMLElement | null>;}+// Viewer-only chrome (source toggle, copy, close). The zoom buttons come from+// the shared <ZoomControls>.function ToolbarButton({onClick,disabled,@@ -149,7 +147,7 @@ function MermaidViewerContent({const { t } = useT("editor");const [showSource, setShowSource] = useState(false);const [copied, setCopied] = useState(false);- const canvas = useDiagramCanvas({ content: layout });+ const canvas = useZoomCanvas({ content: layout });const handleCopySource = useCallback(async () => {if (await copyText(chart)) {@@ -208,50 +206,7 @@ function MermaidViewerContent({{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>+ <ZoomControls canvas={canvas} disabled={showSource} /><div className="ml-auto flex items-center gap-0.5"><ToolbarButton@@ -312,45 +267,23 @@ function MermaidViewerContent({<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}+ <ZoomCanvas+ canvas={canvas}+ content={layout}+ label={t(($) => $.mermaid.canvas_label)}+ className="bg-muted"+ canvasRef={canvasRef}>{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>+ <iframe+ className="mermaid-viewer-frame"+ sandbox=""+ srcDoc={viewerDocument}+ title={t(($) => $.mermaid.viewer_title)}+ style={{ width: `${layout.width}px`, height: `${layout.height}px` }}+ />)}- </div>+ </ZoomCanvas>)}</>);diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex cf7266065f..dfef34be2e 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -461,7 +461,7 @@ describe("ReadonlyContent Mermaid rendering", () => {return found!;});- expect(document.querySelector(".mermaid-viewer-canvas")).toBeNull();+ expect(document.querySelector(".zoom-canvas")).toBeNull();fireEvent.click(expandButton);@@ -479,7 +479,7 @@ describe("ReadonlyContent Mermaid rendering", () => {fireEvent.keyDown(document, { key: "Escape" });await waitFor(() => {- expect(document.querySelector(".mermaid-viewer-canvas")).toBeNull();+ expect(document.querySelector(".zoom-canvas")).toBeNull();});});diff --git a/packages/views/editor/styles/mermaid.css b/packages/views/editor/styles/mermaid.cssindex 3f14275f5d..9b6bcb490d 100644--- a/packages/views/editor/styles/mermaid.css+++ b/packages/views/editor/styles/mermaid.css@@ -164,61 +164,8 @@background: color-mix(in srgb, white 15%, transparent);}-/* 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-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;- }-}-+/* Full-screen viewer frame. The canvas that pans/zooms it is shared with the+ image preview and lives in ./zoom-canvas.css. */.mermaid-viewer-frame {border: 0;display: block;diff --git a/packages/views/editor/styles/zoom-canvas.css b/packages/views/editor/styles/zoom-canvas.cssnew file mode 100644index 0000000000..a3397aea56--- /dev/null+++ b/packages/views/editor/styles/zoom-canvas.css@@ -0,0 +1,73 @@+/*+ * Shared pan/zoom canvas — the Mermaid viewer and the image attachment+ * preview both render through `ZoomCanvas` (editor/zoom-canvas.tsx).+ *+ * Not scoped to `.rich-text-editor`: both viewers are portaled to+ * document.body and never render inside the editor subtree. The background is+ * deliberately left to the caller so each surface can pick its own backdrop.+ */++.zoom-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;+ cursor: grab;+ /* Claim every touch gesture: browser pan/pinch would otherwise scroll or+ zoom the page underneath instead of moving the content. */+ touch-action: none;+ /* A pan that leaves the canvas would otherwise start a native text selection+ and highlight the toolbar text plus the whole content 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;+}++.zoom-canvas:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: -2px;+}++.zoom-canvas.is-panning {+ cursor: grabbing;+}++.zoom-canvas-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 content tracks the+ input exactly — easing direct manipulation reads as lag, not polish. */+.zoom-canvas-content.is-animated {+ transition: transform 150ms ease-out;+}++@media (prefers-reduced-motion: reduce) {+ .zoom-canvas-content.is-animated {+ transition: none;+ }+}++/* Unmeasured fallback: content whose natural size can't be read (an SVG with+ only a viewBox has no intrinsic size in Chromium) has nothing to build a+ transform against. Keep the same element chain as the measured branch so+ React swaps classes instead of remounting — a remount would drop a decoded+ image and flash — and just letterbox the content in place. */+.zoom-canvas-fit {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 1rem;+}diff --git a/packages/views/editor/utils/diagram-transform.test.ts b/packages/views/editor/utils/zoom-transform.test.tssimilarity index 76%rename from packages/views/editor/utils/diagram-transform.test.tsrename to packages/views/editor/utils/zoom-transform.test.tsindex 699513294e..6c93cd0556 100644--- a/packages/views/editor/utils/diagram-transform.test.ts+++ b/packages/views/editor/utils/zoom-transform.test.ts@@ -7,14 +7,15 @@ import {clampTransform,computeFitScale,computeFitTransform,+ computeMinScale,distanceBetween,midpointOf,panBy,wheelZoomFactor,zoomByAtCenter,zoomToAt,- type DiagramTransform,-} from "./diagram-transform";+ type ZoomTransform,+} from "./zoom-transform";const VIEWPORT = { width: 1000, height: 600 };@@ -43,8 +44,14 @@ describe("computeFitScale", () => {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("goes below the default minimum for content that cannot fit at 25%", () => {+ // A full-page screenshot is routinely 10x taller than the canvas. Flooring+ // the fit at MIN_SCALE would open it already cropped, with no zoom level+ // that shows all of it.+ const fit = computeFitScale({ width: 1600, height: 8000 }, VIEWPORT);++ expect(fit).toBeLessThan(MIN_SCALE);+ expect(fit).toBeCloseTo(VIEWPORT.height / 8000, 10);});it("returns 1 when either size is unknown, so a 0x0 measure never divides by zero", () => {@@ -91,7 +98,7 @@ describe("clampTransform", () => {});it("leaves an in-bounds transform untouched", () => {- const transform: DiagramTransform = { scale: 1, x: 100, y: 50 };+ const transform: ZoomTransform = { scale: 1, x: 100, y: 50 };expect(clampTransform(transform, content, VIEWPORT)).toEqual(transform);});@@ -101,7 +108,7 @@ 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 start: ZoomTransform = { scale: 1, x: 0, y: 0 };const anchor = { x: 200, y: 100 };const zoomed = zoomToAt(start, 2, anchor, content, VIEWPORT);@@ -129,7 +136,7 @@ describe("zoomToAt", () => {});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 };+ const atMax: ZoomTransform = { scale: MAX_SCALE, x: 10, y: 20 };expect(zoomToAt(atMax, MAX_SCALE * 2, { x: 100, y: 100 }, content, VIEWPORT)).toBe(atMax);});@@ -137,7 +144,7 @@ describe("zoomToAt", () => {describe("zoomByAtCenter", () => {it("zooms about the viewport center for button/keyboard input", () => {- const start: DiagramTransform = { scale: 1, x: 0, y: 0 };+ const start: ZoomTransform = { 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);@@ -198,3 +205,34 @@ describe("pinch helpers", () => {expect(midpointOf({ x: 0, y: 0 }, { x: 10, y: 20 })).toEqual({ x: 5, y: 10 });});});++describe("computeMinScale", () => {+ it("is the default floor for content that fits comfortably", () => {+ expect(computeMinScale({ width: 800, height: 400 }, VIEWPORT)).toBe(MIN_SCALE);+ });++ it("drops to the fit scale for content too large to fit at the default floor", () => {+ const content = { width: 1600, height: 8000 };++ expect(computeMinScale(content, VIEWPORT)).toBe(computeFitScale(content, VIEWPORT));+ });++ it("keeps the fitted transform of a long screenshot intact through a clamp", () => {+ // Regression guard: with a hard 0.25 floor, clampTransform snapped the fit+ // scale back up and the image opened cropped.+ const content = { width: 1600, height: 8000 };+ const fitted = computeFitTransform(content, VIEWPORT);++ expect(clampTransform(fitted, content, VIEWPORT)).toEqual(fitted);+ expect(content.height * fitted.scale).toBeLessThanOrEqual(VIEWPORT.height);+ });++ it("lets zoomToAt reach the fit scale of a long screenshot", () => {+ const content = { width: 1600, height: 8000 };+ const fitScale = computeFitScale(content, VIEWPORT);++ const zoomed = zoomToAt({ scale: 1, x: 0, y: 0 }, 0.0001, { x: 0, y: 0 }, content, VIEWPORT);++ expect(zoomed.scale).toBe(fitScale);+ });+});diff --git a/packages/views/editor/utils/diagram-transform.ts b/packages/views/editor/utils/zoom-transform.tssimilarity index 67%rename from packages/views/editor/utils/diagram-transform.tsrename to packages/views/editor/utils/zoom-transform.tsindex e2bcbb9580..6e3c879464 100644--- a/packages/views/editor/utils/diagram-transform.ts+++ b/packages/views/editor/utils/zoom-transform.ts@@ -1,11 +1,13 @@/**- * Pan/zoom math for the Mermaid diagram viewer.+ * Pan/zoom math for the shared zoom canvas — Mermaid diagrams and image+ * previews both drive their viewer through this module.*- * 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.+ * Content is never asked to zoom itself: a Mermaid diagram lives inside an+ * empty-sandbox iframe that cannot run scripts, and an `<img>` has no zoom of+ * its own either. All interaction is driven from the host document by+ * transforming the wrapper around the content, so this module stays pure+ * DOM-free math: it is the single place where "where is the content 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@@ -23,16 +25,18 @@ export interface Point {y: number;}-export interface DiagramTransform {+export interface ZoomTransform {scale: number;x: number;y: number;}+// Default lower zoom bound. Only a default: `computeMinScale` lowers it for+// content that cannot fit at 25% — see the comment there.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+// How much of the content 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;@@ -44,9 +48,9 @@ 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 {+export function clampScale(scale: number, minScale: number = MIN_SCALE): number {if (!Number.isFinite(scale)) return 1;- return Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale));+ return Math.min(MAX_SCALE, Math.max(minScale, scale));}function hasArea(size: Size): boolean {@@ -60,23 +64,42 @@ function hasArea(size: Size): boolean {/*** 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.+ * size. A small diagram or thumbnail opened in a large viewer should read at+ * 100%, not be blown up until it looks broken — same convention as macOS+ * Preview.+ *+ * Deliberately NOT floored at MIN_SCALE: a full-page screenshot ten times+ * taller than the canvas fits at ~0.1, and returning 0.25 instead would open+ * it already cropped.*/export function computeFitScale(content: Size, viewport: Size): number {if (!hasArea(content) || !hasArea(viewport)) return 1;- return clampScale(+ return Math.min(+ MAX_SCALE,Math.min(1, viewport.width / content.width, viewport.height / content.height),);}+/**+ * Lower zoom bound for a given content/viewport pair: MIN_SCALE normally, but+ * never above the fit scale.+ *+ * Without this, "fit to view" is unreachable for content more than 4x the+ * canvas in either axis — exactly the long-screenshot case — because every+ * clamp would snap the scale back up to 25% and leave the content cropped+ * with no way to see all of it.+ */+export function computeMinScale(content: Size, viewport: Size): number {+ return Math.min(MIN_SCALE, computeFitScale(content, viewport));+}+/** Centers `content` at `scale` inside `viewport`. */export function centerTransform(content: Size,viewport: Size,scale: number,-): DiagramTransform {+): ZoomTransform {return {scale,x: (viewport.width - content.width * scale) / 2,@@ -85,23 +108,23 @@ export function centerTransform(}/** Default view: fit to viewport, centered. */-export function computeFitTransform(content: Size, viewport: Size): DiagramTransform {+export function computeFitTransform(content: Size, viewport: Size): ZoomTransform {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+ * Keeps at least `MIN_VISIBLE_PX` of the content inside the viewport (or all of+ * it, when the content is smaller than that margin), so the canvas can never be* panned into nothing.*/export function clampTransform(- transform: DiagramTransform,+ transform: ZoomTransform,content: Size,viewport: Size,-): DiagramTransform {+): ZoomTransform {if (!hasArea(content) || !hasArea(viewport)) return transform;- const scale = clampScale(transform.scale);+ const scale = clampScale(transform.scale, computeMinScale(content, viewport));const scaledWidth = content.width * scale;const scaledHeight = content.height * scale;const marginX = Math.min(MIN_VISIBLE_PX, scaledWidth);@@ -126,13 +149,13 @@ export function clampTransform(* zoom track the cursor/fingers instead of drifting toward a corner.*/export function zoomToAt(- transform: DiagramTransform,+ transform: ZoomTransform,nextScale: number,anchor: Point,content: Size,viewport: Size,-): DiagramTransform {- const scale = clampScale(nextScale);+): ZoomTransform {+ const scale = clampScale(nextScale, computeMinScale(content, viewport));if (scale === transform.scale) return transform;const ratio = scale / transform.scale;@@ -150,22 +173,22 @@ export function zoomToAt(/** Multiplicative zoom (wheel notch, +/- key, toolbar button) about `anchor`. */export function zoomByAt(- transform: DiagramTransform,+ transform: ZoomTransform,factor: number,anchor: Point,content: Size,viewport: Size,-): DiagramTransform {+): ZoomTransform {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,+ transform: ZoomTransform,factor: number,content: Size,viewport: Size,-): DiagramTransform {+): ZoomTransform {return zoomByAt(transform,factor,@@ -176,12 +199,12 @@ export function zoomByAtCenter(}export function panBy(- transform: DiagramTransform,+ transform: ZoomTransform,deltaX: number,deltaY: number,content: Size,viewport: Size,-): DiagramTransform {+): ZoomTransform {return clampTransform({ scale: transform.scale, x: transform.x + deltaX, y: transform.y + deltaY },content,diff --git a/packages/views/editor/zoom-canvas.tsx b/packages/views/editor/zoom-canvas.tsxnew file mode 100644index 0000000000..3a9203e421--- /dev/null+++ b/packages/views/editor/zoom-canvas.tsx@@ -0,0 +1,199 @@+"use client";++/**+ * ZoomCanvas + ZoomControls — the pan/zoom viewport shared by the Mermaid+ * viewer and the image attachment preview.+ *+ * Split into a hook (`useZoomCanvas`, all behaviour) and two presentational+ * pieces because the toolbar and the canvas live in different parents: each+ * surface owns its own header, so it calls the hook, drops `<ZoomControls>`+ * wherever its chrome belongs, and renders `<ZoomCanvas>` as the body. Content+ * comes in as children — this module knows the content's natural size and+ * nothing else about it.+ */++import { useCallback, type ReactNode, type RefObject } from "react";+import { Frame, Maximize, Minus, Plus } from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { createShortcutChord, type ShortcutChord } from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";+import { useT } from "../i18n";+import type { ZoomCanvasApi } from "./hooks/use-zoom-canvas";+import type { Size } from "./utils/zoom-transform";+import "./styles/zoom-canvas.css";++const ZOOM_IN_SHORTCUT = createShortcutChord("Plus");+const ZOOM_OUT_SHORTCUT = createShortcutChord("Minus");+const FIT_SHORTCUT = createShortcutChord("0");++function ToolbarButton({+ onClick,+ disabled,+ label,+ shortcut,+ children,+}: {+ onClick: () => void;+ disabled?: boolean;+ label: string;+ shortcut?: ShortcutChord;+ children: ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ 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}+ </TooltipTrigger>+ <TooltipContent side="top" sideOffset={8}>+ {label}+ {shortcut && <ShortcutKeycaps shortcut={shortcut} className="ml-1.5" />}+ </TooltipContent>+ </Tooltip>+ );+}++export function ZoomControls({+ canvas,+ disabled,+ className,+}: {+ canvas: ZoomCanvasApi;+ /** Set while the surface shows something other than the canvas (e.g. source view). */+ disabled?: boolean;+ className?: string;+}) {+ const { t } = useT("editor");++ return (+ <TooltipProvider delay={300}>+ <div className={cn("flex items-center gap-0.5", className)}>+ <ToolbarButton+ onClick={canvas.zoomOut}+ disabled={!canvas.canZoomOut || disabled}+ label={t(($) => $.canvas.zoom_out)}+ shortcut={ZOOM_OUT_SHORTCUT}+ >+ <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 || disabled}+ label={t(($) => $.canvas.zoom_in)}+ shortcut={ZOOM_IN_SHORTCUT}+ >+ <Plus className="size-4" />+ </ToolbarButton>+ <ToolbarButton+ onClick={canvas.fit}+ disabled={disabled}+ label={t(($) => $.canvas.zoom_fit)}+ shortcut={FIT_SHORTCUT}+ >+ <Frame className="size-4" />+ </ToolbarButton>+ <ToolbarButton+ onClick={canvas.zoomToActualSize}+ disabled={disabled}+ label={t(($) => $.canvas.zoom_actual)}+ >+ <Maximize className="size-4" />+ </ToolbarButton>+ </div>+ </TooltipProvider>+ );+}++export function ZoomCanvas({+ canvas,+ content,+ label,+ className,+ canvasRef,+ autoFocus,+ children,+}: {+ canvas: ZoomCanvasApi;+ /** Natural size of the children, or null while it is still unknown. */+ content: Size | null;+ /** Accessible name — surfaces describe their own content. */+ label: string;+ className?: string;+ canvasRef?: RefObject<HTMLDivElement | null>;+ /**+ * Focus the canvas on mount. Needed on surfaces without a focus-managing+ * Dialog: the keyboard controls are canvas-scoped, so without this the+ * +/-/0 and arrow keys do nothing until the user happens to click first.+ */+ autoFocus?: boolean;+ children: ReactNode;+}) {+ // Stable identity: an inline ref callback is a new function every render, so+ // React would detach (setViewportNode(null)) and reattach on each one.+ const setCanvasNode = useCallback(+ (node: HTMLDivElement | null) => {+ if (canvasRef) canvasRef.current = node;+ canvas.setViewportNode(node);+ if (node && autoFocus) node.focus({ preventScroll: true });+ },+ [canvasRef, canvas.setViewportNode, autoFocus],+ );++ return (+ <div+ ref={setCanvasNode}+ className={cn("zoom-canvas", canvas.isPanning && "is-panning", className)}+ // `application` tells screen readers to pass arrow keys through to the+ // canvas instead of using them for their own navigation.+ role="application"+ aria-label={label}+ tabIndex={0}+ onPointerDown={canvas.handlePointerDown}+ onPointerMove={canvas.handlePointerMove}+ onPointerUp={canvas.handlePointerUp}+ onPointerCancel={canvas.handlePointerUp}+ onDoubleClick={canvas.handleDoubleClick}+ onKeyDown={canvas.handleKeyDown}+ >+ <div+ className={cn(+ content ? "zoom-canvas-content" : "zoom-canvas-fit",+ content && canvas.isAnimated && "is-animated",+ )}+ style={+ content+ ? {+ width: `${content.width}px`,+ height: `${content.height}px`,+ transform: `translate(${canvas.transform.x}px, ${canvas.transform.y}px) scale(${canvas.transform.scale})`,+ }+ : undefined+ }+ >+ {children}+ </div>+ </div>+ );+}diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 06e44dcab2..86c91ac344 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -34,7 +34,14 @@"copy_link": "Copy link","delete": "Delete","link_copied": "Link copied",- "copy_link_failed": "Failed to copy link"+ "copy_link_failed": "Failed to copy link",+ "canvas_label": "Image canvas. Drag to pan, scroll to zoom, double-click to toggle actual size."+ },+ "canvas": {+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "zoom_fit": "Fit to view",+ "zoom_actual": "Actual size"},"attachment": {"download_failed": "Couldn't fetch a download link. Try again in a moment.",@@ -96,11 +103,6 @@"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",diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex d861e064dd..ec56605a4c 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -34,7 +34,14 @@"copy_link": "リンクをコピー","delete": "削除","link_copied": "リンクをコピーしました",- "copy_link_failed": "リンクをコピーできませんでした"+ "copy_link_failed": "リンクをコピーできませんでした",+ "canvas_label": "画像キャンバス。ドラッグで移動、スクロールで拡大縮小、ダブルクリックで実際のサイズに切り替えできます。"+ },+ "canvas": {+ "zoom_in": "拡大",+ "zoom_out": "縮小",+ "zoom_fit": "画面に合わせる",+ "zoom_actual": "実際のサイズ"},"attachment": {"download_failed": "ダウンロードリンクを取得できませんでした。しばらくしてからもう一度お試しください。",@@ -89,11 +96,6 @@"copy_source": "ダイアグラムのソースをコピー","show_source": "ソースを表示","show_diagram": "ダイアグラムを表示",- "zoom_in": "拡大",- "zoom_out": "縮小",- "zoom_fit": "画面に合わせる",- "zoom_actual": "実際のサイズ",- "reset_view": "表示をリセット","export": "エクスポート","export_png": "PNG をダウンロード","export_svg": "SVG をダウンロード",diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 35610a16d3..477f385cf6 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -34,7 +34,14 @@"copy_link": "링크 복사","delete": "삭제","link_copied": "링크를 복사했습니다",- "copy_link_failed": "링크를 복사하지 못했습니다"+ "copy_link_failed": "링크를 복사하지 못했습니다",+ "canvas_label": "이미지 캔버스. 드래그하여 이동, 스크롤하여 확대/축소, 두 번 클릭하여 실제 크기로 전환할 수 있습니다."+ },+ "canvas": {+ "zoom_in": "확대",+ "zoom_out": "축소",+ "zoom_fit": "화면에 맞추기",+ "zoom_actual": "실제 크기"},"attachment": {"download_failed": "다운로드 링크를 가져오지 못했습니다. 잠시 후 다시 시도하세요.",@@ -89,11 +96,6 @@"copy_source": "다이어그램 소스 복사","show_source": "소스 표시","show_diagram": "다이어그램 표시",- "zoom_in": "확대",- "zoom_out": "축소",- "zoom_fit": "화면에 맞추기",- "zoom_actual": "실제 크기",- "reset_view": "보기 초기화","export": "내보내기","export_png": "PNG 다운로드","export_svg": "SVG 다운로드",diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex ab5a6bd47f..f0bd2bff70 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -34,7 +34,14 @@"copy_link": "复制链接","delete": "删除","link_copied": "已复制链接",- "copy_link_failed": "复制链接失败"+ "copy_link_failed": "复制链接失败",+ "canvas_label": "图片画布,拖动可平移,滚动可缩放,双击可切换实际大小。"+ },+ "canvas": {+ "zoom_in": "放大",+ "zoom_out": "缩小",+ "zoom_fit": "适应窗口",+ "zoom_actual": "实际大小"},"attachment": {"download_failed": "下载链接获取失败,请稍后重试。",@@ -96,11 +103,6 @@"copy_source": "复制图表源码","show_source": "显示源码","show_diagram": "显示图表",- "zoom_in": "放大",- "zoom_out": "缩小",- "zoom_fit": "适应窗口",- "zoom_actual": "实际大小",- "reset_view": "重置视图","export": "导出","export_png": "下载 PNG","export_svg": "下载 SVG",