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(gallery): gate touch drags with a hold-to-drag sensor

Lincoln Stein449acfd0b107
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
index fa0cea4466..8be97e4d27 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
@@ -29,6 +29,17 @@ const THUMBNAIL_DRAG_CSS = {
filter: 'saturate(0.4)',
} as const;
+/**
+ * The tile while a touch hold has armed the drag gate (before movement starts
+ * the drag): the same desaturation, easing in as the hold completes so the
+ * user can see the gesture flip from scroll to drag. Set as
+ * `data-drag-armed` by the hold-to-drag sensor.
+ */
+const THUMBNAIL_ARMED_CSS = {
+ ...THUMBNAIL_HOVER_CSS,
+ '&[data-drag-armed=true]': { filter: 'saturate(0.4)' },
+} as const;
+
const PREVIEW_IMAGE_STYLE = {
borderRadius: '0.375rem',
boxShadow: '0 8px 24px rgb(0 0 0 / 45%)',
@@ -142,9 +153,16 @@ const GalleryThumbnail = ({
const handleContextMenu = useCallback(
(event: MouseEvent) => {
event.preventDefault();
- onContextMenu(item, event.clientX, event.clientY);
+
+ // A long-press that armed or started a touch drag is drag intent, not
+ // menu intent: the native menu is already suppressed by the sensor, and
+ // the app menu must not open under a gesture that is about to move the
+ // image.
+ if (!isDragging) {
+ onContextMenu(item, event.clientX, event.clientY);
+ }
},
- [item, onContextMenu]
+ [isDragging, item, onContextMenu]
);
const handleClick = useCallback((event: MouseEvent) => onClick(item, event), [item, onClick]);
@@ -173,7 +191,7 @@ const GalleryThumbnail = ({
borderColor={isSelected || isCompared ? 'accent.solid' : 'border.subtle'}
borderWidth="2px"
boxShadow={isCompared ? 'inset 0 0 0 1px {colors.accent.solid}' : undefined}
- css={isDragging ? THUMBNAIL_DRAG_CSS : THUMBNAIL_HOVER_CSS}
+ css={isDragging ? THUMBNAIL_DRAG_CSS : THUMBNAIL_ARMED_CSS}
minW="0"
opacity={isDragging ? 0.4 : undefined}
overflow="hidden"
@@ -182,8 +200,9 @@ const GalleryThumbnail = ({
rounded="md"
// Pan, don't drag: `none` would hand every touch-drag to the drag
// sensor before the browser could scroll the grid. Allowing the pan
- // lets a moving finger scroll (the sensor detaches on touchcancel);
- // dragging still works via the TouchSensor's hold delay.
+ // lets a moving finger scroll (the hold-to-drag sensor releases the
+ // gesture when the browser claims it); dragging still works after a
+ // sustained hold.
touchAction="pan-y"
w="full"
onContextMenu={handleContextMenu}
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index 961a5cecaa..0baaa4e540 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -3,8 +3,6 @@ import {
DndContext,
DragOverlay,
KeyboardSensor,
- MouseSensor,
- TouchSensor,
useSensor,
useSensors,
type DragEndEvent,
@@ -44,6 +42,12 @@ import { useTranslation } from 'react-i18next';
import { BottomPanel } from './BottomPanel';
import { CenterArea } from './CenterArea';
import { DocumentTitleProgress } from './DocumentTitleProgress';
+import {
+ HoldToDragSensor,
+ PrimaryMouseSensor,
+ TOUCH_DRAG_HOLD_DELAY_MS,
+ TOUCH_DRAG_MOVE_TOLERANCE_PX,
+} from './holdToDragSensor';
import { WorkbenchNotificationToaster } from './notifications';
import { LeftPanel, RightPanel } from './Panels';
import { StatusBar } from './StatusBar';
@@ -61,21 +65,6 @@ const DND_MODIFIERS = [restrictToWindowEdges];
* scrolls from afar are prevented by the visibility check inside
* widgetCollisionDetection, not by shrinking zones.
*/
-/**
- * Touch drags activate only after a sustained hold: a `PointerSensor` with a
- * distance constraint claims a touch-drag at 6px, which makes every
- * scrollable surface of draggable items (the gallery grid, the filmstrip)
- * unscrollable by touch — the drag wins the gesture before the browser can
- * pan. The `TouchSensor`'s delay constraint leaves the gesture alone while
- * the hold is pending (its touchmove listener does not preventDefault until
- * activated), so an early move pans the surface and the sensor detaches on
- * `touchcancel`; a hold that outlasts the delay — moving no more than
- * `TOUCH_DRAG_MOVE_TOLERANCE_PX` — activates the drag, which then owns the
- * gesture. Mouse pointers keep the immediate distance activation.
- */
-const TOUCH_DRAG_HOLD_DELAY_MS = 400;
-const TOUCH_DRAG_MOVE_TOLERANCE_PX = 10;
-
const DND_AUTO_SCROLL = { acceleration: 5 };
export const WorkbenchShell = () => {
@@ -87,8 +76,10 @@ export const WorkbenchShell = () => {
const rightRegion = useActiveProjectSelector((project) => project.widgetRegions.right);
const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);
const sensors = useSensors(
- useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
- useSensor(TouchSensor, {
+ // `PrimaryMouseSensor`/`HoldToDragSensor` replace the stock `PointerSensor`:
+ // see holdToDragSensor.ts for why touch gestures need the hold gate.
+ useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(HoldToDragSensor, {
activationConstraint: { delay: TOUCH_DRAG_HOLD_DELAY_MS, tolerance: TOUCH_DRAG_MOVE_TOLERANCE_PX },
}),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
diff --git a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx
new file mode 100644
index 0000000000..479e0bb6a0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx
@@ -0,0 +1,330 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import { DndContext, useDraggable, useSensor, useSensors } from '@dnd-kit/core';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { HoldToDragSensor, PrimaryMouseSensor } from './holdToDragSensor';
+
+// Small enough to exercise the gate with real timers; production uses 400ms/10px.
+// Gesture moves are 20px: comfortably past both the tolerance and the 6px
+// immediate-activation distance.
+const HOLD_DELAY_MS = 120;
+const HOLD_TOLERANCE_PX = 10;
+
+// The arm wait must clear the hold delay even with interact()'s 50ms sleeps.
+const HOLD_ELAPSED_MS = HOLD_DELAY_MS + 60;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 50);
+ });
+ });
+
+const wait = (ms: number): Promise<void> =>
+ act(async () => {
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, ms);
+ });
+ });
+
+const pointer = (type: string, target: EventTarget, clientX: number, clientY: number, init: PointerEventInit = {}) => {
+ target.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button: 0,
+ cancelable: true,
+ clientX,
+ clientY,
+ isPrimary: true,
+ pointerId: 1,
+ pointerType: 'touch',
+ ...init,
+ })
+ );
+};
+
+const mouse = (type: string, target: EventTarget, clientX: number, clientY: number, button = 0) => {
+ target.dispatchEvent(new MouseEvent(type, { bubbles: true, button, cancelable: true, clientX, clientY }));
+};
+
+/**
+ * The draggable must live in a component INSIDE `DndContext`: React context
+ * flows downward, so a `useDraggable` in the same component that renders the
+ * provider would read dnd-kit's default internal context instead.
+ */
+const DraggableTile = ({ onClick, pannable }: { onClick: () => void; pannable: boolean }) => {
+ const { listeners, setNodeRef } = useDraggable({ id: 'tile' });
+
+ return (
+ // A button like the filmstrip thumb the sensor also serves.
+ <button
+ ref={setNodeRef}
+ {...listeners}
+ data-testid="tile"
+ onClick={onClick}
+ style={{ height: 100, touchAction: pannable ? 'auto' : 'none', width: 100 }}
+ type="button"
+ />
+ );
+};
+
+const renderHarness = async (options?: { pannable?: boolean }) => {
+ const pannable = options?.pannable ?? true;
+ const events = {
+ onClick: vi.fn(),
+ onDragCancel: vi.fn(),
+ onDragEnd: vi.fn(),
+ onDragStart: vi.fn(),
+ };
+
+ const Harness = () => {
+ const sensors = useSensors(
+ useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(HoldToDragSensor, {
+ activationConstraint: { delay: HOLD_DELAY_MS, tolerance: HOLD_TOLERANCE_PX },
+ })
+ );
+
+ return (
+ <DndContext
+ sensors={sensors}
+ onDragCancel={events.onDragCancel}
+ onDragEnd={events.onDragEnd}
+ onDragStart={events.onDragStart}
+ >
+ {/* The scroll container makes the tile touch-pannable, which is what the
+ hold gate arbitrates; `touch-action: none` opts the tile out of it. */}
+ <div style={{ height: 300, overflow: 'auto', width: 300 }}>
+ <DraggableTile onClick={events.onClick} pannable={pannable} />
+ </div>
+ </DndContext>
+ );
+ };
+
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await interact(() => {
+ root?.render(<Harness />);
+ });
+
+ return { events, tile: () => host!.querySelector<HTMLElement>('[data-testid="tile"]')! };
+};
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('HoldToDragSensor touch gate', () => {
+ it('gives an early move to the native scroll instead of activating a drag', async () => {
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ // Moved beyond the tolerance well before the hold delay elapses.
+ await interact(() => pointer('pointermove', document, 150, 190));
+
+ expect(events.onDragStart).not.toHaveBeenCalled();
+ expect(tile().getAttribute('data-drag-armed')).toBeNull();
+
+ // The gate is spent: nothing activates later, however long the finger stays.
+ await wait(HOLD_ELAPSED_MS);
+ await interact(() => pointer('pointermove', document, 150, 220));
+
+ expect(events.onDragStart).not.toHaveBeenCalled();
+ expect(events.onDragCancel).not.toHaveBeenCalled();
+ });
+
+ it('arms after a sustained hold, then drags on the follow-up move', async () => {
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+
+ // The armed cue is the visual half of the gate: hold complete, move to drag.
+ expect(tile().getAttribute('data-drag-armed')).toBe('true');
+
+ await interact(() => pointer('pointermove', document, 170, 150));
+
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+ expect(tile().getAttribute('data-drag-armed')).toBeNull();
+
+ await interact(() => pointer('pointerup', document, 190, 150));
+
+ expect(events.onDragEnd).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats a motionless armed hold that lifts as an ordinary tap', async () => {
+ // The stock TouchSensor delay constraint activates on the timer alone, so a
+ // deliberate slow tap selected nothing and the trailing click was swallowed.
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+
+ await interact(() => {
+ pointer('pointerup', document, 150, 150);
+ tile().dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
+ });
+
+ expect(events.onDragStart).not.toHaveBeenCalled();
+ expect(tile().getAttribute('data-drag-armed')).toBeNull();
+ // The tap still selects: nothing activated, so the click is not swallowed.
+ expect(events.onClick).toHaveBeenCalledOnce();
+ });
+
+ it('swallows the trailing click of a drag that lifted on its own tile', async () => {
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+ await interact(() => pointer('pointermove', document, 170, 150));
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ // The click must land within the 50ms post-lift window the swallow covers,
+ // exactly as a browser's compat click after a touch lift would.
+ await interact(() => {
+ pointer('pointerup', document, 170, 150);
+ tile().dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
+ });
+
+ expect(events.onClick).not.toHaveBeenCalled();
+ expect(events.onDragEnd).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases the gesture on pointercancel and accepts a new one', async () => {
+ // The browser claims the gesture (a native pan). A sensor that stops without
+ // ending the gesture leaves dnd-kit's activation guard set, which blocks
+ // every later drag on the context until reload.
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+ await interact(() => pointer('pointermove', document, 170, 150));
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ await interact(() => pointer('pointercancel', document, 170, 150));
+ expect(events.onDragCancel).toHaveBeenCalledTimes(1);
+
+ // A fresh gesture must still work: the pointercancel did not brick the context.
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+ await interact(() => pointer('pointermove', document, 170, 150));
+
+ expect(events.onDragStart).toHaveBeenCalledTimes(2);
+
+ // End the gesture: a sensor left mid-drag outlives the unmounted harness
+ // (its listeners are on the shared window/document) and would leak into
+ // the next test in this page.
+ await interact(() => pointer('pointerup', document, 170, 150));
+ });
+
+ it('cancels the hold when a second finger lands', async () => {
+ // A second finger during the hold is pinch or scroll intent; the armed
+ // gesture must not hijack the subsequent two-finger scroll.
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await interact(() => pointer('pointerdown', document, 100, 100, { isPrimary: false, pointerId: 2 }));
+
+ await wait(HOLD_ELAPSED_MS);
+ expect(tile().getAttribute('data-drag-armed')).toBeNull();
+
+ await interact(() => pointer('pointermove', document, 170, 150));
+
+ expect(events.onDragStart).not.toHaveBeenCalled();
+ });
+
+ it('lets the context menu through when armed, and suppresses it mid-drag', async () => {
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+ expect(tile().getAttribute('data-drag-armed')).toBe('true');
+
+ // Android's long-press menu (~500ms) outlasts the hold: menu intent, so the
+ // menu is allowed and the gate disarms instead of dragging over it.
+ const menuWhileArmed = new MouseEvent('contextmenu', { bubbles: true, cancelable: true });
+ await interact(() => window.dispatchEvent(menuWhileArmed));
+
+ expect(menuWhileArmed.defaultPrevented).toBe(false);
+ expect(tile().getAttribute('data-drag-armed')).toBeNull();
+
+ await interact(() => pointer('pointermove', document, 170, 150));
+ expect(events.onDragStart).not.toHaveBeenCalled();
+
+ // While the drag is live, the native menu is suppressed as with stock sensors.
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await wait(HOLD_ELAPSED_MS);
+ await interact(() => pointer('pointermove', document, 170, 150));
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ const menuWhileDragging = new MouseEvent('contextmenu', { bubbles: true, cancelable: true });
+ await interact(() => window.dispatchEvent(menuWhileDragging));
+
+ expect(menuWhileDragging.defaultPrevented).toBe(true);
+
+ // End the gesture so the sensor cannot leak into the next test in this page.
+ await interact(() => pointer('pointerup', document, 170, 150));
+ });
+
+ it('activates immediately by distance on a surface that cannot pan', async () => {
+ const { events, tile } = await renderHarness({ pannable: false });
+
+ // No hold: `touch-action: none` means the browser can never pan, so there
+ // is nothing to arbitrate and a small movement starts the drag at once.
+ await interact(() => pointer('pointerdown', tile(), 150, 150));
+ await interact(() => pointer('pointermove', document, 170, 150));
+
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ await interact(() => pointer('pointerup', document, 170, 150));
+
+ expect(events.onDragEnd).toHaveBeenCalledTimes(1);
+ });
+
+ it('activates immediately by distance for pen pointers on a pannable surface', async () => {
+ const { events, tile } = await renderHarness();
+
+ await interact(() => pointer('pointerdown', tile(), 150, 150, { pointerType: 'pen' }));
+ await interact(() => pointer('pointermove', document, 170, 150, { pointerType: 'pen' }));
+
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ await interact(() => pointer('pointerup', document, 170, 150, { pointerType: 'pen' }));
+
+ expect(events.onDragEnd).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('PrimaryMouseSensor button guard', () => {
+ it('starts drags for the primary button only', async () => {
+ const { events, tile } = await renderHarness();
+
+ // Middle-click (and other aux buttons) must not pick the tile up: the stock
+ // MouseSensor only rejects the right button.
+ await interact(() => mouse('mousedown', tile(), 150, 150, 1));
+ await interact(() => mouse('mousemove', document, 170, 150));
+
+ expect(events.onDragStart).not.toHaveBeenCalled();
+
+ await interact(() => mouse('mousedown', tile(), 150, 150));
+ await interact(() => mouse('mousemove', document, 170, 150));
+
+ expect(events.onDragStart).toHaveBeenCalledTimes(1);
+
+ await interact(() => mouse('mouseup', document, 170, 150));
+
+ expect(events.onDragEnd).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts
new file mode 100644
index 0000000000..b4d46a2c6a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts
@@ -0,0 +1,389 @@
+import { MouseSensor, type Activator, type SensorOptions, type SensorProps } from '@dnd-kit/core';
+
+/**
+ * Sensors for the shell's drag-and-drop that make touch scrolling possible.
+ *
+ * A distance-only activation constraint (the stock `PointerSensor` setup)
+ * claims a touch-drag as soon as the pointer moves a few pixels — before the
+ * browser can start panning — so any scrollable surface of draggable items
+ * (the gallery grid, the preview filmstrip) is unscrollable by touch: the
+ * image is picked up and dragged instead.
+ *
+ * `HoldToDragSensor` arbitrates the gesture for touch pointers with a timing
+ * gate, and keeps pens and the pre-gate behavior for surfaces that cannot pan:
+ *
+ * - A touch `pointerdown` starts a hold. While the hold is pending the sensor
+ * leaves the gesture strictly alone, so the browser is free to pan: an early
+ * move past the tolerance cancels the gate and the native scroll keeps the
+ * gesture. When the hold elapses the gate *arms* — the draggable node gets
+ * `data-drag-armed` so the tile can show its cue — and only movement past
+ * the tolerance after that starts the drag. A motionless hold that lifts is
+ * therefore an ordinary tap: the sensor never activates, no click is
+ * suppressed, and selection works exactly as before.
+ * - If the touched element sits under a `touch-action: none` (itself, or any
+ * ancestor below the first scroll container) the browser can never pan, so
+ * there is nothing to arbitrate: touch drags activate on a small distance,
+ * the pre-gate behavior. This keeps non-scrolling drag surfaces (the preview
+ * frame, floating widget windows) feeling immediate.
+ * - Pen pointers activate on a small distance, like the mouse: pen panning
+ * cannot be `preventDefault`ed after the fact (no touch events fire for a
+ * pen), so a hold gate would hand the armed gesture to the browser's pan
+ * claim unpredictably.
+ *
+ * Once the drag is active, the sensor holds the browser's pan off with a
+ * document-level non-passive `touchmove` listener — pointer events cannot
+ * `preventDefault` a pan — so the gesture cannot be stolen mid-drag.
+ *
+ * Every path through the state machine ends the gesture explicitly
+ * (`onEnd`/`onCancel`), which is what clears dnd-kit's activation guard; a
+ * sensor that stops mid-gesture without doing so blocks every later drag on
+ * the context until reload. In particular, `pointercancel` — the browser
+ * claiming the gesture for a pan — is handled for every pointer type, which
+ * is why pens route through this sensor instead of reaching `MouseSensor`
+ * (whose mouse-event set has no cancel event).
+ */
+
+export const TOUCH_DRAG_HOLD_DELAY_MS = 400;
+export const TOUCH_DRAG_MOVE_TOLERANCE_PX = 10;
+
+/** Distance that activates a drag when no hold gate applies (mouse, pen, non-pannable surfaces). */
+const DRAG_ACTIVATION_DISTANCE_PX = 6;
+
+const ARMED_CUE_ATTRIBUTE = 'data-drag-armed';
+
+const isScrollableOverflow = (overflow: string) =>
+ overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay';
+
+/**
+ * Whether the browser may pan from a touch starting on `target`: true unless a
+ * `touch-action: none` appears on the element itself or an ancestor below the
+ * first scroll container. (`touch-action` intersects down the ancestor chain,
+ * so a `none` anywhere below the scroller forbids the pan outright.)
+ */
+const canSurfacePan = (target: EventTarget | null): boolean => {
+ let element = target instanceof Element ? target : null;
+
+ while (element) {
+ const { overflowX, overflowY, touchAction } = getComputedStyle(element);
+
+ if (touchAction === 'none') {
+ return false;
+ }
+
+ if (isScrollableOverflow(overflowX) || isScrollableOverflow(overflowY)) {
+ return true;
+ }
+
+ element = element.parentElement;
+ }
+
+ return true;
+};
+
+const stopClickPropagation = (event: Event) => {
+ event.stopPropagation();
+};
+
+export interface HoldToDragSensorOptions extends SensorOptions {
+ activationConstraint?: {
+ delay: number;
+ tolerance: number;
+ };
+ onActivation?(props: { event: Event }): void;
+}
+
+type Gate = 'immediate' | 'waiting' | 'armed' | 'active';
+
+export class HoldToDragSensor {
+ static activators: Activator<HoldToDragSensorOptions>[] = [
+ {
+ eventName: 'onPointerDown',
+ handler: (event, options) => {
+ const nativeEvent = event.nativeEvent as PointerEvent;
+
+ if (!nativeEvent.isPrimary || nativeEvent.button !== 0) {
+ return false;
+ }
+
+ if (nativeEvent.pointerType !== 'touch' && nativeEvent.pointerType !== 'pen') {
+ return false;
+ }
+
+ options.onActivation?.({ event: nativeEvent });
+ return true;
+ },
+ },
+ ];
+
+ /**
+ * Mirror of `TouchSensor.setup()`: a non-passive `touchmove` listener present
+ * from startup makes `preventDefault()` work in touchmove listeners added
+ * later (required for iOS Safari), which the active drag relies on.
+ */
+ static setup(): () => void {
+ const noop = () => {};
+
+ window.addEventListener('touchmove', noop, { capture: false, passive: false });
+
+ return () => window.removeEventListener('touchmove', noop);
+ }
+
+ autoScrollEnabled = true;
+
+ private readonly props: SensorProps<HoldToDragSensorOptions>;
+ private readonly document: Document;
+ private readonly pointerId: number;
+ private readonly startX: number;
+ private readonly startY: number;
+ private readonly tolerance: number;
+ private readonly cueNode: HTMLElement | null;
+ private readonly abortController = new AbortController();
+ private holdTimer: number | null = null;
+ private gate: Gate | 'idle' = 'idle';
+ private detached = false;
+
+ constructor(props: SensorProps<HoldToDragSensorOptions>) {
+ this.props = props;
+
+ const event = props.event as PointerEvent;
+ this.document = event.target instanceof Element ? event.target.ownerDocument : window.document;
+ this.pointerId = event.pointerId;
+ this.startX = event.clientX;
+ this.startY = event.clientY;
+ this.cueNode = props.activeNode.node.current;
+
+ const { activationConstraint } = props.options ?? {};
+ this.tolerance = activationConstraint?.tolerance ?? TOUCH_DRAG_MOVE_TOLERANCE_PX;
+
+ // Pointer listeners live on the document, not the touched element: the
+ // element may unmount mid-gesture (the virtualized grid under auto-scroll),
+ // and document-level listeners keep receiving the events.
+ const { signal } = this.abortController;
+ this.document.addEventListener('pointermove', this.handlePointerMove, { signal });
+ this.document.addEventListener('pointerup', this.handlePointerEnd, { signal });
+ this.document.addEventListener('pointercancel', this.handlePointerCancel, { signal });
+ this.document.addEventListener('pointerdown', this.handleSecondaryPointerDown, { signal });
+ this.document.addEventListener('touchmove', this.handleTouchMove, { passive: false, signal });
+ this.document.addEventListener('keydown', this.handleKeyDown, { signal });
+ this.document.addEventListener('visibilitychange', this.handleCancel, { signal });
+ window.addEventListener('resize', this.handleCancel, { signal });
+ window.addEventListener('contextmenu', this.handleContextMenu, { signal });
+ window.addEventListener('dragstart', this.handleNativeDragStart, { signal });
+
+ if (event.pointerType === 'pen' || !canSurfacePan(event.target)) {
+ this.gate = 'immediate';
+ return;
+ }
+
+ this.gate = 'waiting';
+ this.holdTimer = window.setTimeout(() => {
+ if (this.gate !== 'waiting') {
+ return;
+ }
+
+ this.gate = 'armed';
+ this.cueNode?.setAttribute(ARMED_CUE_ATTRIBUTE, 'true');
+ this.props.onPending(
+ this.props.active,
+ { delay: this.delay, tolerance: this.tolerance },
+ { x: this.startX, y: this.startY }
+ );
+ }, this.delay);
+ }
+
+ private get delay(): number {
+ return this.props.options?.activationConstraint?.delay ?? TOUCH_DRAG_HOLD_DELAY_MS;
+ }
+
+ private readonly handlePointerMove = (event: PointerEvent) => {
+ if (event.pointerId !== this.pointerId) {
+ return;
+ }
+
+ if (this.gate === 'active') {
+ this.props.onMove({ x: event.clientX, y: event.clientY });
+ return;
+ }
+
+ const distance = Math.hypot(event.clientX - this.startX, event.clientY - this.startY);
+
+ if (this.gate === 'immediate') {
+ if (distance > DRAG_ACTIVATION_DISTANCE_PX) {
+ this.startDrag();
+ }
+
+ return;
+ }
+
+ if (this.gate === 'armed') {
+ // The hold succeeded; movement beyond the tolerance is the drag itself.
+ if (distance > this.tolerance) {
+ this.startDrag();
+ }
+
+ return;
+ }
+
+ // Waiting: movement past the tolerance is scrolling intent. The native
+ // scroll keeps the gesture; stop tracking it.
+ if (distance > this.tolerance) {
+ this.endGesture(false);
+ }
+ };
+
+ private readonly handlePointerEnd = (event: PointerEvent) => {
+ if (event.pointerId !== this.pointerId) {
+ return;
+ }
+
+ // A lift: an ordinary tap (never activated) or the end of a drag. Both end
+ // the gesture; only an activated drag suppresses the trailing click.
+ this.endGesture(true);
+ };
+
+ private readonly handlePointerCancel = (event: PointerEvent) => {
+ if (event.pointerId !== this.pointerId) {
+ return;
+ }
+
+ // The browser claimed the gesture (a native pan). Its event stream ends
+ // here, so the sensor must too — a stuck gesture blocks all later drags.
+ this.cancelGesture();
+ };
+
+ private readonly handleSecondaryPointerDown = (event: PointerEvent) => {
+ if (this.gate === 'active') {
+ // A second finger during a live drag changes nothing.
+ return;
+ }
+
+ if (!event.isPrimary) {
+ // A second finger during the hold is pinch or scroll intent, never a drag.
+ this.cancelGesture();
+ }
+ };
+
+ private readonly handleTouchMove = (event: TouchEvent) => {
+ // While the drag is live, hold the browser's pan off: pointer events cannot
+ // preventDefault a pan, so this is the only thing keeping the gesture.
+ if (this.gate === 'active' && event.cancelable) {
+ event.preventDefault();
+ }
+ };
+
+ private readonly handleContextMenu = (event: MouseEvent) => {
+ if (this.gate === 'armed') {
+ // Android's long-press menu (~500ms) outlasts the hold delay. Treat it as
+ // menu intent: disarm so a drag cannot start over the open menu, and let
+ // the menu through.
+ this.cancelGesture();
+ return;
+ }
+
+ // Mid-drag or mid-gesture: suppress the native menu, as the stock sensors do.
+ event.preventDefault();
+ };
+
+ private readonly handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ this.cancelGesture();
+ }
+ };
+
+ private readonly handleCancel = () => {
+ this.cancelGesture();
+ };
+
+ private readonly handleNativeDragStart = (event: Event) => {
+ event.preventDefault();
+ };
+
+ private startDrag() {
+ this.clearHoldTimer();
+ this.clearArmedCue();
+ this.gate = 'active';
+
+ // A drag that ends where it started must not also click its own tile, so
+ // swallow the trailing click. Removed shortly after detach (not with the
+ // other listeners) so the click that follows the lift stays swallowed.
+ this.document.addEventListener('click', stopClickPropagation, true);
+ this.document.getSelection()?.removeAllRanges();
+ // Keep the selection clear for the whole drag, as the stock sensors do.
+ this.document.addEventListener('selectionchange', this.clearSelection, { signal: this.abortController.signal });
+ this.props.onStart({ x: this.startX, y: this.startY });
+ }
+
+ private readonly clearSelection = () => {
+ this.document.getSelection()?.removeAllRanges();
+ };
+
+ /**
+ * Ends the in-flight gesture. Mirrors the stock sensors' end semantics:
+ * `onAbort` when nothing ever activated, then `onEnd`/`onCancel` — the call
+ * that clears dnd-kit's activation guard.
+ */
+ private endGesture(ended: boolean) {
+ const activated = this.gate === 'active';
+
+ this.detach();
+
+ if (!activated) {
+ this.props.onAbort(this.props.active);
+ }
+
+ if (ended) {
+ this.props.onEnd();
+ } else {
+ this.props.onCancel();
+ }
+ }
+
+ private cancelGesture() {
+ this.endGesture(false);
+ }
+
+ private clearHoldTimer() {
+ if (this.holdTimer !== null) {
+ window.clearTimeout(this.holdTimer);
+ this.holdTimer = null;
+ }
+ }
+
+ private clearArmedCue() {
+ this.cueNode?.removeAttribute(ARMED_CUE_ATTRIBUTE);
+ }
+
+ detach() {
+ if (this.detached) {
+ return;
+ }
+
+ this.detached = true;
+ this.gate = 'idle';
+ this.clearHoldTimer();
+ this.clearArmedCue();
+ this.abortController.abort();
+ setTimeout(() => this.document.removeEventListener('click', stopClickPropagation, true), 50);
+ }
+}
+
+/**
+ * The stock `MouseSensor` activates for any non-right button, where the
+ * `PointerSensor` it replaces only ever accepted the primary button. Restore
+ * that guard so middle-click and back/forward buttons cannot start drags.
+ */
+export class PrimaryMouseSensor extends MouseSensor {}
+
+PrimaryMouseSensor.activators = [
+ {
+ eventName: 'onMouseDown',
+ handler: ({ nativeEvent: event }, { onActivation }) => {
+ if (event.button !== 0) {
+ return false;
+ }
+
+ onActivation?.({ event });
+ return true;
+ },
+ },
+];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
index 7b9efcc7b1..25511dca2b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
@@ -119,7 +119,7 @@ const FilmstripThumb = ({
borderColor={isSelected ? 'accent.solid' : 'border.subtle'}
borderWidth="2px"
boxSize={size}
- css={isDragging ? FILMSTRIP_THUMB_DRAG_CSS : undefined}
+ css={isDragging ? FILMSTRIP_THUMB_DRAG_CSS : FILMSTRIP_THUMB_ARMED_CSS}
cursor="pointer"
flexShrink={0}
opacity={isDragging ? 0.4 : undefined}
@@ -127,8 +127,8 @@ const FilmstripThumb = ({
position="relative"
rounded="sm"
// Pan, don't drag: the strip scrolls horizontally, so a moving finger
- // must scroll it (the drag sensor detaches on touchcancel); dragging
- // still works via the TouchSensor's hold delay.
+ // must scroll it (the hold-to-drag sensor releases the gesture when the
+ // browser claims it); dragging still works after a sustained hold.
touchAction="pan-x"
onClick={handleClick}
>
@@ -146,6 +146,13 @@ const FILMSTRIP_CONTAIN_CSS = { contain: 'inline-size' } as const;
/** Same touch drag cue as the gallery grid: the source thumb desaturates while dragged. */
const FILMSTRIP_THUMB_DRAG_CSS = { filter: 'saturate(0.4)' } as const;
+/**
+ * Same armed cue as the gallery grid: desaturation while a sustained touch
+ * hold has armed the drag gate (before movement starts the drag). Set as
+ * `data-drag-armed` by the hold-to-drag sensor.
+ */
+const FILMSTRIP_THUMB_ARMED_CSS = { '&[data-drag-armed=true]': { filter: 'saturate(0.4)' } } as const;
+
// The thumb row centers itself with `h="full"`, which needs the content
// wrapper to actually span the viewport height rather than shrink to it.
const FILMSTRIP_CONTENT_PROPS = { h: 'full' } as const;