Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(preview): loupe zoom/pan; move image actions to widget header slot

joshistoaste8eecec50b9b
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index cb1a0ec666..9adc0921d1 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -805,7 +805,9 @@
"deletePreviewImage": "Delete preview image",
"nextComparisonMode": "Next comparison mode",
"swapComparisonImages": "Swap comparison images",
- "togglePreview": "Toggle preview"
+ "togglePreview": "Toggle preview",
+ "zoomToActual": "Zoom preview to 100%",
+ "zoomToFit": "Zoom preview to fit"
},
"compare": "Compare",
"emptyDescription": "Generate to Gallery, then select a thumbnail in the Gallery widget to inspect it here.",
@@ -817,6 +819,7 @@
"nextImageInBoard": "Next image in board",
"noGallerySelection": "No gallery selection",
"previousImageInBoard": "Previous image in board",
+ "resetZoom": "Reset zoom",
"showInProgressDiffusion": "Show in-progress diffusion",
"sideBySide": "Side by Side",
"slider": "Slider",
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
index 4ca8e72a92..5211e25dda 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
@@ -1,25 +1,20 @@
-import type { GalleryImage } from '@workbench/gallery/api';
-import type { ImageActions } from '@workbench/image-actions';
import type { GeneratedImageContract } from '@workbench/types';
-import { Badge, Box, HStack, Stack, Text } from '@chakra-ui/react';
+import { Badge, HStack, Stack, Text } from '@chakra-ui/react';
import { Button } from '@workbench/components/ui';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { PreviewDensity } from './previewDensity';
-import { PreviewActionStrip } from './PreviewActionStrip';
import { PreviewLiveStatusLine } from './PreviewLiveReadout';
/**
- * The preview's info card: board context ("N of M"), the action strip,
- * prev/next navigation and the image identity rows. Later phases add the step
- * message and metadata rail here — never in the widget shell.
+ * The preview's info card: board context ("N of M"), prev/next navigation and
+ * the image identity rows. Image actions live in the widget header's actions
+ * slot (`PreviewHeaderActions`), not here.
*/
export const PreviewFooter = ({
- actionImage,
- actions,
boardImageCount,
boardName,
density,
@@ -31,8 +26,6 @@ export const PreviewFooter = ({
onPrevious,
selectedIndex,
}: {
- actionImage: GalleryImage | null;
- actions: ImageActions;
boardImageCount: number;
boardName: string;
density: PreviewDensity;
@@ -63,12 +56,6 @@ export const PreviewFooter = ({
</Text>
</HStack>
<HStack flexShrink={0} gap="1">
- {actionImage ? (
- <>
- <PreviewActionStrip actions={actions} density={density} image={actionImage} />
- <Box bg="border.subtle" flexShrink={0} h="4" mx="0.5" w="1px" />
- </>
- ) : null}
<Button
aria-label={t('widgets.preview.previousImageInBoard')}
disabled={selectedIndex <= 0}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index 501c9fa906..db7a33d9f8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -1,9 +1,12 @@
+/* eslint-disable react/react-compiler */
import type { StreamingImageSource } from '@workbench/images/streamingImageSource';
import { Badge, Box, Flex, type SystemStyleObject } from '@chakra-ui/react';
-import { useCallback, useMemo, type CSSProperties, type MouseEvent, type ReactNode } from 'react';
+import { useCallback, useMemo, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from 'react';
+import { useTranslation } from 'react-i18next';
import { PreviewLiveOverlay } from './PreviewLiveReadout';
+import { usePreviewLoupe, type PreviewLoupeControls } from './usePreviewLoupe';
/**
* The preview's image surface: a dot-grid backdrop with an aspect-fitted,
@@ -34,6 +37,7 @@ export const PreviewFrame = ({
isLive,
liveBadgeLabel,
liveQueueItemId,
+ loupeControlsRef,
onContextMenu,
padding,
shouldAntialiasLiveImage,
@@ -48,6 +52,8 @@ export const PreviewFrame = ({
liveBadgeLabel: string;
/** When set, the static live badge is replaced by the live progress readout for this run. */
liveQueueItemId?: string | null;
+ /** Imperative zoom controls, for hotkeys registered by the widget shell. */
+ loupeControlsRef?: Ref<PreviewLoupeControls>;
onContextMenu?: (x: number, y: number) => void;
padding?: string;
shouldAntialiasLiveImage: boolean;
@@ -55,6 +61,12 @@ export const PreviewFrame = ({
/** `framed` = bordered surface for a selected image; `inset` = flush surface for the empty state. */
variant: 'framed' | 'inset';
}) => {
+ const { t } = useTranslation();
+ const loupe = usePreviewLoupe({
+ controlsRef: loupeControlsRef,
+ enabled: variant === 'framed' && !isLive,
+ naturalWidth: frameWidth,
+ });
const handleContextMenu = useCallback(
(event: MouseEvent<HTMLDivElement>) => {
if (onContextMenu) {
@@ -139,20 +151,46 @@ export const PreviewFrame = ({
w="full"
>
<Box
+ ref={loupe.frameRefCallback}
bg="transparent"
borderWidth="1px"
borderColor={isLive ? 'accent.solid' : 'border.emphasized'}
boxShadow="0 24px 80px rgba(0,0,0,0.42)"
css={getFittedFrameCss(frameWidth, frameHeight)}
+ cursor={loupe.isZoomed ? 'grab' : undefined}
overflow="hidden"
position="relative"
rounded="lg"
onContextMenu={onContextMenu ? handleContextMenu : undefined}
+ {...loupe.frameProps}
>
{source ? (
- <img alt={source.alt} height={frameHeight} src={source.src} style={imageStyle} width={frameWidth} />
+ <img
+ ref={loupe.imageRef}
+ alt={source.alt}
+ height={frameHeight}
+ src={source.src}
+ style={imageStyle}
+ width={frameWidth}
+ />
) : null}
{liveBadge}
+ {loupe.zoomPercent !== null ? (
+ <Badge
+ aria-label={t('widgets.preview.resetZoom')}
+ as="button"
+ bottom="2"
+ cursor="pointer"
+ position="absolute"
+ right="2"
+ size="xs"
+ title={t('widgets.preview.resetZoom')}
+ variant="solid"
+ onClick={loupe.reset}
+ >
+ {loupe.zoomPercent}%
+ </Badge>
+ ) : null}
</Box>
</Flex>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
index 0ad0d44f13..a926eed30c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
@@ -1,4 +1,6 @@
-import { Icon } from '@chakra-ui/react';
+import type { WidgetViewProps } from '@workbench/types';
+
+import { Box, HStack, Icon } from '@chakra-ui/react';
import { useProgressImage } from '@workbench/backend/progressImageStore';
import { IconButton } from '@workbench/components/ui';
import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
@@ -6,10 +8,20 @@ import { HourglassIcon } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-export const PreviewHeaderActions = () => {
+import { PreviewActionStrip } from './PreviewActionStrip';
+import { usePreviewHeaderContext } from './previewHeaderStore';
+
+/**
+ * The preview widget's header actions: the image action strip for the current
+ * selection (published by the view via `previewHeaderStore`) plus the
+ * in-progress diffusion toggle. Actions live here — in the frame's standard
+ * header slot — like every other widget, not in the widget body.
+ */
+export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
const { t } = useTranslation();
const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
const hasProgressImage = useProgressImage() !== null;
+ const { actionImage, actions } = usePreviewHeaderContext();
const dispatch = useWorkbenchDispatch();
const label = showProgressImagesInViewer
? t('widgets.preview.hideInProgressDiffusion')
@@ -24,16 +36,28 @@ export const PreviewHeaderActions = () => {
);
return (
- <IconButton
- aria-label={label}
- colorPalette={showProgressImagesInViewer ? 'accent' : 'gray'}
- opacity={hasProgressImage || showProgressImagesInViewer ? 1 : 0.7}
- size="2xs"
- title={label}
- variant={showProgressImagesInViewer ? 'solid' : 'ghost'}
- onClick={toggleProgressImages}
- >
- <Icon as={HourglassIcon} boxSize="3.5" />
- </IconButton>
+ <HStack gap="1">
+ {actionImage && actions ? (
+ <>
+ <PreviewActionStrip
+ actions={actions}
+ density={region === 'center' ? 'full' : 'compact'}
+ image={actionImage}
+ />
+ <Box bg="border.subtle" flexShrink={0} h="4" w="1px" />
+ </>
+ ) : null}
+ <IconButton
+ aria-label={label}
+ colorPalette={showProgressImagesInViewer ? 'accent' : 'gray'}
+ opacity={hasProgressImage || showProgressImagesInViewer ? 1 : 0.7}
+ size="2xs"
+ title={label}
+ variant={showProgressImagesInViewer ? 'solid' : 'ghost'}
+ onClick={toggleProgressImages}
+ >
+ <Icon as={HourglassIcon} boxSize="3.5" />
+ </IconButton>
+ </HStack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 34f008d9cd..567f53149b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -12,12 +12,7 @@ import {
type GalleryView,
} from '@workbench/gallery/api';
import { getGallerySettings } from '@workbench/gallery/settings';
-import {
- ImageContextMenu,
- useImageActions,
- type ImageActions,
- type ImageContextMenuTarget,
-} from '@workbench/image-actions';
+import { ImageContextMenu, useImageActions, type ImageContextMenuTarget } from '@workbench/image-actions';
import { imageUrlToStreamingSource, progressImageToStreamingSource } from '@workbench/images/streamingImageSource';
import { useStreamingImageSource } from '@workbench/images/useStreamingImageSource';
import {
@@ -34,9 +29,11 @@ import {
useWidgetValuesSelector,
useWorkbenchDispatch,
} from '@workbench/WorkbenchContext';
-import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type KeyboardEvent } from 'react';
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';
import { useTranslation } from 'react-i18next';
+import type { PreviewLoupeControls } from './usePreviewLoupe';
+
import { PreviewCompare } from './PreviewCompare';
import { usePreviewDensity, type PreviewDensity } from './previewDensity';
import { PreviewFooter } from './PreviewFooter';
@@ -164,6 +161,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
const selectedImageRef = useRef(selectedImage);
const boardImagesRef = useRef(boardImages);
+ const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);
selectedImageRef.current = selectedImage;
boardImagesRef.current = boardImages;
@@ -368,15 +366,18 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);
const selectedImageName = selectedImage?.imageName ?? null;
- // Publish the header label context ("[board] / [image]") for the widget
- // frame; the frame chrome renders outside this view, so an external store is
- // the sync channel. Cleared on unmount so a stale title never outlives us.
+ // Publish the header chrome context (the "[board] / [image]" label and the
+ // action strip's image + actions) for the widget frame; the chrome renders
+ // outside this view, so an external store is the sync channel. Cleared on
+ // unmount so stale chrome never outlives us.
useEffect(() => {
previewHeaderStore.set({
+ actionImage: contextMenuImage,
+ actions: imageActions,
boardName: selectedImageName === null ? null : boardName,
imageName: selectedImageName,
});
- }, [boardName, selectedImageName]);
+ }, [boardName, contextMenuImage, imageActions, selectedImageName]);
useEffect(() => () => previewHeaderStore.clear(), []);
@@ -406,6 +407,16 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
if (commandId === 'viewer.deleteImage' && selectedImage) {
void imageActions.deleteImages([selectedImage.imageName]);
+ return;
+ }
+
+ if (commandId === 'viewer.zoomToActual') {
+ loupeControlsRef.current?.zoomToActual();
+ return;
+ }
+
+ if (commandId === 'viewer.zoomToFit') {
+ loupeControlsRef.current?.reset();
}
});
@@ -414,6 +425,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
['viewer.toggleViewer', t('widgets.preview.commands.togglePreview'), ['z']],
['viewer.swapImages', t('widgets.preview.commands.swapComparisonImages'), ['c']],
['viewer.deleteImage', t('widgets.preview.commands.deletePreviewImage'), ['delete', 'backspace']],
+ ['viewer.zoomToActual', t('widgets.preview.commands.zoomToActual'), ['1']],
+ ['viewer.zoomToFit', t('widgets.preview.commands.zoomToFit'), ['f']],
] as const;
const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [
runtime.commands.register({ handler: () => executeViewerHotkey(id), id, title }),
@@ -441,8 +454,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
/>
) : (
<SelectedImagePreview
- actionImage={contextMenuImage}
- actions={imageActions}
+ loupeControlsRef={loupeControlsRef}
boardImageCount={boardImages.length}
boardName={boardName}
density={density}
@@ -474,13 +486,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
};
const SelectedImagePreview = ({
- actionImage,
- actions,
boardImageCount,
boardName,
density,
image,
isLoadingBoard,
+ loupeControlsRef,
progressImage,
selectedIndex,
shouldAntialiasProgressImage,
@@ -488,13 +499,12 @@ const SelectedImagePreview = ({
onNext,
onPrevious,
}: {
- actionImage: GalleryImage | null;
- actions: ImageActions;
boardImageCount: number;
boardName: string;
density: PreviewDensity;
image: GeneratedImageContract;
isLoadingBoard: boolean;
+ loupeControlsRef?: Ref<PreviewLoupeControls>;
progressImage: LatestProgressImageSnapshot | null;
selectedIndex: number;
shouldAntialiasProgressImage: boolean;
@@ -535,11 +545,13 @@ const SelectedImagePreview = ({
return (
<Stack gap="3" h="full" minH="0" outline="none" tabIndex={0} w="full" onKeyDown={handleKeyDown}>
<PreviewFrame
+ key={`${image.imageName}:${isProgressImage ? 'live' : 'still'}`}
frameHeight={previewHeight}
frameWidth={previewWidth}
isLive={isProgressImage}
liveBadgeLabel={t('common.generating')}
liveQueueItemId={liveQueueItemId}
+ loupeControlsRef={loupeControlsRef}
padding={density === 'full' ? '6' : '3'}
shouldAntialiasLiveImage={shouldAntialiasProgressImage}
source={previewImage}
@@ -547,8 +559,6 @@ const SelectedImagePreview = ({
onContextMenu={onContextMenu}
/>
<PreviewFooter
- actionImage={actionImage}
- actions={actions}
boardImageCount={boardImageCount}
boardName={boardName}
density={density}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
index 9517f81fff..224dd03628 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
@@ -1,18 +1,26 @@
+import type { GalleryImage } from '@workbench/gallery/api';
+import type { ImageActions } from '@workbench/image-actions';
+
import { createExternalStore } from '@workbench/externalStore';
/**
- * Header context published by the preview view so the widget frame's label can
- * show "[board] / [image]" without refetching boards. The preview is a
- * singleton widget (`allowMultiple: false`), so one module-level store is safe.
- * Cleared when the view unmounts or nothing is selected; the label falls back
- * to the static widget title.
+ * Header context published by the preview view so the widget frame's chrome
+ * (label + header actions) can render the current selection without refetching
+ * boards or re-instantiating image actions. The preview is a singleton widget
+ * (`allowMultiple: false`), so one module-level store is safe. Cleared when
+ * the view unmounts or nothing is selected; the chrome falls back to the
+ * static title and hides the action strip.
*/
export interface PreviewHeaderContext {
+ /** The selected image with board/star context, ready for image actions. */
+ actionImage: GalleryImage | null;
+ /** The view's `useImageActions` instance (carries delete-neighbor handling). */
+ actions: ImageActions | null;
boardName: string | null;
imageName: string | null;
}
-const emptyContext: PreviewHeaderContext = { boardName: null, imageName: null };
+const emptyContext: PreviewHeaderContext = { actionImage: null, actions: null, boardName: null, imageName: null };
const store = createExternalStore<PreviewHeaderContext>(emptyContext);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
new file mode 100644
index 0000000000..4fe12cac43
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
@@ -0,0 +1,264 @@
+import {
+ useEffectEvent,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type MouseEvent,
+ type PointerEvent,
+ type Ref,
+} from 'react';
+
+/**
+ * Lightweight zoom/pan for the preview frame: wheel zooms around the cursor,
+ * left-drag pans, double-click toggles fit ⇄ 100%. Implemented as a CSS
+ * transform applied imperatively (rAF-batched) to the img inside the fitted
+ * frame — high-frequency pointer data never passes through React state; only
+ * the rounded zoom percent does, for the corner chip. `scale === 1` is "fit"
+ * (the frame's natural CSS size); the chip reports percent of the image's
+ * actual pixels. Resets are handled by remounting the frame per image.
+ */
+
+/** Max zoom, as a fraction of the image's actual pixel size. */
+const MAX_ACTUAL_ZOOM = 8;
+/** Wheel-to-zoom sensitivity. */
+const WHEEL_ZOOM_FACTOR = 0.0015;
+/** Switch to pixelated rendering at/above this actual-pixel zoom. */
+const PIXELATED_ACTUAL_ZOOM = 2;
+
+export interface PreviewLoupeControls {
+ reset(): void;
+ zoomToActual(): void;
+}
+
+interface LoupeTransform {
+ scale: number;
+ tx: number;
+ ty: number;
+}
+
+const clampAxis = (t: number, frameLen: number, contentLen: number): number =>
+ contentLen <= frameLen ? (frameLen - contentLen) / 2 : Math.min(0, Math.max(frameLen - contentLen, t));
+
+export const usePreviewLoupe = ({
+ controlsRef,
+ enabled,
+ naturalWidth,
+}: {
+ controlsRef?: Ref<PreviewLoupeControls>;
+ enabled: boolean;
+ naturalWidth: number;
+}) => {
+ const frameRef = useRef<HTMLDivElement | null>(null);
+ const imageRef = useRef<HTMLImageElement | null>(null);
+ const transformRef = useRef<LoupeTransform>({ scale: 1, tx: 0, ty: 0 });
+ const rafRef = useRef<number | null>(null);
+ const panPointerRef = useRef<{ pointerId: number; startX: number; startY: number; tx: number; ty: number } | null>(
+ null
+ );
+ const [zoomPercent, setZoomPercent] = useState<number | null>(null);
+
+ const getActualZoom = (scale: number): number => {
+ const renderedWidth = frameRef.current?.clientWidth ?? 0;
+
+ return renderedWidth > 0 && naturalWidth > 0 ? (scale * renderedWidth) / naturalWidth : scale;
+ };
+
+ const apply = useEffectEvent(() => {
+ if (rafRef.current !== null) {
+ return;
+ }
+
+ rafRef.current = requestAnimationFrame(() => {
+ rafRef.current = null;
+ const image = imageRef.current;
+ const transform = transformRef.current;
+
+ if (!image) {
+ return;
+ }
+
+ const isFit = transform.scale === 1;
+
+ image.style.transform = isFit ? '' : `translate(${transform.tx}px, ${transform.ty}px) scale(${transform.scale})`;
+ image.style.transformOrigin = '0 0';
+
+ const actualZoom = getActualZoom(transform.scale);
+
+ image.style.imageRendering = !isFit && actualZoom >= PIXELATED_ACTUAL_ZOOM ? 'pixelated' : '';
+ setZoomPercent(isFit ? null : Math.round(actualZoom * 100));
+ });
+ });
+
+ const setTransform = useEffectEvent((next: LoupeTransform) => {
+ const frame = frameRef.current;
+
+ if (!frame) {
+ return;
+ }
+
+ const frameWidth = frame.clientWidth;
+ const frameHeight = frame.clientHeight;
+ const scale = Math.max(1, Math.min(next.scale, (MAX_ACTUAL_ZOOM * naturalWidth) / Math.max(1, frameWidth)));
+
+ transformRef.current =
+ scale === 1
+ ? { scale: 1, tx: 0, ty: 0 }
+ : {
+ scale,
+ tx: clampAxis(next.tx, frameWidth, frameWidth * scale),
+ ty: clampAxis(next.ty, frameHeight, frameHeight * scale),
+ };
+ apply();
+ });
+
+ const zoomAroundPoint = useEffectEvent((pointX: number, pointY: number, nextScale: number) => {
+ const { scale, tx, ty } = transformRef.current;
+ const ratio = nextScale / scale;
+
+ setTransform({
+ scale: nextScale,
+ tx: pointX - (pointX - tx) * ratio,
+ ty: pointY - (pointY - ty) * ratio,
+ });
+ });
+
+ const reset = useEffectEvent(() => setTransform({ scale: 1, tx: 0, ty: 0 }));
+
+ const zoomToActual = useEffectEvent(() => {
+ const frame = frameRef.current;
+
+ if (!frame || frame.clientWidth === 0) {
+ return;
+ }
+
+ const scale = Math.max(1, naturalWidth / frame.clientWidth);
+
+ zoomAroundPoint(frame.clientWidth / 2, frame.clientHeight / 2, scale);
+ });
+
+ useImperativeHandle(controlsRef, () => ({ reset, zoomToActual }), []);
+
+ // The wheel listener must be attached manually with `passive: false` —
+ // React's synthetic wheel events cannot preventDefault. Ref callback with
+ // cleanup, so there is no effect to keep in sync.
+ const [frameRefCallback] = useState(() => (node: HTMLDivElement | null) => {
+ frameRef.current = node;
+
+ if (!node) {
+ return;
+ }
+
+ const handleWheel = (event: WheelEvent): void => {
+ event.preventDefault();
+ const rect = node.getBoundingClientRect();
+ const { scale } = transformRef.current;
+ // Trackpad pinch arrives as ctrl+wheel with finer deltas.
+ const sensitivity = event.ctrlKey ? WHEEL_ZOOM_FACTOR * 4 : WHEEL_ZOOM_FACTOR;
+
+ zoomAroundPoint(
+ event.clientX - rect.left,
+ event.clientY - rect.top,
+ scale * Math.exp(-event.deltaY * sensitivity)
+ );
+ };
+
+ node.addEventListener('wheel', handleWheel, { passive: false });
+
+ return () => {
+ node.removeEventListener('wheel', handleWheel);
+
+ if (rafRef.current !== null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ };
+ });
+
+ const handlePointerDown = (event: PointerEvent<HTMLDivElement>): void => {
+ if (event.button !== 0 || transformRef.current.scale === 1) {
+ return;
+ }
+
+ event.preventDefault();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ panPointerRef.current = {
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startY: event.clientY,
+ tx: transformRef.current.tx,
+ ty: transformRef.current.ty,
+ };
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLDivElement>): void => {
+ const pan = panPointerRef.current;
+
+ if (!pan || pan.pointerId !== event.pointerId) {
+ return;
+ }
+
+ event.preventDefault();
+ setTransform({
+ scale: transformRef.current.scale,
+ tx: pan.tx + (event.clientX - pan.startX),
+ ty: pan.ty + (event.clientY - pan.startY),
+ });
+ };
+
+ const handlePointerEnd = (event: PointerEvent<HTMLDivElement>): void => {
+ if (panPointerRef.current?.pointerId !== event.pointerId) {
+ return;
+ }
+
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+
+ panPointerRef.current = null;
+ };
+
+ const handleDoubleClick = (event: MouseEvent<HTMLDivElement>): void => {
+ const frame = frameRef.current;
+
+ if (!frame) {
+ return;
+ }
+
+ if (transformRef.current.scale !== 1) {
+ reset();
+ return;
+ }
+
+ const rect = frame.getBoundingClientRect();
+ const scale = Math.max(1, naturalWidth / frame.clientWidth);
+
+ zoomAroundPoint(event.clientX - rect.left, event.clientY - rect.top, scale);
+ };
+
+ if (!enabled) {
+ return {
+ frameProps: null,
+ frameRefCallback: null,
+ imageRef: null,
+ isZoomed: false,
+ reset,
+ zoomPercent: null,
+ };
+ }
+
+ return {
+ frameProps: {
+ onDoubleClick: handleDoubleClick,
+ onLostPointerCapture: handlePointerEnd,
+ onPointerCancel: handlePointerEnd,
+ onPointerDown: handlePointerDown,
+ onPointerMove: handlePointerMove,
+ onPointerUp: handlePointerEnd,
+ },
+ frameRefCallback,
+ imageRef,
+ isZoomed: zoomPercent !== null,
+ reset,
+ zoomPercent,
+ };
+};