Skip to content

The agent that grows with you

fix(desktop): fit zoomable overlay content on open

Konstantin Khlopkov6dfaab11d593
diff --git a/apps/desktop/src/components/ui/use-zoom-pan.ts b/apps/desktop/src/components/ui/use-zoom-pan.ts
index a645902fd6a..cbe6b744989 100644
--- a/apps/desktop/src/components/ui/use-zoom-pan.ts
+++ b/apps/desktop/src/components/ui/use-zoom-pan.ts
@@ -3,6 +3,7 @@ import {
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
+ useLayoutEffect,
useRef,
useState
} from 'react'
@@ -19,6 +20,9 @@ const MIN_SCALE = 0.25
const MAX_SCALE = 8
const WHEEL_STEP = 1.1
const BUTTON_STEP = 1.25
+// A fitted diagram can shrink far below the interactive zoom-out floor, so
+// surfaces that fit content (see `setContentEl`) pass this via `minScale`.
+export const FIT_MIN_SCALE = 0.05
// Pointer travel (px) below which a single-pointer gesture counts as a click
// rather than a pan. Lets consumers (e.g. an image lightbox) close on a clean
// click while still panning after a real drag.
@@ -33,7 +37,9 @@ interface UseZoomPanOptions {
/**
* Headless pan/zoom transform shared by every zoomable surface (image lightbox,
* diagram/artifact viewer, …). Wheel zooms toward the cursor, drag pans,
- * two-finger pinch zooms + pans, and the +/- buttons zoom toward centre.
+ * two-finger pinch zooms + pans, and the +/- buttons zoom toward centre. When
+ * a content element is registered via `setContentEl`, the initial view fits
+ * the content into the stage (never upscaling).
*
* The wheel listener is attached natively (non-passive) so `preventDefault`
* actually stops the page/dialog from scrolling underneath, which a React
@@ -51,7 +57,8 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
// `enabled` flips (the lightbox img renders inside a dialog portal, a commit
// later than the open flag). An effect keyed on [enabled] alone would capture
// a null ref and never attach the native wheel listener. Re-rendering on
- // mount re-runs that effect with the node in hand.
+ // mount re-runs that effect with the node in hand. It doubles as the fit
+ // stage when a content element is registered.
const [node, setNode] = useState<T | null>(null)
const refCallback = useCallback((instance: T | null) => {
@@ -69,6 +76,11 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
const pointers = useRef(new Map<number, { x: number; y: number }>())
const pinch = useRef<{ dist: number; midX: number; midY: number } | null>(null)
+ // The content wrapper the fit path measures (see fit). Null on surfaces
+ // that zoom their only child directly (image lightbox), which opt out of
+ // fitting.
+ const [contentEl, setContentEl] = useState<HTMLDivElement | null>(null)
+
// Zoom toward (cx, cy), measured from the surface centre, keeping that point fixed.
const zoomAt = useCallback(
(factor: number, cx = 0, cy = 0) => {
@@ -82,19 +94,78 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
[clamp]
)
+ // Shrink the content so it fits the stage, never upscale it. The stage grid
+ // centers the content, so the fit transform needs no translation. Content
+ // with no measurable size yet (async render, e.g. mermaid) stays as-is — a
+ // zero scale would blank the overlay instead of waiting for geometry.
+ const fit = useCallback(() => {
+ if (!node || !contentEl) {
+ return
+ }
+
+ const availableW = node.clientWidth
+ const availableH = node.clientHeight
+ const contentW = contentEl.scrollWidth
+ const contentH = contentEl.scrollHeight
+
+ if (availableW <= 0 || availableH <= 0 || contentW <= 0 || contentH <= 0) {
+ return
+ }
+
+ const scale = Math.min(availableW / contentW, availableH / contentH, 1)
+
+ setTransform({ scale: clamp(scale), x: 0, y: 0 })
+ }, [clamp, contentEl, node])
+
+ // Manual zoom/pan opts out of refitting until reset; while the view is still
+ // the fitted one, stage or content resizes (dialog resize, async SVG
+ // appearing, window resize) re-fit instead of stranding a zoomed view.
+ const fittedRef = useRef(true)
+
+ const fitIfFitted = useCallback(() => {
+ if (fittedRef.current) {
+ fit()
+ }
+ }, [fit])
+
+ // The overlay lives in a portal that mounts its DOM in a later commit than
+ // the hook consumer, so node state (not object refs) drives the
+ // subscription: attaching the nodes re-runs this effect and the fit rides
+ // the observer's spec-guaranteed first delivery once geometry exists.
+ useLayoutEffect(() => {
+ if (!node || !contentEl || typeof ResizeObserver === 'undefined') {
+ return
+ }
+
+ const observer = new ResizeObserver(fitIfFitted)
+
+ observer.observe(node)
+ observer.observe(contentEl)
+
+ return () => observer.disconnect()
+ }, [contentEl, fitIfFitted, node])
+
const reset = useCallback(() => {
setTransform({ scale: 1, x: 0, y: 0 })
setMoved(false)
setPanning(false)
- }, [])
+ fittedRef.current = true
+ // Refit when a content element is registered; surfaces without one (the
+ // image lightbox) keep the identity view.
+ fit()
+ }, [fit])
const zoomIn = useCallback(() => {
+ fittedRef.current = false
+
const node = ref.current
const rect = node?.getBoundingClientRect()
zoomAt(BUTTON_STEP, rect ? rect.width / 2 : 0, rect ? rect.height / 2 : 0)
}, [zoomAt])
const zoomOut = useCallback(() => {
+ fittedRef.current = false
+
const node = ref.current
const rect = node?.getBoundingClientRect()
zoomAt(1 / BUTTON_STEP, rect ? rect.width / 2 : 0, rect ? rect.height / 2 : 0)
@@ -111,14 +182,15 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
const onWheel = (event: WheelEvent) => {
event.preventDefault()
- // macOS smart zoom (two-finger double-tap) → reset, not zoom-in.
+ // macOS smart zoom (two-finger double-tap) → fitted view, not zoom-in.
if (isSmartZoomWheel(event)) {
- setTransform({ scale: 1, x: 0, y: 0 })
- setMoved(false)
+ reset()
return
}
+ fittedRef.current = false
+
const rect = node.getBoundingClientRect()
const cx = event.clientX - rect.left - rect.width / 2
const cy = event.clientY - rect.top - rect.height / 2
@@ -129,7 +201,7 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
node.addEventListener('wheel', onWheel, { passive: false })
return () => node.removeEventListener('wheel', onWheel)
- }, [enabled, node, zoomAt])
+ }, [enabled, node, reset, zoomAt])
const endPan = useCallback(() => {
drag.current = null
@@ -140,6 +212,7 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
event.currentTarget.setPointerCapture?.(event.pointerId)
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY })
setMoved(false)
+ fittedRef.current = false
if (pointers.current.size === 1) {
drag.current = { x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY }
@@ -259,6 +332,7 @@ export function useZoomPan<T extends HTMLElement = HTMLElement>(options: UseZoom
ref: refCallback,
reset,
scale: transform.scale,
+ setContentEl,
stageProps: {
onPointerCancel,
onPointerDown,
diff --git a/apps/desktop/src/components/ui/zoomable-fit.test.tsx b/apps/desktop/src/components/ui/zoomable-fit.test.tsx
new file mode 100644
index 00000000000..f0cbc29214a
--- /dev/null
+++ b/apps/desktop/src/components/ui/zoomable-fit.test.tsx
@@ -0,0 +1,189 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { Zoomable } from './zoomable'
+
+// jsdom computes no layout: the fit path reads clientWidth/clientHeight off
+// the stage and scrollWidth/scrollHeight off the content wrapper, so plain
+// DOM properties can stand in for real geometry. The fake observer mirrors
+// browser timing — entries are delivered after layout, not during mount.
+class FakeResizeObserver {
+ private static instances: FakeResizeObserver[] = []
+ private targets = new Set<Element>()
+
+ constructor(private readonly cb: ResizeObserverCallback) {
+ FakeResizeObserver.instances.push(this)
+ }
+
+ observe(target: Element) {
+ this.targets.add(target)
+ }
+
+ unobserve(target: Element) {
+ this.targets.delete(target)
+ }
+
+ disconnect() {
+ this.targets.clear()
+ }
+
+ static deliver() {
+ for (const instance of FakeResizeObserver.instances) {
+ for (const target of instance.targets) {
+ instance.cb([], instance as unknown as ResizeObserver)
+ }
+ }
+ }
+
+ static reset() {
+ FakeResizeObserver.instances = []
+ }
+}
+
+function installFakeObserver() {
+ vi.stubGlobal('ResizeObserver', FakeResizeObserver)
+}
+
+// The content wrapper carries the transform style; the stage is the pan/zoom
+// surface two levels up.
+function findNodes() {
+ const overlay = screen.getByTestId('overlay')
+ const content = overlay.parentElement as HTMLElement
+ const stage = content.parentElement?.parentElement as HTMLElement
+
+ return { content, stage }
+}
+
+function fakeLayout(stage: HTMLElement, content: HTMLElement, w = 4758, h = 1671) {
+ Object.defineProperty(stage, 'clientWidth', { configurable: true, value: 1000 })
+ Object.defineProperty(stage, 'clientHeight', { configurable: true, value: 600 })
+ Object.defineProperty(content, 'scrollWidth', { configurable: true, value: w })
+ Object.defineProperty(content, 'scrollHeight', { configurable: true, value: h })
+}
+
+afterEach(() => {
+ cleanup()
+ FakeResizeObserver.reset()
+ vi.unstubAllGlobals()
+})
+
+describe('Zoomable overlay fit', () => {
+ it('fits oversized content into the stage when the overlay opens', () => {
+ installFakeObserver()
+ render(
+ <Zoomable label="Open diagram" overlay={<div data-testid="overlay">diagram</div>}>
+ <div>Inline diagram</div>
+ </Zoomable>
+ )
+
+ fireEvent.click(screen.getByTitle('Open diagram'))
+
+ const { content, stage } = findNodes()
+ fakeLayout(stage, content)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ // 1000/4758 ≈ 0.2102 — below the old MIN_SCALE floor of 0.25, so this
+ // also pins the lower clamp.
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(0.2101723413198823)')
+ })
+
+ it('does not scale content that already fits beyond 100%', () => {
+ installFakeObserver()
+ render(
+ <Zoomable label="Open diagram" overlay={<div data-testid="overlay">diagram</div>}>
+ <div>Inline diagram</div>
+ </Zoomable>
+ )
+
+ fireEvent.click(screen.getByTitle('Open diagram'))
+
+ const { content, stage } = findNodes()
+ fakeLayout(stage, content, 800, 400)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(1)')
+ })
+
+ it('keeps zero-size content at identity until real geometry exists', () => {
+ installFakeObserver()
+ render(
+ <Zoomable label="Open diagram" overlay={<div data-testid="overlay">diagram</div>}>
+ <div>Inline diagram</div>
+ </Zoomable>
+ )
+
+ fireEvent.click(screen.getByTitle('Open diagram'))
+
+ const { content, stage } = findNodes()
+ fakeLayout(stage, content, 0, 0)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ // Mermaid renders async: on first layout the content has no size yet and
+ // the fit must not collapse the transform to a zero scale.
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(1)')
+ })
+
+ it('returns to the fitted view from the toolbar reset button', () => {
+ installFakeObserver()
+ render(
+ <Zoomable label="Open diagram" overlay={<div data-testid="overlay">diagram</div>}>
+ <div>Inline diagram</div>
+ </Zoomable>
+ )
+
+ fireEvent.click(screen.getByTitle('Open diagram'))
+
+ const { content, stage } = findNodes()
+ fakeLayout(stage, content)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Zoom in' }))
+ expect(content.style.transform).not.toBe('translate(0px, 0px) scale(0.2101723413198823)')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(0.2101723413198823)')
+
+ // After reset the view is the fitted one again, so a later geometry
+ // change must re-fit rather than leave the reset scale behind.
+ fakeLayout(stage, content, 2379, 835)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(0.4203446826397646)')
+ })
+
+ it('keeps the fitted view tracking later geometry changes', () => {
+ installFakeObserver()
+ render(
+ <Zoomable label="Open diagram" overlay={<div data-testid="overlay">diagram</div>}>
+ <div>Inline diagram</div>
+ </Zoomable>
+ )
+
+ fireEvent.click(screen.getByTitle('Open diagram'))
+
+ const { content, stage } = findNodes()
+
+ // Mermaid SVG lands after the dialog opened: a second delivery with the
+ // real geometry must re-fit instead of leaving the identity transform.
+ fakeLayout(stage, content)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+ fakeLayout(stage, content, 2379, 835)
+ act(() => {
+ FakeResizeObserver.deliver()
+ })
+
+ expect(content.style.transform).toBe('translate(0px, 0px) scale(0.4203446826397646)')
+ })
+})
diff --git a/apps/desktop/src/components/ui/zoomable.tsx b/apps/desktop/src/components/ui/zoomable.tsx
index 5c1a5f35984..7d1c2ea4b9f 100644
--- a/apps/desktop/src/components/ui/zoomable.tsx
+++ b/apps/desktop/src/components/ui/zoomable.tsx
@@ -7,7 +7,7 @@ import { Tip } from '@/components/ui/tooltip'
import { Check, Copy, Maximize, RefreshCw, X, ZoomIn, ZoomOut } from '@/lib/icons'
import { cn } from '@/lib/utils'
-import { useZoomPan } from './use-zoom-pan'
+import { FIT_MIN_SCALE, useZoomPan } from './use-zoom-pan'
interface ZoomableProps {
/** Inline content; also the default full-view content. */
@@ -69,8 +69,11 @@ function ZoomPanViewer({
onOpenChange: (open: boolean) => void
open: boolean
}) {
- const { panning, ref, reset, stageProps, style, zoomIn, zoomOut } = useZoomPan<HTMLDivElement>({
- enabled: open
+ // minScale: a wide diagram's fitted view can shrink far below the default
+ // zoom-out floor; the fit (not the clamp) owns how small the view gets.
+ const { panning, ref, reset, setContentEl, stageProps, style, zoomIn, zoomOut } = useZoomPan<HTMLDivElement>({
+ enabled: open,
+ minScale: FIT_MIN_SCALE
})
useEffect(() => {
@@ -95,7 +98,7 @@ function ZoomPanViewer({
{...stageProps}
>
<div className="absolute inset-0 grid place-items-center">
- <div className="origin-center" style={style}>
+ <div className="origin-center" ref={setContentEl} style={style}>
{children}
</div>
</div>
diff --git a/apps/desktop/src/lib/svg-image-inline-cap.test.ts b/apps/desktop/src/lib/svg-image-inline-cap.test.ts
new file mode 100644
index 00000000000..d1af0749d06
--- /dev/null
+++ b/apps/desktop/src/lib/svg-image-inline-cap.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+
+import { normalizeSvgSize } from './svg-image'
+
+// Real mermaid 11.16 output shape for an oversized diagram: width="100%" plus
+// an inline max-width that pins the intrinsic width in pixels.
+const WIDE_SVG =
+ '<svg xmlns="http://www.w3.org/2000/svg" width="100%" class="flowchart" style="max-width: 4758.394px;" viewBox="0 0 4758.394 1671.458" role="graphics-document document"><g><rect width="4758" height="1671"/></g></svg>'
+
+describe('normalizeSvgSize', () => {
+ it('neutralises an inline pixel max-width so CSS width caps can apply', () => {
+ const out = normalizeSvgSize(WIDE_SVG)
+
+ // The inline max-width used to beat the max-w-full / max-w-[85vw] caps on
+ // both the inline preview and the overlay, so a wide diagram rendered at
+ // intrinsic width.
+ expect(out).toContain('max-width: 100%')
+ expect(out).not.toContain('max-width: 4758')
+ expect(out).toContain('width="4758.394"')
+ expect(out).toContain('height="1671.458"')
+ })
+
+ it('keeps an inline max-width that is already relative', () => {
+ const svg =
+ '<svg xmlns="http://www.w3.org/2000/svg" width="100%" style="max-width: 100%;" viewBox="0 0 300 100"><g/></svg>'
+
+ const out = normalizeSvgSize(svg)
+
+ expect(out).toContain('max-width: 100%')
+ })
+})
diff --git a/apps/desktop/src/lib/svg-image.ts b/apps/desktop/src/lib/svg-image.ts
index 80657122c71..a9397dc969d 100644
--- a/apps/desktop/src/lib/svg-image.ts
+++ b/apps/desktop/src/lib/svg-image.ts
@@ -32,6 +32,16 @@ export function normalizeSvgSize(svg: string): string {
return svg
}
+ // Mermaid pins the intrinsic width with an inline max-width in pixels. An
+ // inline style beats the container's width caps (max-w-full and friends),
+ // so a wide diagram renders at full intrinsic width in the inline preview
+ // instead of shrinking to the pane. Relative values stay untouched.
+ const maxWidth = el.style.getPropertyValue('max-width')
+
+ if (maxWidth && !isPercentLength(maxWidth) && !maxWidth.trim().endsWith('vw')) {
+ el.style.setProperty('max-width', '100%')
+ }
+
const box = viewBoxSize(el)
if (!box) {