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(preview): make saved images draggable
joshistoast1252c2006b57
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 9e195dcfb6..0457e6534a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -1,7 +1,10 @@/* eslint-disable react/react-compiler */import type { StreamingImageSource } from '@workbench/images/streamingImageSource';+import type { GalleryImageDragImage } from '@workbench/widgets/gallery/galleryDnd';import { Badge, Box, Flex, type SystemStyleObject } from '@chakra-ui/react';+import { useDraggable } from '@dnd-kit/core';+import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';import { useCallback, useMemo, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';@@ -33,6 +36,7 @@ export const getFittedFrameCss = (width: number, height: number): SystemStyleObjexport const PreviewFrame = ({children,+ dragImage,frameHeight,frameWidth,isLive,@@ -47,6 +51,8 @@ export const PreviewFrame = ({}: {/** Rendered instead of the fitted frame when there is no image source (inset variant only). */children?: ReactNode;+ /** Saved gallery image represented by this frame. Live progress frames are never draggable. */+ dragImage?: GalleryImageDragImage;frameHeight: number;frameWidth: number;isLive: boolean;@@ -68,6 +74,27 @@ export const PreviewFrame = ({enabled: variant === 'framed' && !isLive,naturalWidth: frameWidth,});+ const dragData = useMemo(() => (dragImage ? getGalleryImageDragData([dragImage]) : undefined), [dragImage]);+ const isDragDisabled = !dragImage || isLive || loupe.isZoomed;+ const {+ isDragging,+ listeners,+ setNodeRef: setDragNodeRef,+ } = useDraggable({+ data: dragData,+ disabled: isDragDisabled,+ id: `preview-image:${dragImage?.imageName ?? 'none'}`,+ });+ const setContentRef = useCallback(+ (element: HTMLDivElement | null) => {+ setDragNodeRef(element);++ if (loupe.contentRef) {+ loupe.contentRef.current = element;+ }+ },+ [loupe.contentRef, setDragNodeRef]+ );// Reset zoom in place when the displayed image changes (or goes live) — a// remount would flash the frame on every selection.@@ -163,19 +190,30 @@ export const PreviewFrame = ({><PreviewCompareDropZone /><Box- ref={loupe.contentRef}+ ref={setContentRef}+ {...listeners}bg="transparent"borderWidth="1px"borderColor={isLive ? 'accent.solid' : 'border.emphasized'}boxShadow="0 24px 80px rgba(0,0,0,0.42)"css={getFittedFrameCss(frameWidth, frameHeight)}+ cursor={isDragDisabled ? undefined : isDragging ? 'grabbing' : 'grab'}+ opacity={isDragging ? 0.55 : undefined}overflow="hidden"position="relative"rounded="lg"+ touchAction={isDragDisabled ? undefined : 'none'}onContextMenu={onContextMenu ? handleContextMenu : undefined}>{source ? (- <img alt={source.alt} height={frameHeight} src={source.src} style={imageStyle} width={frameWidth} />+ <img+ alt={source.alt}+ draggable={false}+ height={frameHeight}+ src={source.src}+ style={imageStyle}+ width={frameWidth}+ />) : null}{liveBadge}</Box>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxnew file mode 100644index 0000000000..4e7d0acf51--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -0,0 +1,155 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import type { StreamingImageSource } from '@workbench/images/streamingImageSource';++import { ChakraProvider } from '@chakra-ui/react';+import {+ DndContext,+ PointerSensor,+ useDndMonitor,+ useDroppable,+ useSensor,+ useSensors,+ type DragEndEvent,+} from '@dnd-kit/core';+import { system } from '@theme/system';+import { widgetCollisionDetection } from '@workbench/widgetDnd';+import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { createInstance } from 'i18next';+import { act } 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 { PreviewFrame } from './PreviewFrame';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ initImmediate: false,+ lng: 'en',+ resources: {+ en: { translation: { widgets: { preview: { dropToCompare: 'Drop to compare', resetZoom: 'Reset zoom' } } } },+ },+});++const source: StreamingImageSource = {+ alt: 'preview.png',+ height: 128,+ kind: 'fallback',+ src: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"/>',+ width: 128,+};++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const interact = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 50);+ });+ });++const DropTarget = () => {+ const { setNodeRef } = useDroppable({ data: { kind: 'test-image-drop' }, id: 'test-image-drop' });++ return (+ <div+ ref={setNodeRef}+ data-testid="drop-target"+ style={{ height: 180, left: 320, position: 'fixed', top: 40, width: 180 }}+ />+ );+};++const DragMonitor = ({+ onDrop,+}: {+ onDrop: (result: { activeData: unknown; overId: string | number | null }) => void;+}) => {+ useDndMonitor({+ onDragEnd: (event: DragEndEvent) =>+ onDrop({ activeData: event.active.data.current, overId: event.over?.id ?? null }),+ });++ return null;+};++const renderHarness = async () => {+ const onDrop = vi.fn();+ const Harness = () => {+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));++ return (+ <DndContext collisionDetection={widgetCollisionDetection} sensors={sensors}>+ <DragMonitor onDrop={onDrop} />+ <div style={{ display: 'flex', height: 220, left: 40, position: 'fixed', top: 40, width: 220 }}>+ <PreviewFrame+ dragImage={{ boardId: 'board-1', imageName: 'preview.png' }}+ frameHeight={128}+ frameWidth={128}+ isLive={false}+ liveBadgeLabel="Generating"+ shouldAntialiasLiveImage+ source={source}+ variant="framed"+ />+ </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>+ );+ });++ return onDrop;+};++const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {+ target.dispatchEvent(+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })+ );+};++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('PreviewFrame image drag', () => {+ it('emits the shared single-gallery-image payload accepted by image drop surfaces', async () => {+ const onDrop = await renderHarness();+ const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;++ await interact(() => pointer('pointerdown', image, 140, 140));+ await interact(() => pointer('pointermove', image.ownerDocument, 170, 140));+ await interact(() => pointer('pointermove', image.ownerDocument, 400, 120));+ await interact(() => pointer('pointerup', image.ownerDocument, 400, 120));++ expect(onDrop).toHaveBeenCalledOnce();+ const result = onDrop.mock.calls[0]?.[0];++ expect(result?.overId).toBe('test-image-drop');+ expect(isGalleryImageDragData(result?.activeData)).toBe(true);+ expect(result?.activeData).toEqual({+ images: [{ boardId: 'board-1', imageName: 'preview.png' }],+ kind: 'gallery-image',+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 1bcaf6ee5c..c362f710b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -614,6 +614,10 @@ const SelectedImagePreview = ({const previewWidth = previewImage?.width ?? image.width;const previewHeight = previewImage?.height ?? image.height;const liveQueueItemId = progressImage?.target?.queueItemId ?? null;+ const dragImage = useMemo(+ () => ({ boardId: actionImage?.boardId ?? 'none', imageName: image.imageName }),+ [actionImage?.boardId, image.imageName]+ );const handleKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {if (event.key === 'ArrowLeft') {@@ -632,6 +636,7 @@ const SelectedImagePreview = ({return (<Stack gap="3" h="full" minH="0" outline="none" tabIndex={0} w="full" onKeyDown={handleKeyDown}><PreviewFrame+ dragImage={dragImage}frameHeight={previewHeight}frameWidth={previewWidth}isLive={isProgressImage}