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.

fix(preview): make the pinch survive real touch plumbing

Lincoln Stein984937531cee
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index e80c6c619a..979a8f7cff 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -291,12 +291,21 @@ export const WorkbenchShell = () => {
</Flex>
<FloatingWidgetLayer />
<GalleryDragCursor />
- <DragOverlay>{activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}</DragOverlay>
+ {/* The overlay renders whenever anything is being dragged, even with no
+ preview to show — and it is a fixed, full-size div over the dragged
+ element. Without this it swallows every pointer event aimed at what
+ is underneath, which is how a second finger meant for the preview's
+ pinch never reaches the preview. */}
+ <DragOverlay style={DRAG_OVERLAY_STYLE}>
+ {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}
+ </DragOverlay>
</DndContext>
</FocusRegionProvider>
);
};
+const DRAG_OVERLAY_STYLE = { pointerEvents: 'none' } as const;
+
const WidgetDragPreview = ({ activeDrag }: { activeDrag: ActiveWidgetDrag }) => (
<HStack bg="bg" borderWidth="1px" gap="2" px="3" py="2" rounded="md" shadow="lg">
<WidgetIcon icon={activeDrag.icon} boxSize="4" />
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
index 31aa3df10a..8041aa0f35 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
@@ -404,8 +404,11 @@ const CompareSidePane = ({
position="relative"
rounded="lg"
// Keeps the browser's own pan and pinch off the pane, so a two-finger
- // gesture reaches the shared loupe instead of scrolling the page.
- touchAction="none"
+ // gesture reaches the shared loupe instead of zooming the page — but only
+ // where there is a loupe: mismatched dimensions leave the panes without
+ // one, and suppressing the browser's gestures there would replace them
+ // with nothing.
+ touchAction={pane ? 'none' : undefined}
{...pane?.frameProps}
>
<img
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index 7063af98ab..d5c530f0c9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -182,8 +182,9 @@ const PreviewImageFrame = ({
// The whole stage is the loupe's viewport, so it — not just the media
// card — has to keep the browser's own pan and pinch off the surface:
// otherwise the first finger of a pinch is claimed as a page gesture and
- // the pointer stream stops mid-zoom.
- touchAction="none"
+ // the pointer stream stops mid-zoom. A live render has no loupe to put in
+ // their place, so it leaves them alone.
+ touchAction={isLive ? undefined : 'none'}
{...loupe.stageProps}
>
{/* Never armed over a live render: arming a comparison pauses live-follow
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx
index 6163d23c78..e31408518f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx
@@ -51,6 +51,45 @@ afterEach(async () => {
root = null;
});
+/** Pane 0 is 200×150; `paneX` is measured from its left edge, at its mid height. */
+const mountHarness = async (): Promise<{
+ images: HTMLImageElement[];
+ pane: HTMLElement;
+ touch: (
+ type: 'pointerdown' | 'pointermove' | 'pointerup' | 'lostpointercapture',
+ pointerId: number,
+ paneX: number,
+ options?: { isPrimary?: boolean; target?: HTMLElement }
+ ) => void;
+}> => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await interact(() => root?.render(<Harness />));
+
+ const pane = host.querySelector<HTMLElement>('[data-testid="frame-0"]')!;
+ const rect = pane.getBoundingClientRect();
+
+ return {
+ images: Array.from(host.querySelectorAll<HTMLImageElement>('img')),
+ pane,
+ touch: (type, pointerId, paneX, { isPrimary = false, target = pane } = {}) => {
+ target.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button: type === 'pointermove' ? -1 : 0,
+ cancelable: true,
+ clientX: rect.left + paneX,
+ clientY: rect.top + 75,
+ isPrimary,
+ pointerId,
+ pointerType: 'touch',
+ })
+ );
+ },
+ };
+};
+
describe('useCompareLoupe', () => {
it('keeps both panes stationary when wheel zoom is already at its maximum', async () => {
host = document.createElement('div');
@@ -82,32 +121,7 @@ describe('useCompareLoupe', () => {
});
it('pinches both panes together around the fingers on one of them', async () => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- await interact(() => root?.render(<Harness />));
-
- const frame = host.querySelector<HTMLElement>('[data-testid="frame-0"]')!;
- const images = Array.from(host.querySelectorAll<HTMLImageElement>('img'));
- const rect = frame.getBoundingClientRect();
- const touch = (
- type: 'pointerdown' | 'pointermove' | 'pointerup',
- pointerId: number,
- paneX: number,
- { isPrimary = false }: { isPrimary?: boolean } = {}
- ) =>
- frame.dispatchEvent(
- new PointerEvent(type, {
- bubbles: true,
- button: type === 'pointermove' ? -1 : 0,
- cancelable: true,
- clientX: rect.left + paneX,
- clientY: rect.top + 75,
- isPrimary,
- pointerId,
- pointerType: 'touch',
- })
- );
+ const { images, touch } = await mountHarness();
await interact(() => {
touch('pointerdown', 1, 50, { isPrimary: true });
@@ -125,4 +139,52 @@ describe('useCompareLoupe', () => {
'translate(-100px, -75px) scale(2)',
]);
});
+
+ it('keeps pinching when a pane loses the capture it handed to the other', async () => {
+ const { images, touch } = await mountHarness();
+
+ await interact(() => {
+ touch('pointerdown', 1, 50, { isPrimary: true });
+ touch('pointerdown', 2, 150);
+ });
+ // Capture moving between the panes — which is what arming a pinch whose
+ // fingers are on different images does — fires `lostpointercapture` on the
+ // pane that held it. Treating that as the finger going up would kill the
+ // gesture before its first move.
+ await interact(() => touch('lostpointercapture', 1, 50));
+ await interact(() => {
+ touch('pointermove', 1, 0);
+ touch('pointermove', 2, 200);
+ });
+
+ expect(images.map((image) => image.style.transform)).toEqual([
+ 'translate(-100px, -75px) scale(2)',
+ 'translate(-100px, -75px) scale(2)',
+ ]);
+ });
+
+ it('hands the pinch over to a one-finger pan, and ends it off the pane', async () => {
+ const { images, touch } = await mountHarness();
+
+ await interact(() => {
+ touch('pointerdown', 1, 50, { isPrimary: true });
+ touch('pointerdown', 2, 150);
+ });
+ await interact(() => {
+ touch('pointermove', 1, -50);
+ touch('pointermove', 2, 250);
+ });
+ expect(images[0]?.style.transform).toBe('translate(-200px, -150px) scale(3)');
+
+ await interact(() => touch('pointerup', 2, 250));
+ // The remaining finger pans both panes from where it is, then lifts over
+ // another part of the page — which the pane itself never sees.
+ await interact(() => touch('pointermove', 1, -30));
+ expect(images[0]?.style.transform).toBe('translate(-180px, -150px) scale(3)');
+
+ await interact(() => touch('pointerup', 1, -30, { target: document.body }));
+ await interact(() => touch('pointermove', 1, 100));
+
+ expect(images[0]?.style.transform).toBe('translate(-180px, -150px) scale(3)');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
index dbe4502ee5..fef60cbc9a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
@@ -8,7 +8,7 @@ import {
type PanZoomPoint,
} from '@workbench/panZoom';
/* eslint-disable react/react-compiler */
-import { useCallback, useRef, useState, type MouseEvent, type PointerEvent } from 'react';
+import { useCallback, useRef, useState, type MouseEvent, type PointerEvent as ReactPointerEvent } from 'react';
import { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';
@@ -55,11 +55,8 @@ interface PinchGesture {
export interface CompareLoupePane {
frameProps: {
onDoubleClick: (event: MouseEvent<HTMLDivElement>) => void;
- onLostPointerCapture: (event: PointerEvent<HTMLDivElement>) => void;
- onPointerCancel: (event: PointerEvent<HTMLDivElement>) => void;
- onPointerDown: (event: PointerEvent<HTMLDivElement>) => void;
- onPointerMove: (event: PointerEvent<HTMLDivElement>) => void;
- onPointerUp: (event: PointerEvent<HTMLDivElement>) => void;
+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ onPointerMove: (event: ReactPointerEvent<HTMLDivElement>) => void;
};
frameRefCallback: (node: HTMLDivElement | null) => void;
imageRefCallback: (node: HTMLImageElement | null) => void;
@@ -184,6 +181,25 @@ export const useCompareLoupe = ({
// One stable set of callbacks per pane index; wheel listeners need manual
// attachment (`passive: false`) so ref callbacks with cleanup own them.
+ /**
+ * The pane a two-finger gesture belongs to: the one containing its midpoint,
+ * so a pinch spanning both panes is measured in the pane it is centred on
+ * rather than in whichever pane the second finger happened to land on (which
+ * would anchor the zoom on that pane's edge, and differently depending on the
+ * order the fingers touched down).
+ */
+ const getGesturePane = useCallback((center: PanZoomPoint, fallback: 0 | 1): 0 | 1 => {
+ for (const index of [0, 1] as const) {
+ const rect = panesRef.current[index].frame?.getBoundingClientRect();
+
+ if (rect && center.x >= rect.left && center.x <= rect.right && center.y >= rect.top && center.y <= rect.bottom) {
+ return index;
+ }
+ }
+
+ return fallback;
+ }, []);
+
const [panes] = useState<[CompareLoupePane, CompareLoupePane]>(() => {
const createPane = (index: 0 | 1): CompareLoupePane => ({
frameProps: {
@@ -207,8 +223,6 @@ export const useCompareLoupe = ({
Math.max(1, naturalWidthRef.current / frame.clientWidth)
);
},
- onLostPointerCapture: (event) => endPointer(event),
- onPointerCancel: (event) => endPointer(event),
onPointerDown: (event) => {
if (event.button !== 0) {
return;
@@ -223,15 +237,9 @@ export const useCompareLoupe = ({
if (pair && !pinchRef.current) {
event.preventDefault();
- const pinch = beginPinch(index, pair);
-
- if (pinch) {
- // Both fingers are captured for the whole gesture, so one that
- // strays off the pane keeps reporting instead of sticking.
- for (const pointerId of pinch.pointerIds) {
- capturePointer(event.currentTarget, pointerId);
- }
- }
+ // Two fingers are never a pan, whether or not the pinch can be armed.
+ panRef.current = null;
+ beginPinch(index, pair);
return;
}
@@ -272,7 +280,6 @@ export const useCompareLoupe = ({
);
setTransform({ fx: next.pan.x, fy: next.pan.y, scale: next.zoom });
},
- onPointerUp: (event) => endPointer(event),
},
frameRefCallback: (node) => {
panesRef.current[index].frame = node;
@@ -282,12 +289,31 @@ export const useCompareLoupe = ({
}
const onWheel = (event: WheelEvent): void => handleWheel(node, event);
+ // A finger only reports to the pane while it is over it (or captured by
+ // it), so the document is what keeps the tracked set honest: it sees a
+ // finger that crosses to the other pane or lifts off both, either of
+ // which would otherwise leave a phantom entry to pinch against.
+ const handleDocumentPointerMove = (event: PointerEvent): void => {
+ const pointers = pointersRef.current;
+
+ if (pointers.has(event.pointerId)) {
+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
+ }
+ };
+ const handleDocumentPointerEnd = (event: PointerEvent): void => endPointer(event.pointerId);
+ const ownerDocument = node.ownerDocument;
node.addEventListener('wheel', onWheel, { passive: false });
+ ownerDocument.addEventListener('pointermove', handleDocumentPointerMove, { passive: true });
+ ownerDocument.addEventListener('pointerup', handleDocumentPointerEnd);
+ ownerDocument.addEventListener('pointercancel', handleDocumentPointerEnd);
apply();
return () => {
node.removeEventListener('wheel', onWheel);
+ ownerDocument.removeEventListener('pointermove', handleDocumentPointerMove);
+ ownerDocument.removeEventListener('pointerup', handleDocumentPointerEnd);
+ ownerDocument.removeEventListener('pointercancel', handleDocumentPointerEnd);
};
},
imageRefCallback: (node) => {
@@ -311,15 +337,25 @@ export const useCompareLoupe = ({
/**
* Arms a pinch on two down pointers, measured in the fraction space of the
- * pane given. Returns null — leaving no gesture — if that pane cannot be
- * measured or the fingers landed on the same spot.
+ * pane the gesture is centred on (`fallbackPane` decides only when the
+ * midpoint is over neither). Returns null — leaving no gesture — if that
+ * pane cannot be measured or the fingers landed on the same spot. Both
+ * fingers are captured for the whole gesture, so one that strays off the
+ * pane keeps driving it instead of silently sticking.
*/
- const beginPinch = (paneIndex: 0 | 1, pointerIds: [number, number]): PinchGesture | null => {
- const frame = panesRef.current[paneIndex].frame;
+ const beginPinch = (fallbackPane: 0 | 1, pointerIds: [number, number]): PinchGesture | null => {
const first = pointersRef.current.get(pointerIds[0]);
const second = pointersRef.current.get(pointerIds[1]);
- if (!frame || !first || !second) {
+ if (!first || !second) {
+ return null;
+ }
+
+ const center = midpointOf(first, second);
+ const paneIndex = getGesturePane(center, fallbackPane);
+ const frame = panesRef.current[paneIndex].frame;
+
+ if (!frame) {
return null;
}
@@ -330,8 +366,6 @@ export const useCompareLoupe = ({
return null;
}
- const center = midpointOf(first, second);
-
panRef.current = null;
pinchRef.current = {
paneIndex,
@@ -342,11 +376,15 @@ export const useCompareLoupe = ({
startTransform: transformRef.current,
};
+ for (const pointerId of pointerIds) {
+ capturePointer(frame, pointerId);
+ }
+
return pinchRef.current;
};
/** Applies a move to the live pinch; reports whether the pinch owns it. */
- const applyPinch = (event: PointerEvent<HTMLDivElement>): boolean => {
+ const applyPinch = (event: ReactPointerEvent<HTMLDivElement>): boolean => {
const pinch = pinchRef.current;
if (!pinch) {
@@ -381,16 +419,20 @@ export const useCompareLoupe = ({
return true;
};
- const endPointer = (event: PointerEvent<HTMLDivElement>): void => {
+ const endPointer = (pointerId: number): void => {
const pointers = pointersRef.current;
- if (pointers.delete(event.pointerId)) {
- releasePointer(event.currentTarget, event.pointerId);
+ if (pointers.delete(pointerId)) {
+ for (const pane of panesRef.current) {
+ if (pane.frame) {
+ releasePointer(pane.frame, pointerId);
+ }
+ }
}
const pinch = pinchRef.current;
- if (pinch?.pointerIds.includes(event.pointerId)) {
+ if (pinch?.pointerIds.includes(pointerId)) {
pinchRef.current = null;
const remaining = [...pointers.keys()];
@@ -398,12 +440,7 @@ export const useCompareLoupe = ({
// left; lifting to a single finger hands the gesture over to a pan, so
// the images keep following that finger without a release and retouch.
if (remaining.length >= 2) {
- const next = beginPinch(pinch.paneIndex, [remaining[0]!, remaining[1]!]);
-
- for (const pointerId of next?.pointerIds ?? []) {
- capturePointer(event.currentTarget, pointerId);
- }
-
+ beginPinch(pinch.paneIndex, [remaining[0]!, remaining[1]!]);
return;
}
@@ -417,7 +454,7 @@ export const useCompareLoupe = ({
return;
}
- if (panRef.current?.pointerId !== event.pointerId) {
+ if (panRef.current?.pointerId !== pointerId) {
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
index 1693f4c98d..0aa73ba8a5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
@@ -71,11 +71,11 @@ const touch = (
pointerId: number,
stageX: number,
stageY: number,
- { isPrimary = false }: { isPrimary?: boolean } = {}
+ { isPrimary = false, target = stage }: { isPrimary?: boolean; target?: HTMLElement } = {}
): void => {
const rect = stage.getBoundingClientRect();
- stage.dispatchEvent(
+ target.dispatchEvent(
new PointerEvent(type, {
bubbles: true,
button: type === 'pointermove' ? -1 : 0,
@@ -176,15 +176,55 @@ describe('usePreviewLoupe', () => {
expect(content.style.transform).toBe('translate(-180px, -140px) scale(3)');
});
- it('does not pair a finger that was never seen lifting with the next touch', async () => {
+ it('does not pair a finger whose release was never seen with the next touch', async () => {
const { content, stage } = await mountHarness();
- // A finger released outside the stage never reports its `pointerup`, so it
- // would otherwise sit in the tracked set and pinch against a later touch.
+ // Belt and braces for a pointer whose end went missing entirely — the first
+ // finger of the next touch clears it, so it cannot pinch against a later
+ // one. (An ordinary release anywhere on the page is seen; see below.)
await interact(() => touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true }));
await interact(() => touch(stage, 'pointerdown', 2, 250, 150, { isPrimary: true }));
await interact(() => touch(stage, 'pointermove', 2, 350, 150));
expect(content.style.transform).toBe('');
});
+
+ it('pinches from where a finger has moved to, not where it left the stage', async () => {
+ const { content, stage } = await mountHarness();
+
+ await interact(() => touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true }));
+ // The finger slides off the stage — over a neighbouring panel, which is
+ // where it now reports. Its tracked position has to follow it there, or the
+ // pinch below arms on a 100px separation instead of the real 200px and
+ // doubles every subsequent zoom.
+ await interact(() => touch(stage, 'pointermove', 1, 50, 150, { target: document.body }));
+ await interact(() => touch(stage, 'pointerdown', 2, 250, 150));
+ await interact(() => {
+ touch(stage, 'pointermove', 1, -50, 150, { target: document.body });
+ touch(stage, 'pointermove', 2, 550, 150);
+ });
+
+ expect(content.style.transform).toContain('scale(3)');
+ });
+
+ it('ends a gesture whose finger lifts away from the stage', async () => {
+ const { content, stage } = await mountHarness();
+
+ await interact(() => startPinch(stage));
+ await interact(() => {
+ touch(stage, 'pointermove', 1, 50, 150);
+ touch(stage, 'pointermove', 2, 350, 150);
+ });
+ await interact(() => touch(stage, 'pointerup', 2, 350, 150));
+ // The remaining finger pans, then lifts over another panel: the stage never
+ // sees that release, so nothing there can end the pan — and a pan left
+ // armed would keep dragging the image on the next unrelated pointer move.
+ await interact(() => touch(stage, 'pointerup', 1, 50, 150, { target: document.body }));
+ const transformAtRelease = content.style.transform;
+
+ await interact(() => touch(stage, 'pointermove', 1, 200, 150));
+
+ expect(transformAtRelease).toBe('translate(-200px, -150px) scale(3)');
+ expect(content.style.transform).toBe(transformAtRelease);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
index 0ca760a5d4..34f665244e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
@@ -13,7 +13,7 @@ import {
useRef,
useState,
type MouseEvent,
- type PointerEvent,
+ type PointerEvent as ReactPointerEvent,
type Ref,
} from 'react';
@@ -93,6 +93,8 @@ export const usePreviewLoupe = ({
/** Every pointer currently down on the stage, in client space, in arrival order. */
const pointersRef = useRef(new Map<number, PanZoomPoint>());
const pinchRef = useRef<PinchGesture | null>(null);
+ /** Whether the touch session's first pointer landed on the draggable image. */
+ const dragCandidateRef = useRef(false);
const lastSourceTokenRef = useRef<string | null | undefined>(undefined);
const [zoomPercent, setZoomPercent] = useState<number | null>(null);
@@ -148,16 +150,18 @@ export const usePreviewLoupe = ({
}
lastSourceTokenRef.current = token;
+ // A gesture in flight is measured against the old image's transform and
+ // layout, so it goes even when the transform itself is already fit —
+ // otherwise it would keep zooming the new image around the old one's
+ // centre. Dropping it leaves the fresh fit alone until the fingers lift.
+ panPointerRef.current = null;
+ pinchRef.current = null;
if (transformRef.current.scale === 1) {
return;
}
transformRef.current = { scale: 1, tx: 0, ty: 0 };
- panPointerRef.current = null;
- // A gesture in flight is measured against a transform that no longer
- // exists; dropping it leaves the fresh fit alone until the fingers lift.
- pinchRef.current = null;
if (rafRef.current === null) {
rafRef.current = requestAnimationFrame(() => {
@@ -235,7 +239,12 @@ export const usePreviewLoupe = ({
[constrainScale, setTransform]
);
- const reset = useCallback(() => setTransform({ scale: 1, tx: 0, ty: 0 }), [setTransform]);
+ // Both commands drop a gesture in flight: a live pinch resolves every move
+ // from the transform it started on, so its next move would undo the command.
+ const reset = useCallback(() => {
+ pinchRef.current = null;
+ setTransform({ scale: 1, tx: 0, ty: 0 });
+ }, [setTransform]);
const zoomToActual = useCallback(() => {
const stage = stageRef.current;
@@ -245,52 +254,14 @@ export const usePreviewLoupe = ({
return;
}
+ pinchRef.current = null;
zoomAroundPoint(stage.clientWidth / 2, stage.clientHeight / 2, Math.max(1, naturalWidth / content.clientWidth));
}, [naturalWidth, zoomAroundPoint]);
useImperativeHandle(controlsRef, () => ({ reset, zoomToActual }), [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 stageRefCallback = useCallback(
- (node: HTMLDivElement | null) => {
- stageRef.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_STEP * 4 : WHEEL_ZOOM_STEP;
-
- 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;
- }
- };
- },
- [zoomAroundPoint]
- );
-
/** Starts a pan from the given pointer's current position, at the current transform. */
- const beginPan = (pointerId: number, from: PanZoomPoint): void => {
+ const beginPan = useCallback((pointerId: number, from: PanZoomPoint): void => {
panPointerRef.current = {
pointerId,
startX: from.x,
@@ -298,19 +269,21 @@ export const usePreviewLoupe = ({
tx: transformRef.current.tx,
ty: transformRef.current.ty,
};
- };
+ }, []);
/**
* Arms a pinch on two down pointers and returns it, or null — leaving no
- * gesture — if the stage cannot be measured or the fingers landed on the
- * same spot.
+ * gesture — if the stage cannot be measured or the fingers landed on the same
+ * spot. Both fingers are captured for the whole gesture, so one that strays
+ * off the stage keeps driving it instead of silently sticking.
*/
- const beginPinch = (stage: HTMLDivElement, pointerIds: [number, number]): PinchGesture | null => {
+ const beginPinch = useCallback((pointerIds: [number, number]): PinchGesture | null => {
+ const stage = stageRef.current;
const content = contentRef.current;
const first = pointersRef.current.get(pointerIds[0]);
const second = pointersRef.current.get(pointerIds[1]);
- if (!content || content.clientWidth === 0 || !first || !second) {
+ if (!stage || !content || content.clientWidth === 0 || !first || !second) {
return null;
}
@@ -335,21 +308,138 @@ export const usePreviewLoupe = ({
startTransform: transformRef.current,
};
+ for (const pointerId of pointerIds) {
+ capturePointer(stage, pointerId);
+ }
+
return pinchRef.current;
- };
+ }, []);
+
+ /**
+ * Ends one pointer, wherever it lifted. Lifting one finger of a three-finger
+ * gesture re-pinches on what is left; lifting to a single finger hands the
+ * gesture over to a pan, so the image keeps following that finger without a
+ * release and re-touch.
+ */
+ const endPointer = useCallback(
+ (pointerId: number): void => {
+ const pointers = pointersRef.current;
+ const stage = stageRef.current;
+
+ if (pointers.delete(pointerId) && stage) {
+ releasePointer(stage, pointerId);
+ }
+
+ const pinch = pinchRef.current;
+
+ if (pinch?.pointerIds.includes(pointerId)) {
+ pinchRef.current = null;
+ const remaining = [...pointers.keys()];
+
+ if (remaining.length >= 2) {
+ beginPinch([remaining[0]!, remaining[1]!]);
+ return;
+ }
+
+ const last = remaining[0];
+ const lastPoint = last === undefined ? undefined : pointers.get(last);
+
+ if (last !== undefined && lastPoint && transformRef.current.scale !== 1) {
+ beginPan(last, lastPoint);
+ }
+
+ return;
+ }
+
+ if (panPointerRef.current?.pointerId !== pointerId) {
+ return;
+ }
+
+ panPointerRef.current = null;
+ },
+ [beginPan, beginPinch]
+ );
+
+ // 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 stageRefCallback = useCallback(
+ (node: HTMLDivElement | null) => {
+ stageRef.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_STEP * 4 : WHEEL_ZOOM_STEP;
+
+ zoomAroundPoint(
+ event.clientX - rect.left,
+ event.clientY - rect.top,
+ scale * Math.exp(-event.deltaY * sensitivity)
+ );
+ };
+
+ // A finger only reports to the stage while it is over it (or captured by
+ // it), so a pointer that wanders onto another panel would otherwise leave
+ // the position last seen — and, if it lifts out there, the pointer itself
+ // — in the tracked set, ready to arm the next pinch from a phantom start.
+ // The document sees every pointer wherever it goes, so it is what keeps
+ // the set honest; the stage's own handlers still drive the gesture.
+ const handleDocumentPointerMove = (event: PointerEvent): void => {
+ const pointers = pointersRef.current;
+
+ if (pointers.has(event.pointerId)) {
+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
+ }
+ };
+ const handleDocumentPointerEnd = (event: PointerEvent): void => endPointer(event.pointerId);
+ const ownerDocument = node.ownerDocument;
+
+ node.addEventListener('wheel', handleWheel, { passive: false });
+ ownerDocument.addEventListener('pointermove', handleDocumentPointerMove, { passive: true });
+ ownerDocument.addEventListener('pointerup', handleDocumentPointerEnd);
+ ownerDocument.addEventListener('pointercancel', handleDocumentPointerEnd);
+
+ return () => {
+ node.removeEventListener('wheel', handleWheel);
+ ownerDocument.removeEventListener('pointermove', handleDocumentPointerMove);
+ ownerDocument.removeEventListener('pointerup', handleDocumentPointerEnd);
+ ownerDocument.removeEventListener('pointercancel', handleDocumentPointerEnd);
+
+ if (rafRef.current !== null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ };
+ },
+ [endPointer, zoomAroundPoint]
+ );
/**
- * A pinch begins with one finger already down, which dnd-kit's pointer sensor
- * has taken as the start of dragging the image out of the preview. The sensor
- * listens for `pointercancel` on the document, so dispatching one there aborts
- * that drag — pending or already started — without disturbing the stage's own
- * handlers, which never see a document-targeted, non-bubbling event.
+ * A pinch can begin with one finger already down on the image, which dnd-kit's
+ * pointer sensor has taken as the start of dragging it out of the preview. The
+ * sensor listens for `pointercancel` on the document, so dispatching one there
+ * aborts that drag — pending or already started — without disturbing the
+ * stage's own handlers, which never see a document-targeted, non-bubbling
+ * event. Only a finger that landed on the image itself can have armed the
+ * sensor, so only then is there a drag to abandon — the event reaches every
+ * sensor on the page, and nothing else here should have to pay for it.
*/
- const cancelPointerDrag = (stage: HTMLDivElement): void => {
- stage.ownerDocument.dispatchEvent(new PointerEvent('pointercancel'));
+ const cancelPointerDrag = (): void => {
+ const stage = stageRef.current;
+
+ if (stage && dragCandidateRef.current) {
+ stage.ownerDocument.dispatchEvent(new PointerEvent('pointercancel'));
+ }
};
- const handlePointerDown = (event: PointerEvent<HTMLDivElement>): void => {
+ const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>): void => {
if (event.button !== 0) {
return;
}
@@ -362,19 +452,17 @@ export const usePreviewLoupe = ({
const pair = trackPointerDown(pointers, event);
+ if (pointers.size === 1) {
+ dragCandidateRef.current = contentRef.current?.contains(event.target as Node) ?? false;
+ }
+
if (pair && !pinchRef.current) {
event.preventDefault();
- const stage = event.currentTarget;
- const pinch = beginPinch(stage, pair);
-
- if (pinch) {
- // Both fingers are captured for the whole gesture, so a finger that
- // strays off the stage keeps reporting instead of silently sticking.
- for (const pointerId of pinch.pointerIds) {
- capturePointer(stage, pointerId);
- }
+ // Two fingers are never a pan, whether or not the pinch can be armed.
+ panPointerRef.current = null;
- cancelPointerDrag(stage);
+ if (beginPinch(pair)) {
+ cancelPointerDrag();
}
return;
@@ -389,7 +477,7 @@ export const usePreviewLoupe = ({
beginPan(event.pointerId, { x: event.clientX, y: event.clientY });
};
- const handlePointerMove = (event: PointerEvent<HTMLDivElement>): void => {
+ const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>): void => {
const pointers = pointersRef.current;
if (pointers.has(event.pointerId)) {
@@ -437,50 +525,6 @@ export const usePreviewLoupe = ({
setTransform({ scale: next.zoom, tx: next.pan.x, ty: next.pan.y });
};
- const handlePointerEnd = (event: PointerEvent<HTMLDivElement>): void => {
- const pointers = pointersRef.current;
-
- if (pointers.delete(event.pointerId)) {
- releasePointer(event.currentTarget, event.pointerId);
- }
-
- const pinch = pinchRef.current;
-
- if (pinch?.pointerIds.includes(event.pointerId)) {
- pinchRef.current = null;
- const remaining = [...pointers.keys()];
-
- // Lifting one finger of a three-finger gesture re-pinches on what is
- // left; lifting to a single finger hands the gesture over to a pan, so
- // the image keeps following that finger without a release and re-touch.
- if (remaining.length >= 2) {
- const stage = event.currentTarget;
- const next = beginPinch(stage, [remaining[0]!, remaining[1]!]);
-
- for (const pointerId of next?.pointerIds ?? []) {
- capturePointer(stage, pointerId);
- }
-
- return;
- }
-
- const last = remaining[0];
- const lastPoint = last === undefined ? undefined : pointers.get(last);
-
- if (last !== undefined && lastPoint && transformRef.current.scale !== 1) {
- beginPan(last, lastPoint);
- }
-
- return;
- }
-
- if (panPointerRef.current?.pointerId !== event.pointerId) {
- return;
- }
-
- panPointerRef.current = null;
- };
-
const handleDoubleClick = (event: MouseEvent<HTMLDivElement>): void => {
const stage = stageRef.current;
const content = contentRef.current;
@@ -521,11 +565,8 @@ export const usePreviewLoupe = ({
reset,
stageProps: {
onDoubleClick: handleDoubleClick,
- onLostPointerCapture: handlePointerEnd,
- onPointerCancel: handlePointerEnd,
onPointerDown: handlePointerDown,
onPointerMove: handlePointerMove,
- onPointerUp: handlePointerEnd,
},
stageRefCallback,
syncDisplayedSource,