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
fix(gallery): preserve delete confirmation
joshistoast4a3773b238c2
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxindex cc6766b68a..446aa84570 100644--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx@@ -1,6 +1,6 @@/* eslint-disable react/react-compiler */import { Dialog, Portal, Stack, Text } from '@chakra-ui/react';-import { useCallback, useState, type ReactNode } from 'react';+import { useCallback, useRef, useState, type ReactNode } from 'react';import { Button, CloseButton } from './Button';@@ -27,25 +27,38 @@ export const ConfirmDialog = ({title: string;}) => {const [isPending, setIsPending] = useState(false);+ const isPendingRef = useRef(false);const handleConfirm = useCallback(async () => {+ if (isPendingRef.current) {+ return;+ }++ isPendingRef.current = true;setIsPending(true);try {await onConfirm();} finally {+ isPendingRef.current = false;setIsPending(false);onClose();}}, [onClose, onConfirm]);+ const handleClose = useCallback(() => {+ if (!isPendingRef.current) {+ onClose();+ }+ }, [onClose]);+const handleOpenChange = useCallback((event: { open: boolean }) => {if (!event.open) {- onClose();+ handleClose();}},- [onClose]+ [handleClose]);const handleConfirmClick = useCallback(() => {@@ -53,7 +66,15 @@ export const ConfirmDialog = ({}, [handleConfirm]);return (- <Dialog.Root open={isOpen} placement="center" role="alertdialog" size="sm" onOpenChange={handleOpenChange}>+ <Dialog.Root+ closeOnEscape={!isPending}+ closeOnInteractOutside={!isPending}+ open={isOpen}+ placement="center"+ role="alertdialog"+ size="sm"+ onOpenChange={handleOpenChange}+ ><Portal><Dialog.Backdrop /><Dialog.Positioner>@@ -67,11 +88,12 @@ export const ConfirmDialog = ({<Stack gap="2">{typeof body === 'string' ? <Text fontSize="xs">{body}</Text> : body}</Stack></Dialog.Body><Dialog.Footer gap="2">- <Button disabled={isPending} size="xs" variant="ghost" onClick={onClose}>+ <Button disabled={isPending} size="xs" variant="ghost" onClick={handleClose}>Cancel</Button><ButtoncolorPalette={isDestructive ? 'red' : 'accent'}+ disabled={isPending}loading={isPending}size="xs"variant="solid"@@ -81,7 +103,7 @@ export const ConfirmDialog = ({</Button></Dialog.Footer><Dialog.CloseTrigger asChild>- <CloseButton color="fg.muted" size="sm" />+ <CloseButton color="fg.muted" disabled={isPending} size="sm" /></Dialog.CloseTrigger></Dialog.Content></Dialog.Positioner>diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxnew file mode 100644index 0000000000..95761466fc--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -0,0 +1,210 @@+import type { GalleryImage } from '@features/gallery';++/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { ImageActions } from './useImageActions';++import { ImageContextMenu, type ImageContextMenuTarget } from './ImageContextMenu';+import { EMPTY_IMAGE_RECALL_CAPABILITIES } from './imageRecall';++const preferences = vi.hoisted(() => ({ confirmImageDeletion: true }));+const NO_BOARDS: [] = [];++vi.mock('@workbench/settings/store', () => ({+ useWorkbenchPreferenceSelector: (selector: (value: { confirmImageDeletion: boolean }) => boolean): boolean =>+ selector(preferences),+}));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));+vi.mock('@workbench/WorkbenchContext', () => ({+ useWorkbenchCommands: () => ({+ generation: { setSource: vi.fn() },+ widgets: { patchValues: vi.fn() },+ }),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const image = (imageName: string): GalleryImage => ({+ boardId: 'none',+ height: 512,+ imageCategory: 'general',+ imageName,+ imageUrl: `/${imageName}`,+ queuedAt: '2026-06-15T00:00:00Z',+ sourceQueueItemId: 'queue-item',+ starred: false,+ thumbnailUrl: `/thumb-${imageName}`,+ width: 512,+});++const createActions = (deleteImages: ImageActions['deleteImages']): ImageActions => ({+ canUseAsReferenceImage: false,+ copyImage: vi.fn(() => Promise.resolve()),+ deleteImages,+ downloadImage: vi.fn(() => Promise.resolve()),+ downloadImages: vi.fn(() => Promise.resolve()),+ getImageRecallCapabilities: vi.fn(() => Promise.resolve(EMPTY_IMAGE_RECALL_CAPABILITIES)),+ moveImagesToBoard: vi.fn(() => Promise.resolve()),+ openImageInPreview: vi.fn(),+ recallImageData: vi.fn(() => Promise.resolve()),+ selectForCompare: vi.fn(),+ sendToCanvas: vi.fn(() => Promise.resolve()),+ setImagesStarred: vi.fn(() => Promise.resolve()),+ useAsReferenceImage: vi.fn(),+});++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 getButton = (label: string): HTMLButtonElement => {+ const button = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(+ (candidate) => candidate.textContent?.trim() === label+ );++ if (!button) {+ throw new Error(`Could not find button: ${label}`);+ }++ return button;+};++const getMenuItem = (label: string): HTMLElement => {+ const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (candidate) => candidate.textContent?.trim() === label+ );++ if (!item) {+ throw new Error(`Could not find menu item: ${label}`);+ }++ return item;+};++const getOpenAlertDialog = (): HTMLElement | null =>+ document.querySelector<HTMLElement>('[role="alertdialog"][data-state="open"]');++const Harness = ({ actions, images }: { actions: ImageActions; images: GalleryImage[] }) => {+ const [target, setTarget] = useState<ImageContextMenuTarget | null>({ images, x: 20, y: 20 });++ return <ImageContextMenu actions={actions} boards={NO_BOARDS} target={target} onClose={() => setTarget(null)} />;+};++const renderMenu = async (actions: ImageActions, images: GalleryImage[]) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await interact(() => {+ root?.render(+ <ChakraProvider value={system}>+ <Harness actions={actions} images={images} />+ </ChakraProvider>+ );+ });+};++beforeEach(() => {+ preferences.confirmImageDeletion = true;+});++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('ImageContextMenu deletion confirmation', () => {+ it('keeps single-image confirmation mounted after the host clears the menu target', async () => {+ const deleteImages = vi.fn(() => Promise.resolve());+ await renderMenu(createActions(deleteImages), [image('single.png')]);++ await interact(() => getMenuItem('Delete Image').click());++ expect(getOpenAlertDialog()).not.toBeNull();+ expect(document.body.textContent).toContain('Delete image?');+ expect(deleteImages).not.toHaveBeenCalled();++ await interact(() => getButton('Delete').click());++ expect(deleteImages).toHaveBeenCalledOnce();+ expect(deleteImages).toHaveBeenCalledWith(['single.png']);+ expect(getOpenAlertDialog()).toBeNull();+ });++ it('cancels without deleting', async () => {+ const deleteImages = vi.fn(() => Promise.resolve());+ await renderMenu(createActions(deleteImages), [image('cancel.png')]);++ await interact(() => getMenuItem('Delete Image').click());+ await interact(() => getButton('Cancel').click());++ expect(deleteImages).not.toHaveBeenCalled();+ expect(getOpenAlertDialog()).toBeNull();+ });++ it('deletes immediately when confirmation is disabled', async () => {+ preferences.confirmImageDeletion = false;+ const deleteImages = vi.fn(() => Promise.resolve());+ await renderMenu(createActions(deleteImages), [image('immediate.png')]);++ await interact(() => getMenuItem('Delete Image').click());++ expect(deleteImages).toHaveBeenCalledOnce();+ expect(deleteImages).toHaveBeenCalledWith(['immediate.png']);+ expect(getOpenAlertDialog()).toBeNull();+ });++ it('captures bulk names and cannot be dismissed or submitted twice while deletion is pending', async () => {+ let resolveDeletion: (() => void) | undefined;+ const deletion = new Promise<void>((resolve) => {+ resolveDeletion = resolve;+ });+ const deleteImages = vi.fn(() => deletion);+ await renderMenu(createActions(deleteImages), [image('first.png'), image('second.png')]);++ await interact(() => getMenuItem('Delete Selection').click());++ expect(document.body.textContent).toContain('Delete 2 images?');+ expect(document.body.textContent).toContain('This permanently deletes these images');++ await interact(() => getButton('Delete').click());++ const cancelButton = getButton('Cancel');+ const confirmButton = getButton('Delete');+ const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');+ expect(deleteImages).toHaveBeenCalledOnce();+ expect(deleteImages).toHaveBeenCalledWith(['first.png', 'second.png']);+ expect(cancelButton.disabled).toBe(true);+ expect(confirmButton.disabled).toBe(true);+ expect(closeButton?.disabled).toBe(true);++ await interact(() => {+ confirmButton.click();+ cancelButton.click();+ closeButton?.click();+ document.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));+ document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="backdrop"]')?.click();+ });++ expect(deleteImages).toHaveBeenCalledOnce();+ expect(getOpenAlertDialog()).not.toBeNull();++ await interact(() => resolveDeletion?.());++ expect(getOpenAlertDialog()).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex 36c84a94cf..6e025fee5c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -2,8 +2,8 @@ import type { GalleryBoard, GalleryImage } from '@features/gallery';/* eslint-disable react/react-compiler */import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';-import { Dialog, HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';-import { Button, MenuContent, Tooltip } from '@platform/ui';+import { HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';+import { ConfirmDialog, MenuContent, Tooltip } from '@platform/ui';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { useWorkbenchCommands } from '@workbench/WorkbenchContext';@@ -114,23 +114,55 @@ export const ImageContextMenu = ({target: ImageContextMenuTarget | null;onClose: () => void;}) => {+ const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);+ const [pendingDeletion, setPendingDeletion] = useState<string[] | null>(null);const images = getImageContextMenuImages(target);const image = images[0] ?? null;- if (!target || !image) {- return null;- }+ const requestDeletion = useCallback(+ (imageNames: string[]) => {+ if (confirmImageDeletion) {+ setPendingDeletion([...imageNames]);+ } else {+ void actions.deleteImages(imageNames);+ }+ },+ [actions, confirmImageDeletion]+ );+ const handleCancelDeletion = useCallback(() => setPendingDeletion(null), []);+ const handleConfirmDeletion = useCallback(async () => {+ if (!pendingDeletion) {+ return;+ }++ await actions.deleteImages(pendingDeletion);+ }, [actions, pendingDeletion]);return (- <ImageContextMenuContent- key={`${image.imageName}:${images.length}`}- actions={actions}- boards={boards}- image={image}- images={images}- target={target}- onClose={onClose}- />+ <>+ {target && image && (+ <ImageContextMenuContent+ key={`${image.imageName}:${images.length}`}+ actions={actions}+ boards={boards}+ image={image}+ images={images}+ target={target}+ onClose={onClose}+ onRequestDeletion={requestDeletion}+ />+ )}+ <ConfirmDialog+ body={`This permanently deletes ${pendingDeletion && pendingDeletion.length > 1 ? 'these images' : 'the image'} from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.`}+ confirmLabel="Delete"+ isOpen={pendingDeletion !== null}+ title={+ pendingDeletion && pendingDeletion.length > 1 ? `Delete ${pendingDeletion.length} images?` : 'Delete image?'+ }+ onClose={handleCancelDeletion}+ onConfirm={handleConfirmDeletion}+ />+ </>);};@@ -141,6 +173,7 @@ const ImageContextMenuContent = ({images,target,onClose,+ onRequestDeletion,}: {actions: ImageActions;boards: GalleryBoard[];@@ -148,9 +181,8 @@ const ImageContextMenuContent = ({images: GalleryImage[];target: ImageContextMenuTarget;onClose: () => void;+ onRequestDeletion: (imageNames: string[]) => void;}) => {- const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);- const [pendingDeletion, setPendingDeletion] = useState<string[] | null>(null);const [recallCapabilities, setRecallCapabilities] = useState<ImageRecallCapabilities>(EMPTY_IMAGE_RECALL_CAPABILITIES);@@ -202,17 +234,6 @@ const ImageContextMenuContent = ({};}, [getImageRecallCapabilities, recallRequestKey]);- const requestDeletion = useCallback(- (names: string[]) => {- if (confirmImageDeletion) {- setPendingDeletion(names);- } else {- void actions.deleteImages(names);- }- },- [actions, confirmImageDeletion]- );-const positioning = useMemo(() => ({getAnchorRect: () => {@@ -232,81 +253,34 @@ const ImageContextMenuContent = ({},[onClose]);- const handleDeleteDialogOpenChange = useCallback((event: { open: boolean }) => {- if (!event.open) {- setPendingDeletion(null);- }- }, []);- const handleCancelDeletion = useCallback(() => setPendingDeletion(null), []);- const handleConfirmDeletion = useCallback(() => {- if (pendingDeletion) {- void actions.deleteImages(pendingDeletion);- }-- setPendingDeletion(null);- }, [actions, pendingDeletion]);-return (- <>- <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>- <Portal>- <Menu.Positioner>- <MenuContent {...MENU_CONTENT_PROPS} maxH="min(28rem, calc(100vh - 2rem))" minW="16rem" overflowY="auto">- {isBulk ? (- <BulkMenuItems- actions={actions}- boards={boards}- imageNames={imageNames}- images={images}- onRequestDeletion={requestDeletion}- />- ) : (- <SingleImageMenuItems- actions={actions}- boards={boards}- image={image}- images={images}- isLoadingRecallCapabilities={isLoadingRecallCapabilities}- onRequestDeletion={requestDeletion}- recallCapabilities={recallCapabilities}- />- )}- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- <Dialog.Root open={pendingDeletion !== null} role="alertdialog" onOpenChange={handleDeleteDialogOpenChange}>- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content>- <Dialog.Header>- <Dialog.Title fontSize="sm">- {pendingDeletion && pendingDeletion.length > 1- ? `Delete ${pendingDeletion.length} images?`- : 'Delete image?'}- </Dialog.Title>- </Dialog.Header>- <Dialog.Body>- <Text color="fg.subtle" fontSize="xs">- This permanently deletes{' '}- {pendingDeletion && pendingDeletion.length > 1 ? 'these images' : 'the image'} from every board and- from disk. This cannot be undone. You can disable this confirmation in Settings.- </Text>- </Dialog.Body>- <Dialog.Footer gap="2">- <Button size="xs" variant="outline" onClick={handleCancelDeletion}>- Cancel- </Button>- <Button colorPalette="red" size="xs" onClick={handleConfirmDeletion}>- Delete- </Button>- </Dialog.Footer>- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>- </>+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Menu.Positioner>+ <MenuContent {...MENU_CONTENT_PROPS} maxH="min(28rem, calc(100vh - 2rem))" minW="16rem" overflowY="auto">+ {isBulk ? (+ <BulkMenuItems+ actions={actions}+ boards={boards}+ imageNames={imageNames}+ images={images}+ onRequestDeletion={onRequestDeletion}+ />+ ) : (+ <SingleImageMenuItems+ actions={actions}+ boards={boards}+ image={image}+ images={images}+ isLoadingRecallCapabilities={isLoadingRecallCapabilities}+ onRequestDeletion={onRequestDeletion}+ recallCapabilities={recallCapabilities}+ />+ )}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>);};