diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 529e398f..b08db6dd 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -186,15 +186,30 @@ function summarizeError(error: unknown): string { return message.split('\n').slice(0, 6).join('\n') } +/** The svg's own LAYOUT box, measured with any transform lifted off it (a + * transform would return the visual box and a scale-1 measure is what + * framing needs). The modal is the only writer of that style, so + * save/restore is safe. */ +function measureSvgLayout(node: SVGSVGElement): { width: number; height: number } { + const previous = node.style.transform + node.style.transform = 'none' + const rect = node.getBoundingClientRect() + node.style.transform = previous + return { width: rect.width, height: rect.height } +} + /** The zoom/pan modal for one rendered diagram (click-to-enlarge). */ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => void }): React.ReactNode { const overlayRef = useRef(null) const stageRef = useRef(null) + const viewportRef = useRef(null) const svgRef = useRef(null) const dragRef = useRef({ active: false, startX: 0, startY: 0 }) const zoomRef = useRef({ scale: 1, tx: 0, ty: 0 }) /** The shell's native window-control band: it eats pointer events (#805). */ const insetTop = useViewportInsetTop() + /** The scale that shows the whole diagram; `reset` returns to it. */ + const fitRef = useRef(1) const applyTransform = (): void => { const node = svgRef.current @@ -203,18 +218,36 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => node.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})` } - /** Zoom by `delta` keeping the stage point (centerX/centerY) fixed. */ + /** Frame the whole diagram (never upscaled past 1:1), centered. */ + const applyFit = useCallback((): void => { + const viewport = viewportRef.current + const node = svgRef.current + let scale = 1 + if (viewport !== null && node !== null) { + const box = viewport.getBoundingClientRect() + const { width, height } = measureSvgLayout(node) + if (box.width > 0 && box.height > 0 && width > 0 && height > 0) { + scale = Math.min(1, box.width / width, box.height / height) + } + } + const clamped = Math.min(8, Math.max(0.2, scale)) + fitRef.current = clamped + zoomRef.current = { scale: clamped, tx: 0, ty: 0 } + applyTransform() + }, []) + + /** Zoom by `delta` keeping the viewport point (centerX/centerY) fixed. */ const zoom = useCallback((delta: number, centerX?: number, centerY?: number): void => { - const stage = stageRef.current - if (stage === null) return - const rect = stage.getBoundingClientRect() + const viewport = viewportRef.current + if (viewport === null) return + const rect = viewport.getBoundingClientRect() const cx = centerX ?? rect.width / 2 const cy = centerY ?? rect.height / 2 const current = zoomRef.current const newScale = Math.min(8, Math.max(0.2, current.scale * delta)) - // The svg is flex-centered in the stage, so its center sits at + // The svg is flex-centered in the viewport, so its center sits at // (rect.width/2, rect.height/2). Solve for the translate that keeps the - // mouse point stationary in stage coordinates across the scale change. + // mouse point stationary in viewport coordinates across the scale change. const sx = rect.width / 2 const sy = rect.height / 2 const ratio = newScale / current.scale @@ -224,8 +257,9 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => applyTransform() }, []) + /** Back to the framed view the modal opened with. */ const reset = useCallback((): void => { - zoomRef.current = { scale: 1, tx: 0, ty: 0 } + zoomRef.current = { scale: fitRef.current, tx: 0, ty: 0 } applyTransform() }, []) @@ -234,26 +268,29 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => // Mount the caller-provided (sanitized) svg clone imperatively: React // types don't accept a raw DOM node as a child, and the modal owns the // node's lifetime (removed on unmount; the preview copy is untouched). + // Framing happens here, after the append, because it needs the svg's laid + // out box: `getBoundingClientRect()` forces the layout the measure needs. useEffect(() => { - const stage = stageRef.current - if (stage === null) return + const viewport = viewportRef.current + if (viewport === null) return svgRef.current = svg - stage.appendChild(svg) + viewport.appendChild(svg) + applyFit() return () => { svg.remove() svgRef.current = null } - }, [svg]) + }, [svg, applyFit]) useEffect(() => { const stage = stageRef.current - const node = svgRef.current + const viewport = viewportRef.current const overlay = overlayRef.current - if (stage === null || node === null || overlay === null) return + if (stage === null || viewport === null || overlay === null) return const onWheel = (event: WheelEvent): void => { event.preventDefault() - const rect = stage.getBoundingClientRect() + const rect = viewport.getBoundingClientRect() zoom(event.deltaY < 0 ? 1.1 : 1 / 1.1, event.clientX - rect.left, event.clientY - rect.top) } const onKey = (event: KeyboardEvent): void => { @@ -283,15 +320,17 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => // React's synthetic wheel is passive; a native listener is required to // preventDefault (the page must not scroll while zooming the modal). + // The wheel rides the whole stage (the padding ring zooms too), the drag + // rides the viewport (so the empty white area pans as well). stage.addEventListener('wheel', onWheel, { passive: false }) - node.addEventListener('mousedown', onMouseDown) + viewport.addEventListener('mousedown', onMouseDown) window.addEventListener('mousemove', onMouseMove) window.addEventListener('mouseup', onMouseUp) window.addEventListener('keydown', onKey) overlay.addEventListener('click', onOverlayClick) return () => { stage.removeEventListener('wheel', onWheel) - node.removeEventListener('mousedown', onMouseDown) + viewport.removeEventListener('mousedown', onMouseDown) window.removeEventListener('mousemove', onMouseMove) window.removeEventListener('mouseup', onMouseUp) window.removeEventListener('keydown', onKey) @@ -339,7 +378,9 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => ✕ -
+
+
+
{t('mermaidZoomHint')}
, document.body, diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index afa9bde0..269a48fe 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -2105,29 +2105,48 @@ body[data-dsh-sidebar-dragging] .bottomPanel { .mermaidModalStage { width: 90vw; height: 80vh; + box-sizing: border-box; overflow: hidden; position: relative; display: flex; align-items: center; justify-content: center; -} - -.mermaidModalStage :global(svg) { - max-width: none; - max-height: none; - cursor: grab; - transform-origin: center center; - user-select: none; - -webkit-user-drag: none; + /* The zoom modal's FIXED viewport surface. The white card used to be painted + on the diagram's own — the very element the modal transforms — so + `scale()` grew the white area together with the diagram and the + content:viewport ratio never changed (issue #683: "跟没有缩放没区别"). + The paint belongs to the viewport, the transform to the content. */ background: var(--dsw-alias-bg-layer-1); padding: 16px; border-radius: 12px; } -.mermaidModalStage :global(svg):active { +/* The clipping box INSIDE the padding ring: the (transformed) svg overflows + here, so the white ring survives any zoom, and the whole area — not just the + drawn diagram — is a drag surface. */ +.mermaidViewport { + position: relative; + width: 100%; + height: 100%; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + cursor: grab; +} + +.mermaidViewport:active { cursor: grabbing; } +.mermaidModalStage :global(svg) { + max-width: none; + max-height: none; + transform-origin: center center; + user-select: none; + -webkit-user-drag: none; +} + .mermaidModalHint { position: absolute; bottom: 16px; diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index 38f3a9da..b5d1bc56 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -579,6 +579,67 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async const modal = page.locator('[data-mermaid-modal]') await pane.locator('[data-mermaid-diagram] svg').first().click() await expect(modal, 'clicking the diagram must open the zoom modal').toHaveCount(1, { timeout: 10_000 }) + // Issue #683: the modal must zoom the CONTENT while the painted card stays + // put. Measured in the real browser because this is a LAYOUT defect — jsdom + // reports every rect as 0 and cannot tell the two apart. The pre-fix code + // painted the card on the transformed , so three "+" steps grew the + // white sheet 1.728× together with the diagram and the content:viewport + // ratio never changed ("跟没有缩放没区别"); the same three steps must now + // leave the viewport's box byte-identical. + const zoomGeometry = await page.evaluate(() => { + const viewport = document.querySelector('[data-mermaid-viewport]') + const stage = viewport?.parentElement ?? null + const svg = viewport?.querySelector('svg') ?? null + const box = (element: Element | null): { width: number; height: number } => { + const rect = element?.getBoundingClientRect() + return { width: Math.round(rect?.width ?? 0), height: Math.round(rect?.height ?? 0) } + } + const scaleOf = (element: Element | null): number => { + const matrix = /matrix\(([-\d.]+)/.exec(element === null ? '' : getComputedStyle(element).transform) + return matrix === null ? 1 : Number(matrix[1]) + } + const before = { + stage: box(stage), viewport: box(viewport), svg: box(svg), scale: scaleOf(svg), + stageBackground: stage === null ? '' : getComputedStyle(stage).backgroundColor, + svgBackground: svg === null ? '' : getComputedStyle(svg).backgroundColor, + svgPadding: svg === null ? '' : getComputedStyle(svg).padding, + } + const zoomIn = [...document.querySelectorAll('[data-mermaid-modal] button')] + .find(button => button.textContent === '+') + for (let step = 0; step < 3; step += 1) zoomIn?.click() + const after = { stage: box(stage), viewport: box(viewport), svg: box(svg), scale: scaleOf(svg) } + return { before, after } + }) + expect( + zoomGeometry.before.scale, + 'the modal must open framed at or below 1:1 instead of clipping the diagram at 100%', + ).toBeLessThanOrEqual(1) + expect( + zoomGeometry.before.svg.height, + 'the framed diagram must fit inside the viewport', + ).toBeLessThanOrEqual(zoomGeometry.before.viewport.height + 1) + expect( + zoomGeometry.after.scale, + 'the + button must scale the content up', + ).toBeGreaterThan(zoomGeometry.before.scale) + expect(zoomGeometry.after.svg, 'the content grows').not.toEqual(zoomGeometry.before.svg) + expect( + zoomGeometry.after.viewport, + 'the viewport must NOT scale with the content (issue #683)', + ).toEqual(zoomGeometry.before.viewport) + expect( + zoomGeometry.after.stage, + 'the painted card must NOT scale with the content either', + ).toEqual(zoomGeometry.before.stage) + expect( + zoomGeometry.before.stageBackground, + 'the card surface belongs to the fixed stage', + ).not.toBe('rgba(0, 0, 0, 0)') + expect( + zoomGeometry.before.svgBackground, + 'the transformed svg must carry no surface of its own', + ).toBe('rgba(0, 0, 0, 0)') + expect(zoomGeometry.before.svgPadding, 'nor the padding ring').toBe('0px') // While it is up, the modal is the plugin's OTHER viewport-sized BODY CHILD: // without the app-region reset the shell's blanket `body > :not(#root)` // no-drag makes it cancel every window-drag strip (and the macOS diff --git a/tests/mermaid-markdown.spec.tsx b/tests/mermaid-markdown.spec.tsx index b6f12353..0da2af8b 100644 --- a/tests/mermaid-markdown.spec.tsx +++ b/tests/mermaid-markdown.spec.tsx @@ -167,3 +167,75 @@ describe('MermaidMarkdown', () => { await unmount(root) }) }) + +/** Open the zoom modal by clicking the rendered diagram. */ +async function openModal(container: HTMLElement): Promise { + // Diagram rendering is queued asynchronously (see waitFor), so a modal test + // must wait for the swap instead of assuming the mount rendered it. + const diagram = await waitFor(() => container.querySelector('[data-mermaid-diagram] svg')) + await act(async () => { + diagram.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + const modal = document.querySelector('[data-mermaid-modal]') + expect(modal, 'clicking the diagram opens the zoom modal').not.toBeNull() + return modal! +} + +/** The modal's viewport (the fixed white surface) and its content svg. */ +function modalParts(modal: HTMLElement): { viewport: HTMLElement; content: SVGSVGElement } { + const viewport = modal.querySelector('[data-mermaid-viewport]') + expect(viewport, 'the modal must own a viewport element').not.toBeNull() + const content = viewport!.querySelector('svg') + expect(content, 'the enlarged diagram must live inside the viewport').not.toBeNull() + return { viewport: viewport!, content: content! } +} + +const toolbarButton = (modal: HTMLElement, label: string): HTMLButtonElement => + [...modal.querySelectorAll('button')].find(button => button.textContent === label) as HTMLButtonElement + +describe('MermaidZoomModal (issue #683)', () => { + it('transforms only the content, never the viewport that paints the card', async () => { + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const modal = await openModal(container) + const { viewport, content } = modalParts(modal) + + expect(content.style.transform, 'the content carries the zoom transform').toMatch(/scale\(/) + expect(viewport.style.transform, 'the viewport (the painted card) must not be transformed').toBe('') + // The card's fix is structural: the paint sits on the stage, the transform + // on the svg — tests/panel-host-css.spec.ts pins the CSS half of that. + expect(content.parentElement, 'the svg is the viewport\'s child').toBe(viewport) + await unmount(root) + }) + + it('zooms from the toolbar and returns to the framed view on reset', async () => { + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const modal = await openModal(container) + const { content } = modalParts(modal) + // jsdom has no layout, so the frame falls back to 1:1 and the reset target + // is 1 — the assertions below are about the wiring, not about pixels. + const framed = content.style.transform + expect(framed).toContain('scale(1)') + + await act(async () => { toolbarButton(modal, '+').click() }) + expect(content.style.transform, 'the + button must zoom the content').toContain('scale(1.2)') + + await act(async () => { toolbarButton(modal, '⟳').click() }) + expect(content.style.transform, 'reset returns to the framed view').toBe(framed) + await unmount(root) + }) + + it('closes on Escape and leaves the preview diagram untouched', async () => { + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const modal = await openModal(container) + const preview = container.querySelector('[data-mermaid-diagram] svg') + + await act(async () => { + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + }) + + expect(document.querySelector('[data-mermaid-modal]'), 'Escape must close the modal').toBeNull() + expect(preview?.isConnected, 'the preview copy stays where it was').toBe(true) + expect(modal.isConnected, 'the enlarged clone is gone').toBe(false) + await unmount(root) + }) +}) diff --git a/tests/panel-host-css.spec.ts b/tests/panel-host-css.spec.ts index 65f42482..6e87ff59 100644 --- a/tests/panel-host-css.spec.ts +++ b/tests/panel-host-css.spec.ts @@ -118,3 +118,44 @@ describe('panel host layer css', () => { } }) }) + +/** + * The mermaid zoom modal's surface must stay on the FIXED viewport, never on + * the element the modal transforms (issue #683). + * + * The white card used to be painted on the diagram's own ``, and the + * modal scales exactly that element — so every wheel step grew the white area + * together with the diagram and the content:viewport ratio never changed + * ("跟没有缩放没区别"). `mermaid.tsx` now transforms the content only; these + * assertions pin the CSS half, which is the half that silently regresses when + * someone moves the paint back for a cosmetic reason. + */ +describe('mermaid zoom modal surface css (issue #683)', () => { + /** Body of one rule, up to the un-indented closing brace. */ + const ruleBody = (selector: string): string | undefined => + new RegExp(`${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\{([\\s\\S]*?)\\n\\}`) + .exec(stripComments(css))?.[1] + + it('paints the card on the stage (the fixed viewport)', () => { + const stage = ruleBody('.mermaidModalStage') + expect(stage, 'the .mermaidModalStage rule must exist').toBeDefined() + expect(stage, 'the viewport owns the surface').toMatch(/background:\s*var\(--dsw-alias-/) + expect(stage, 'and the ring that survives zooming').toMatch(/padding:\s*16px/) + }) + + it('leaves the transformed svg with no surface of its own', () => { + const svg = ruleBody('.mermaidModalStage :global(svg)') + expect(svg, 'the .mermaidModalStage svg rule must exist').toBeDefined() + for (const paint of ['background', 'padding', 'border-radius']) { + expect(svg, `the transformed svg must not carry ${paint} (issue #683)`).not.toContain(paint) + } + expect(svg, 'the content still scales about its own centre').toMatch(/transform-origin:\s*center center/) + }) + + it('clips the transformed svg inside the padding ring', () => { + const viewport = ruleBody('.mermaidViewport') + expect(viewport, 'the .mermaidViewport rule must exist').toBeDefined() + expect(viewport).toMatch(/overflow:\s*hidden/) + expect(viewport).toMatch(/cursor:\s*grab/) + }) +})