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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): swipe between gallery items in the preview on touch devices
Lincoln Steincd1a311e3563
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 094bf0410f..c2784109e8 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1,6 +1,6 @@{- "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",- "capturedAt": "2026-09-23",+ "browserExecutable": "/home/lstein/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",+ "capturedAt": "2026-09-25","routes": [{"activatedResourceBaseline": {@@ -14,13 +14,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 122.20000000298023,+ "domContentLoadedMedianMs": 94.20000004768372,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 122.29999999701977,- "longestTaskMaxMs": 76,+ "loadMedianMs": 94.30000001192093,+ "longestTaskMaxMs": 62,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -30,13 +30,13 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 32,- "scriptRawBytes": 1814643,- "scriptRequestCount": 28,- "totalRawBytes": 2009050+ "otherRawBytes": 169978,+ "requestCount": 31,+ "scriptRawBytes": 1815741,+ "scriptRequestCount": 27,+ "totalRawBytes": 2011542},- "routeReadyMedianMs": 259.09999999403954,+ "routeReadyMedianMs": 209.20000004768372,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -52,13 +52,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 121.29999999701977,+ "domContentLoadedMedianMs": 98.10000002384186,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 121.5,- "longestTaskMaxMs": 75,+ "loadMedianMs": 98.19999998807907,+ "longestTaskMaxMs": 65,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -68,13 +68,13 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 32,- "scriptRawBytes": 1814643,- "scriptRequestCount": 28,- "totalRawBytes": 2009050+ "otherRawBytes": 169978,+ "requestCount": 31,+ "scriptRawBytes": 1815741,+ "scriptRequestCount": 27,+ "totalRawBytes": 2011542},- "routeReadyMedianMs": 269.09999999403954,+ "routeReadyMedianMs": 220,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -90,15 +90,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 122.59999999403954,+ "domContentLoadedMedianMs": 106.60000002384186,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 122.70000000298023,- "longestTaskMaxMs": 161,+ "loadMedianMs": 106.80000001192093,+ "longestTaskMaxMs": 130,"owner": "workbench",- "projectSwitchMedianMs": 31.700000002980232,+ "projectSwitchMedianMs": 32.5,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -106,13 +106,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 99,- "scriptRawBytes": 3766409,- "scriptRequestCount": 94,- "totalRawBytes": 4117192+ "otherRawBytes": 169978,+ "requestCount": 98,+ "scriptRawBytes": 3779849,+ "scriptRequestCount": 93,+ "totalRawBytes": 4132026},- "routeReadyMedianMs": 410.5,+ "routeReadyMedianMs": 345.30000001192093,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -128,15 +128,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 122,+ "domContentLoadedMedianMs": 99.59999996423721,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 122.19999998807907,- "longestTaskMaxMs": 153,+ "loadMedianMs": 99.69999998807907,+ "longestTaskMaxMs": 128,"owner": "workbench",- "projectSwitchMedianMs": 43.5,+ "projectSwitchMedianMs": 47.89999997615814,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -144,13 +144,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 99,- "scriptRawBytes": 3766409,- "scriptRequestCount": 94,- "totalRawBytes": 4117192+ "otherRawBytes": 169978,+ "requestCount": 98,+ "scriptRawBytes": 3779849,+ "scriptRequestCount": 93,+ "totalRawBytes": 4132026},- "routeReadyMedianMs": 421.69999998807907,+ "routeReadyMedianMs": 346.7999999523163,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -159,20 +159,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309242,+ "largestAssetRawBytes": 309204,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 503197,+ "scriptRawBytes": 503187,"scriptRequestCount": 9,- "totalRawBytes": 503197+ "totalRawBytes": 503187},- "domContentLoadedMedianMs": 125.8999999910593,+ "domContentLoadedMedianMs": 96.80000001192093,"id": "editor-canvas",- "layoutAckMedianMs": 2.5,- "layoutReturnSwitchMedianMs": 45.79999999701977,- "layoutSwitchMedianMs": 84.20000000298023,- "loadMedianMs": 126,- "longestTaskMaxMs": 159,+ "layoutAckMedianMs": 2.799999952316284,+ "layoutReturnSwitchMedianMs": 47,+ "layoutSwitchMedianMs": 69.89999997615814,+ "loadMedianMs": 97,+ "longestTaskMaxMs": 132,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -182,13 +182,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 108,- "scriptRawBytes": 4269606,- "scriptRequestCount": 103,- "totalRawBytes": 4620389+ "otherRawBytes": 169978,+ "requestCount": 107,+ "scriptRawBytes": 4283036,+ "scriptRequestCount": 102,+ "totalRawBytes": 4635213},- "routeReadyMedianMs": 1120.5,+ "routeReadyMedianMs": 1015.8999999761581,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -197,20 +197,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309242,+ "largestAssetRawBytes": 309204,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 503197,+ "scriptRawBytes": 503187,"scriptRequestCount": 9,- "totalRawBytes": 503197+ "totalRawBytes": 503187},- "domContentLoadedMedianMs": 122,+ "domContentLoadedMedianMs": 94.80000001192093,"id": "editor-canvas","layoutAckMedianMs": 2.5,- "layoutReturnSwitchMedianMs": 51.29999999701977,- "layoutSwitchMedianMs": 86.1000000089407,- "loadMedianMs": 122.20000000298023,- "longestTaskMaxMs": 194,+ "layoutReturnSwitchMedianMs": 44.19999998807907,+ "layoutSwitchMedianMs": 72.5,+ "loadMedianMs": 94.89999997615814,+ "longestTaskMaxMs": 145,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -220,13 +220,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 108,- "scriptRawBytes": 4269606,- "scriptRequestCount": 103,- "totalRawBytes": 4620389+ "otherRawBytes": 169978,+ "requestCount": 107,+ "scriptRawBytes": 4283036,+ "scriptRequestCount": 102,+ "totalRawBytes": 4635213},- "routeReadyMedianMs": 1125.5,+ "routeReadyMedianMs": 1012.6999999880791,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -238,17 +238,17 @@"largestAssetRawBytes": 175033,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 398142,+ "scriptRawBytes": 398110,"scriptRequestCount": 6,- "totalRawBytes": 413555+ "totalRawBytes": 413523},- "domContentLoadedMedianMs": 124.20000000298023,+ "domContentLoadedMedianMs": 95.30000001192093,"id": "editor-workflow",- "layoutAckMedianMs": 2.5,- "layoutReturnSwitchMedianMs": 32.19999998807907,- "layoutSwitchMedianMs": 95,- "loadMedianMs": 124.29999999701977,- "longestTaskMaxMs": 157,+ "layoutAckMedianMs": 2.199999988079071,+ "layoutReturnSwitchMedianMs": 28.900000035762787,+ "layoutSwitchMedianMs": 79.80000001192093,+ "loadMedianMs": 95.30000001192093,+ "longestTaskMaxMs": 131,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -258,13 +258,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 106,- "scriptRawBytes": 4164551,- "scriptRequestCount": 100,- "totalRawBytes": 4530747+ "otherRawBytes": 169978,+ "requestCount": 105,+ "scriptRawBytes": 4177959,+ "scriptRequestCount": 99,+ "totalRawBytes": 4545549},- "routeReadyMedianMs": 1126.7999999970198,+ "routeReadyMedianMs": 1022.8999999761581,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -276,17 +276,17 @@"largestAssetRawBytes": 175033,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 398142,+ "scriptRawBytes": 398110,"scriptRequestCount": 6,- "totalRawBytes": 413555+ "totalRawBytes": 413523},- "domContentLoadedMedianMs": 123.6000000089407,+ "domContentLoadedMedianMs": 101.90000003576279,"id": "editor-workflow",- "layoutAckMedianMs": 2.5999999940395355,- "layoutReturnSwitchMedianMs": 39.70000000298023,- "layoutSwitchMedianMs": 127.6000000089407,- "loadMedianMs": 123.70000000298023,- "longestTaskMaxMs": 381,+ "layoutAckMedianMs": 2.300000011920929,+ "layoutReturnSwitchMedianMs": 37.19999998807907,+ "layoutSwitchMedianMs": 111.10000002384186,+ "loadMedianMs": 102.10000002384186,+ "longestTaskMaxMs": 293,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -296,13 +296,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 106,- "scriptRawBytes": 4164551,- "scriptRequestCount": 100,- "totalRawBytes": 4530747+ "otherRawBytes": 169978,+ "requestCount": 105,+ "scriptRawBytes": 4177959,+ "scriptRequestCount": 99,+ "totalRawBytes": 4545549},- "routeReadyMedianMs": 1161.5999999940395,+ "routeReadyMedianMs": 1078.1000000238419,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -318,13 +318,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 124.8999999910593,+ "domContentLoadedMedianMs": 98.90000003576279,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 45,- "loadMedianMs": 125,- "longestTaskMaxMs": 153,+ "layoutSwitchMedianMs": 35.39999997615814,+ "loadMedianMs": 99.10000002384186,+ "longestTaskMaxMs": 130,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -334,13 +334,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 99,- "scriptRawBytes": 3766409,- "scriptRequestCount": 94,- "totalRawBytes": 4117192+ "otherRawBytes": 169978,+ "requestCount": 98,+ "scriptRawBytes": 3779849,+ "scriptRequestCount": 93,+ "totalRawBytes": 4132026},- "routeReadyMedianMs": 1354,+ "routeReadyMedianMs": 1248.5999999642372,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -356,13 +356,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 124,+ "domContentLoadedMedianMs": 96.89999997615814,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 52.400000005960464,- "loadMedianMs": 124,- "longestTaskMaxMs": 152,+ "layoutSwitchMedianMs": 43.59999996423721,+ "loadMedianMs": 97,+ "longestTaskMaxMs": 136,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -372,13 +372,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 168584,- "requestCount": 99,- "scriptRawBytes": 3766409,- "scriptRequestCount": 94,- "totalRawBytes": 4117192+ "otherRawBytes": 169978,+ "requestCount": 98,+ "scriptRawBytes": 3779849,+ "scriptRequestCount": 93,+ "totalRawBytes": 4132026},- "routeReadyMedianMs": 1370,+ "routeReadyMedianMs": 1285.9000000357628,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}@@ -1747,6 +1747,7 @@"source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx",+ "source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",@@ -1759,11 +1760,13 @@"source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",+ "source:src/workbench/widgets/preview/previewSwipe.ts","source:src/workbench/widgets/preview/settingsContribution.ts","source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",+ "source:src/workbench/widgets/preview/usePreviewSwipe.ts","source:src/workbench/widgets/project/manifest.ts","source:src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx","source:src/workbench/widgets/queue-status/implementation.ts",@@ -2952,6 +2955,7 @@"source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx",+ "source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",@@ -2964,11 +2968,13 @@"source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",+ "source:src/workbench/widgets/preview/previewSwipe.ts","source:src/workbench/widgets/preview/settingsContribution.ts","source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",+ "source:src/workbench/widgets/preview/usePreviewSwipe.ts","source:src/workbench/widgets/project/manifest.ts","source:src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx","source:src/workbench/widgets/queue-status/implementation.ts",@@ -4077,6 +4083,7 @@"source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx",+ "source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",@@ -4089,11 +4096,13 @@"source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",+ "source:src/workbench/widgets/preview/previewSwipe.ts","source:src/workbench/widgets/preview/settingsContribution.ts","source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",+ "source:src/workbench/widgets/preview/usePreviewSwipe.ts","source:src/workbench/widgets/project/manifest.ts","source:src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx","source:src/workbench/widgets/queue-status/implementation.ts",diff --git a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.tsindex 9881af7211..f66e4dec54 100644--- a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts@@ -2,9 +2,10 @@ import { MouseSensor, type Activator, type SensorOptions, type SensorProps } fro/*** For touch on pannable surfaces, hold first, then require movement: early movement yields to scrolling and- * motionless holds remain taps. Pen and touch-action:none surfaces activate by distance. Once armed, a non-passive- * touchmove listener prevents native pan from stealing the gesture. Every exit, including pointercancel, calls- * onEnd/onCancel to clear dnd-kit's activation guard.+ * motionless holds remain taps. Pen and touch-action:none surfaces activate by distance, unless the surface marks+ * itself with `data-drag-hold-on-touch` because it owns one-finger gestures of its own (the preview swipe); early+ * movement then yields to that gesture. Once armed, a non-passive touchmove listener prevents native pan from+ * stealing the gesture. Every exit, including pointercancel, calls onEnd/onCancel to clear dnd-kit's activation guard.*/export const TOUCH_DRAG_HOLD_DELAY_MS = 400;@@ -44,6 +45,10 @@ const canSurfacePan = (target: EventTarget | null): boolean => {return true;};+/** Whether a touch surface claims one-finger movement for its own gesture, so a drag needs the hold. */+const requestsTouchHold = (target: EventTarget | null): boolean =>+ target instanceof Element && target.closest('[data-drag-hold-on-touch="true"]') !== null;+const stopClickPropagation = (event: Event) => {event.stopPropagation();};@@ -134,7 +139,7 @@ export class HoldToDragSensor {window.addEventListener('contextmenu', this.handleContextMenu, { signal });window.addEventListener('dragstart', this.handleNativeDragStart, { signal });- if (event.pointerType === 'pen' || !canSurfacePan(event.target)) {+ if (event.pointerType === 'pen' || (!canSurfacePan(event.target) && !requestsTouchHold(event.target))) {this.gate = 'immediate';return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex e42ecc348b..6811fac440 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -19,6 +19,7 @@ import {useState,type CSSProperties,type MouseEvent,+ type PointerEvent,type ReactNode,type Ref,type SyntheticEvent,@@ -27,6 +28,7 @@ import { useTranslation } from 'react-i18next';import { PreviewCompareDropZone } from './PreviewCompareDropZone';import { FittedFrame, PreviewStage } from './PreviewStage';+import { PreviewSwipeNeighbors } from './PreviewSwipeNeighbor';import {clearVideoSpanPlaybackState,consumeVideoSpanPlaybackRequest,@@ -36,6 +38,7 @@ import {subscribeVideoSpanPlaybackRequests,} from './spanPlaybackRequest';import { usePreviewLoupe, type PreviewLoupeControls, type PreviewZoomState } from './usePreviewLoupe';+import { usePreviewSwipe, type PreviewSwipeNavigation } from './usePreviewSwipe';export type PreviewMediaSource =| { itemKey: GalleryItemKey; kind: 'image'; source: StreamingImageSource }@@ -49,6 +52,8 @@ interface PreviewFrameProps {/** Keep the last denoise frame until source decoding completes, then notify onSourceLoaded. */holdSource?: StreamingImageSource | null;onSourceLoaded?: (src: string) => void;+ /** A small, usually cached rendition (the thumbnail) shown until a settled image's full pixels load. */+ placeholderSrc?: string;isItemCurrent?: (itemKey: GalleryItemKey) => boolean;/** Keep live-frame geometry identical to finished media; progress/device text belongs to external chrome. */isLive: boolean;@@ -60,6 +65,8 @@ interface PreviewFrameProps {paddingBottom?: string;shouldAntialiasLiveImage: boolean;source: PreviewMediaSource | null;+ /** Touch swipe navigation between neighbors; framed, settled images only. */+ swipe?: PreviewSwipeNavigation;videoControllerRef?: Ref<PreviewVideoFrameController>;variant: 'framed' | 'inset';}@@ -78,6 +85,7 @@ export const PreviewFrame = (props: PreviewFrameProps) => {padding={props.padding}paddingBottom={props.paddingBottom}source={props.source}+ swipe={props.swipe}videoControllerRef={props.videoControllerRef}/>);@@ -99,8 +107,10 @@ const PreviewImageFrame = ({onZoomChange,padding,paddingBottom,+ placeholderSrc,shouldAntialiasLiveImage,source,+ swipe: swipeNavigation,variant,}: Omit<PreviewFrameProps, 'isItemCurrent' | 'onVideoCopyAvailabilityChange' | 'source' | 'videoControllerRef'> & {source: StreamingImageSource | null;@@ -115,6 +125,9 @@ const PreviewImageFrame = ({const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);const isDragDisabled = !dragItem || isLive || loupe.isZoomed;const disabledDragId = useId();+ const dragId = dragItem+ ? getGalleryItemDragId(dragItem, 'preview-frame')+ : `preview-frame:disabled:${disabledDragId}`;const {isDragging,listeners,@@ -122,19 +135,55 @@ const PreviewImageFrame = ({} = useDraggable({data: dragData,disabled: isDragDisabled,- id: dragItem ? getGalleryItemDragId(dragItem, 'preview-frame') : `preview-frame:disabled:${disabledDragId}`,+ id: dragId,});+ const isSwipeEnabled = variant === 'framed' && !isLive && swipeNavigation !== undefined;+ const displayedSourceToken = variant === 'framed' && !isLive && source ? source.src : null;+ const swipe = usePreviewSwipe({+ displayedSourceToken,+ dragId,+ enabled: isSwipeEnabled,+ isZoomed: loupe.isZoomed,+ navigation: swipeNavigation ?? null,+ });+ const { contentTrackRef, onPointerDown: handleSwipePointerDown, stageRefCallback: swipeStageRefCallback } = swipe;const setContentRef = useCallback((element: HTMLDivElement | null) => {setDragNodeRef(element);+ contentTrackRef(element);+ const cleanupLoupe = contentRefCallback?.(element);++ return () => {+ cleanupLoupe?.();+ contentTrackRef(null);+ setDragNodeRef(null);+ };+ },+ [contentRefCallback, contentTrackRef, setDragNodeRef]+ );+ const setStageRef = useCallback(+ (element: HTMLDivElement | null) => {+ const cleanupLoupe = stageRefCallback?.(element);+ const cleanupSwipe = swipeStageRefCallback(element);- return contentRefCallback?.(element);+ return () => {+ cleanupLoupe?.();+ cleanupSwipe?.();+ };},- [contentRefCallback, setDragNodeRef]+ [stageRefCallback, swipeStageRefCallback]);// Reset zoom in place when the displayed image changes (or goes live) — a// remount would flash the frame on every selection.- loupe.syncDisplayedSource(variant === 'framed' && !isLive && source ? source.src : null);+ loupe.syncDisplayedSource(displayedSourceToken);+ const loupeStageProps = loupe.stageProps;+ const handleStagePointerDown = useCallback(+ (event: PointerEvent<HTMLDivElement>) => {+ loupeStageProps?.onPointerDown(event);+ handleSwipePointerDown(event);+ },+ [handleSwipePointerDown, loupeStageProps]+ );const handleContextMenu = useCallback((event: MouseEvent<HTMLDivElement>) => {if (onContextMenu) {@@ -151,6 +200,8 @@ const PreviewImageFrame = ({display: 'block',height: 'auto',imageRendering: isLive && !shouldAntialiasLiveImage ? 'pixelated' : undefined,+ // Positioned, so it paints over the absolutely positioned placeholder beneath it.+ position: 'relative',width: '100%',}),[isLive, shouldAntialiasLiveImage]@@ -158,10 +209,21 @@ const PreviewImageFrame = ({const imageRef = useRef<HTMLImageElement | null>(null);const [settledSrc, setSettledSrc] = useState<string | null>(null);const isHolding = Boolean(holdSource && source && settledSrc !== source.src);+ // Settled images mount one element per source: a reused element whose new source is still downloading would keep+ // painting the previous image until the new one arrived (a swipe landing on the wrong picture, then a flash). Live+ // frames keep reusing theirs, since each denoise step is a new data URL.+ const imageKey = isLive ? undefined : source?.src;+ const [loadedSrc, setLoadedSrc] = useState<string | null>(null);+ const isShowingPlaceholder = Boolean(placeholderSrc && !isLive && !isHolding && source && loadedSrc !== source.src);const handleSourceSettled = useCallback((event: SyntheticEvent<HTMLImageElement>) => {const src = event.currentTarget.getAttribute('src');+ // Only a frame with a placeholder tracks loading; live frames never have one.+ if (src !== null && placeholderSrc) {+ setLoadedSrc(src);+ }+// Only tracked while a hold is up: a live frame is a new data URL every// step, and settling each one would re-render the frame per step for// nothing.@@ -172,7 +234,7 @@ const PreviewImageFrame = ({setSettledSrc(src);onSourceLoaded?.(src);},- [holdSource, onSourceLoaded]+ [holdSource, onSourceLoaded, placeholderSrc]);// A hold arriving after the image already decoded (a cached image, or the// element reused across a source swap) would never see a load event.@@ -208,7 +270,19 @@ const PreviewImageFrame = ({);const media = source ? (<>+ {isShowingPlaceholder ? (+ // Keyed like the image above it, for the same reason: a reused element would show the last thumbnail.+ <img+ key={placeholderSrc}+ aria-hidden="true"+ alt=""+ draggable={false}+ src={placeholderSrc}+ style={PLACEHOLDER_IMAGE_STYLE}+ />+ ) : null}<img+ key={imageKey}ref={imageRef}alt={source.alt}draggable={false}@@ -243,7 +317,7 @@ const PreviewImageFrame = ({return (<PreviewStage- ref={stageRefCallback}+ ref={setStageRef}cursor={loupe.isZoomed ? 'grab' : undefined}fill="flex"padding={padding}@@ -252,6 +326,7 @@ const PreviewImageFrame = ({// behavior.touchAction={isLive ? undefined : 'none'}{...loupe.stageProps}+ onPointerDown={handleStagePointerDown}>{/** Disable comparison drops over live renders because comparison would pause follow and expose stale@@ -263,14 +338,25 @@ const PreviewImageFrame = ({{...listeners}bg="transparent"cursor={isDragDisabled ? undefined : isDragging ? 'grabbing' : 'grab'}+ // One-finger movement swipes, so a touch drag needs the hold first (see holdToDragSensor).+ data-drag-hold-on-touch={isSwipeEnabled ? 'true' : undefined}frameHeight={frameHeight}frameWidth={frameWidth}opacity={isDragging ? 0.55 : undefined}+ style={swipe.restStyle}touchAction={isDragDisabled ? undefined : 'none'}onContextMenu={onContextMenu ? handleContextMenu : undefined}>{media}</FittedFrame>+ {isSwipeEnabled && swipe.showsNeighbors ? (+ <PreviewSwipeNeighbors+ neighbors={swipeNavigation.neighbors}+ nextTrackRef={swipe.nextTrackRef}+ previousTrackRef={swipe.previousTrackRef}+ restStyle={swipe.restStyle}+ />+ ) : null}</PreviewStage>);};@@ -285,6 +371,7 @@ const PreviewVideo = ({padding,paddingBottom,source,+ swipe: swipeNavigation,videoControllerRef,}: {dragItem?: GalleryItemRef;@@ -296,6 +383,7 @@ const PreviewVideo = ({padding?: string;paddingBottom?: string;source: Extract<PreviewMediaSource, { kind: 'video' }>;+ swipe?: PreviewSwipeNavigation;videoControllerRef?: Ref<PreviewVideoFrameController>;}) => {const { t } = useTranslation();@@ -303,6 +391,9 @@ const PreviewVideo = ({// Use a corner drag grip for video so native seek-bar scrubbing cannot activate gallery dragging.const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);const disabledDragId = useId();+ const dragId = dragItem+ ? getGalleryItemDragId(dragItem, 'preview-frame')+ : `preview-frame:disabled:${disabledDragId}`;const {isDragging,listeners,@@ -310,8 +401,35 @@ const PreviewVideo = ({} = useDraggable({data: dragData,disabled: !dragItem,- id: dragItem ? getGalleryItemDragId(dragItem, 'preview-frame') : `preview-frame:disabled:${disabledDragId}`,+ id: dragId,+ });+ // Each clip mounts its own player, so a landed swipe simply unmounts this one at rest.+ const swipe = usePreviewSwipe({+ displayedSourceToken: source.src,+ dragId,+ enabled: swipeNavigation !== undefined,+ isZoomed: false,+ navigation: swipeNavigation ?? null,});+ const { onPointerDown: handleSwipePointerDown } = swipe;+ // The native control bar owns touches along the frame's bottom edge: seeking and volume must never swipe. A+ // fullscreen player is out of the carousel entirely; navigating would unmount it and drop fullscreen.+ const handleStagePointerDown = useCallback(+ (event: PointerEvent<HTMLDivElement>) => {+ const video = videoRef.current;+ const frame = video?.getBoundingClientRect();++ if (+ (frame && event.clientY >= frame.bottom - VIDEO_CONTROL_BAND_PX) ||+ (video && video.ownerDocument.fullscreenElement === video)+ ) {+ return;+ }++ handleSwipePointerDown(event);+ },+ [handleSwipePointerDown]+ );const automaticRefreshUsedRef = useRef(false);const pendingRefreshRef = useRef<Promise<boolean> | null>(null);const [hasFailed, setHasFailed] = useState(false);@@ -712,12 +830,22 @@ const PreviewVideo = ({);return (- <PreviewStage fill="flex" padding={padding} paddingBottom={paddingBottom}>+ <PreviewStage+ ref={swipe.stageRefCallback}+ fill="flex"+ padding={padding}+ paddingBottom={paddingBottom}+ // Horizontal travel is the swipe's; without a swipe the browser keeps its native gestures.+ touchAction={swipeNavigation ? 'pan-y pinch-zoom' : undefined}+ onPointerDown={swipeNavigation ? handleStagePointerDown : undefined}+ ><FittedFrame+ ref={swipe.contentTrackRef}bg="black"frameHeight={frameHeight}frameWidth={frameWidth}opacity={isDragging ? 0.55 : undefined}+ style={swipe.restStyle}onContextMenu={onContextMenu ? handleContextMenu : undefined}>{dragItem ? (@@ -801,6 +929,14 @@ const PreviewVideo = ({</>) : null}</FittedFrame>+ {swipeNavigation && swipe.showsNeighbors ? (+ <PreviewSwipeNeighbors+ neighbors={swipeNavigation.neighbors}+ nextTrackRef={swipe.nextTrackRef}+ previousTrackRef={swipe.previousTrackRef}+ restStyle={swipe.restStyle}+ />+ ) : null}</PreviewStage>);};@@ -855,6 +991,22 @@ interface VideoSpan {*/const SPAN_SEEK_TOLERANCE_SECONDS = 0.05;+/**+ * Height of the native video controls, measured up from the frame's bottom edge; touches there never swipe. Tall+ * enough for Chrome Android's timeline, which sits above its button row.+ */+const VIDEO_CONTROL_BAND_PX = 72;++/** Fills the fitted frame, which already has the image's aspect ratio. */+const PLACEHOLDER_IMAGE_STYLE: CSSProperties = {+ height: '100%',+ inset: 0,+ objectFit: 'contain',+ pointerEvents: 'none',+ position: 'absolute',+ width: '100%',+};+/** How long a span waits for an element that could not act on it yet. */const PARKED_SPAN_TTL_MS = 15_000;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsxnew file mode 100644index 0000000000..9674dd3805--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx@@ -0,0 +1,476 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import type { GalleryItem } from '@features/gallery';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext, useDndMonitor, useDroppable, useSensor, useSensors } from '@dnd-kit/core';+import { system } from '@theme/system';+import { HoldToDragSensor, PrimaryMouseSensor } from '@workbench/shell/holdToDragSensor';+import { widgetCollisionDetection } from '@workbench/widgetDnd';+import { createInstance } from 'i18next';+import { act, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { PreviewNeighbor } from './usePreviewNavigation';++import { PreviewFrame } from './PreviewFrame';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ initAsync: false,+ lng: 'en',+ resources: { en: { translation: { widgets: { preview: { dragVideo: 'Drag video' } } } } },+});++// The production hold, so a slow runner cannot arm a drag between a touch and its first quick move.+const HOLD_DELAY_MS = 400;+const STAGE_WIDTH = 300;++const svg = (fill: string) =>+ `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="${fill}"/></svg>`;++const makeItem = (name: string, kind: 'image' | 'video' = 'image'): GalleryItem => {+ const base = {+ boardId: 'none',+ category: 'general' as const,+ createdAt: '2026-01-01T00:00:00Z',+ fullUrl: svg(name),+ height: 128,+ isIntermediate: false,+ name,+ starred: false,+ thumbnailUrl: svg(name),+ width: 128,+ };++ return kind === 'image' ? { ...base, kind } : { ...base, durationSeconds: 1, kind };+};++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, ms = 50): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, ms);+ });+ });++/**+ * Dispatch a touch pointer event stamped at `at` ms on a virtual gesture clock: release velocity is read from event+ * timestamps, so stamping them keeps flicks and slow drags independent of how fast the runner is.+ */+const touch = (+ type: string,+ target: EventTarget,+ clientX: number,+ clientY: number,+ at: number,+ init: PointerEventInit = {}+) => {+ const event = new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ cancelable: true,+ clientX,+ clientY,+ isPrimary: true,+ pointerId: 1,+ pointerType: 'touch',+ ...init,+ });++ Object.defineProperty(event, 'timeStamp', { value: at });+ target.dispatchEvent(event);+};++/** Horizontal touch path: down at the first x, a move per later x, then up, each `stepMs` apart on the gesture clock. */+const swipe = async (+ target: HTMLElement,+ xs: number[],+ { stepMs = 16, y = 140 }: { stepMs?: number; y?: number } = {}+) => {+ const base = performance.now();++ await interact(() => touch('pointerdown', target, xs[0]!, y, base), 0);++ for (const [index, x] of xs.slice(1).entries()) {+ await interact(() => touch('pointermove', document, x, y, base + (index + 1) * stepMs), 0);+ }++ await interact(() => touch('pointerup', document, xs.at(-1)!, y, base + xs.length * stepMs), 0);+};++const isAtRest = (element: HTMLElement): boolean => ['', 'none'].includes(element.style.translate);++const DropTarget = () => {+ const { setNodeRef } = useDroppable({ data: { kind: 'test-drop' }, id: 'test-drop' });++ return <div ref={setNodeRef} style={{ height: 120, left: 420, position: 'fixed', top: 40, width: 120 }} />;+};++const DropMonitor = ({ onDrop }: { onDrop: (overId: string | number | null) => void }) => {+ useDndMonitor({ onDragEnd: (event) => onDrop(event.over?.id ?? null) });++ return null;+};++/**+ * A three-item carousel whose navigation moves a real selection, so a committed swipe re-renders the frame with the+ * next source the way Preview does.+ */+const renderCarousel = async ({+ items = [makeItem('red'), makeItem('green'), makeItem('blue')],+ navigateResult = true,+ next,+ start = 1,+}: {+ items?: GalleryItem[];+ /** `pending` never settles, like a page fetch that hangs. */+ navigateResult?: boolean | 'pending';+ /** Overrides the next neighbor derived from `items`. */+ next?: PreviewNeighbor;+ start?: number;+} = {}) => {+ const onNavigate = vi.fn<(direction: -1 | 1) => Promise<boolean>>();+ const onDrop = vi.fn();++ const Carousel = () => {+ const [index, setIndex] = useState(start);+ const item = items[index]!;+ const toNeighbor = (candidate: GalleryItem | undefined): PreviewNeighbor =>+ candidate ? { item: candidate, kind: 'item' } : null;++ onNavigate.mockImplementation((direction) => {+ if (navigateResult === 'pending') {+ return new Promise<boolean>(() => {});+ }++ if (navigateResult) {+ setIndex((current) => current + direction);+ }++ return Promise.resolve(navigateResult);+ });++ return (+ <PreviewFrame+ dragItem={{ kind: item.kind, name: item.name }}+ frameHeight={item.height}+ frameWidth={item.width}+ isLive={false}+ shouldAntialiasLiveImage+ source={+ item.kind === 'image'+ ? {+ itemKey: `image:${item.name}`,+ kind: 'image',+ source: { alt: item.name, height: 128, kind: 'fallback', src: item.fullUrl, width: 128 },+ }+ : {+ itemKey: `video:${item.name}`,+ kind: 'video',+ label: item.name,+ poster: item.thumbnailUrl,+ src: item.fullUrl,+ }+ }+ swipe={{+ neighbors: {+ next: next === undefined ? toNeighbor(items[index + 1]) : next,+ previous: toNeighbor(items[index - 1]),+ },+ onNavigate,+ }}+ variant="framed"+ />+ );+ };++ const Harness = () => {+ const sensors = useSensors(+ useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),+ useSensor(HoldToDragSensor, { activationConstraint: { delay: HOLD_DELAY_MS, tolerance: 10 } })+ );++ return (+ <DndContext collisionDetection={widgetCollisionDetection} sensors={sensors}>+ <DropMonitor onDrop={onDrop} />+ <div style={{ display: 'flex', height: 240, left: 40, position: 'fixed', top: 40, width: STAGE_WIDTH }}>+ <Carousel />+ </div>+ <DropTarget />+ </DndContext>+ );+ };++ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await interact(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <Harness />+ </ChakraProvider>+ </I18nextProvider>+ );+ });++ const media = () => host!.querySelector<HTMLElement>('img[alt]:not([alt=""]), video')!;++ return {+ content: () => media().parentElement!,+ media,+ neighbors: () => [...host!.querySelectorAll<HTMLElement>('[data-swipe-neighbor]')],+ onDrop,+ onNavigate,+ };+};++const offsetOf = (element: HTMLElement): number => Number.parseFloat(element.style.translate) || 0;++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('PreviewFrame touch swipe', () => {+ it('flicks to the next image and lands the new selection at rest in the same commit', async () => {+ const carousel = await renderCarousel();+ const image = carousel.media();++ expect(image.getAttribute('alt')).toBe('green');++ // Record where the track sits in the very task that mounts the new image, before anything can paint.+ const frame = carousel.content();+ const offsetsAtSwap: string[] = [];+ const observer = new MutationObserver(() => offsetsAtSwap.push(frame.style.translate));++ observer.observe(frame, { childList: true });++ const base = performance.now();++ await interact(() => touch('pointerdown', image, 200, 140, base));+ await interact(() => touch('pointermove', document, 170, 140, base + 16));+ await interact(() => touch('pointermove', document, 130, 140, base + 32));++ // Mid-gesture the image and its neighbors follow the finger.+ expect(offsetOf(carousel.content())).toBe(-70);+ expect(carousel.neighbors().map(offsetOf)).toEqual([-70, -70]);++ await interact(() => touch('pointerup', document, 130, 140, base + 48));+ await vi.waitFor(() => expect(carousel.media().getAttribute('alt')).toBe('blue'));+ observer.disconnect();++ expect(carousel.onNavigate).toHaveBeenCalledExactlyOnceWith(1);+ // The parked offset never reaches a painted frame of the new image: it and both neighbors are back at rest.+ expect(offsetsAtSwap.length).toBeGreaterThan(0);+ expect(offsetsAtSwap.every((offset) => ['', 'none'].includes(offset))).toBe(true);+ // The new image is a new element: a reused one would keep painting the old picture until the new one loaded.+ expect(carousel.media()).not.toBe(image);+ expect(isAtRest(carousel.content())).toBe(true);+ expect(carousel.neighbors()).toHaveLength(2);+ expect(carousel.neighbors().every(isAtRest)).toBe(true);+ // Once a neighbor's full image loads, its thumbnail underlay is gone, leaving exactly what the frame will show+ // (blue is the last image, so only the previous panel has one).+ await vi.waitFor(() =>+ expect(carousel.neighbors().map((neighbor) => neighbor.querySelectorAll('img').length)).toEqual([1, 0])+ );+ });++ it('commits a slow drag past the threshold, and returns a short one without navigating', async () => {+ const carousel = await renderCarousel();++ // 50px, lifted after resting: the release carries no velocity and stays under 40% of the stage.+ await swipe(carousel.media(), [100, 125, 150, 150], { stepMs: 150 });+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true));++ expect(carousel.onNavigate).not.toHaveBeenCalled();++ // 140px the same way passes 40%.+ await swipe(carousel.media(), [60, 130, 200, 200], { stepMs: 150 });+ await vi.waitFor(() => expect(carousel.media().getAttribute('alt')).toBe('red'));++ expect(carousel.onNavigate).toHaveBeenCalledExactlyOnceWith(-1);+ });++ it('resists past the last image and settles back without navigating', async () => {+ const carousel = await renderCarousel({ start: 2 });+ const image = carousel.media();+ const base = performance.now();++ await interact(() => touch('pointerdown', image, 250, 140, base));+ await interact(() => touch('pointermove', document, 150, 140, base + 16));+ await interact(() => touch('pointermove', document, 50, 140, base + 32));++ // 200px of finger travel with nothing to reveal moves the image well under a third of the stage.+ expect(offsetOf(carousel.content())).toBeLessThan(0);+ expect(offsetOf(carousel.content())).toBeGreaterThan(-STAGE_WIDTH * 0.3);++ await interact(() => touch('pointerup', document, 50, 140, base + 48));+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true));++ expect(carousel.onNavigate).not.toHaveBeenCalled();+ });++ it('slides the image back when the step does not happen', async () => {+ const carousel = await renderCarousel({ navigateResult: false });++ await swipe(carousel.media(), [200, 170, 140]);+ await vi.waitFor(() => expect(carousel.onNavigate).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true));++ expect(carousel.media().getAttribute('alt')).toBe('green');+ });++ it('shows a loading neighbor for an unloaded page and returns if the step never lands', async () => {+ const carousel = await renderCarousel({ navigateResult: 'pending', next: { kind: 'more' } });++ await swipe(carousel.media(), [200, 170, 140]);++ const next = carousel.neighbors().find((neighbor) => neighbor.dataset.swipeNeighbor === 'next')!;++ expect(next.querySelector('.chakra-spinner')).not.toBeNull();+ await vi.waitFor(() => expect(offsetOf(carousel.content())).toBe(-STAGE_WIDTH));+ // The park is bounded even while the fetch is still in flight.+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true), { timeout: 3000 });++ expect(carousel.onNavigate).toHaveBeenCalledOnce();+ expect(carousel.media().getAttribute('alt')).toBe('green');+ });++ it('sends a caught return home on a tap instead of committing it', async () => {+ const carousel = await renderCarousel();+ const base = performance.now();++ // Drag past the commit threshold, then flick back: the release cancels and the image starts home.+ await interact(() => touch('pointerdown', carousel.media(), 250, 140, base), 0);+ await interact(() => touch('pointermove', document, 40, 140, base + 150), 0);+ await interact(() => touch('pointermove', document, 80, 140, base + 166), 0);+ await interact(() => touch('pointerup', document, 80, 140, base + 182), 0);++ // Catch it on the way and lift without moving.+ await interact(() => touch('pointerdown', carousel.media(), 150, 140, base + 200), 0);+ await interact(() => touch('pointerup', document, 150, 140, base + 260));+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true));++ expect(carousel.onNavigate).not.toHaveBeenCalled();+ });++ it('leaves a held touch to drag-and-drop, including one that catches a returning image', async () => {+ const carousel = await renderCarousel();++ // Moving before the hold elapses is a swipe, never a drag.+ await swipe(carousel.media(), [200, 170, 140]);+ await vi.waitFor(() => expect(carousel.media().getAttribute('alt')).toBe('blue'));++ expect(carousel.onDrop).not.toHaveBeenCalled();++ // A short drag starts the image home; a touch that catches it and holds arms the drag, which then wins.+ const image = carousel.media();+ const base = performance.now();++ await swipe(image, [150, 170, 175, 175], { stepMs: 150 });+ await interact(() => touch('pointerdown', image, 150, 140, base + 1000), HOLD_DELAY_MS + 100);+ await interact(() => touch('pointermove', document, 250, 120, base + 2000));+ await interact(() => touch('pointermove', document, 480, 100, base + 2016));+ // The armed drag sent the caught image home; the drag's own moves never move the track.+ await vi.waitFor(() => expect(isAtRest(carousel.content())).toBe(true));+ await interact(() => touch('pointermove', document, 482, 100, base + 2032));++ expect(isAtRest(carousel.content())).toBe(true);++ await interact(() => touch('pointerup', document, 482, 100, base + 2048));++ expect(carousel.onDrop).toHaveBeenCalledExactlyOnceWith('test-drop');+ expect(carousel.onNavigate).toHaveBeenCalledOnce();+ });++ it('pans a zoomed image instead of swiping', async () => {+ const carousel = await renderCarousel();+ const stage = carousel.content().parentElement!;++ await interact(() =>+ stage.dispatchEvent(+ new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 190, clientY: 160, deltaY: -600 })+ )+ );+ await vi.waitFor(() => expect(carousel.content().style.transform).toContain('scale'));++ await swipe(carousel.media(), [200, 170, 140]);+ await interact(() => {}, 400);++ expect(carousel.onNavigate).not.toHaveBeenCalled();+ expect(isAtRest(carousel.content())).toBe(true);+ });++ it('ignores mouse drags, which keep dragging the image', async () => {+ const carousel = await renderCarousel();+ const image = carousel.media();+ const mouse = { pointerType: 'mouse' };++ await interact(() => touch('pointerdown', image, 150, 140, 0, mouse));+ image.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 150, clientY: 140 }));+ await interact(() => {+ touch('pointermove', document, 250, 120, 16, mouse);+ document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 250, clientY: 120 }));+ });+ await interact(() => {+ touch('pointermove', document, 480, 100, 32, mouse);+ document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 480, clientY: 100 }));+ });++ expect(isAtRest(carousel.content())).toBe(true);++ await interact(() => {+ touch('pointerup', document, 480, 100, 48, mouse);+ document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, clientX: 480, clientY: 100 }));+ });++ expect(carousel.onNavigate).not.toHaveBeenCalled();+ expect(carousel.onDrop).toHaveBeenCalledExactlyOnceWith('test-drop');+ });++ it('hands a second finger to the pinch with the image back at rest', async () => {+ const carousel = await renderCarousel();+ const image = carousel.media();+ const base = performance.now();++ await interact(() => touch('pointerdown', image, 200, 140, base));+ await interact(() => touch('pointermove', document, 160, 140, base + 16));+ await interact(() => touch('pointerdown', image, 240, 140, base + 32, { isPrimary: false, pointerId: 2 }));++ expect(isAtRest(carousel.content())).toBe(true);++ await interact(() => {+ touch('pointerup', document, 100, 140, base + 48);+ touch('pointerup', document, 240, 140, base + 48, { isPrimary: false, pointerId: 2 });+ }, 400);++ expect(carousel.onNavigate).not.toHaveBeenCalled();+ });++ it('swipes a video from its picture but leaves the native control bar alone', async () => {+ const carousel = await renderCarousel({ items: [makeItem('red'), makeItem('clip', 'video'), makeItem('blue')] });+ const video = carousel.media();+ const rect = video.getBoundingClientRect();++ await swipe(video, [200, 170, 140], { y: rect.bottom - 10 });+ await interact(() => {}, 400);++ expect(carousel.onNavigate).not.toHaveBeenCalled();++ await swipe(video, [200, 170, 140], { y: rect.top + 20 });+ await vi.waitFor(() => expect(carousel.media().getAttribute('alt')).toBe('blue'));++ expect(carousel.onNavigate).toHaveBeenCalledExactlyOnceWith(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsxindex 624e17230c..ae5154a973 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -4,10 +4,11 @@ import type { QueueItem } from '@features/queue/contracts';import type { WidgetViewProps } from '@workbench/widgetContracts';import { ChakraProvider } from '@chakra-ui/react';-import { DndContext } from '@dnd-kit/core';+import { DndContext, useSensor, useSensors, type DndContextProps } from '@dnd-kit/core';import { requestGalleryItemReveal } from '@features/gallery/contracts';import { QueryClient, QueryClientProvider, type InfiniteData } from '@tanstack/react-query';import { system } from '@theme/system';+import { HoldToDragSensor, PrimaryMouseSensor } from '@workbench/shell/holdToDragSensor';import i18next from 'i18next';import { act, useCallback } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -336,18 +337,28 @@ const FollowProbe = () => {return <span ref={ref} />;};+// The shell's sensors, so touch on the preview arbitrates between swipe and drag as it does in the app.+const ShellDndContext = ({ children }: Pick<DndContextProps, 'children'>) => {+ const sensors = useSensors(+ useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),+ useSensor(HoldToDragSensor)+ );++ return <DndContext sensors={sensors}>{children}</DndContext>;+};+const renderTree = async (client: QueryClient) => {await act(async () => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}><QueryClientProvider client={client}>- <DndContext>+ <ShellDndContext><LivePreviewFollowProvider><FollowProbe /><PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} /></LivePreviewFollowProvider>- </DndContext>+ </ShellDndContext></QueryClientProvider></ChakraProvider></I18nextProvider>@@ -459,6 +470,47 @@ const getBoundary = (): HTMLElement => {return boundary;};+/** A one-finger flick across the preview image: 90px in three quick moves. */+const flickPreview = async (direction: -1 | 1) => {+ const image = host!.querySelector<HTMLImageElement>('img[alt]:not([alt=""])')!;+ const rect = image.getBoundingClientRect();+ const y = rect.top + rect.height / 2;+ let x = rect.left + rect.width / 2;+ // Stamped 16ms apart on a virtual clock: release velocity comes from event timestamps, not the runner's speed.+ let at = performance.now();+ const touch = (type: string, target: EventTarget) => {+ const event = new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ clientX: x,+ clientY: y,+ isPrimary: true,+ pointerId: 1,+ pointerType: 'touch',+ });++ Object.defineProperty(event, 'timeStamp', { value: (at += 16) });+ target.dispatchEvent(event);+ };+ const step = async (type: string, target: EventTarget) => {+ await act(async () => {+ touch(type, target);+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 16);+ });+ });+ };++ await step('pointerdown', image);++ for (let move = 0; move < 3; move += 1) {+ x -= direction * 30;+ await step('pointermove', image.ownerDocument);+ }++ await step('pointerup', image.ownerDocument);+};+const pressArrow = async (key: 'ArrowLeft' | 'ArrowRight') => {await act(async () => {getBoundary().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key }));@@ -1888,4 +1940,24 @@ describe('preview keyboard navigation boundary', () => {Object.defineProperty(globalThis, 'Image', { configurable: true, value: NativeImage, writable: true });}});++ it('flicks the preview image onto the neighbor the arrow keys would select', async () => {+ await render();+ await expect.poll(() => selectedThumb()).toBe('newest');+ await flickPreview(1);++ await vi.waitFor(() => {+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: 'oldest' }),+ undefined,+ expect.any(Number),+ true+ );+ });+ // The swipe and the step agree: the panel that slid in shows that same item at full size.+ expect(+ [...host!.querySelectorAll('[data-swipe-neighbor="next"] img')].map((image) => image.getAttribute('src'))+ ).toContain('/images/oldest/full');+ expect(host?.querySelector('[data-swipe-neighbor="previous"] img')).toBeNull();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsxindex da26ac7755..ae05e583e7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx@@ -15,6 +15,8 @@ export const previewGridCss = {} as const;export const getFittedFrameCss = (width: number, height: number): SystemStyleObject => ({+ // The cue gallery thumbnails give when a touch hold arms their drag; only a draggable frame is ever armed.+ '&[data-drag-armed=true]': { filter: 'saturate(0)' },aspectRatio: `${width} / ${height}`,height: 'auto',maxHeight: '100%',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewSwipeNeighbor.tsxnew file mode 100644index 0000000000..a7fc89f11a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx@@ -0,0 +1,132 @@+import type { GalleryItem } from '@features/gallery';++import { Flex, Spinner } from '@chakra-ui/react';+import { useCallback, useState, type CSSProperties, type Ref } from 'react';++import type { PreviewNeighbor, PreviewNeighbors } from './usePreviewNavigation';++import { FittedFrame } from './PreviewStage';++/** Both neighbors of a swipeable stage, once the swipe has anything to show. */+export const PreviewSwipeNeighbors = ({+ neighbors,+ nextTrackRef,+ previousTrackRef,+ restStyle,+}: {+ neighbors: PreviewNeighbors;+ nextTrackRef: Ref<HTMLDivElement>;+ previousTrackRef: Ref<HTMLDivElement>;+ restStyle: CSSProperties;+}) => (+ <>+ <PreviewSwipeNeighbor+ neighbor={neighbors.previous}+ restStyle={restStyle}+ side="previous"+ trackRef={previousTrackRef}+ />+ <PreviewSwipeNeighbor neighbor={neighbors.next} restStyle={restStyle} side="next" trackRef={nextTrackRef} />+ </>+);++/**+ * One stage-width beside the preview, the item a swipe slides in. It shares the stage's padding and container+ * queries, so it fits exactly as the item will once selected; images use the full URL that navigation prefetches,+ * making the post-commit swap pixel-identical. An unloaded page shows a spinner while the step fetches it; a live+ * session shows the bare stage.+ */+const PreviewSwipeNeighbor = ({+ neighbor,+ restStyle,+ side,+ trackRef,+}: {+ neighbor: PreviewNeighbor;+ restStyle: CSSProperties;+ side: 'next' | 'previous';+ trackRef: Ref<HTMLDivElement>;+}) => (+ <Flex+ ref={trackRef}+ align="center"+ aria-hidden="true"+ bottom="0"+ css={NEIGHBOR_CSS}+ data-swipe-neighbor={side}+ justify="center"+ left={side === 'next' ? '100%' : '-100%'}+ pointerEvents="none"+ position="absolute"+ style={restStyle}+ top="0"+ w="full"+ >+ {neighbor?.kind === 'more' ? <Spinner color="fg.muted" size="md" /> : null}+ {neighbor?.kind === 'item' ? (+ // Keyed by URL: every layer is a new element per neighbor, so none can keep painting the previous picture while+ // its own loads.+ <NeighborMedia key={neighbor.item.fullUrl} item={neighbor.item} />+ ) : null}+ </Flex>+);++/**+ * The thumbnail (usually cached already) lies under the full image until that loads, so a swipe faster than the+ * download still reveals the right picture; it is removed once the full image arrives, leaving exactly what the+ * frame will show. No shadow: the neighbor sits just beyond the stage edge, where the frame shadow would bleed in.+ */+const NeighborMedia = ({ item }: { item: GalleryItem }) => {+ const [isLoaded, setIsLoaded] = useState(false);+ const handleSettled = useCallback(() => setIsLoaded(true), []);++ return (+ <FittedFrame+ bg={item.kind === 'video' ? 'black' : 'transparent'}+ boxShadow="none"+ frameHeight={item.height}+ frameWidth={item.width}+ >+ {item.kind === 'image' && !isLoaded ? (+ <img alt="" draggable={false} src={item.thumbnailUrl} style={THUMBNAIL_UNDERLAY_STYLE} />+ ) : null}+ <img+ ref={item.width * item.height <= DECODE_AHEAD_MAX_PIXELS ? decodeAhead : undefined}+ alt=""+ draggable={false}+ height={item.height}+ src={item.kind === 'video' ? item.thumbnailUrl : item.fullUrl}+ style={item.kind === 'video' ? VIDEO_POSTER_STYLE : IMAGE_STYLE}+ width={item.width}+ onError={handleSettled}+ onLoad={handleSettled}+ />+ </FittedFrame>+ );+};++/**+ * Largest neighbor decoded ahead of time. Above it (big upscales), the decoded bitmap would hold hundreds of MB per+ * neighbor for a swipe that may never come, so the image decodes when revealed instead.+ */+const DECODE_AHEAD_MAX_PIXELS = 4096 * 4096;++/** Off-stage images are never painted, so without a decode hint the first swipe frame could show them blank. */+const decodeAhead = (image: HTMLImageElement | null): void => {+ void image?.decode().catch(() => {});+};++// `inherit` copies the stage's padding, chrome inset included, onto this box.+const NEIGHBOR_CSS = { padding: 'inherit' } as const;++const IMAGE_STYLE: CSSProperties = { display: 'block', height: 'auto', position: 'relative', width: '100%' };++const THUMBNAIL_UNDERLAY_STYLE: CSSProperties = {+ height: '100%',+ inset: 0,+ objectFit: 'contain',+ position: 'absolute',+ width: '100%',+};++const VIDEO_POSTER_STYLE: CSSProperties = { display: 'block', height: '100%', objectFit: 'contain', width: '100%' };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex c76844dac5..e0e8eb4ac5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -62,6 +62,7 @@ import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, typeimport { useTranslation } from 'react-i18next';import type { PreviewLoupeControls } from './usePreviewLoupe';+import type { PreviewSwipeNavigation } from './usePreviewSwipe';import { useLivePreviewFollow } from './livePreviewFollow';import { PreviewCompare } from './PreviewCompare';@@ -223,8 +224,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {getSelectionPage,handleNavigationKeyDown,isLoadingBoard,+ navigate,navigationCursor,navigationQueryKey,+ neighbors,selectPreviewItem,} = usePreviewNavigation({followedSessionId: activeGalleryPlaceholder?.id ?? null,@@ -242,6 +245,11 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {semanticQuery: gallerySemanticQuery,});+ const swipeNavigation = useMemo<PreviewSwipeNavigation>(+ () => ({ neighbors, onNavigate: navigate }),+ [navigate, neighbors]+ );+const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);const getItemActionContext = useCallback(() => ({@@ -607,6 +615,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {item={selectedItem}loupeControlsRef={loupeControlsRef}shouldAntialiasProgressImage={antialiasProgressImages}+ swipe={swipeNavigation}onContextMenu={openItemContextMenu}/>) : (@@ -615,6 +624,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {filmstrip={filmstrip}isItemCurrent={isItemCurrent}item={selectedItem}+ swipe={swipeNavigation}videoControllerRef={videoControllerRef}onContextMenu={openItemContextMenu}onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}@@ -676,6 +686,7 @@ const SelectedImagePreview = ({frameWidth={previewImage?.width ?? item.width}holdSource={holdSource}item={item}+ placeholderSrc={item.thumbnailUrl}shouldAntialiasHoldImage={shouldAntialiasProgressImage}source={source}onSourceLoaded={handleSourceLoaded}@@ -722,6 +733,7 @@ interface SelectedMediaPreviewProps {loupeControlsRef?: Ref<PreviewLoupeControls>;onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;onContextMenu: (x: number, y: number) => void;+ swipe?: PreviewSwipeNavigation;videoControllerRef?: Ref<PreviewVideoFrameController>;}@@ -750,8 +762,10 @@ const SelectedMediaPreview = ({loupeControlsRef,onCopyAvailabilityChange,onSourceLoaded,+ placeholderSrc,shouldAntialiasHoldImage,source,+ swipe,onContextMenu,videoControllerRef,}: SelectedMediaPreviewProps & {@@ -760,6 +774,7 @@ const SelectedMediaPreview = ({frameWidth: number;holdSource?: StreamingImageSource | null;onSourceLoaded?: (src: string) => void;+ placeholderSrc?: string;shouldAntialiasHoldImage?: boolean;source: Parameters<typeof PreviewFrame>[0]['source'];}) => (@@ -779,8 +794,10 @@ const SelectedMediaPreview = ({onVideoCopyAvailabilityChange={onCopyAvailabilityChange}onZoomChange={setZoomReadout}padding={getMediaStagePadding(density)}+ placeholderSrc={placeholderSrc}shouldAntialiasLiveImage={shouldAntialiasHoldImage ?? true}source={source}+ swipe={swipe}variant="framed"videoControllerRef={videoControllerRef}onContextMenu={onContextMenu}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.test.tsnew file mode 100644index 0000000000..d2b4ba8791--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';++import {+ classifySwipeIntent,+ getSwipeVelocity,+ recordSwipeSample,+ resolveSwipeRelease,+ rubberBand,+ unrubberBand,+ type SwipeSample,+} from './previewSwipe';++const WIDTH = 800;+const both = () => true;++describe('classifySwipeIntent', () => {+ it('waits inside the slop, then claims sideways travel and releases vertical travel', () => {+ expect(classifySwipeIntent(6, 6)).toBe('pending');+ expect(classifySwipeIntent(-12, 4)).toBe('swipe');+ expect(classifySwipeIntent(5, 14)).toBe('reject');+ });+});++describe('getSwipeVelocity', () => {+ const track = (points: [time: number, x: number][]): SwipeSample[] => {+ const samples: SwipeSample[] = [];++ for (const [time, x] of points) {+ recordSwipeSample(samples, { time, x });+ }++ return samples;+ };++ it('measures only the recent motion, so an early burst does not count at a slow release', () => {+ // 200px in the first 20ms, then 10px over the next 100ms.+ const samples = track([+ [0, 0],+ [20, -200],+ [70, -205],+ [120, -210],+ ]);++ expect(getSwipeVelocity(samples, 120)).toBeCloseTo(-0.1, 2);+ });++ it('reads a finger that rested before lifting as stopped', () => {+ const samples = track([+ [0, 0],+ [16, -60],+ [32, -120],+ ]);++ expect(getSwipeVelocity(samples, 32)).toBeCloseTo(-3.75, 2);+ expect(getSwipeVelocity(samples, 250)).toBe(0);+ });+});++describe('rubberBand', () => {+ it('follows small overscroll closely and never reaches a third of the width', () => {+ expect(rubberBand(20, WIDTH)).toBeGreaterThan(18);+ expect(rubberBand(10_000, WIDTH)).toBeLessThan(WIDTH * 0.3);+ expect(rubberBand(-10_000, WIDTH)).toBeGreaterThan(-WIDTH * 0.3);+ });++ it('inverts, so a caught overscroll resumes from the finger travel that produced it', () => {+ for (const travel of [-900, -40, 25, 600]) {+ expect(unrubberBand(rubberBand(travel, WIDTH), WIDTH)).toBeCloseTo(travel, 6);+ }+ });+});++describe('resolveSwipeRelease', () => {+ it('commits a short flick toward the next item, and a slow drag only past the threshold', () => {+ expect(resolveSwipeRelease({ canNavigate: both, offset: -60, velocity: -1.2, width: WIDTH })).toMatchObject({+ direction: 1,+ kind: 'commit',+ });+ expect(resolveSwipeRelease({ canNavigate: both, offset: 400, velocity: 0.05, width: WIDTH })).toMatchObject({+ direction: -1,+ kind: 'commit',+ });+ expect(resolveSwipeRelease({ canNavigate: both, offset: 200, velocity: 0.05, width: WIDTH }).kind).toBe('cancel');+ });++ it('returns a drag that is flicked back toward where it started, however far it went', () => {+ expect(resolveSwipeRelease({ canNavigate: both, offset: -600, velocity: 1.5, width: WIDTH }).kind).toBe('cancel');+ });++ it('never commits toward a missing neighbor', () => {+ const onlyPrevious = (direction: 1 | -1) => direction === -1;++ expect(resolveSwipeRelease({ canNavigate: onlyPrevious, offset: -600, velocity: -2, width: WIDTH }).kind).toBe(+ 'cancel'+ );+ });++ it('finishes faster flicks sooner, within bounds', () => {+ const duration = (velocity: number) => {+ const release = resolveSwipeRelease({ canNavigate: both, offset: -100, velocity, width: WIDTH });++ return release.durationMs;+ };++ expect(duration(-4)).toBeLessThan(duration(-1));+ expect(duration(-50)).toBeGreaterThan(0);+ expect(duration(-0.5)).toBeLessThanOrEqual(320);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.tsnew file mode 100644index 0000000000..68191b97b0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSwipe.ts@@ -0,0 +1,118 @@+/**+ * Pure swipe physics for the preview carousel: gesture intent, finger-velocity estimation, edge resistance, and the+ * release decision. Offsets are stage-space pixels; negative moves the image left, revealing the next item.+ */++/** Travel that decides a touch; matches the touch drag sensor's tolerance, so a still-waiting drag yields on the same move. */+export const SWIPE_SLOP_PX = 10;+/** Release speed (px/ms) that commits regardless of distance. */+export const SWIPE_FLICK_VELOCITY = 0.4;+/** Fraction of the stage width past which a slow release commits. */+export const SWIPE_COMMIT_FRACTION = 0.4;+/** Only the last stretch of motion counts toward release velocity, so a pause before lifting is not a flick. */+const VELOCITY_WINDOW_MS = 100;+/** Settle speed floor (px/ms), so a slow or velocity-free release still finishes briskly. */+const MIN_SETTLE_VELOCITY = 1.5;+const MIN_SETTLE_MS = 90;+const MAX_SETTLE_MS = 320;+/** Share of the stage width an overscroll can approach at the gallery's ends. */+const RUBBER_BAND_LIMIT = 0.3;++export type SwipeDirection = -1 | 1;++export interface SwipeSample {+ time: number;+ x: number;+}++/** Returns +1 (next) or -1 (previous) for the item an offset reveals; zero reveals nothing. */+export const getRevealedDirection = (offset: number): SwipeDirection | 0 => (offset < 0 ? 1 : offset > 0 ? -1 : 0);++/** Horizontal intent once travel leaves the slop: claim sideways motion, release vertical motion, else keep waiting. */+export const classifySwipeIntent = (dx: number, dy: number): 'pending' | 'reject' | 'swipe' => {+ if (Math.hypot(dx, dy) <= SWIPE_SLOP_PX) {+ return 'pending';+ }++ return Math.abs(dx) > Math.abs(dy) ? 'swipe' : 'reject';+};++/** Appends a sample, discarding those older than the velocity window. */+export const recordSwipeSample = (samples: SwipeSample[], sample: SwipeSample): void => {+ samples.push(sample);++ while (samples.length > 2 && sample.time - samples[0]!.time > VELOCITY_WINDOW_MS) {+ samples.shift();+ }+};++/** Finger speed in px/ms over the recent window; zero when the finger rested at the end. */+export const getSwipeVelocity = (samples: readonly SwipeSample[], now: number): number => {+ const last = samples.at(-1);+ const first = samples.find((sample) => now - sample.time <= VELOCITY_WINDOW_MS);++ if (!last || !first || last === first || now - last.time > VELOCITY_WINDOW_MS) {+ return 0;+ }++ const elapsed = last.time - first.time;++ return elapsed > 0 ? (last.x - first.x) / elapsed : 0;+};++/** Diminishing overscroll: follows the finger at first, then approaches a fixed share of the width. */+export const rubberBand = (offset: number, width: number): number => {+ if (width <= 0) {+ return 0;+ }++ const limit = width * RUBBER_BAND_LIMIT;++ return Math.sign(offset) * limit * (1 - 1 / (Math.abs(offset) / limit + 1));+};++/** The finger travel that `rubberBand` shows as `displayed`, so a caught overscroll resumes without a jump. */+export const unrubberBand = (displayed: number, width: number): number => {+ const limit = width * RUBBER_BAND_LIMIT;+ const magnitude = Math.min(Math.abs(displayed), limit * 0.999);++ return width <= 0 ? 0 : (Math.sign(displayed) * limit * magnitude) / (limit - magnitude);+};++export type SwipeRelease =+ | { direction: SwipeDirection; durationMs: number; kind: 'commit' }+ | { durationMs: number; kind: 'cancel' };++/**+ * Decide a release: a flick toward an available neighbor, or a slow drag past the commit fraction, commits; anything+ * else, including a flick back toward the start, returns to rest. Settle time follows the finger's speed, so fast+ * flicks finish fast.+ */+export const resolveSwipeRelease = ({+ canNavigate,+ offset,+ velocity,+ width,+}: {+ canNavigate: (direction: SwipeDirection) => boolean;+ offset: number;+ velocity: number;+ width: number;+}): SwipeRelease => {+ const direction = getRevealedDirection(offset);+ const isFlick = Math.abs(velocity) >= SWIPE_FLICK_VELOCITY;+ const isFlickForward = isFlick && Math.sign(velocity) === Math.sign(offset);+ const isPastThreshold = width > 0 && Math.abs(offset) >= width * SWIPE_COMMIT_FRACTION;++ if (direction !== 0 && canNavigate(direction) && (isFlickForward || (!isFlick && isPastThreshold))) {+ return { direction, durationMs: getSettleDuration(width - Math.abs(offset), velocity), kind: 'commit' };+ }++ return { durationMs: getSettleDuration(Math.abs(offset), velocity), kind: 'cancel' };+};++const getSettleDuration = (distance: number, velocity: number): number =>+ Math.min(MAX_SETTLE_MS, Math.max(MIN_SETTLE_MS, distance / Math.max(Math.abs(velocity), MIN_SETTLE_VELOCITY)));++/** Ease-out quadratic: starts at twice the average speed, so a flick hands off without a visible stall. */+export const easeOutQuad = (progress: number): number => 1 - (1 - progress) * (1 - progress);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 4472dea899..7f42710e31 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -112,12 +112,38 @@ export const mergePreviewBoardItems = (const toItemEntries = (items: readonly GalleryItem[]): GalleryNavigationEntry[] =>items.map((item) => ({ item, kind: 'item' }));+/**+ * A step's destination: a saved item, a running session, a page not loaded yet (`more`), or nothing (null).+ */+export type PreviewNeighbor =+ | { kind: 'item'; item: GalleryItem }+ | { kind: 'more' }+ | { kind: 'session'; id: string }+ | null;++export interface PreviewNeighbors {+ next: PreviewNeighbor;+ previous: PreviewNeighbor;+}++const NO_NEIGHBORS: PreviewNeighbors = { next: null, previous: null };++const toNeighbor = (entry: GalleryNavigationEntry | null): PreviewNeighbor =>+ entry === null+ ? null+ : entry.kind === 'item'+ ? { item: entry.item, kind: 'item' }+ : { id: entry.id, kind: 'session' };+export interface PreviewNavigationState {/** Every saved item the arrows can reach, in order: the starred strip, then the listing. */boardItems: GalleryItem[];handleNavigationKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;isLoadingBoard: boolean;- navigate: (offset: -1 | 1) => void;+ /** Resolves true once a step was dispatched; false when there was nowhere to go or the step went stale. */+ navigate: (offset: -1 | 1) => Promise<boolean>;+ /** What each step would land on, so a swipe can show it before committing. */+ neighbors: PreviewNeighbors;/** The selection's index in `boardItems`; -1 while following live or off the list. */navigationCursor: number;/** Identity of the backing query — the action context's filter identity. */@@ -410,49 +436,55 @@ export const usePreviewNavigation = ({? -1: boardItems.findIndex((item) => toGalleryItemKey(item) === selectedItemKey);- // Share navigation between keyboard and footer; comparison does not step saved images.+ // Preview is the only surface that walks a paginated listing across its pages, so at a loaded edge the next page+ // wins over the strip seam; the strip is reached from the listing's first page.+ const isAtLoadedBackendBoundary = useCallback(+ (offset: -1 | 1): boolean =>+ followedSessionId === null &&+ selectedItemKey !== null &&+ (offset === 1+ ? backendBoardItems.at(-1) !== undefined &&+ toGalleryItemKey(backendBoardItems.at(-1)!) === selectedItemKey &&+ hasNextBoardItemsPage+ : backendBoardItems[0] !== undefined &&+ toGalleryItemKey(backendBoardItems[0]) === selectedItemKey &&+ hasPreviousBoardItemsPage),+ [backendBoardItems, followedSessionId, hasNextBoardItemsPage, hasPreviousBoardItemsPage, selectedItemKey]+ );++ // Share navigation between keyboard, footer, and swipe; comparison does not step saved images.const navigate = useCallback(- (offset: -1 | 1) => {+ (offset: -1 | 1): Promise<boolean> => {if (isComparing) {- return;+ return Promise.resolve(false);}const direction = offset === 1 ? 'right' : 'left';- const stepTo = (entry: GalleryNavigationEntry | null, data: typeof boardItemsData) => {+ const stepTo = (entry: GalleryNavigationEntry | null, data: typeof boardItemsData): boolean => {if (entry?.kind === 'session') {followSession(entry.id);} else if (entry) {stampSelection(entry.item, data);}++ return entry !== null;};- // Preview is the only surface that walks a paginated listing across- // its pages, so at a loaded edge the next page wins over the strip- // seam; the strip is reached from the listing's first page.- const isAtLoadedBackendBoundary =- followedSessionId === null &&- selectedItemKey !== null &&- (offset === 1- ? backendBoardItems.at(-1) !== undefined &&- toGalleryItemKey(backendBoardItems.at(-1)!) === selectedItemKey &&- hasNextBoardItemsPage- : backendBoardItems[0] !== undefined &&- toGalleryItemKey(backendBoardItems[0]) === selectedItemKey &&- hasPreviousBoardItemsPage);-- if (!isAtLoadedBackendBoundary) {- stepTo(getGalleryNavigationStep(navigationSections, cursorKey, direction), boardItemsData);- return;++ if (!isAtLoadedBackendBoundary(offset)) {+ return Promise.resolve(+ stepTo(getGalleryNavigationStep(navigationSections, cursorKey, direction), boardItemsData)+ );}if (offset === 1 ? isFetchingNextBoardItemsPage : isFetchingPreviousBoardItemsPage) {- return;+ return Promise.resolve(false);}const fetchBoundaryPage = offset === 1 ? fetchNextBoardItemsPage : fetchPreviousBoardItemsPage;- void fetchBoundaryPage().then((result) => {+ return fetchBoundaryPage().then((result) => {if (result.isError || navigationContextKeyRef.current !== navigationContextKey) {- return;+ return false;}// Against the data just fetched: the item is not in the pages this@@ -464,26 +496,22 @@ export const usePreviewNavigation = ({toItemEntries(mergeListingItems(flattenPreviewItems(result.data))),];- stepTo(getGalleryNavigationStep(nextSections, cursorKey, direction), result.data);+ return stepTo(getGalleryNavigationStep(nextSections, cursorKey, direction), result.data);});},[- backendBoardItems,boardItemsData,cursorKey,fetchNextBoardItemsPage,fetchPreviousBoardItemsPage,- followedSessionId,followSession,- hasNextBoardItemsPage,- hasPreviousBoardItemsPage,+ isAtLoadedBackendBoundary,isComparing,isFetchingNextBoardItemsPage,isFetchingPreviousBoardItemsPage,mergeListingItems,navigationContextKey,navigationSections,- selectedItemKey,sessionEntries,stampSelection,stripEntries,@@ -508,16 +536,32 @@ export const usePreviewNavigation = ({// arrow press a second time.event.preventDefault();event.stopPropagation();- navigate(event.key === 'ArrowLeft' ? -1 : 1);+ void navigate(event.key === 'ArrowLeft' ? -1 : 1);},[isComparing, navigate]);- // Prefetch adjacent media to avoid decode flashes during navigation.- const previousNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor - 1];- const nextNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor + 1];- const previousNeighborUrl = previousNeighbor?.kind === 'image' ? previousNeighbor.fullUrl : null;- const nextNeighborUrl = nextNeighbor?.kind === 'image' ? nextNeighbor.fullUrl : null;+ // The same resolution navigate() makes, so a swipe reveals what committing it will select.+ const neighbors = useMemo((): PreviewNeighbors => {+ if (isComparing) {+ return NO_NEIGHBORS;+ }++ const resolve = (offset: -1 | 1): PreviewNeighbor =>+ isAtLoadedBackendBoundary(offset)+ ? { kind: 'more' }+ : toNeighbor(getGalleryNavigationStep(navigationSections, cursorKey, offset === 1 ? 'right' : 'left'));++ return { next: resolve(1), previous: resolve(-1) };+ }, [cursorKey, isAtLoadedBackendBoundary, isComparing, navigationSections]);++ // Prefetch the images a step would land on to avoid decode flashes during navigation.+ const previousNeighborUrl =+ neighbors.previous?.kind === 'item' && neighbors.previous.item.kind === 'image'+ ? neighbors.previous.item.fullUrl+ : null;+ const nextNeighborUrl =+ neighbors.next?.kind === 'item' && neighbors.next.item.kind === 'image' ? neighbors.next.item.fullUrl : null;useEffect(() => {[previousNeighborUrl, nextNeighborUrl].forEach((url) => {@@ -532,6 +576,7 @@ export const usePreviewNavigation = ({handleNavigationKeyDown,isLoadingBoard,navigate,+ neighbors,navigationCursor,navigationQueryKey,getSelectionPage,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewSwipe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewSwipe.tsnew file mode 100644index 0000000000..5d27457211--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewSwipe.ts@@ -0,0 +1,474 @@+/* eslint-disable react/refs */+import { useDndMonitor, type DndMonitorListener, type UniqueIdentifier } from '@dnd-kit/core';+import {+ useCallback,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+ type PointerEvent as ReactPointerEvent,+} from 'react';++import type { PreviewNeighbors } from './usePreviewNavigation';++import {+ classifySwipeIntent,+ easeOutQuad,+ getRevealedDirection,+ getSwipeVelocity,+ recordSwipeSample,+ resolveSwipeRelease,+ rubberBand,+ unrubberBand,+ type SwipeDirection,+ type SwipeSample,+} from './previewSwipe';++/**+ * Touch carousel over the fitted preview: one finger drags the media and its neighbors sideways, and release either+ * settles back or slides the neighbor in and navigates. Offsets are written to the elements' `translate` property+ * outside React, leaving `transform` to the loupe. A committed slide parks on the neighbor until the displayed source+ * changes; React itself clears the offset in the commit that renders the new source (see `restStyle`), so the+ * newly selected image lands where its neighbor stood, with no frame of either image out of place.+ */++/** How long a committed slide may wait, fetch included, for its selection to render before returning. */+const PARK_TIMEOUT_MS = 1500;+/** Return time when the gesture itself carries no speed: a cancelled touch or a step that did not happen. */+const RETURN_MS = 220;++type TrackRole = 'content' | 'next' | 'previous';++interface SwipeGesture {+ /** Finger-space offset the gesture started from: nonzero when it caught a returning image. */+ baseOffset: number;+ phase: 'declined' | 'pending' | 'tracking';+ pointerId: number;+ samples: SwipeSample[];+ startX: number;+ startY: number;+ /** Stage width, measured once when the gesture starts tracking. */+ width: number;+}++interface SwipeSettle {+ frame: number;+ onDone: () => void;+ target: number;+}++export interface PreviewSwipeNavigation {+ neighbors: PreviewNeighbors;+ /** Resolves true once the step is dispatched; false leaves the current item in place. */+ onNavigate: (direction: SwipeDirection) => Promise<boolean>;+}++/** Two spellings of "no offset", so each landing changes the rendered style and React writes it. */+const REST_STYLES = { '': { translate: '' }, none: { translate: 'none' } } as const satisfies Record<+ string,+ CSSProperties+>;++const matchesMedia = (query: string): boolean =>+ typeof globalThis.matchMedia === 'function' && globalThis.matchMedia(query).matches;++export const usePreviewSwipe = ({+ displayedSourceToken,+ dragId,+ enabled,+ isZoomed,+ navigation,+}: {+ /** Identity of the displayed media; a change is a selection landing. */+ displayedSourceToken: string | null;+ /** The frame's draggable: once its drag claims a touch, the touch is never a swipe. */+ dragId: UniqueIdentifier;+ enabled: boolean;+ isZoomed: boolean;+ navigation: PreviewSwipeNavigation | null;+}) => {+ const stageRef = useRef<HTMLElement | null>(null);+ const trackRefs = useRef(new Map<TrackRole, HTMLElement>());+ const offsetRef = useRef(0);+ const gestureRef = useRef<SwipeGesture | null>(null);+ const settleRef = useRef<SwipeSettle | null>(null);+ /** Set while a committed slide waits for its selection; the token fences a late navigation result. */+ const parkedRef = useRef<{ timeout: number; token: number } | null>(null);+ const parkSequenceRef = useRef(0);+ // Neighbors mount up front where touch is the primary input, otherwise on the first touch, so mouse sessions (and+ // touchscreen laptops driven by a mouse) never hold or decode them.+ const [showsNeighbors, setShowsNeighbors] = useState(() => matchesMedia('(pointer: coarse)'));+ // Render-time mirrors, so the stable handlers below read the current props.+ const inputRef = useRef({ enabled, isZoomed, navigation });++ inputRef.current = { enabled, isZoomed, navigation };++ const writeOffset = useCallback((offset: number) => {+ offsetRef.current = offset;+ const translate = offset === 0 ? '' : `${offset}px 0`;++ for (const element of trackRefs.current.values()) {+ element.style.translate = translate;+ }+ }, []);++ const canNavigate = useCallback((direction: SwipeDirection): boolean => {+ const neighbors = inputRef.current.navigation?.neighbors;++ return neighbors !== undefined && (direction === 1 ? neighbors.next : neighbors.previous) !== null;+ }, []);++ const stopSettle = useCallback(() => {+ const settle = settleRef.current;++ if (settle) {+ cancelAnimationFrame(settle.frame);+ settleRef.current = null;+ }+ }, []);++ const clearPark = useCallback(() => {+ const parked = parkedRef.current;++ if (parked) {+ window.clearTimeout(parked.timeout);+ parkedRef.current = null;+ }+ }, []);++ const settleTo = useCallback(+ (target: number, durationMs: number, onDone: () => void = () => {}) => {+ stopSettle();+ const from = offsetRef.current;++ if (durationMs <= 0 || from === target || matchesMedia('(prefers-reduced-motion: reduce)')) {+ writeOffset(target);+ onDone();+ return;+ }++ const start = performance.now();+ const tick = (now: number): void => {+ const progress = Math.min(1, (now - start) / durationMs);++ writeOffset(from + (target - from) * easeOutQuad(progress));++ if (progress < 1) {+ settleRef.current!.frame = requestAnimationFrame(tick);+ return;+ }++ settleRef.current = null;+ onDone();+ };++ settleRef.current = { frame: requestAnimationFrame(tick), onDone, target };+ },+ [stopSettle, writeOffset]+ );++ /** Return to rest from wherever the track is. The track has one writer: any live gesture gives it up. */+ const returnToRest = useCallback(+ (durationMs: number) => {+ clearPark();++ if (gestureRef.current) {+ gestureRef.current.phase = 'declined';+ }++ settleTo(0, durationMs);+ },+ [clearPark, settleTo]+ );++ const commit = useCallback(+ (direction: SwipeDirection) => {+ const token = ++parkSequenceRef.current;+ // Bounded from the start, page fetch included: a slow or failed step must never strand the stage on a neighbor.+ const timeout = window.setTimeout(() => {+ if (parkedRef.current?.token === token) {+ returnToRest(RETURN_MS);+ }+ }, PARK_TIMEOUT_MS);++ parkedRef.current = { timeout, token };++ let step: Promise<boolean>;++ try {+ step = inputRef.current.navigation?.onNavigate(direction) ?? Promise.resolve(false);+ } catch {+ step = Promise.resolve(false);+ }++ void step+ .catch(() => false)+ .then((stepped) => {+ // A step that happened parks until its source lands (or times out); a landing already unparked this one.+ if (!stepped && parkedRef.current?.token === token) {+ returnToRest(RETURN_MS);+ }+ });+ },+ [returnToRest]+ );++ const release = useCallback(+ (gesture: SwipeGesture, now: number) => {+ const decision = resolveSwipeRelease({+ canNavigate,+ offset: offsetRef.current,+ velocity: getSwipeVelocity(gesture.samples, now),+ width: gesture.width,+ });++ if (decision.kind === 'cancel') {+ settleTo(0, decision.durationMs);+ return;+ }++ settleTo(-decision.direction * gesture.width, decision.durationMs, () => commit(decision.direction));+ },+ [canNavigate, commit, settleTo]+ );++ /** A touch that never became a swipe leaves a caught image where it was; send it home. */+ const restoreIfStranded = useCallback(() => {+ if (offsetRef.current !== 0 && !parkedRef.current && !settleRef.current) {+ settleTo(0, RETURN_MS);+ }+ }, [settleTo]);++ const handlePointerMove = useCallback(+ (event: PointerEvent) => {+ const gesture = gestureRef.current;++ if (!gesture || gesture.pointerId !== event.pointerId || gesture.phase === 'declined') {+ return;+ }++ const dx = event.clientX - gesture.startX;++ if (gesture.phase === 'pending') {+ const intent = classifySwipeIntent(dx, event.clientY - gesture.startY);++ if (intent === 'pending') {+ return;+ }++ if (intent === 'reject') {+ gesture.phase = 'declined';+ restoreIfStranded();+ return;+ }++ gesture.phase = 'tracking';+ gesture.width = stageRef.current?.clientWidth ?? 0;+ }++ recordSwipeSample(gesture.samples, { time: event.timeStamp, x: event.clientX });++ // A parked track still shows the committed neighbor; the gesture resumes once the new image lands.+ if (parkedRef.current) {+ return;+ }++ const raw = gesture.baseOffset + dx;+ const direction = getRevealedDirection(raw);++ writeOffset(direction !== 0 && !canNavigate(direction) ? rubberBand(raw, gesture.width) : raw);+ },+ [canNavigate, restoreIfStranded, writeOffset]+ );++ const handlePointerEnd = useCallback(+ (event: PointerEvent) => {+ const gesture = gestureRef.current;++ if (!gesture || gesture.pointerId !== event.pointerId) {+ return;+ }++ gestureRef.current = null;++ if (parkedRef.current) {+ return;+ }++ if (gesture.phase !== 'tracking' || event.type === 'pointercancel') {+ if (gesture.phase === 'tracking') {+ settleTo(0, RETURN_MS);+ } else {+ restoreIfStranded();+ }++ return;+ }++ release(gesture, event.timeStamp);+ },+ [release, restoreIfStranded, settleTo]+ );++ // Document-level so a finger that leaves the stage still moves and releases the track.+ const stageRefCallback = useCallback(+ (node: HTMLElement | null) => {+ stageRef.current = node;++ if (!node) {+ return;+ }++ const ownerDocument = node.ownerDocument;++ ownerDocument.addEventListener('pointermove', handlePointerMove, { passive: true });+ ownerDocument.addEventListener('pointerup', handlePointerEnd);+ ownerDocument.addEventListener('pointercancel', handlePointerEnd);++ return () => {+ ownerDocument.removeEventListener('pointermove', handlePointerMove);+ ownerDocument.removeEventListener('pointerup', handlePointerEnd);+ ownerDocument.removeEventListener('pointercancel', handlePointerEnd);+ gestureRef.current = null;+ stopSettle();+ clearPark();+ };+ },+ [clearPark, handlePointerEnd, handlePointerMove, stopSettle]+ );++ // Elements that move with the track, registered through stable per-role callbacks so React never re-attaches them.+ const [trackRefCallbacks] = useState(() => {+ const makeTrackRef = (role: TrackRole) => (element: HTMLElement | null) => {+ if (!element) {+ trackRefs.current.delete(role);+ return;+ }++ trackRefs.current.set(role, element);+ element.style.translate = offsetRef.current === 0 ? '' : `${offsetRef.current}px 0`;+ };++ return { content: makeTrackRef('content'), next: makeTrackRef('next'), previous: makeTrackRef('previous') };+ });++ // A new source is a landing (or an outside selection). React owns the visible reset: every track element renders+ // `restStyle`, and flipping it between two spellings of "no offset" makes React write it in the very commit that+ // renders the new source, before paint. The imperative state behind it is retired here, during render, the same way+ // the loupe resets its zoom; that relies on selection arriving through the synchronous project store, so this render+ // is never discarded by a transition or suspense.+ const [rest, setRest] = useState({ token: displayedSourceToken, translate: '' as '' | 'none' });++ if (rest.token !== displayedSourceToken) {+ setRest({ token: displayedSourceToken, translate: rest.translate === '' ? 'none' : '' });++ const wasParked = parkedRef.current !== null;+ const gesture = gestureRef.current;++ clearPark();+ stopSettle();+ offsetRef.current = 0;++ // A finger that flicked again during the slide keeps going on the new image, restarting from rest with its+ // travel since the slide landed; any other gesture belonged to the old image.+ if (gesture && wasParked && gesture.phase === 'tracking') {+ gesture.baseOffset = 0;+ gesture.startX = gesture.samples.at(-1)?.x ?? gesture.startX;+ } else if (gesture && !(wasParked && gesture.phase === 'pending')) {+ gestureRef.current = null;+ }+ }++ const handlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLElement>): void => {+ if (event.pointerType !== 'touch') {+ return;+ }++ if (!event.isPrimary) {+ // A second finger is a pinch: hand the stage to the loupe with the image back at rest.+ if (gestureRef.current) {+ gestureRef.current = null;++ if (!parkedRef.current) {+ settleTo(0, 0);+ }+ }++ return;+ }++ setShowsNeighbors(true);++ const { enabled: isEnabled, isZoomed: isZoomedNow, navigation: currentNavigation } = inputRef.current;++ if (!isEnabled || isZoomedNow || !currentNavigation) {+ return;+ }++ const settle = settleRef.current;++ // A committed slide completes now, so a quick follow-up flick is never dropped behind an animation. A return is+ // caught where it is and resumes from the finger travel that put it there; until the touch moves far enough+ // to be a swipe, it can still be a tap or a hold-to-drag, and either sends the image home.+ let baseOffset = 0;++ if (settle && settle.target !== 0) {+ stopSettle();+ writeOffset(settle.target);+ settle.onDone();+ } else if (settle) {+ stopSettle();+ const width = stageRef.current?.clientWidth ?? 0;+ const direction = getRevealedDirection(offsetRef.current);++ baseOffset =+ direction !== 0 && !canNavigate(direction) ? unrubberBand(offsetRef.current, width) : offsetRef.current;+ }++ gestureRef.current = {+ baseOffset,+ phase: 'pending',+ pointerId: event.pointerId,+ samples: [{ time: event.timeStamp, x: event.clientX }],+ startX: event.clientX,+ startY: event.clientY,+ width: 0,+ };+ },+ [canNavigate, settleTo, stopSettle, writeOffset]+ );++ // A drag of this frame owns its touch outright: a hold armed it (pending), or a grip started it before the finger+ // travelled far enough to swipe.+ const dndListener = useMemo((): DndMonitorListener => {+ const yieldToDrag = (id: UniqueIdentifier): void => {+ const gesture = gestureRef.current;++ if (id !== dragId || !gesture) {+ return;+ }++ gesture.phase = 'declined';+ restoreIfStranded();+ };++ return {+ onDragPending: (event) => yieldToDrag(event.id),+ onDragStart: (event) => yieldToDrag(event.active.id),+ };+ }, [dragId, restoreIfStranded]);++ useDndMonitor(dndListener);++ return {+ contentTrackRef: trackRefCallbacks.content,+ nextTrackRef: trackRefCallbacks.next,+ onPointerDown: handlePointerDown,+ previousTrackRef: trackRefCallbacks.previous,+ /** Render as every track element's `style`; see the landing comment above. */+ restStyle: REST_STYLES[rest.translate],+ showsNeighbors,+ stageRefCallback,+ };+};