Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(ui): animate dialogs and menus out instead of unmounting on close

Josh Corbett54a82a4bd5a9
diff --git a/invokeai/frontend/webv2/src/app/App.tsx b/invokeai/frontend/webv2/src/app/App.tsx
index 9513e3daef..80e4af17db 100644
--- a/invokeai/frontend/webv2/src/app/App.tsx
+++ b/invokeai/frontend/webv2/src/app/App.tsx
@@ -1,5 +1,6 @@
import { AppProviders } from '@app/AppProviders';
import { ChakraProvider } from '@chakra-ui/react';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { AppToaster } from '@platform/ui/toaster';
import { RouterProvider } from '@tanstack/react-router';
import { system } from '@theme/system';
@@ -21,10 +22,12 @@ const AlphaNoticeGate = () => {
const isDue = useWorkbenchSettingsSelector(
(snapshot) => snapshot.status === 'ready' && !snapshot.preferences.alphaNoticeAcknowledged
);
+ // Stays mounted through the close animation instead of vanishing on dismissal.
+ const dialog = useExitPresence(isDue);
- return isDue ? (
+ return dialog.isMounted ? (
<Suspense fallback={null}>
- <AlphaNoticeDialog />
+ <AlphaNoticeDialog onExitComplete={dialog.release} />
</Suspense>
) : null;
};
@@ -36,10 +39,12 @@ const WhatsNewDialog = lazy(() =>
/** Load the What's New notes when a new version has not been seen yet, or when the app menu asks for them. */
const WhatsNewGate = () => {
const { isOpen } = useWhatsNew();
+ // Stays mounted through the close animation instead of vanishing with the open state.
+ const dialog = useExitPresence(isOpen);
- return isOpen ? (
+ return dialog.isMounted ? (
<Suspense fallback={null}>
- <WhatsNewDialog />
+ <WhatsNewDialog onExitComplete={dialog.release} />
</Suspense>
) : null;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx
new file mode 100644
index 0000000000..c8439c231a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx
@@ -0,0 +1,101 @@
+import type { GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { GeneratePresetsPopover } from './GeneratePresetsPopover';
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en' });
+
+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 ADAPTER = {
+ generateValues: { getSnapshot: () => ({}), subscribe: () => () => {} },
+ models: { catalog: [] },
+ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() },
+ presets: {
+ presets: [
+ { id: 'preset-1', label: 'Portrait', values: {} },
+ { id: 'preset-2', label: 'Landscape', values: {} },
+ ],
+ remove: vi.fn(),
+ rename: vi.fn(),
+ },
+ project: { activeProjectId: 'project-1' },
+ settings: { patchGenerateSettings: vi.fn() },
+} as unknown as GenerationUiAdapter;
+
+/** The popover is a dialog too; this selects the modal dialog's content. */
+const modalDialog = () => document.querySelector('[data-scope="dialog"][data-part="content"]');
+const renameInput = () => modalDialog()?.querySelector<HTMLInputElement>('input[name="renameValue"]');
+/** Untranslated in tests, so every row's rename button shares one label; rows keep catalog order. */
+const renameButtons = () => document.querySelectorAll<HTMLElement>('[aria-label="widgets.generate.renamePresetNamed"]');
+
+const openRename = async (index: number) => {
+ if (renameButtons().length === 0) {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label="widgets.generate.presets"]')!));
+ await expect.poll(() => renameButtons().length).toBeGreaterThan(index);
+ }
+
+ await act(() => renameButtons()[index]!.click());
+ await expect.poll(() => modalDialog()?.getAttribute('data-state')).toBe('open');
+};
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={ADAPTER}>
+ <GeneratePresetsPopover />
+ </GenerationUiProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+});
+
+describe('GeneratePresetsPopover', () => {
+ it('animates the rename dialog out instead of unmounting it on close', async () => {
+ await openRename(0);
+ expect(renameInput()?.value).toBe('Portrait');
+
+ const frames = closingFrames(
+ await recordDialogExit(modalDialog()!, () => act(() => userEvent.keyboard('{Escape}')))
+ );
+ await expect.poll(() => modalDialog()).toBeNull();
+
+ expect(frames).not.toHaveLength(0);
+ });
+
+ it('starts a rename reopened during the exit animation from the newly chosen preset', async () => {
+ await openRename(0);
+ await act(() => userEvent.type(renameInput()!, ' draft'));
+ await act(() => userEvent.keyboard('{Escape}'));
+ // Still animating out: a dialog reused for the next open would keep this draft and the old preset's name.
+ expect(modalDialog()?.getAttribute('data-state')).toBe('closed');
+
+ await openRename(1);
+
+ expect(renameInput()?.value).toBe('Landscape');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
index 616bd23a8b..7f8c3fa991 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
@@ -8,6 +8,7 @@ import {
} from '@features/generation/core/baseGenerationPolicies';
import { GENERATE_TOOL_MODEL_PICK_KEYS, normalizeGenerateSettings } from '@features/generation/core/settings';
import { resolveGenerateWidgetValues } from '@features/generation/settings';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import {
Button,
ConfirmDialog,
@@ -38,7 +39,7 @@ const PRESET_ROW_SEPARATOR = <Separator borderColor="border.subtle" />;
/** Below this many presets, a search box is more furniture than help. */
const SEARCH_VISIBLE_MIN_PRESETS = 6;
-type PresetDialogState = { mode: 'save' } | { mode: 'rename'; preset: GeneratePresetRecord };
+type PresetDialogSubject = { mode: 'save' } | { mode: 'rename'; preset: GeneratePresetRecord };
/** Ignore presentation and non-applied keys, including seed unless its mode is fixed. */
const getPresetComparisonKey = (settings: GenerateSettings): string => {
@@ -131,7 +132,8 @@ export const GeneratePresetsPopover = () => {
const ui = useGenerationUi();
const [isOpen, setIsOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
- const [dialog, setDialog] = useState<PresetDialogState | null>(null);
+ const [dialogSubject, setDialogSubject] = useState<PresetDialogSubject | null>(null);
+ const dialog = useExitRetainedValue(dialogSubject);
const [pendingDelete, setPendingDelete] = useState<GeneratePresetRecord | null>(null);
// Tooltip and Popover must share the trigger ID to preserve anchoring.
const triggerId = useId();
@@ -221,13 +223,16 @@ export const GeneratePresetsPopover = () => {
[i18n.resolvedLanguage, models, projectId, supportedModels, t, ui.notifications, ui.settings]
);
- const openSaveDialog = useCallback(() => setDialog({ mode: 'save' }), []);
- const openRenameDialog = useCallback((preset: GeneratePresetRecord) => setDialog({ mode: 'rename', preset }), []);
- const closeDialog = useCallback(() => setDialog(null), []);
+ const openSaveDialog = useCallback(() => setDialogSubject({ mode: 'save' }), []);
+ const openRenameDialog = useCallback(
+ (preset: GeneratePresetRecord) => setDialogSubject({ mode: 'rename', preset }),
+ []
+ );
+ const closeDialog = useCallback(() => setDialogSubject(null), []);
const handleDialogSubmit = useCallback(
(label: string) => {
- if (dialog?.mode === 'rename') {
- ui.presets.rename(dialog.preset.id, label);
+ if (dialogSubject?.mode === 'rename') {
+ ui.presets.rename(dialogSubject.preset.id, label);
return;
}
@@ -239,7 +244,7 @@ export const GeneratePresetsPopover = () => {
ui.presets.save(label, { ...snapshot });
}
},
- [dialog, ui.generateValues, ui.presets]
+ [dialogSubject, ui.generateValues, ui.presets]
);
const cancelDelete = useCallback(() => setPendingDelete(null), []);
@@ -341,16 +346,20 @@ export const GeneratePresetsPopover = () => {
</Popover.Positioner>
</Portal>
</Popover.Root>
- {dialog ? (
+ {dialog.value ? (
<RenameDialog
- initialName={dialog.mode === 'rename' ? dialog.preset.label : ''}
- isOpen
+ key={dialog.generation}
+ initialName={dialog.value.mode === 'rename' ? dialog.value.preset.label : ''}
+ isOpen={dialog.isOpen}
label={t('widgets.generate.presetName')}
- submitLabel={dialog.mode === 'rename' ? t('common.rename') : t('widgets.generate.savePresetAction')}
+ submitLabel={dialog.value.mode === 'rename' ? t('common.rename') : t('widgets.generate.savePresetAction')}
title={
- dialog.mode === 'rename' ? t('widgets.generate.renamePresetTitle') : t('widgets.generate.savePresetTitle')
+ dialog.value.mode === 'rename'
+ ? t('widgets.generate.renamePresetTitle')
+ : t('widgets.generate.savePresetTitle')
}
onClose={closeDialog}
+ onExitComplete={dialog.release}
onSubmit={handleDialogSubmit}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx
index 33318eb5ac..1d329a38da 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx
@@ -36,7 +36,7 @@ const renderDialog = async (entries = ENTRIES) => {
await act(() => {
root?.render(
<ChakraProvider value={system}>
- <WildcardImportDialog entries={entries} onCancel={vi.fn()} onConfirm={onConfirm} />
+ <WildcardImportDialog entries={entries} isOpen onCancel={vi.fn()} onConfirm={onConfirm} />
</ChakraProvider>
);
});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx
index 610e19943d..ecfa4d122d 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx
@@ -31,12 +31,17 @@ const REJECTION_KEY: Record<WildcardImportRejection, string> = {
/** Default conflicts to skip and show explicit rejection reasons. */
export const WildcardImportDialog = ({
entries,
+ isOpen,
onCancel,
onConfirm,
+ onExitComplete,
}: {
entries: readonly WildcardImportEntry[];
+ isOpen: boolean;
onCancel: () => void;
onConfirm: (resolutions: Record<string, WildcardImportResolution>) => Promise<void>;
+ /** After the close animation; the host releases the retained import here. */
+ onExitComplete?: () => void;
}) => {
const { t } = useTranslation();
const [resolutions, setResolutions] = useState<Record<string, WildcardImportResolution>>({});
@@ -137,10 +142,11 @@ export const WildcardImportDialog = ({
body={body}
confirmLabel={t('widgets.generate.dynamicPrompts.import')}
isDestructive={false}
- isOpen
+ isOpen={isOpen}
title={t('widgets.generate.dynamicPrompts.importWildcards')}
onClose={onCancel}
onConfirm={handleConfirm}
+ onExitComplete={onExitComplete}
/>
);
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
index 3832d2ed3d..ed4accc86a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
@@ -17,6 +17,7 @@ import {
WILDCARD_IMPORT_ACCEPT,
WildcardFileError,
} from '@features/generation/ui/wildcardFiles';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -45,6 +46,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
entries: WildcardImportEntry[];
owner: AccountScope;
} | null>(null);
+ const importDialog = useExitRetainedValue(pendingImport);
const reportError = useCallback(
(area: string, caught: unknown, fallback: string) =>
@@ -252,8 +254,15 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
/>
{/* Use a separate directory input to preserve relative wildcard paths. */}
<input {...DIRECTORY_INPUT_PROPS} hidden ref={directoryInputRef} type="file" onChange={handleDirectoryChange} />
- {pendingImport ? (
- <WildcardImportDialog entries={pendingImport.entries} onCancel={cancelImport} onConfirm={confirmImport} />
+ {importDialog.value ? (
+ <WildcardImportDialog
+ key={importDialog.generation}
+ entries={importDialog.value.entries}
+ isOpen={importDialog.isOpen}
+ onCancel={cancelImport}
+ onConfirm={confirmImport}
+ onExitComplete={importDialog.release}
+ />
) : null}
</HStack>
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
index a32df15b05..ea47ae91d6 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
@@ -4,6 +4,7 @@ import { ChakraProvider } from '@chakra-ui/react';
import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';
import { WILDCARD_COLLECTION_FORMATS } from '@features/generation/ui/wildcardFiles';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -137,6 +138,28 @@ it('quietly refuses a conflict-dialog import after its originating account rotat
expect(applyWrites).not.toHaveBeenCalled();
});
+it('animates the conflict dialog out instead of unmounting it on cancel', async () => {
+ accountLifecycle.activate('wildcard-dialog-exit', ':user:wildcard-dialog-exit');
+ await renderPanel();
+
+ const input = host!.querySelector<HTMLInputElement>(
+ `input[accept="${'.txt,.yaml,.yml,.json,text/plain,application/json'}"]`
+ )!;
+ await act(async () => {
+ await userEvent.upload(input, new File(['blue'], 'colors.txt', { type: 'text/plain' }));
+ });
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toContain('colors');
+ }
+});
+
describe('wildcard values editor', () => {
it('colours attention and nested dynamic syntax in the values', async () => {
await openEditor(true);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
index 7caa0a2c49..d6b3cec080 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
@@ -12,6 +12,7 @@ import { FindInGalleryButton } from '@features/gallery/mediaSlot';
import { getEffectiveReferenceImage } from '@features/generation/core/referenceImage';
import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';
import { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { IconButton, ToggleDot, Tooltip } from '@platform/ui';
import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, CropIcon, ImageIcon, RulerIcon, Trash2Icon } from 'lucide-react';
import { memo, useCallback, useRef, useState } from 'react';
@@ -371,6 +372,7 @@ const ReferenceImageThumbnail = ({
}) => {
const { t } = useTranslation();
const [isCropOpen, setIsCropOpen] = useState(false);
+ const cropDialog = useExitPresence(isCropOpen);
const effectiveImage = image ? getEffectiveReferenceImage(image) : null;
const urls = image ? getReferenceImageUrls(image) : null;
@@ -452,8 +454,15 @@ const ReferenceImageThumbnail = ({
</HStack>
) : null}
</Box>
- {image && isCropOpen ? (
- <ReferenceImageCropDialog image={image} isOpen={isCropOpen} onApply={onCrop} onClose={closeCrop} />
+ {image && cropDialog.isMounted ? (
+ <ReferenceImageCropDialog
+ key={cropDialog.generation}
+ image={image}
+ isOpen={cropDialog.isOpen}
+ onApply={onCrop}
+ onClose={closeCrop}
+ onExitComplete={cropDialog.release}
+ />
) : null}
</>
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
index 7701a16b12..2fc7775bfe 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
@@ -170,11 +170,14 @@ export const ReferenceImageCropDialog = ({
isOpen,
onApply,
onClose,
+ onExitComplete,
}: {
image: GenerateReferenceImageAsset;
isOpen: boolean;
onApply: (image: GenerateReferenceImageAsset) => void;
onClose: () => void;
+ /** After the close animation; the host releases the retained dialog here. */
+ onExitComplete?: () => void;
}) => {
const { t } = useTranslation();
const { gallery, notifications } = useGenerationUi();
@@ -298,7 +301,14 @@ export const ReferenceImageCropDialog = ({
}, [close, cropBox, gallery, image, notifications, onApply, onClose]);
return (
- <Dialog.Root lazyMount open={isOpen} size="lg" unmountOnExit onOpenChange={handleOpenChange}>
+ <Dialog.Root
+ lazyMount
+ open={isOpen}
+ size="lg"
+ unmountOnExit
+ onExitComplete={onExitComplete}
+ onOpenChange={handleOpenChange}
+ >
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx
new file mode 100644
index 0000000000..f5269113d7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx
@@ -0,0 +1,82 @@
+import type { GenerateReferenceImage } from '@features/generation/core/types';
+import type { GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { ReferenceImageCard } from './ReferenceImageCard';
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en' });
+
+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 noop = vi.fn();
+const ADAPTER = {
+ gallery: { touchImages: vi.fn() },
+ notifications: { reportError: vi.fn() },
+} as unknown as GenerationUiAdapter;
+
+const REFERENCE: GenerateReferenceImage = {
+ config: {
+ image: { original: { image: { height: 512, image_name: 'original.png', width: 512 } } },
+ type: 'external_reference_image',
+ },
+ id: 'reference',
+ isEnabled: true,
+};
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={ADAPTER}>
+ <ReferenceImageCard
+ count={1}
+ index={0}
+ referenceImage={REFERENCE}
+ selectedModel={undefined}
+ onFindInGallery={noop}
+ onMove={noop}
+ onPatch={noop}
+ onRemove={noop}
+ onUseSize={noop}
+ />
+ </GenerationUiProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+});
+
+describe('reference image crop dialog', () => {
+ it('animates out instead of unmounting on close', async () => {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="common.crop"]')!));
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="dialog"]')!;
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ expect(frames).not.toHaveLength(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
index e4b2787fb3..011308cf06 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
@@ -8,13 +8,10 @@ import { isLinkableType } from '@features/models/core/relationships';
import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';
import { getModelSourceHref } from '@features/models/core/taxonomy';
import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';
-import {
- ModelActionConfirmDialog,
- ModelActionMenuItems,
- type PendingModelAction,
-} from '@features/models/ui/shared/ModelActionsMenu';
+import { ModelActionMenuItems, type PendingModelAction } from '@features/models/ui/shared/ModelActionsMenu';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { formatBytes } from '@platform/i18n/languages';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { areArraysEqual } from '@platform/state/selectors';
import { Button, IconButton, MenuContent } from '@platform/ui';
import { HuggingFaceIcon } from '@platform/ui/VendoredIcon';
@@ -132,8 +129,19 @@ const selectCpuOnlyModel = (snapshot: ModelsSnapshot, modelKey: string): CpuOnly
const areTriggerPhrasesModelsEqual = (left: TriggerPhrasesModel | null, right: TriggerPhrasesModel | null): boolean =>
left?.key === right?.key && areArraysEqual(left?.trigger_phrases ?? [], right?.trigger_phrases ?? []);
-/** Mount keyed by model key so detail forms cannot leak state between models. */
-export const ModelDetail = ({ modelKey, onDeleted }: { modelKey: string; onDeleted: () => void }) => {
+type RequestModelActionConfirm = (pending: NonNullable<PendingModelAction>) => void;
+
+/**
+ * Mount keyed by model key so detail forms cannot leak state between models. The host owns the confirmation dialog
+ * because a delete unmounts this detail before the dialog finishes closing.
+ */
+export const ModelDetail = ({
+ modelKey,
+ onRequestConfirm,
+}: {
+ modelKey: string;
+ onRequestConfirm: RequestModelActionConfirm;
+}) => {
const { t } = useTranslation();
const model = useModelsSelector((snapshot) => selectModelShell(snapshot, modelKey));
@@ -149,7 +157,7 @@ export const ModelDetail = ({ modelKey, onDeleted }: { modelKey: string; onDelet
return (
<Stack gap="4" pb="4">
- <ModelIdentitySectionContainer modelKey={model.key} onDeleted={onDeleted} />
+ <ModelIdentitySectionContainer modelKey={model.key} onRequestConfirm={onRequestConfirm} />
{supportsCpuOnlySetting(model) ? (
<>
@@ -185,15 +193,15 @@ export const ModelDetail = ({ modelKey, onDeleted }: { modelKey: string; onDelet
interface ModelIdentitySectionProps {
isMissing: boolean;
model: ModelIdentityModel;
- onDeleted: () => void;
+ onRequestConfirm: RequestModelActionConfirm;
}
const ModelIdentitySectionContainer = memo(function ModelIdentitySectionContainer({
modelKey,
- onDeleted,
+ onRequestConfirm,
}: {
modelKey: string;
- onDeleted: () => void;
+ onRequestConfirm: RequestModelActionConfirm;
}) {
const model = useModelsSelector((snapshot) => selectModelIdentity(snapshot, modelKey));
const isMissing = useModelsSelector((snapshot) => snapshot.missingModelKeys.has(modelKey));
@@ -202,13 +210,13 @@ const ModelIdentitySectionContainer = memo(function ModelIdentitySectionContaine
return null;
}
- return <ModelIdentitySection isMissing={isMissing} model={model} onDeleted={onDeleted} />;
+ return <ModelIdentitySection isMissing={isMissing} model={model} onRequestConfirm={onRequestConfirm} />;
});
const ModelIdentitySection = memo(function ModelIdentitySection({
isMissing,
model,
- onDeleted,
+ onRequestConfirm,
}: ModelIdentitySectionProps) {
const notify = useNotify();
const { t } = useTranslation();
@@ -249,7 +257,7 @@ const ModelIdentitySection = memo(function ModelIdentitySection({
<ModelDetailActions
isEditing={isEditing}
model={model}
- onDeleted={onDeleted}
+ onRequestConfirm={onRequestConfirm}
onToggleEditing={() => setEditingModelKey((key) => (key === model.key ? null : model.key))}
/>
</HStack>
@@ -273,22 +281,21 @@ const ModelIdentitySection = memo(function ModelIdentitySection({
const ModelDetailActions = ({
isEditing,
model,
- onDeleted,
+ onRequestConfirm,
onToggleEditing,
}: {
isEditing: boolean;
model: ModelIdentityModel;
- onDeleted: () => void;
+ onRequestConfirm: RequestModelActionConfirm;
onToggleEditing: () => void;
}) => {
const { t } = useTranslation();
- const [pendingAction, setPendingAction] = useState<PendingModelAction>(null);
const [isActionBusy, setIsActionBusy] = useState(false);
return (
<HStack flexShrink={0} gap="1" wrap="wrap">
{isConvertibleToDiffusers(model) ? (
- <Button variant="outline" onClick={() => setPendingAction({ kind: 'convert', model })}>
+ <Button variant="outline" onClick={() => onRequestConfirm({ kind: 'convert', model })}>
<Icon as={HuggingFaceIcon} boxSize="3" />
{t('models.convertToDiffusers')}
</Button>
@@ -310,13 +317,12 @@ const ModelDetailActions = ({
extraItems={<ModelSettingsMenuItems modelKey={model.key} />}
model={model}
onBusyChange={setIsActionBusy}
- onRequestConfirm={setPendingAction}
+ onRequestConfirm={onRequestConfirm}
/>
</MenuContent>
</Menu.Positioner>
</Portal>
</Menu.Root>
- <ModelActionConfirmDialog pending={pendingAction} onClose={() => setPendingAction(null)} onDeleted={onDeleted} />
</HStack>
);
};
@@ -410,6 +416,7 @@ const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: Mode
const { t } = useTranslation();
const modelsDir = useModelsSelector((snapshot) => snapshot.modelsDir);
const [isPathDialogOpen, setIsPathDialogOpen] = useState(false);
+ const pathDialog = useExitPresence(isPathDialogOpen);
// Managed models store paths relative to the models directory; show the
// resolved absolute path so it can be found on disk.
const fullPath = resolveModelAbsolutePath(model.path, modelsDir);
@@ -496,7 +503,15 @@ const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: Mode
</DataList.Item>
))}
</DataList.Root>
- {isPathDialogOpen ? <UpdatePathDialog model={model} onClose={() => setIsPathDialogOpen(false)} /> : null}
+ {pathDialog.isMounted ? (
+ <UpdatePathDialog
+ key={pathDialog.generation}
+ isOpen={pathDialog.isOpen}
+ model={model}
+ onClose={() => setIsPathDialogOpen(false)}
+ onExitComplete={pathDialog.release}
+ />
+ ) : null}
</>
);
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx
index e111d14ecc..254d6288de 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx
@@ -14,11 +14,16 @@ import { useTranslation } from 'react-i18next';
/** Update only the record's absolute path; never move files or repoint managed relative paths. */
export const UpdatePathDialog = ({
+ isOpen,
model,
onClose,
+ onExitComplete,
}: {
+ isOpen: boolean;
model: Pick<ModelConfig, 'key' | 'name' | 'path'>;
onClose: () => void;
+ /** After the close animation; the host releases the retained dialog here. */
+ onExitComplete: () => void;
}) => {
const { t } = useTranslation();
const notify = useNotify();
@@ -50,8 +55,9 @@ export const UpdatePathDialog = ({
return (
<Dialog.Root
- open
+ open={isOpen}
size="md"
+ onExitComplete={onExitComplete}
onOpenChange={(event) => {
if (!event.open) {
onClose();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx
new file mode 100644
index 0000000000..21a0b858e8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx
@@ -0,0 +1,60 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { MaintenanceMenu } from './MaintenanceMenu';
+
+vi.mock('@features/models/data/api', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getOrphanedModels: vi.fn(() => Promise.resolve([])),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('MaintenanceMenu', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ accountLifecycle.activate('maintenance-menu-test', ':user:maintenance-menu-test');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <MaintenanceMenu />
+ </ChakraProvider>
+ )
+ );
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('animates the orphaned-models dialog out instead of unmounting it on close', async () => {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.libraryMaintenance"]')!));
+ await expect.poll(() => document.querySelector('[role="menuitem"][data-value="sync"]')).not.toBeNull();
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role="menuitem"][data-value="sync"]')!));
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="dialog"]')!;
+ await expect.poll(() => dialog.textContent).toContain('models.noOrphaned');
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toContain('models.noOrphaned');
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
index 159e63908b..58f1141ebf 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
@@ -4,6 +4,7 @@ import { emptyModelCache } from '@features/models/data/api';
import { getModelsSnapshot, refreshModels } from '@features/models/data/modelsStore';
import { OrphanedModelsDialog } from '@features/models/ui/library/OrphanedModelsDialog';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { useScopedAction } from '@platform/react/useScopedAction';
import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ConfirmDialog, IconButton, MenuContent } from '@platform/ui';
@@ -15,6 +16,7 @@ export const MaintenanceMenu = () => {
const { t } = useTranslation();
const notify = useNotify();
const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false);
+ const syncDialog = useExitPresence(isSyncDialogOpen);
const [isEmptyCacheConfirmOpen, setIsEmptyCacheConfirmOpen] = useState(false);
// Separate instances: run ignores re-entry, and a slow cache emptying must
// not swallow a refresh (or vice versa).
@@ -77,7 +79,14 @@ export const MaintenanceMenu = () => {
</Menu.Positioner>
</Portal>
</Menu.Root>
- {isSyncDialogOpen ? <OrphanedModelsDialog onClose={() => setIsSyncDialogOpen(false)} /> : null}
+ {syncDialog.isMounted ? (
+ <OrphanedModelsDialog
+ key={syncDialog.generation}
+ isOpen={syncDialog.isOpen}
+ onClose={() => setIsSyncDialogOpen(false)}
+ onExitComplete={syncDialog.release}
+ />
+ ) : null}
<ConfirmDialog
body={t('models.emptyCacheConfirmBody')}
confirmLabel={t('models.emptyCache')}
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx
index 6dc23391ce..be6659f305 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx
@@ -8,6 +8,7 @@ import {
ModelActionMenuItems,
type PendingModelAction,
} from '@features/models/ui/shared/ModelActionsMenu';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { MenuContent } from '@platform/ui';
import { useState } from 'react';
@@ -25,19 +26,22 @@ export const ModelRowContextMenu = ({
const [pendingConfirm, setPendingConfirm] = useState<PendingModelAction>(null);
// Captured with the request: the menu target clears when the menu closes, before the dialog does.
const [confirmFocusTarget, setConfirmFocusTarget] = useState<(() => HTMLElement | null) | null>(null);
- const model = useModelsSelector((snapshot) => (target ? (snapshot.modelsByKey.get(target.modelKey) ?? null) : null));
+ // Kept through the exit animation; keyed by model so another row's menu still opens at its own anchor.
+ const { release, value: shown } = useExitRetainedValue(target);
+ const model = useModelsSelector((snapshot) => (shown ? (snapshot.modelsByKey.get(shown.modelKey) ?? null) : null));
return (
<>
<Menu.Root
- key={target ? target.modelKey : 'closed'}
+ key={shown ? shown.modelKey : 'none'}
lazyMount
open={target !== null}
positioning={{
- getAnchorRect: () => (target ? { height: 1, width: 1, x: target.x, y: target.y } : null),
+ getAnchorRect: () => (shown ? { height: 1, width: 1, x: shown.x, y: shown.y } : null),
placement: 'bottom-start',
}}
unmountOnExit
+ onExitComplete={release}
onOpenChange={(event) => {
if (!event.open) {
onClose();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
index 7782271b6c..9411e7f74b 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
@@ -21,7 +21,16 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
/** Rescan after partial orphan deletion and keep the dialog open for retrying remaining paths. */
-export const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
+export const OrphanedModelsDialog = ({
+ isOpen,
+ onClose,
+ onExitComplete,
+}: {
+ isOpen: boolean;
+ onClose: () => void;
+ /** After the close animation; the host releases the retained dialog here. */
+ onExitComplete: () => void;
+}) => {
const { t } = useTranslation();
const notify = useNotify();
const [orphans, setOrphans] = useState<OrphanedModelInfo[] | null>(null);
@@ -105,9 +114,10 @@ export const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
return (
<Dialog.Root
- open
+ open={isOpen}
scrollBehavior="inside"
size="md"
+ onExitComplete={onExitComplete}
onOpenChange={(event) => {
if (!event.open) {
onClose();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx
new file mode 100644
index 0000000000..fb3f763b8a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx
@@ -0,0 +1,106 @@
+import type { ModelConfig } from '@features/models/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';
+import { getModelsUiSnapshotForTests, openModelDetail } from '@features/models/ui/uiStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { DetailPane } from './DetailPane';
+
+const api = vi.hoisted(() => ({ deleteModel: vi.fn(() => Promise.resolve()) }));
+
+vi.mock('@features/models/data/api', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ deleteModel: api.deleteModel,
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string, options?: { name?: string }) => `${key}${options?.name ?? ''}` }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const VAE = {
+ base: 'sdxl',
+ file_size: 1024,
+ format: 'checkpoint',
+ hash: 'hash-vae',
+ key: 'vae-1',
+ name: 'Model VAE',
+ path: '/models/vae.safetensors',
+ source: '/models/vae.safetensors',
+ source_type: 'path',
+ type: 'vae',
+} as ModelConfig;
+
+const pathDialog = () =>
+ [...document.querySelectorAll('[role="dialog"]')].find((dialog) => dialog.textContent.includes('models.currentPath'));
+
+describe('models DetailPane', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ accountLifecycle.activate('detail-pane-test', ':user:detail-pane-test');
+ setModelsSnapshotForTests({ models: [VAE], status: 'loaded' });
+ openModelDetail(VAE.key);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <DetailPane />
+ </ChakraProvider>
+ )
+ );
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('animates the delete confirmation out after the deleted model leaves the pane', async () => {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.actions"]')!));
+ await expect.poll(() => document.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull();
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]')!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+ const confirm = [...dialog.querySelectorAll('button')].find(
+ (button) => button.textContent === 'models.deleteModel'
+ );
+
+ const frames = closingFrames(
+ await recordDialogExit(dialog, async () => {
+ await act(() => userEvent.click(confirm!));
+ await expect.poll(() => getModelsUiSnapshotForTests().activeModelKey).toBeNull();
+ })
+ );
+
+ expect(api.deleteModel).toHaveBeenCalledWith(VAE.key, expect.anything());
+ expect(frames).not.toHaveLength(0);
+ // It still names the model it deleted while it animates out.
+ for (const frame of frames) {
+ expect(frame.text).toContain('models.deleteBodyModel VAE');
+ }
+ });
+
+ it('animates the update-path dialog out instead of unmounting it on close', async () => {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.updatePath"]')!));
+ await expect.poll(() => pathDialog()?.getAttribute('data-state')).toBe('open');
+
+ const frames = closingFrames(
+ await recordDialogExit(pathDialog()!, () => act(() => userEvent.keyboard('{Escape}')))
+ );
+ await expect.poll(() => pathDialog()).toBeUndefined();
+
+ expect(frames).not.toHaveLength(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx
index e652262338..f046722006 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx
@@ -5,12 +5,13 @@ import { AddModelsView } from '@features/models/ui/add-models/AddModelsView';
import { ApiKeysSection } from '@features/models/ui/credentials/ApiKeysSection';
import { ModelDetail } from '@features/models/ui/detail/ModelDetail';
import { InstallQueueBar } from '@features/models/ui/install-queue/InstallQueueBar';
+import { ModelActionConfirmDialog, type PendingModelAction } from '@features/models/ui/shared/ModelActionsMenu';
import { updateModelsUi, useModelsUiSelector, type ModelManagerTab } from '@features/models/ui/uiStore';
import { Scrollable, Tabs } from '@platform/ui';
import { ManagerDetailHeader } from '@platform/ui/ManagerLayout';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { BoxIcon, KeyRoundIcon, PlusIcon } from 'lucide-react';
-import { useCallback } from 'react';
+import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
/** The tabbed detail pane: selected model, Add Models, API Keys, and queue footer. */
@@ -84,25 +85,32 @@ export const DetailPane = () => {
const DetailTab = ({ modelKey }: { modelKey: string | null }) => {
const { t } = useTranslation();
+ // Owned above the keyed detail: a delete unmounts it while this dialog is still animating out.
+ const [pendingAction, setPendingAction] = useState<PendingModelAction>(null);
const handleDeleted = useCallback(() => updateModelsUi({ activeModelKey: null }), []);
- if (modelKey === null) {
- return (
- <Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">
- <Icon as={BoxIcon} boxSize="8" color="fg.subtle" />
- <Text color="fg.muted" fontSize="lg" fontWeight="600">
- {t('models.selectModel')}
- </Text>
- <Text color="fg.subtle" fontSize="md" maxW="22rem" textAlign="center">
- {t('models.selectModelDescription')}
- </Text>
- </Flex>
- );
- }
-
return (
- <Scrollable h="full" label={t('models.details')} minH="0" p="3">
- <ModelDetail key={modelKey} modelKey={modelKey} onDeleted={handleDeleted} />
- </Scrollable>
+ <>
+ {modelKey === null ? (
+ <Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">
+ <Icon as={BoxIcon} boxSize="8" color="fg.subtle" />
+ <Text color="fg.muted" fontSize="lg" fontWeight="600">
+ {t('models.selectModel')}
+ </Text>
+ <Text color="fg.subtle" fontSize="md" maxW="22rem" textAlign="center">
+ {t('models.selectModelDescription')}
+ </Text>
+ </Flex>
+ ) : (
+ <Scrollable h="full" label={t('models.details')} minH="0" p="3">
+ <ModelDetail key={modelKey} modelKey={modelKey} onRequestConfirm={setPendingAction} />
+ </Scrollable>
+ )}
+ <ModelActionConfirmDialog
+ pending={pendingAction}
+ onClose={() => setPendingAction(null)}
+ onDeleted={handleDeleted}
+ />
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx
index 9b188dfaee..0d6b481c06 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx
@@ -3,22 +3,28 @@ import type { NodePackInfo } from '@features/nodes/core/catalog';
import { Badge, Box, Flex, HStack, Icon, Spinner, Stack, Text } from '@chakra-ui/react';
import { isProblemPack } from '@features/nodes/core/library';
-import { UninstallPackDialog } from '@features/nodes/ui/shared/UninstallPackDialog';
import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@features/workflow/react';
import { Button } from '@platform/ui';
import { EmptyState } from '@platform/ui/EmptyState';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { BlocksIcon, TriangleAlertIcon, Trash2Icon } from 'lucide-react';
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { NodePreviewCard } from './NodePreviewCard';
/**
* Build previews from backend invocation templates; nodeTypes are invocation keys and nodePack identifies their
- * owning pack.
+ * owning pack. The host owns the uninstall confirmation because an uninstall unmounts this detail before the dialog
+ * finishes closing.
*/
-export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => void; pack: NodePackInfo }) => {
+export const NodePackDetail = ({
+ onRequestUninstall,
+ pack,
+}: {
+ onRequestUninstall: (pack: NodePackInfo) => void;
+ pack: NodePackInfo;
+}) => {
const { t } = useTranslation();
const status = useInvocationTemplatesSelector((snapshot) => snapshot.status);
const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);
@@ -62,7 +68,10 @@ export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => v
</Text>
) : null}
</Stack>
- <UninstallButton onUninstalled={onUninstalled} pack={pack} />
+ <Button colorPalette="red" flexShrink={0} variant="outline" onClick={() => onRequestUninstall(pack)}>
+ <Icon as={Trash2Icon} boxSize="3" />
+ {t('nodes.uninstall')}
+ </Button>
</HStack>
<Stack gap="2">
@@ -92,22 +101,3 @@ export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => v
</Stack>
);
};
-
-const UninstallButton = ({ onUninstalled, pack }: { onUninstalled: () => void; pack: NodePackInfo }) => {
- const { t } = useTranslation();
- const [isConfirmOpen, setIsConfirmOpen] = useState(false);
-
- return (
- <>
- <Button colorPalette="red" flexShrink={0} variant="outline" onClick={() => setIsConfirmOpen(true)}>
- <Icon as={Trash2Icon} boxSize="3" />
- {t('nodes.uninstall')}
- </Button>
- <UninstallPackDialog
- pack={isConfirmOpen ? pack : null}
- onClose={() => setIsConfirmOpen(false)}
- onUninstalled={onUninstalled}
- />
- </>
- );
-};
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.browser.test.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.browser.test.tsx
new file mode 100644
index 0000000000..fbf5a9f958
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.browser.test.tsx
@@ -0,0 +1,85 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { setCustomNodesSnapshotForTests } from '@features/nodes/data/nodesStore';
+import { openNodePackDetail } from '@features/nodes/ui/nodesUiStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { DetailPane } from './DetailPane';
+
+const api = vi.hoisted(() => ({
+ getPackWorkflowCount: vi.fn(() => Promise.resolve(0)),
+ uninstallCustomNodePack: vi.fn(() => Promise.resolve({ message: 'Uninstalled', name: 'pack-a' })),
+}));
+
+vi.mock('@features/nodes/data/api', async (importOriginal) => ({ ...(await importOriginal<object>()), ...api }));
+vi.mock('@features/workflow/react', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ensureInvocationTemplatesLoaded: vi.fn(),
+ useInvocationTemplatesSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({ error: null, status: 'loaded', templates: {} }),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string, options?: { name?: string }) => `${key}${options?.name ?? ''}` }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const PACK = { name: 'pack-a', nodeCount: 0, nodeTypes: [], path: '/custom_nodes/pack-a' };
+
+describe('nodes DetailPane', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ accountLifecycle.activate('nodes-detail-pane-test', ':user:nodes-detail-pane-test');
+ setCustomNodesSnapshotForTests({ nodePacks: [PACK], status: 'loaded' });
+ openNodePackDetail(PACK.name);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <DetailPane />
+ </ChakraProvider>
+ )
+ );
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('animates the uninstall confirmation out after the uninstalled pack leaves the pane', async () => {
+ const uninstall = [...document.querySelectorAll('button')].find(
+ (button) => button.textContent === 'nodes.uninstall'
+ );
+ await act(() => userEvent.click(uninstall!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+ const confirm = [...dialog.querySelectorAll('button')].find(
+ (button) => button.textContent === 'nodes.uninstallPack'
+ );
+
+ const frames = closingFrames(
+ await recordDialogExit(dialog, async () => {
+ await act(() => userEvent.click(confirm!));
+ await expect.poll(() => host.textContent).toContain('nodes.selectPack');
+ })
+ );
+
+ expect(api.uninstallCustomNodePack).toHaveBeenCalledWith(PACK.name, expect.anything());
+ expect(frames).not.toHaveLength(0);
+ // It still names the pack it uninstalled while it animates out.
+ for (const frame of frames) {
+ expect(frame.text).toContain('nodes.uninstallTitlepack-a');
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsx
index d08c6b9b2b..5016383792 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsx
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsx
@@ -7,10 +7,12 @@ import { NodeActivityBar } from '@features/nodes/ui/activity/NodeActivityBar';
import { AddNodesView } from '@features/nodes/ui/add-nodes/AddNodesView';
import { NodePackDetail } from '@features/nodes/ui/detail/NodePackDetail';
import { updateNodesUi, useNodesUiSelector, type NodesManagerTab } from '@features/nodes/ui/nodesUiStore';
+import { UninstallPackDialog } from '@features/nodes/ui/shared/UninstallPackDialog';
import { Scrollable, Tabs } from '@platform/ui';
import { ManagerDetailHeader } from '@platform/ui/ManagerLayout';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { BlocksIcon, PlusIcon } from 'lucide-react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
/** Right side of the nodes manager: selected pack details, Add Nodes, and activity footer. */
@@ -62,24 +64,31 @@ export const DetailPane = () => {
const DetailTab = ({ activePack }: { activePack: NodePackInfo | null }) => {
const { t } = useTranslation();
-
- if (!activePack) {
- return (
- <Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">
- <Icon as={BlocksIcon} boxSize="8" color="fg.subtle" />
- <Text color="fg.muted" fontSize="lg" fontWeight="600">
- {t('nodes.selectPack')}
- </Text>
- <Text color="fg.muted" fontSize="md" maxW="22rem" textAlign="center">
- {t('nodes.selectPackDescription')}
- </Text>
- </Flex>
- );
- }
+ // Owned above the detail: an uninstall unmounts it while this dialog is still animating out.
+ const [pendingUninstall, setPendingUninstall] = useState<NodePackInfo | null>(null);
return (
- <Scrollable h="full" label={t('nodes.details')} minH="0" p="3">
- <NodePackDetail pack={activePack} onUninstalled={() => updateNodesUi({ activePackName: null })} />
- </Scrollable>
+ <>
+ {activePack ? (
+ <Scrollable h="full" label={t('nodes.details')} minH="0" p="3">
+ <NodePackDetail pack={activePack} onRequestUninstall={setPendingUninstall} />
+ </Scrollable>
+ ) : (
+ <Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">
+ <Icon as={BlocksIcon} boxSize="8" color="fg.subtle" />
+ <Text color="fg.muted" fontSize="lg" fontWeight="600">
+ {t('nodes.selectPack')}
+ </Text>
+ <Text color="fg.muted" fontSize="md" maxW="22rem" textAlign="center">
+ {t('nodes.selectPackDescription')}
+ </Text>
+ </Flex>
+ )}
+ <UninstallPackDialog
+ pack={pendingUninstall}
+ onClose={() => setPendingUninstall(null)}
+ onUninstalled={() => updateNodesUi({ activePackName: null })}
+ />
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx
new file mode 100644
index 0000000000..03f7239fc6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx
@@ -0,0 +1,62 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+vi.mock('@features/queue/publicApi', () => ({
+ createProductionQueueRealtimeRuntime: () => ({ dispose: vi.fn(), start: vi.fn() }),
+}));
+vi.mock('@features/queue/data/generationDevicesStore', () => ({ refreshGenerationDevices: vi.fn() }));
+
+import { clearQueueConfirmation, requestQueueConfirmation } from './queueConfirmationStore';
+import { QueueDataRuntime } from './QueueDataRuntime';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueueDataRuntime />
+ </ChakraProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ clearQueueConfirmation();
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+it('animates a queue confirmation out with its text instead of unmounting it on close', async () => {
+ await act(() =>
+ requestQueueConfirmation({
+ body: 'Cancel every item?',
+ confirmLabel: 'Cancel all',
+ onConfirm: vi.fn(),
+ title: 'Clear',
+ })
+ );
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+
+ // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toContain('Cancel every item?');
+ }
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx
index 2fd71d26f0..b83c688340 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx
@@ -23,20 +23,23 @@ export const attachQueueDataRuntime = (): (() => void) => {
return runtime.dispose;
};
+const noop = () => undefined;
+
/** React is only the idempotent lifecycle adapter for the non-React runtime. */
export const QueueDataRuntime = () => {
const confirmation = useQueueConfirmation();
useMountEffect(attachQueueDataRuntime);
- return confirmation ? (
+ // Always mounted, so a cleared confirmation animates out; the dialog keeps the text it showed while it closes.
+ return (
<ConfirmDialog
- body={confirmation.body}
- confirmLabel={confirmation.confirmLabel}
- isOpen={true}
- title={confirmation.title}
+ body={confirmation?.body}
+ confirmLabel={confirmation?.confirmLabel ?? ''}
+ isOpen={confirmation !== null}
+ title={confirmation?.title ?? ''}
onClose={clearQueueConfirmation}
- onConfirm={confirmation.onConfirm}
+ onConfirm={confirmation?.onConfirm ?? noop}
/>
- ) : null;
+ );
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.browser.test.tsx
index 0ccd4c98b2..eb56d9bae6 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.browser.test.tsx
@@ -4,6 +4,7 @@ import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext'
import { ChakraProvider } from '@chakra-ui/react';
import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
import { act, StrictMode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -106,7 +107,11 @@ describe('AddNodeDialog search', () => {
host.remove();
});
- const renderOpen = async ({ groupByCategory = true } = {}) => {
+ const renderOpen = async ({
+ groupByCategory = true,
+ isOpen = true,
+ registerModalHotkeyLayer = (): (() => void) => () => {},
+ } = {}) => {
const onAddNode = vi.fn();
const adapter = {
getProjectGraph: () => ({ edges: [], nodes: [] }),
@@ -114,7 +119,7 @@ describe('AddNodeDialog search', () => {
getSnapshot: () => ({ workflowGroupNodesByCategory: groupByCategory }),
subscribe: () => () => {},
},
- registerModalHotkeyLayer: () => () => {},
+ registerModalHotkeyLayer,
} as unknown as WorkflowUiAdapter;
await act(() => {
@@ -123,7 +128,7 @@ describe('AddNodeDialog search', () => {
<WorkflowUiProvider adapter={adapter}>
<AddNodeDialog
connectionFilter={null}
- isOpen
+ isOpen={isOpen}
onAddConnector={vi.fn()}
onAddCurrentImage={vi.fn()}
onAddNode={onAddNode}
@@ -163,6 +168,33 @@ describe('AddNodeDialog search', () => {
expect(document.querySelector('[aria-label="Expand all categories"]')).toBeNull();
});
+ it('animates out on close, then starts the next open with an empty search', async () => {
+ const { search } = await renderOpen();
+ await act(() => userEvent.type(search, 'integer'));
+ const dialog = document.querySelector('[role="dialog"]')!;
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => renderOpen({ isOpen: false })));
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ expect(frames).not.toHaveLength(0);
+ expect((await renderOpen()).search.value).toBe('');
+ });
+
+ it('gives hotkeys back to the workbench as it closes, not after it animates out', async () => {
+ let isDialogShownAtRelease: boolean | null = null;
+ const registerModalHotkeyLayer = vi.fn(
+ () => () => (isDialogShownAtRelease = document.querySelector('[role="dialog"]') !== null)
+ );
+ await renderOpen({ registerModalHotkeyLayer });
+ expect(registerModalHotkeyLayer).toHaveBeenCalledExactlyOnceWith('workflow-add-node');
+
+ await renderOpen({ isOpen: false, registerModalHotkeyLayer });
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ expect(isDialogShownAtRelease).toBe(true);
+ expect(registerModalHotkeyLayer).toHaveBeenCalledOnce();
+ });
+
it('adds the best match on Enter instead of toggling its category', async () => {
const { onAddNode, search } = await renderOpen();
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx
index c975cb30e3..dd6a113bb5 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx
@@ -11,6 +11,7 @@ import {
LOOP_LINKAGE_FIELD,
resolveConnectorSource,
} from '@features/workflow/utility';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { IconButton, Tooltip } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
@@ -321,6 +322,15 @@ export const AddNodeDialog = ({
onAddNote: () => void;
onOpenChange: (isOpen: boolean) => void;
}) => {
+ // The content stays mounted through the exit animation; a fresh mount per open resets search and expansion.
+ const content = useExitPresence(isOpen);
+ // The store clears the connection on close; keep filtering by it while the dialog animates out.
+ const [shownConnectionFilter, setShownConnectionFilter] = useState(connectionFilter);
+
+ if (isOpen && shownConnectionFilter !== connectionFilter) {
+ setShownConnectionFilter(connectionFilter);
+ }
+
const onDialogOpenChange = useCallback(
(event: { open: boolean }) => {
if (!event.open) {
@@ -337,11 +347,14 @@ export const AddNodeDialog = ({
scrollBehavior="inside"
size="md"
unmountOnExit
+ onExitComplete={content.release}
onOpenChange={onDialogOpenChange}
>
- {isOpen ? (
+ {isOpen ? <AddNodeModalLayer /> : null}
+ {content.isMounted ? (
<AddNodeDialogContent
- connectionFilter={connectionFilter}
+ key={content.generation}
+ connectionFilter={shownConnectionFilter}
onAddCurrentImage={onAddCurrentImage}
onAddConnector={onAddConnector}
onAddNode={onAddNode}
@@ -353,6 +366,15 @@ export const AddNodeDialog = ({
);
};
+/** Blocks workbench hotkeys only while open; the content outlives the open state through its exit animation. */
+const AddNodeModalLayer = () => {
+ const { registerModalHotkeyLayer } = useWorkflowUi();
+
+ useMountEffect(() => registerModalHotkeyLayer('workflow-add-node'));
+
+ return null;
+};
+
const AddNodeDialogContent = ({
connectionFilter,
onAddCurrentImage,
@@ -368,7 +390,7 @@ const AddNodeDialogContent = ({
onAddNote: () => void;
onOpenChange: (isOpen: boolean) => void;
}) => {
- const { getProjectGraph, registerModalHotkeyLayer } = useWorkflowUi();
+ const { getProjectGraph } = useWorkflowUi();
const error = useInvocationTemplatesSelector((snapshot) => snapshot.error);
const status = useInvocationTemplatesSelector((snapshot) => snapshot.status);
const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);
@@ -377,20 +399,10 @@ const AddNodeDialogContent = ({
const [activeIndex, setActiveIndex] = useState<number | null>(null);
const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);
const groupByCategory = useWorkflowPreferencesSelector((preferences) => preferences.workflowGroupNodesByCategory);
-
- useMountEffect(() => registerModalHotkeyLayer('workflow-add-node'));
const isSearching = searchTerm.trim().length > 0;
- const close = useCallback(
- (added: boolean) => {
- onOpenChange(false);
-
- if (added) {
- setSearchTerm('');
- }
- },
- [onOpenChange]
- );
+ // Each open mounts fresh content, so the search needs no reset here; clearing it would reflow the closing list.
+ const close = useCallback(() => onOpenChange(false), [onOpenChange]);
const groups = useMemo<CategoryGroup[]>(() => {
const query = parseSearchQuery(searchTerm);
@@ -409,7 +421,7 @@ const AddNodeDialogContent = ({
nodePack: 'invokeai',
onAdd: () => {
onAddConnector();
- close(true);
+ close();
},
title: 'Connector',
},
@@ -423,7 +435,7 @@ const AddNodeDialogContent = ({
nodePack: 'invokeai',
onAdd: () => {
onAddNote();
- close(true);
+ close();
},
title: 'Notes',
},
@@ -434,7 +446,7 @@ const AddNodeDialogContent = ({
nodePack: 'invokeai',
onAdd: () => {
onAddCurrentImage();
- close(true);
+ close();
},
title: 'Current Image',
},
@@ -467,7 +479,7 @@ const AddNodeDialogContent = ({
nodePack: template.nodePack,
onAdd: () => {
onAddNode(template);
- close(true);
+ close();
},
rank,
title: template.title,
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
index f8384c6e46..6c6f528e17 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
@@ -9,6 +9,7 @@ import { ChakraProvider } from '@chakra-ui/react';
import { GalleryHostProvider } from '@features/gallery/picker';
import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utility';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
import { act, StrictMode, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -362,35 +363,37 @@ describe('WorkflowLibraryDetailPanel', () => {
setTimeout(resolve, 0);
});
+ const panelTree = (selected: WorkflowLibraryEntry | null, projectWorkflows: readonly ProjectWorkflowEntry[]) => (
+ <StrictMode>
+ <ChakraProvider value={system}>
+ <WorkflowUiProvider adapter={ADAPTER}>
+ <GalleryHostProvider host={GALLERY_HOST}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDetailPanel
+ contextMenuPoint={null}
+ contextMenuTriggerId={null}
+ entry={selected}
+ projectWorkflows={projectWorkflows}
+ onClose={onClose}
+ onContextMenuClose={NOOP}
+ onDeleted={onDeleted}
+ onDuplicated={onDuplicated}
+ onOpen={onOpen}
+ onPreview={onPreview}
+ />
+ </WorkflowGraphPreviewProvider>
+ </GalleryHostProvider>
+ </WorkflowUiProvider>
+ </ChakraProvider>
+ </StrictMode>
+ );
+
const renderPanel = async (
selected: WorkflowLibraryEntry | null,
projectWorkflows: readonly ProjectWorkflowEntry[] = NO_COPIES
) => {
await act(async () => {
- root.render(
- <StrictMode>
- <ChakraProvider value={system}>
- <WorkflowUiProvider adapter={ADAPTER}>
- <GalleryHostProvider host={GALLERY_HOST}>
- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
- <WorkflowLibraryDetailPanel
- contextMenuPoint={null}
- contextMenuTriggerId={null}
- entry={selected}
- projectWorkflows={projectWorkflows}
- onClose={onClose}
- onContextMenuClose={NOOP}
- onDeleted={onDeleted}
- onDuplicated={onDuplicated}
- onOpen={onOpen}
- onPreview={onPreview}
- />
- </WorkflowGraphPreviewProvider>
- </GalleryHostProvider>
- </WorkflowUiProvider>
- </ChakraProvider>
- </StrictMode>
- );
+ root.render(panelTree(selected, projectWorkflows));
await settleFrame();
});
};
@@ -837,6 +840,35 @@ describe('WorkflowLibraryDetailPanel', () => {
expect(onDeleted).toHaveBeenCalledTimes(1);
});
+ it('animates the delete confirmation out when the deleted workflow leaves the panel', async () => {
+ // As in the library dialog: the delete clears the selection, and with no other workflow the panel empties.
+ onDeleted = vi.fn(() => root.render(panelTree(null, NO_COPIES)));
+ await renderPanel(TEXT_TO_IMAGE);
+ await clickMenuItem('delete');
+
+ const confirm = document.querySelector<HTMLElement>('[role="alertdialog"]')!;
+ const confirmButton = [...confirm.querySelectorAll('button')].find(
+ (candidate) => (candidate.textContent ?? '').trim() === 'Delete'
+ );
+
+ const frames = closingFrames(
+ await recordDialogExit(confirm, () =>
+ act(async () => {
+ confirmButton?.click();
+ await settleFrame();
+ })
+ )
+ );
+
+ expect(onDeleted).toHaveBeenCalledTimes(1);
+ expect(panel()).toBeNull();
+ expect(frames).not.toHaveLength(0);
+ // It still names the workflow it deleted while it animates out.
+ for (const frame of frames) {
+ expect(frame.text).toContain('Delete "Text to image"');
+ }
+ });
+
it('reports a failed delete without claiming the workflow is gone', async () => {
queries.deleteLibraryWorkflow.mockRejectedValue(new Error('network down'));
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
index f98572e9c7..f00ea891d5 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
@@ -100,7 +100,8 @@ export const WorkflowLibraryDetailPanel = ({
const { openDocumentInNewProject } = useWorkflowGraphPreview();
const openAddModels = useOpenAddModels();
const { installMany } = useInstallActions();
- const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
+ // The name is captured on request: a delete moves the selection, or empties this panel, before the dialog closes.
+ const [deleteTargetName, setDeleteTargetName] = useState<string | null>(null);
// Guard duplicate creation until the copy exists, including copies landing outside the visible category.
const [isDuplicatePending, setIsDuplicatePending] = useState(false);
const isDuplicatePendingRef = useRef(false);
@@ -311,8 +312,12 @@ export const WorkflowLibraryDetailPanel = ({
}, [entry, notify, t]);
const handleDownload = useCallback(() => void download(), [download]);
- const openDeleteConfirm = useCallback(() => setIsDeleteConfirmOpen(true), []);
- const closeDeleteConfirm = useCallback(() => setIsDeleteConfirmOpen(false), []);
+ const openDeleteConfirm = useCallback(() => {
+ if (entry) {
+ setDeleteTargetName(entry.item.name || t('workflowLibrary.untitled'));
+ }
+ }, [entry, t]);
+ const closeDeleteConfirm = useCallback(() => setDeleteTargetName(null), []);
// A pointer point is a fixed rect; the tile button is the menu's trigger, so the menu follows it as it scrolls.
const contextMenuPositioning = useMemo(
@@ -366,14 +371,9 @@ export const WorkflowLibraryDetailPanel = ({
}
}, [entry, notify, onDeleted, t]);
- if (!entry) {
- return (
- <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />
- );
- }
-
- const { item, tags } = entry;
- const name = item.name || t('workflowLibrary.untitled');
+ const item = entry?.item ?? null;
+ const tags = entry?.tags ?? [];
+ const name = item ? item.name || t('workflowLibrary.untitled') : '';
const openLabel = hasCopies ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open');
// One item set behind both the rail's overflow button and a card's right-click.
@@ -408,7 +408,7 @@ export const WorkflowLibraryDetailPanel = ({
value="download-json"
onSelect={handleDownload}
/>
- {item.category === 'user' ? (
+ {item?.category === 'user' ? (
<MenuActionItem
hint={t('workflowLibrary.renameTemplateHint')}
icon={PencilIcon}
@@ -417,7 +417,7 @@ export const WorkflowLibraryDetailPanel = ({
onSelect={openRename}
/>
) : null}
- {item.category === 'user' ? (
+ {item?.category === 'user' ? (
// Bundled defaults are not the account's to delete.
<MenuActionItem
hint={t('workflowLibrary.deleteHint')}
@@ -432,133 +432,146 @@ export const WorkflowLibraryDetailPanel = ({
);
return (
- <Stack
- borderColor="border.subtle"
- borderWidth="1px"
- data-workflow-detail={item.workflow_id}
- flexShrink={0}
- gap="0"
- minH="0"
- rounded="md"
- w={DETAIL_RAIL_WIDTH}
- >
- <Scrollable flex="1" label={name} minH="0">
- <Stack gap="2" minW="0" p="2.5">
- <WorkflowLibraryThumbnail
- key={item.workflow_id}
- item={item}
- workflowDocument={entry.enrichment.status === 'ready' ? entry.enrichment.document : null}
- />
-
- {/*
- * Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits
- * containment without truncation.
- */}
- <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">
- {name}
- </Text>
-
- {item.description ? (
- <Text color="fg.muted" fontSize="xs" lineClamp={4}>
- {item.description}
- </Text>
- ) : null}
-
- {tags.length > 0 ? (
- <HStack flexWrap="wrap" gap="1" minW="0">
- {tags.map((tag) => (
- <Badge key={tag} variant="subtle">
- {tag}
- </Badge>
- ))}
+ <>
+ {item ? (
+ <Stack
+ borderColor="border.subtle"
+ borderWidth="1px"
+ data-workflow-detail={item.workflow_id}
+ flexShrink={0}
+ gap="0"
+ minH="0"
+ rounded="md"
+ w={DETAIL_RAIL_WIDTH}
+ >
+ <Scrollable flex="1" label={name} minH="0">
+ <Stack gap="2" minW="0" p="2.5">
+ <WorkflowLibraryThumbnail
+ key={item.workflow_id}
+ item={item}
+ workflowDocument={enrichment?.status === 'ready' ? enrichment.document : null}
+ />
+
+ {/*
+ * Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits
+ * containment without truncation.
+ */}
+ <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">
+ {name}
+ </Text>
+
+ {item.description ? (
+ <Text color="fg.muted" fontSize="xs" lineClamp={4}>
+ {item.description}
+ </Text>
+ ) : null}
+
+ {tags.length > 0 ? (
+ <HStack flexWrap="wrap" gap="1" minW="0">
+ {tags.map((tag) => (
+ <Badge key={tag} variant="subtle">
+ {tag}
+ </Badge>
+ ))}
+ </HStack>
+ ) : null}
+
+ <WorkflowRequirementsList
+ errorMessage={enrichment?.status === 'error' ? enrichment.message : null}
+ resolved={resolved}
+ onFindModel={handleFindModel}
+ />
+ </Stack>
+ </Scrollable>
+
+ <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">
+ <HStack gap="2" minW="0">
+ {installableCount > 0 ? (
+ <Button
+ bg="bg.warning"
+ color="fg.warning"
+ flex="1"
+ minW="0"
+ size="lg"
+ _hover={INSTALL_HOVER}
+ onClick={handleInstall}
+ >
+ {t('workflowLibrary.installModels', { count: installableCount })}
+ </Button>
+ ) : (
+ <Button flex="1" minW="0" size="lg" onClick={handleOpen}>
+ {openLabel}
+ </Button>
+ )}
+ <Menu.Root ids={moreActionsIds}>
+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the
+ menu never takes focus and the first pointer move onto it closes it. */}
+ <Menu.Trigger asChild>
+ <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>
+ <IconButton aria-label={t('workflowLibrary.moreActions')} size="lg" variant="outline">
+ <EllipsisIcon />
+ </IconButton>
+ </Tooltip>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="16rem">{actionItems}</MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
</HStack>
- ) : null}
-
- <WorkflowRequirementsList
- errorMessage={enrichment?.status === 'error' ? enrichment.message : null}
- resolved={resolved}
- onFindModel={handleFindModel}
- />
- </Stack>
- </Scrollable>
-
- <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">
- <HStack gap="2" minW="0">
- {installableCount > 0 ? (
<Button
- bg="bg.warning"
- color="fg.warning"
- flex="1"
- minW="0"
+ disabled={enrichment?.status !== 'ready'}
size="lg"
- _hover={INSTALL_HOVER}
- onClick={handleInstall}
+ variant="outline"
+ w="full"
+ onClick={handlePreview}
>
- {t('workflowLibrary.installModels', { count: installableCount })}
+ <WorkflowIcon />
+ {t('workflowLibrary.previewGraph')}
</Button>
- ) : (
- <Button flex="1" minW="0" size="lg" onClick={handleOpen}>
- {openLabel}
- </Button>
- )}
- <Menu.Root ids={moreActionsIds}>
- {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the
- menu never takes focus and the first pointer move onto it closes it. */}
- <Menu.Trigger asChild>
- <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>
- <IconButton aria-label={t('workflowLibrary.moreActions')} size="lg" variant="outline">
- <EllipsisIcon />
- </IconButton>
- </Tooltip>
- </Menu.Trigger>
+ </Stack>
+
+ {/* Naming the card as the trigger makes this a nested layer of the dialog: the
+ dialog's focus trap then lets the menu keep focus, and closing returns it to the card. */}
+ <Menu.Root
+ ids={contextMenuIds}
+ open={contextMenuPoint !== null}
+ positioning={contextMenuPositioning}
+ onOpenChange={handleContextMenuOpenChange}
+ onPointerDownOutside={keepCardMenuOpenForRetarget}
+ >
<Portal>
<Menu.Positioner>
- <MenuContent minW="16rem">{actionItems}</MenuContent>
+ <MenuContent data-workflow-context-menu minW="16rem">
+ {actionItems}
+ </MenuContent>
</Menu.Positioner>
</Portal>
</Menu.Root>
- </HStack>
- <Button disabled={enrichment?.status !== 'ready'} size="lg" variant="outline" w="full" onClick={handlePreview}>
- <WorkflowIcon />
- {t('workflowLibrary.previewGraph')}
- </Button>
- </Stack>
-
- {/* Naming the card as the trigger makes this a nested layer of the dialog: the
- dialog's focus trap then lets the menu keep focus, and closing returns it to the card. */}
- <Menu.Root
- ids={contextMenuIds}
- open={contextMenuPoint !== null}
- positioning={contextMenuPositioning}
- onOpenChange={handleContextMenuOpenChange}
- onPointerDownOutside={keepCardMenuOpenForRetarget}
- >
- <Portal>
- <Menu.Positioner>
- <MenuContent data-workflow-context-menu minW="16rem">
- {actionItems}
- </MenuContent>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
-
- <RenameDialog
- initialName={name}
- isOpen={isRenameOpen}
- label={t('workflowLibrary.templateName')}
- submitLabel={t('workflowLibrary.rename')}
- title={t('workflowLibrary.renameTemplateTitle')}
- onClose={closeRename}
- onSubmit={submitRename}
- />
+
+ <RenameDialog
+ initialName={name}
+ isOpen={isRenameOpen}
+ label={t('workflowLibrary.templateName')}
+ submitLabel={t('workflowLibrary.rename')}
+ title={t('workflowLibrary.renameTemplateTitle')}
+ onClose={closeRename}
+ onSubmit={submitRename}
+ />
+ </Stack>
+ ) : (
+ <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />
+ )}
+ {/* Outside the rail: a delete empties or retargets it while this dialog animates out. */}
<ConfirmDialog
- body={t('workflowLibrary.deleteConfirmBody', { name })}
+ body={t('workflowLibrary.deleteConfirmBody', { name: deleteTargetName ?? '' })}
confirmLabel={t('workflowLibrary.delete')}
- isOpen={isDeleteConfirmOpen}
+ isOpen={deleteTargetName !== null}
title={t('workflowLibrary.deleteConfirmTitle')}
onClose={closeDeleteConfirm}
onConfirm={confirmDelete}
/>
- </Stack>
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.browser.test.tsx b/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.browser.test.tsx
new file mode 100644
index 0000000000..7db13e8172
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.browser.test.tsx
@@ -0,0 +1,69 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useExitRetainedValue } from './useExitRetainedValue';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+const capture = vi.fn<(result: ReturnType<typeof useExitRetainedValue<{ name: string }>>) => void>();
+
+const Probe = ({ subject }: { subject: { name: string } | null }) => {
+ capture(useExitRetainedValue(subject));
+ return null;
+};
+
+const render = (subject: { name: string } | null) => act(() => root?.render(<Probe subject={subject} />));
+const retained = () => capture.mock.lastCall![0];
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ capture.mockClear();
+});
+
+describe('useExitRetainedValue', () => {
+ it('keeps the last open subject through the exit and drops it on release, never while open', async () => {
+ host = document.createElement('div');
+ root = createRoot(host);
+ const first = { name: 'first' };
+ const renamed = { name: 'renamed' };
+
+ await render(first);
+ const opened = retained().generation;
+ await act(() => retained().release());
+ expect(retained()).toMatchObject({ isOpen: true, value: first });
+
+ // A subject rebuilt while open updates in place rather than remounting.
+ await render(renamed);
+ expect(retained()).toMatchObject({ generation: opened, isOpen: true, value: renamed });
+
+ await render(null);
+ expect(retained()).toMatchObject({ generation: opened, isOpen: false, value: renamed });
+
+ await act(() => retained().release());
+ expect(retained().value).toBeNull();
+ });
+
+ it('gives a reopen during the exit a fresh generation and ignores the stale release', async () => {
+ host = document.createElement('div');
+ root = createRoot(host);
+ const subject = { name: 'subject' };
+
+ await render(subject);
+ const opened = retained().generation;
+ await render(null);
+ const releaseFirstExit = retained().release;
+
+ await render(subject);
+ expect(retained()).toMatchObject({ isOpen: true, value: subject });
+ expect(retained().generation).toBe(opened + 1);
+
+ await act(() => releaseFirstExit());
+ expect(retained()).toMatchObject({ isOpen: true, value: subject });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.ts b/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.ts
new file mode 100644
index 0000000000..cb6fefeb62
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/react/useExitRetainedValue.ts
@@ -0,0 +1,53 @@
+import { useCallback, useState } from 'react';
+
+interface Retained<Value> {
+ generation: number;
+ isOpen: boolean;
+ value: Value | null;
+}
+
+/**
+ * Keep an overlay's subject while its exit animation plays. Callers that render `{subject ? <Dialog open /> : null}`
+ * unmount the dialog the moment it closes, so it vanishes instead of animating out. Render while `value` is non-null,
+ * pass `isOpen` as the dialog's open state, `release` as its `onExitComplete`, and `generation` as its key so each
+ * open starts a fresh form.
+ *
+ * `generation` changes only when the overlay opens, so a subject that changes while open (a refreshed record)
+ * updates `value` without remounting. An object subject must keep its identity while its inputs are unchanged
+ * (memoize it): a new object on every render never settles. Release relies on the overlay reporting its exit:
+ * one that closes before it ever rendered open (a lazy chunk still loading) reports nothing, so the last value stays
+ * mounted, closed and inert, until the next open replaces it.
+ */
+export const useExitRetainedValue = <Value extends NonNullable<unknown>>(subject: Value | null) => {
+ const [retained, setRetained] = useState<Retained<Value>>(() => ({
+ generation: subject === null ? 0 : 1,
+ isOpen: subject !== null,
+ value: subject,
+ }));
+ const isOpen = subject !== null;
+
+ // Adjusted during render (React's pattern for state derived from a changing prop), so the overlay never renders a
+ // frame with a stale open state.
+ if (isOpen && !retained.isOpen) {
+ setRetained({ generation: retained.generation + 1, isOpen: true, value: subject });
+ } else if (isOpen && retained.value !== subject) {
+ // Track the latest open subject, so the closing overlay shows what it last showed.
+ setRetained({ ...retained, value: subject });
+ } else if (!isOpen && retained.isOpen) {
+ setRetained({ ...retained, isOpen: false });
+ }
+
+ const release = useCallback(
+ () => setRetained((current) => (current.isOpen ? current : { ...current, value: null })),
+ []
+ );
+
+ return { generation: retained.generation, isOpen, release, value: isOpen ? subject : retained.value };
+};
+
+/** `useExitRetainedValue` for an overlay with no subject: `isMounted` stays true until its exit animation ends. */
+export const useExitPresence = (isOpen: boolean) => {
+ const { generation, release, value } = useExitRetainedValue(isOpen ? true : null);
+
+ return { generation, isMounted: value !== null, isOpen, release };
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
new file mode 100644
index 0000000000..fbd9dcf6f1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
@@ -0,0 +1,61 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act, useCallback, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { ConfirmDialog } from './ConfirmDialog';
+import { closingFrames, recordDialogExit } from './dialogExit.testing';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const noop = () => undefined;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('ConfirmDialog', () => {
+ it('keeps the text it showed while it animates out after its host clears the subject', async () => {
+ // The usual host shape: the subject drives the copy and is cleared the moment the dialog closes.
+ const Host = () => {
+ const [subject, setSubject] = useState<string | null>('Sunset');
+ const close = useCallback(() => setSubject(null), []);
+
+ return (
+ <ChakraProvider value={system}>
+ <ConfirmDialog
+ body={`Delete ${subject ?? ''}?`}
+ confirmLabel={subject ? 'Delete' : 'OK'}
+ isOpen={subject !== null}
+ title={subject ? 'Delete image' : 'Delete items'}
+ onClose={close}
+ onConfirm={noop}
+ />
+ </ChakraProvider>
+ );
+ };
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => root?.render(<Host />));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+ const confirm = [...dialog.querySelectorAll('button')].find((button) => button.textContent === 'Delete')!;
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.click(confirm))));
+
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toContain('Delete image');
+ expect(frame.text).toContain('Delete Sunset?');
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
index 6858946d56..5f71570d32 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
@@ -1,5 +1,6 @@
import { Dialog, Portal, Stack, Text } from '@chakra-ui/react';
-import { useCallback, useRef, useState, type ReactNode } from 'react';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
+import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';
import { Button, CloseButton } from './Button';
@@ -12,6 +13,7 @@ export const ConfirmDialog = ({
isOpen,
onClose,
onConfirm,
+ onExitComplete,
title,
}: {
body: ReactNode;
@@ -22,10 +24,24 @@ export const ConfirmDialog = ({
isOpen: boolean;
onClose: () => void;
onConfirm: () => Promise<void> | void;
+ /** After the close animation; hosts that retain the dialog's subject release it here. */
+ onExitComplete?: () => void;
title: string;
}) => {
const [isPending, setIsPending] = useState(false);
const isPendingRef = useRef(false);
+ // Hosts often clear the subject the dialog describes as it closes; keep the text it showed while it animates out.
+ const live = useMemo(
+ () => ({ body, confirmLabel, isDestructive, title }),
+ [body, confirmLabel, isDestructive, title]
+ );
+ const shown = useExitRetainedValue(isOpen ? live : null);
+ const text = shown.value ?? live;
+ const { release } = shown;
+ const handleExitComplete = useCallback(() => {
+ release();
+ onExitComplete?.();
+ }, [onExitComplete, release]);
const handleConfirm = useCallback(async () => {
if (isPendingRef.current) {
@@ -71,6 +87,7 @@ export const ConfirmDialog = ({
open={isOpen}
role="alertdialog"
size="sm"
+ onExitComplete={handleExitComplete}
onOpenChange={handleOpenChange}
>
<Portal>
@@ -78,23 +95,25 @@ export const ConfirmDialog = ({
<Dialog.Positioner>
<Dialog.Content>
<Dialog.Header>
- <Dialog.Title>{title}</Dialog.Title>
+ <Dialog.Title>{text.title}</Dialog.Title>
</Dialog.Header>
<Dialog.Body>
- <Stack gap="2">{typeof body === 'string' ? <Text fontSize="md">{body}</Text> : body}</Stack>
+ <Stack gap="2">
+ {typeof text.body === 'string' ? <Text fontSize="md">{text.body}</Text> : text.body}
+ </Stack>
</Dialog.Body>
<Dialog.Footer>
<Button disabled={isPending} variant="ghost" onClick={handleClose}>
Cancel
</Button>
<Button
- colorPalette={isDestructive ? 'red' : 'accent'}
+ colorPalette={text.isDestructive ? 'red' : 'accent'}
disabled={isPending}
loading={isPending}
variant="solid"
onClick={handleConfirmClick}
>
- {confirmLabel}
+ {text.confirmLabel}
</Button>
</Dialog.Footer>
<Dialog.CloseTrigger asChild>
diff --git a/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx
index 94e0c4404e..9e7bc16855 100644
--- a/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx
@@ -1,5 +1,6 @@
import { chakra, Dialog, Input, Portal, Stack } from '@chakra-ui/react';
-import { useCallback, useState, type FormEvent } from 'react';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
+import { useCallback, useMemo, useState, type FormEvent } from 'react';
import { Button, CloseButton } from './Button';
import { Field } from './Field';
@@ -11,6 +12,7 @@ export const RenameDialog = ({
isOpen,
label = 'Project name',
onClose,
+ onExitComplete,
onSubmit,
submitLabel = 'Rename',
submitUnchanged = false,
@@ -21,12 +23,23 @@ export const RenameDialog = ({
isOpen: boolean;
label?: string;
onClose: () => void;
+ /** After the close animation; hosts that retain the dialog's subject release it here. */
+ onExitComplete?: () => void;
onSubmit: (name: string) => Promise<void> | void;
submitLabel?: string;
submitUnchanged?: boolean;
title?: string;
}) => {
const [isPending, setIsPending] = useState(false);
+ // Keep the labels the dialog showed while it animates out, even if the host clears its subject on close.
+ const live = useMemo(() => ({ label, submitLabel, title }), [label, submitLabel, title]);
+ const shown = useExitRetainedValue(isOpen ? live : null);
+ const text = shown.value ?? live;
+ const { release } = shown;
+ const handleExitComplete = useCallback(() => {
+ release();
+ onExitComplete?.();
+ }, [onExitComplete, release]);
const commit = useCallback(
async (value: string) => {
@@ -76,6 +89,7 @@ export const RenameDialog = ({
open={isOpen}
size="xs"
unmountOnExit
+ onExitComplete={handleExitComplete}
onOpenChange={handleOpenChange}
>
<Portal>
@@ -84,11 +98,11 @@ export const RenameDialog = ({
<Dialog.Content>
<chakra.form onSubmit={handleSubmit}>
<Dialog.Header>
- <Dialog.Title>{title}</Dialog.Title>
+ <Dialog.Title>{text.title}</Dialog.Title>
</Dialog.Header>
<Dialog.Body>
<Stack gap="2">
- <Field label={label}>
+ <Field label={text.label}>
<Input autoFocus defaultValue={initialName} name="renameValue" size="lg" />
</Field>
</Stack>
@@ -98,7 +112,7 @@ export const RenameDialog = ({
Cancel
</Button>
<Button loading={isPending} type="submit" variant="solid">
- {submitLabel}
+ {text.submitLabel}
</Button>
</Dialog.Footer>
</chakra.form>
diff --git a/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts b/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts
new file mode 100644
index 0000000000..9868b00ba4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts
@@ -0,0 +1,35 @@
+import { expect } from 'vitest';
+
+export interface DialogExitFrame {
+ state: string | null;
+ text: string;
+}
+
+/**
+ * Close an open dialog and record each `data-state` it passes through, with its text at that moment, until it
+ * unmounts or settles closed. A dialog its host unmounted on close never reaches `closed`, so it cannot have animated
+ * out; the text shows what it displayed while it did. Independent of animation duration and reduced motion.
+ */
+export const recordDialogExit = async (
+ dialog: Element,
+ close: () => Promise<unknown> | unknown
+): Promise<DialogExitFrame[]> => {
+ const frames: DialogExitFrame[] = [];
+ const observer = new MutationObserver(() =>
+ frames.push({ state: dialog.getAttribute('data-state'), text: dialog.textContent ?? '' })
+ );
+ observer.observe(dialog, { attributeFilter: ['data-state'] });
+
+ try {
+ await close();
+ await expect.poll(() => !dialog.isConnected || dialog.getAttribute('data-state') === 'closed').toBe(true);
+ } finally {
+ observer.disconnect();
+ }
+
+ return frames;
+};
+
+/** The frames a dialog showed while closing; empty when its host unmounted it instead. */
+export const closingFrames = (frames: readonly DialogExitFrame[]): DialogExitFrame[] =>
+ frames.filter((frame) => frame.state === 'closed');
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
index 0017381c71..ee3f615283 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
@@ -1,4 +1,6 @@
import { ChakraProvider } from '@chakra-ui/react';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import i18n from 'i18next';
@@ -79,21 +81,55 @@ const entry = (id: string, title: string, run = vi.fn()): PaletteEntry => ({
const storeHostEntries = [entry('first', 'First command')];
+/** Mirrors the Workbench and Launchpad hosts: mounted while open, then until the close animation finishes. */
const StorePaletteHost = () => {
const isOpen = useIsCommandPaletteOpen();
+ const dialog = useExitPresence(isOpen);
return (
<>
<button type="button" onClick={openCommandPalette}>
Open palette
</button>
- {isOpen ? (
- <CommandPaletteDialog entries={storeHostEntries} isOpen modifierKeyLabel="ctrl" onClose={closeCommandPalette} />
+ {dialog.isMounted ? (
+ <CommandPaletteDialog
+ key={dialog.generation}
+ entries={storeHostEntries}
+ isOpen={isOpen}
+ modifierKeyLabel="ctrl"
+ onClose={closeCommandPalette}
+ onExitComplete={dialog.release}
+ />
) : null}
</>
);
};
+const renderStorePaletteHost = async () => {
+ await i18nReady;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={new QueryClient()}>
+ <StorePaletteHost />
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+ });
+ const button = document.querySelector<HTMLButtonElement>('button');
+ expect(button).not.toBeNull();
+
+ return button!;
+};
+
const renderPalette = async ({
entries,
onClose = vi.fn(),
@@ -162,28 +198,9 @@ afterEach(async () => {
describe('CommandPaletteDialog interaction', () => {
it('restores focus through the store-driven host lifecycle and preserves the first return target', async () => {
- await i18nReady;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- await act(async () => {
- root?.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <QueryClientProvider client={new QueryClient()}>
- <StorePaletteHost />
- </QueryClientProvider>
- </ChakraProvider>
- </I18nextProvider>
- );
- await new Promise<void>((resolve) => {
- requestAnimationFrame(() => resolve());
- });
- });
- const button = document.querySelector<HTMLButtonElement>('button');
- expect(button).not.toBeNull();
+ const button = await renderStorePaletteHost();
- await act(() => userEvent.click(button!));
+ await act(() => userEvent.click(button));
const input = await waitFor(() => {
const node = document.querySelector<HTMLInputElement>('[name="command-palette-query"]');
expect(node).not.toBeNull();
@@ -196,6 +213,19 @@ describe('CommandPaletteDialog interaction', () => {
await waitFor(() => expect(document.activeElement).toBe(button));
});
+ it('animates the palette out instead of unmounting it on close', async () => {
+ const button = await renderStorePaletteHost();
+ await act(() => userEvent.click(button));
+ await waitFor(() => expect(document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open'));
+ const dialog = document.querySelector('[role="dialog"]')!;
+
+ const frames = await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}')));
+
+ // An unmounted palette never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(closingFrames(frames)).not.toHaveLength(0);
+ await waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
+ });
+
it('exposes an accessible focused search field and runs the stable highlighted command in bare > mode', async () => {
const firstRun = vi.fn();
const secondRun = vi.fn();
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
index a884bbd54f..ba196a351c 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
@@ -47,12 +47,15 @@ export const CommandPaletteDialog = ({
isOpen,
modifierKeyLabel,
onClose,
+ onExitComplete,
providers = NO_PROVIDERS,
}: {
entries: PaletteEntry[];
isOpen: boolean;
modifierKeyLabel: string;
onClose: () => void;
+ /** After the close animation; hosts that keep the palette mounted while it closes unmount it here. */
+ onExitComplete?: () => void;
providers?: PaletteSearchProvider[];
}) => {
const onDialogOpenChange = useCallback(
@@ -74,16 +77,16 @@ export const CommandPaletteDialog = ({
restoreFocus
scrollBehavior="inside"
unmountOnExit
+ onExitComplete={onExitComplete}
onOpenChange={onDialogOpenChange}
>
- {isOpen ? (
- <CommandPaletteContent
- entries={entries}
- modifierKeyLabel={modifierKeyLabel}
- providers={providers}
- onClose={onClose}
- />
- ) : null}
+ <CommandPaletteContent
+ entries={entries}
+ isOpen={isOpen}
+ modifierKeyLabel={modifierKeyLabel}
+ providers={providers}
+ onClose={onClose}
+ />
</Dialog.Root>
);
};
@@ -92,11 +95,13 @@ export default CommandPaletteDialog;
const CommandPaletteContent = ({
entries,
+ isOpen,
modifierKeyLabel,
onClose,
providers,
}: {
entries: PaletteEntry[];
+ isOpen: boolean;
modifierKeyLabel: string;
onClose: () => void;
providers: PaletteSearchProvider[];
@@ -143,7 +148,8 @@ const CommandPaletteContent = ({
return (
<Portal>
- {controller.stage?.clearPreview ? <StagePreviewLifetime stage={controller.stage} /> : null}
+ {/* A preview ends when the palette closes, not when its exit animation finishes. */}
+ {isOpen && controller.stage?.clearPreview ? <StagePreviewLifetime stage={controller.stage} /> : null}
<Dialog.Backdrop bg="blackAlpha.300" />
<Dialog.Positioner alignItems="flex-start" pt="15vh">
<Dialog.Content
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteHotkey.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteHotkey.browser.test.tsx
index 59ccf1fccb..232154835f 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteHotkey.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteHotkey.browser.test.tsx
@@ -28,10 +28,24 @@ vi.mock('react-i18next', () => ({
}),
}));
+const launchpadDialog = vi.hoisted(() => ({ onExitComplete: null as (() => void) | null }));
+
vi.mock('./LaunchpadCommandPaletteDialog', () => ({
- default: ({ modifierKeyLabel }: { modifierKeyLabel: string }) => (
- <div data-modifier-key-label={modifierKeyLabel} data-testid="launchpad-palette" />
- ),
+ default: ({
+ isOpen,
+ modifierKeyLabel,
+ onExitComplete,
+ }: {
+ isOpen: boolean;
+ modifierKeyLabel: string;
+ onExitComplete: () => void;
+ }) => {
+ launchpadDialog.onExitComplete = onExitComplete;
+
+ return (
+ <div data-modifier-key-label={modifierKeyLabel} data-open={String(isOpen)} data-testid="launchpad-palette" />
+ );
+ },
}));
import { LaunchpadCommandPalette } from './LaunchpadCommandPalette';
@@ -103,6 +117,21 @@ describe('Launchpad command-palette hotkeys', () => {
expectPaletteState('closed');
});
+ it('keeps the lazy dialog mounted while it animates closed, then unmounts it', async () => {
+ await renderLaunchpad();
+ const palette = () => document.querySelector<HTMLElement>('[data-testid="launchpad-palette"]');
+
+ await press({ code: 'KeyK', ctrlKey: true, key: 'k' });
+ await expect.poll(() => palette()?.dataset.open).toBe('true');
+
+ await press({ code: 'KeyK', ctrlKey: true, key: 'k' });
+ expectPaletteState('closed');
+ expect(palette()?.dataset.open).toBe('false');
+
+ await act(() => launchpadDialog.onExitComplete?.());
+ expect(palette()).toBeNull();
+ });
+
it('replaces the default binding and installs every custom binding', async () => {
testPreferences.customHotkeys = { 'app.openCommandPalette': ['alt+p', 'alt+o'] };
await renderLaunchpad();
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
index 4a050ef63f..ba65348228 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
@@ -1,3 +1,4 @@
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { OPEN_COMMAND_PALETTE_HOTKEY } from '@workbench/hotkeys/catalog';
import { MOD_KEY_LABEL, toTinykeysBinding } from '@workbench/hotkeys/keys';
@@ -29,30 +30,41 @@ const LaunchpadCommandPaletteHotkeys = ({ keys }: { keys: readonly string[] }) =
return null;
};
-/** Lightweight Launchpad runtime and lazy dialog host. */
+/** Lightweight Launchpad runtime and lazy dialog host; the dialog stays mounted while it animates closed. */
export const LaunchpadCommandPalette = () => {
const isOpen = useIsCommandPaletteOpen();
+ const dialog = useExitPresence(isOpen);
const customHotkeys = useWorkbenchPreferenceSelector((preferences) => preferences.customHotkeys);
const paletteHotkeys = applyCustomHotkeys(OPEN_COMMAND_PALETTE_HOTKEY, customHotkeys).keys;
return (
<>
<LaunchpadCommandPaletteHotkeys key={paletteHotkeys.join('\n')} keys={paletteHotkeys} />
- {isOpen ? <OpenLaunchpadCommandPalette /> : null}
+ {dialog.isMounted ? (
+ <MountedLaunchpadCommandPalette key={dialog.generation} isOpen={isOpen} onExitComplete={dialog.release} />
+ ) : null}
</>
);
};
-const OpenLaunchpadCommandPalette = () => {
+const MountedLaunchpadCommandPalette = ({
+ isOpen,
+ onExitComplete,
+}: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+}) => {
const preferences = useWorkbenchPreferences();
return (
<Suspense fallback={null}>
<LazyLaunchpadCommandPaletteDialog
+ isOpen={isOpen}
modifierKeyLabel={MOD_KEY_LABEL}
preferences={preferences}
settingsEntryDeps={SETTINGS_ENTRY_DEPS}
onClose={closeCommandPalette}
+ onExitComplete={onExitComplete}
/>
</Suspense>
);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
index a5cbb0c8ee..425e61f8be 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
@@ -13,13 +13,17 @@ import { buildOpenSettingsEntry, buildSettingsEntries } from './entries';
/** Launchpad-only palette adapter: navigation and settings, no editor providers. */
const LaunchpadCommandPaletteDialog = ({
+ isOpen,
modifierKeyLabel,
onClose,
+ onExitComplete,
preferences,
settingsEntryDeps,
}: {
+ isOpen: boolean;
modifierKeyLabel: string;
onClose: () => void;
+ onExitComplete: () => void;
preferences: WorkbenchPreferences;
settingsEntryDeps: SettingsEntryDeps;
}) => {
@@ -82,7 +86,15 @@ const LaunchpadCommandPaletteDialog = ({
t,
]);
- return <CommandPaletteDialog entries={entries} isOpen modifierKeyLabel={modifierKeyLabel} onClose={onClose} />;
+ return (
+ <CommandPaletteDialog
+ entries={entries}
+ isOpen={isOpen}
+ modifierKeyLabel={modifierKeyLabel}
+ onClose={onClose}
+ onExitComplete={onExitComplete}
+ />
+ );
};
export default LaunchpadCommandPaletteDialog;
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.browser.test.tsx
new file mode 100644
index 0000000000..ff01ff0f94
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.browser.test.tsx
@@ -0,0 +1,93 @@
+import type * as settingsStoreModule from '@workbench/settings/store';
+
+import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const workbenchDialog = vi.hoisted(() => ({ mounts: 0, onExitComplete: null as (() => void) | null }));
+
+vi.mock('@workbench/settings/store', async (importOriginal) => ({
+ ...(await importOriginal<typeof settingsStoreModule>()),
+ useWorkbenchPreferences: () => ({}),
+}));
+
+vi.mock('./WorkbenchCommandPaletteDialog', async () => {
+ const { useMountEffect } = await import('@platform/react/useMountEffect');
+
+ const WorkbenchCommandPaletteDialog = ({
+ isOpen,
+ onExitComplete,
+ }: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+ }) => {
+ useMountEffect(() => {
+ workbenchDialog.mounts += 1;
+ workbenchDialog.onExitComplete = onExitComplete;
+ });
+
+ return <div data-open={String(isOpen)} data-testid="workbench-palette" />;
+ };
+
+ return { default: WorkbenchCommandPaletteDialog };
+});
+
+import { closeCommandPalette, openCommandPalette } from './paletteStore';
+import { WorkbenchCommandPalette } from './WorkbenchCommandPalette';
+
+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 palette = () => document.querySelector<HTMLElement>('[data-testid="workbench-palette"]');
+
+beforeEach(async () => {
+ workbenchDialog.mounts = 0;
+ workbenchDialog.onExitComplete = null;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => root?.render(<WorkbenchCommandPalette />));
+});
+
+afterEach(async () => {
+ await act(() => {
+ closeCommandPalette();
+ root?.unmount();
+ });
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('WorkbenchCommandPalette host', () => {
+ it('keeps the lazy dialog mounted while it animates closed, but releases workbench hotkeys at close', async () => {
+ await act(() => openCommandPalette());
+ await expect.poll(() => palette()?.dataset.open).toBe('true');
+ expect(isHotkeyModalLayerActive()).toBe(true);
+
+ await act(() => closeCommandPalette());
+ expect(palette()?.dataset.open).toBe('false');
+ expect(isHotkeyModalLayerActive()).toBe(false);
+
+ await act(() => workbenchDialog.onExitComplete?.());
+ expect(palette()).toBeNull();
+
+ // Each open starts a fresh palette rather than reusing the one that closed.
+ await act(() => openCommandPalette());
+ await expect.poll(() => palette()?.dataset.open).toBe('true');
+ expect(workbenchDialog.mounts).toBe(2);
+ });
+
+ it('starts a fresh palette when reopened before the previous one finished closing', async () => {
+ await act(() => openCommandPalette());
+ await expect.poll(() => palette()?.dataset.open).toBe('true');
+ await act(() => closeCommandPalette());
+
+ await act(() => openCommandPalette());
+ expect(palette()?.dataset.open).toBe('true');
+ expect(workbenchDialog.mounts).toBe(2);
+ expect(isHotkeyModalLayerActive()).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
index d848e0e51e..6fd4b24acc 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
@@ -1,4 +1,5 @@
import { requestQueueItemReveal } from '@features/queue/reveal';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
import { formatHotkeyForPlatform, MOD_KEY_LABEL } from '@workbench/hotkeys/keys';
@@ -15,30 +16,48 @@ export const loadWorkbenchCommandPaletteDialog = () => import('./WorkbenchComman
const LazyWorkbenchCommandPaletteDialog = lazy(loadWorkbenchCommandPaletteDialog);
-/** Lightweight route host; the palette implementation is loaded only while open. */
+/** Lightweight route host; the palette implementation is loaded only while open or animating closed. */
export const WorkbenchCommandPalette = () => {
const isOpen = useIsCommandPaletteOpen();
+ const dialog = useExitPresence(isOpen);
- return isOpen ? <OpenWorkbenchCommandPalette /> : null;
+ return dialog.isMounted ? (
+ <>
+ {isOpen ? <CommandPaletteModalLayer /> : null}
+ <MountedWorkbenchCommandPalette key={dialog.generation} isOpen={isOpen} onExitComplete={dialog.release} />
+ </>
+ ) : null;
};
-const OpenWorkbenchCommandPalette = () => {
- const preferences = useWorkbenchPreferences();
-
+const CommandPaletteModalLayer = () => {
useMountEffect(() => registerHotkeyModalLayer('command-palette'));
+ return null;
+};
+
+const MountedWorkbenchCommandPalette = ({
+ isOpen,
+ onExitComplete,
+}: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+}) => {
+ const preferences = useWorkbenchPreferences();
+
return (
<Suspense fallback={null}>
<LazyWorkbenchCommandPaletteDialog
catalog={firstPartyHotkeyCatalog}
formatHotkey={formatHotkeyForPlatform}
getWidgetsForRegion={getWidgetsForRegion}
+ isOpen={isOpen}
modifierKeyLabel={MOD_KEY_LABEL}
openWidgetPlacement={openWidgetPlacement}
preferences={preferences}
requestQueueItemReveal={requestQueueItemReveal}
settingsEntryDeps={SETTINGS_ENTRY_DEPS}
onClose={closeCommandPalette}
+ onExitComplete={onExitComplete}
/>
</Suspense>
);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
index b9d847fa30..bcaae355ed 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
@@ -61,8 +61,10 @@ const WorkbenchCommandPaletteDialog = ({
catalog,
formatHotkey,
getWidgetsForRegion,
+ isOpen,
modifierKeyLabel,
onClose,
+ onExitComplete,
openWidgetPlacement,
preferences,
requestQueueItemReveal,
@@ -71,8 +73,10 @@ const WorkbenchCommandPaletteDialog = ({
catalog: readonly HotkeyDefinition[];
formatHotkey: (hotkey: string) => string[];
getWidgetsForRegion: typeof GetWidgetsForRegion;
+ isOpen: boolean;
modifierKeyLabel: string;
onClose: () => void;
+ onExitComplete: () => void;
openWidgetPlacement: typeof OpenWidgetPlacement;
preferences: WorkbenchPreferences;
requestQueueItemReveal: (itemId: number) => void;
@@ -273,10 +277,11 @@ const WorkbenchCommandPaletteDialog = ({
return (
<CommandPaletteDialog
entries={entries}
- isOpen
+ isOpen={isOpen}
modifierKeyLabel={modifierKeyLabel}
providers={providers}
onClose={onClose}
+ onExitComplete={onExitComplete}
/>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx
index 77d5656b45..1063a10332 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsDialog.tsx
@@ -7,10 +7,23 @@ import { useTranslation } from 'react-i18next';
import type { ProjectFileOptionsRequest } from './ProjectFileOptionsProvider';
-export const ProjectFileOptionsDialog = ({ request }: { request: ProjectFileOptionsRequest }) => {
+const ProjectFileOptionsModalLayer = () => {
+ useMountEffect(() => registerHotkeyModalLayer('project-file-options'));
+
+ return null;
+};
+
+export const ProjectFileOptionsDialog = ({
+ isOpen,
+ onExitComplete,
+ request,
+}: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+ request: ProjectFileOptionsRequest;
+}) => {
const { t } = useTranslation();
const [includeFonts, setIncludeFonts] = useState(false);
- useMountEffect(() => registerHotkeyModalLayer('project-file-options'));
const close = useCallback(() => request.settle(null), [request]);
const isExport = request.kind === 'export';
const returnFocus = useCallback(
@@ -32,7 +45,15 @@ export const ProjectFileOptionsDialog = ({ request }: { request: ProjectFileOpti
const confirm = useCallback(() => request.settle({ includeFonts }), [includeFonts, request]);
return (
- <Dialog.Root open placement="center" size="sm" finalFocusEl={returnFocus} onOpenChange={handleOpenChange}>
+ <Dialog.Root
+ open={isOpen}
+ placement="center"
+ size="sm"
+ finalFocusEl={returnFocus}
+ onExitComplete={onExitComplete}
+ onOpenChange={handleOpenChange}
+ >
+ {isOpen ? <ProjectFileOptionsModalLayer /> : null}
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx
index c835c9d911..a730863bde 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.browser.test.tsx
@@ -2,7 +2,9 @@ import { ChakraProvider } from '@chakra-ui/react';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import { settleAnimations } from '@platform/browser/settleAnimations.testing';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
+import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -91,3 +93,22 @@ it('cancels a pending choice when its account goes away', async () => {
expect(results).toEqual([null]);
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
});
+
+it('animates the dialog out instead of unmounting it when the choice settles', async () => {
+ await render();
+ await act(() => page.getByRole('button', { name: 'Export', exact: true }).click());
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="dialog"]')!;
+
+ const frames = await recordDialogExit(dialog, async () => {
+ await act(() => page.getByRole('button', { name: 'Cancel', exact: true }).click());
+ expect(results).toEqual([null]);
+ // Workbench hotkeys resume at close, not after the exit animation.
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ });
+
+ // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(closingFrames(frames)).not.toHaveLength(0);
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+ expect(results).toEqual([null]);
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx
index 98ecf1ae83..a9f81a95c8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.tsx
@@ -1,3 +1,4 @@
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { type AccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import {
@@ -45,6 +46,8 @@ export const useProjectFileOptions = (): ProjectFileOptionsControl => {
export const ProjectFileOptionsProvider = ({ children }: { children: ReactNode }) => {
const [request, setRequest] = useState<ProjectFileOptionsRequest | null>(null);
+ // Settling closes the dialog; its request stays rendered until the close animation finishes.
+ const dialog = useExitRetainedValue(request);
const current = useRef<ProjectFileOptionsRequest | null>(null);
const ticket = useRef(0);
const requestOptions = useCallback((kind: ProjectFileOptionsRequest['kind'], name: string, owner: AccountScope) => {
@@ -86,9 +89,14 @@ export const ProjectFileOptionsProvider = ({ children }: { children: ReactNode }
return (
<ProjectFileOptionsContext.Provider value={control}>
{children}
- {request ? (
+ {dialog.value ? (
<Suspense fallback={null}>
- <ProjectFileOptionsDialog key={request.ticket} request={request} />
+ <ProjectFileOptionsDialog
+ key={dialog.value.ticket}
+ isOpen={dialog.isOpen}
+ request={dialog.value}
+ onExitComplete={dialog.release}
+ />
</Suspense>
) : null}
</ProjectFileOptionsContext.Provider>
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx
index 8254785466..82db26cb0e 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx
@@ -44,16 +44,40 @@ vi.mock('@platform/state/accountLifecycle', () => ({
captureAccountScope: () => harness.owner,
isAccountScopeCurrent: () => harness.accountCurrent,
}));
+// Exposes whether the host keeps the dialog mounted (the real one needs that to animate out); like the real dialog,
+// it closes after confirming even when the confirmation fails.
vi.mock('@platform/ui/ConfirmDialog', () => ({
- ConfirmDialog: ({ body, isOpen, onConfirm }: { body: string; isOpen: boolean; onConfirm(): Promise<void> | void }) =>
- isOpen ? (
- <div>
- <span>{body}</span>
- <button data-testid="confirm-discard" onClick={() => void onConfirm()}>
- confirm
- </button>
- </div>
- ) : null,
+ ConfirmDialog: ({
+ body,
+ isOpen,
+ onClose,
+ onConfirm,
+ }: {
+ body: string;
+ isOpen: boolean;
+ onClose(): void;
+ onConfirm(): Promise<void> | void;
+ }) => (
+ <div data-open={String(isOpen)} data-testid="discard-dialog">
+ {isOpen ? (
+ <>
+ <span>{body}</span>
+ <button
+ data-testid="confirm-discard"
+ onClick={async () => {
+ try {
+ await onConfirm();
+ } finally {
+ onClose();
+ }
+ }}
+ >
+ confirm
+ </button>
+ </>
+ ) : null}
+ </div>
+ ),
}));
vi.mock('@workbench/projects/projectLifecycleLocks', () => ({
acquireProjectMutationLock: vi.fn(() => Promise.resolve(harness.lockResult)),
@@ -195,6 +219,22 @@ describe('QueueRecoveryNotice', () => {
expect(harness.lockResult.kind === 'acquired' ? harness.lockResult.release : undefined).toHaveBeenCalledOnce();
});
+ it('keeps the discard confirmation mounted to animate out when the last project is discarded', async () => {
+ let remaining = ['closed-1'];
+ harness.listProjectIds.mockImplementation(() => Promise.resolve({ kind: 'available', projectIds: [...remaining] }));
+ harness.deleteForProject.mockImplementation(() => {
+ remaining = [];
+ return Promise.resolve({ kind: 'removed' });
+ });
+ await renderNotice();
+ await clickButton('shell.queueRecovery.discard');
+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-discard"]')!));
+ await vi.waitFor(() => expect(document.body.textContent).not.toContain('shell.queueRecovery.title'));
+
+ // The notice is gone, but the dialog closes rather than being unmounted mid-animation.
+ expect(document.querySelector('[data-testid="discard-dialog"]')).toHaveAttribute('data-open', 'false');
+ });
+
it('opens the selected existing project without reading its journal payload', async () => {
await renderNotice({ openProjectIds: ['open-project'] });
await clickButton('shell.queueRecovery.open');
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx
index be0b8438f4..2355323a22 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx
@@ -4,7 +4,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
import { useQueryClient } from '@tanstack/react-query';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -165,8 +165,12 @@ export const QueueRecoveryNotice = ({
</HStack>
);
}
+
+ // The discard confirmation renders beside whichever notice applies, so the refetch that follows a discard can
+ // remove the notice while the dialog animates closed.
+ let notice: ReactNode = null;
if (query.data?.kind === 'unavailable' || query.isError) {
- return (
+ notice = (
<Alert.Root borderRadius="none" size="lg" status="warning" variant="surface">
<Alert.Indicator />
<Alert.Content>
@@ -175,13 +179,8 @@ export const QueueRecoveryNotice = ({
</Alert.Content>
</Alert.Root>
);
- }
- if (!projectId) {
- return null;
- }
-
- return (
- <>
+ } else if (projectId) {
+ notice = (
<Alert.Root borderRadius="none" size="lg" status="warning" variant="surface">
<Alert.Indicator />
<Alert.Content>
@@ -236,6 +235,12 @@ export const QueueRecoveryNotice = ({
</HStack>
</Alert.Content>
</Alert.Root>
+ );
+ }
+
+ return (
+ <>
+ {notice}
<ConfirmDialog
body={t('shell.queueRecovery.discardConfirmBody')}
confirmLabel={t('shell.queueRecovery.discard')}
diff --git a/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx
index 1a2c6df983..2e1d40861a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx
@@ -18,7 +18,7 @@ const AlphaNoticeModalLayer = () => {
};
/** Wait for account preferences before showing the notice; dismissal follows the account. */
-export const AlphaNoticeDialog = () => {
+export const AlphaNoticeDialog = ({ onExitComplete }: { onExitComplete?: () => void }) => {
const { t } = useTranslation();
const isOpen = useWorkbenchSettingsSelector(
(snapshot) => snapshot.status === 'ready' && !snapshot.preferences.alphaNoticeAcknowledged
@@ -38,6 +38,7 @@ export const AlphaNoticeDialog = () => {
open={isOpen}
role="alertdialog"
size="sm"
+ onExitComplete={onExitComplete}
onOpenChange={handleOpenChange}
>
{isOpen ? <AlphaNoticeModalLayer /> : null}
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx
index 1353e011cc..a6832852ae 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx
@@ -92,13 +92,26 @@ const CanvasDestinationButton = ({
);
};
+const PasteMediaModalLayer = () => {
+ useMountEffect(() => registerHotkeyModalLayer('paste-media'));
+
+ return null;
+};
+
/**
* Upload pasted media to the current board before forwarding it to canvas/reference actions so assets remain
* findable.
*/
-export const PasteMediaDialog = ({ request }: { request: PasteMediaRequest }) => {
+export const PasteMediaDialog = ({
+ isOpen,
+ onExitComplete,
+ request,
+}: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+ request: PasteMediaRequest;
+}) => {
const { t } = useTranslation();
- useMountEffect(() => registerHotkeyModalLayer('paste-media'));
const projectId = useActiveProjectId();
const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
const generateValues = useWidgetValuesSelector('generate', selectGenerateValues);
@@ -191,13 +204,15 @@ export const PasteMediaDialog = ({ request }: { request: PasteMediaRequest }) =>
return (
<>
<Dialog.Root
- open
+ open={isOpen}
finalFocusEl={returnFocus}
initialFocusEl={getInitialFocusEl}
placement="center"
size="sm"
+ onExitComplete={onExitComplete}
onOpenChange={handleOpenChange}
>
+ {isOpen ? <PasteMediaModalLayer /> : null}
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx
index 34c005c247..50d284fdf3 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx
@@ -2,6 +2,7 @@ import type { GalleryImageItem } from '@features/gallery/contracts';
import type { Project } from '@workbench/projectContracts';
import { ChakraProvider } from '@chakra-ui/react';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { applyThemeToRoot } from '@theme/applyTheme';
import { system } from '@theme/system';
@@ -277,4 +278,21 @@ describe('PasteMediaRuntime', () => {
await expect.element(pasteDialog()).not.toBeInTheDocument();
expect(mocks.uploadFiles).not.toHaveBeenCalled();
});
+
+ it('animates the dialog out instead of unmounting it, releasing workbench hotkeys at close', async () => {
+ paste(document.body, [imageFile()]);
+ await expect
+ .poll(() => document.querySelector('[role="dialog"][data-state]')?.getAttribute('data-state'))
+ .toBe('open');
+ const dialog = document.querySelector('[role="dialog"][data-state]')!;
+
+ const frames = await recordDialogExit(dialog, async () => {
+ await page.getByRole('button', { name: i18n.t('common.cancel') }).click();
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ });
+
+ // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(closingFrames(frames)).not.toHaveLength(0);
+ await expect.poll(() => document.querySelector('[role="dialog"][data-state]')).toBeNull();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx
index 61320e1765..2df261b0ff 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx
@@ -1,4 +1,5 @@
import { classifyGalleryUpload } from '@features/gallery/contracts';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { isEditableHotkeyTarget } from '@workbench/hotkeys/keys';
import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
@@ -27,6 +28,8 @@ const PasteMediaDialog = lazy(() =>
export const PasteMediaRuntime = () => {
const [request, setRequest] = useState<PasteMediaRequest | null>(null);
const settle = useCallback(() => setRequest(null), []);
+ // Settling closes the dialog; its request stays rendered until the close animation finishes.
+ const dialog = useExitRetainedValue(request);
useMountEffect(() => {
let ticket = 0;
@@ -54,9 +57,14 @@ export const PasteMediaRuntime = () => {
return () => document.removeEventListener('paste', handlePaste);
});
- return request ? (
+ return dialog.value ? (
<Suspense fallback={null}>
- <PasteMediaDialog key={request.ticket} request={request} />
+ <PasteMediaDialog
+ key={dialog.value.ticket}
+ isOpen={dialog.isOpen}
+ request={dialog.value}
+ onExitComplete={dialog.release}
+ />
</Suspense>
) : null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx
index 7735a1f6e1..966618055b 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx
@@ -46,13 +46,35 @@ const harness = vi.hoisted(() => ({
}));
vi.mock('@platform/browser/downloadBlob', () => ({ downloadText: harness.downloadText }));
+// Exposes whether the host keeps the dialog mounted (the real one needs that to animate out); like the real dialog,
+// it closes after confirming even when the confirmation fails.
vi.mock('@platform/ui/ConfirmDialog', () => ({
- ConfirmDialog: ({ isOpen, onConfirm }: { isOpen: boolean; onConfirm(): Promise<void> | void }) =>
- isOpen ? (
- <button data-testid="confirm-resolution" onClick={() => void onConfirm()}>
- confirm
- </button>
- ) : null,
+ ConfirmDialog: ({
+ isOpen,
+ onClose,
+ onConfirm,
+ }: {
+ isOpen: boolean;
+ onClose(): void;
+ onConfirm(): Promise<void> | void;
+ }) => (
+ <div data-open={String(isOpen)} data-testid="resolution-dialog">
+ {isOpen ? (
+ <button
+ data-testid="confirm-resolution"
+ onClick={async () => {
+ try {
+ await onConfirm();
+ } finally {
+ onClose();
+ }
+ }}
+ >
+ confirm
+ </button>
+ ) : null}
+ </div>
+ ),
}));
vi.mock('@workbench/projects/syncStore', () => ({
useProjectSyncSelector: (selector: (snapshot: unknown) => unknown) =>
@@ -196,6 +218,24 @@ describe('ProjectConflictBanner', () => {
);
});
+ it('keeps the confirmation mounted to animate out after resolving clears the banner', async () => {
+ harness.conflict = { detectedAt: '2026-09-03T12:00:00.000Z', kind: 'revision', serverRevision: 2 };
+ harness.replaceProjectFromServer.mockImplementationOnce(() => {
+ harness.conflict = undefined;
+ });
+ await renderBanner();
+ const useServer = Array.from(document.querySelectorAll('button')).find(
+ (button) => button.textContent === 'shell.projectConflict.useServer'
+ );
+
+ await act(() => userEvent.click(useServer!));
+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-resolution"]')!));
+ await vi.waitFor(() =>
+ expect(document.querySelector('[data-testid="resolution-dialog"]')).toHaveAttribute('data-open', 'false')
+ );
+ expect(document.body.textContent).not.toContain('shell.projectConflict.revisionTitle');
+ });
+
it('keeps the fence when use-server resolution fails', async () => {
harness.conflict = { detectedAt: '2026-09-03T12:00:00.000Z', kind: 'revision', serverRevision: 2 };
harness.resolveConflictUseServer.mockRejectedValueOnce(new Error('offline'));
diff --git a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
index 9340844e21..916238c3f3 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
@@ -177,10 +177,6 @@ export const ProjectConflictBanner = () => {
const conflict = sync?.conflict;
const schemaRefusal = sync?.schemaRefusal;
const hasProjectAlert = Boolean(conflict || schemaRefusal || localDraftStatus !== 'ok');
- if (!hasProjectAlert && !recoverableDraft) {
- return null;
- }
-
const title = schemaRefusal
? t('shell.projectConflict.schemaTitle')
: conflict?.kind === 'deleted'
@@ -321,33 +317,32 @@ export const ProjectConflictBanner = () => {
</Alert.Content>
</Alert.Root>
) : null}
- {hasProjectAlert || recoverableDraft ? (
- <ConfirmDialog
- body={t(
- resolutionAction === 'delete-recoverable'
- ? 'shell.projectConflict.deleteDraftConfirmBody'
- : resolutionAction === 'save-as-new'
- ? 'shell.projectConflict.saveAsNewConfirmBody'
- : resolutionAction === 'use-server'
- ? 'shell.projectConflict.useServerConfirmBody'
- : 'shell.projectConflict.discardConfirmBody'
- )}
- confirmLabel={t(
- resolutionAction === 'delete-recoverable'
- ? 'shell.projectConflict.deleteDraft'
- : resolutionAction === 'save-as-new'
- ? 'shell.projectConflict.saveAsNew'
- : resolutionAction === 'use-server'
- ? 'shell.projectConflict.useServer'
- : 'shell.projectConflict.discard'
- )}
- isDestructive={resolutionAction !== 'save-as-new'}
- isOpen={resolutionAction !== null}
- title={t('shell.projectConflict.confirmTitle')}
- onClose={closeConfirmation}
- onConfirm={confirmResolution}
- />
- ) : null}
+ {/* Always mounted: resolving a conflict can clear both alerts while the confirmation animates out. */}
+ <ConfirmDialog
+ body={t(
+ resolutionAction === 'delete-recoverable'
+ ? 'shell.projectConflict.deleteDraftConfirmBody'
+ : resolutionAction === 'save-as-new'
+ ? 'shell.projectConflict.saveAsNewConfirmBody'
+ : resolutionAction === 'use-server'
+ ? 'shell.projectConflict.useServerConfirmBody'
+ : 'shell.projectConflict.discardConfirmBody'
+ )}
+ confirmLabel={t(
+ resolutionAction === 'delete-recoverable'
+ ? 'shell.projectConflict.deleteDraft'
+ : resolutionAction === 'save-as-new'
+ ? 'shell.projectConflict.saveAsNew'
+ : resolutionAction === 'use-server'
+ ? 'shell.projectConflict.useServer'
+ : 'shell.projectConflict.discard'
+ )}
+ isDestructive={resolutionAction !== 'save-as-new'}
+ isOpen={resolutionAction !== null}
+ title={t('shell.projectConflict.confirmTitle')}
+ onClose={closeConfirmation}
+ onConfirm={confirmResolution}
+ />
</>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx
index 76a731f3ff..c73715a95a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx
@@ -54,7 +54,7 @@ const WhatsNewModalLayer = () => {
*/
const keepOpenOnFocusOutside = (event: { preventDefault: () => void }) => event.preventDefault();
-export const WhatsNewDialog = () => {
+export const WhatsNewDialog = ({ onExitComplete }: { onExitComplete?: () => void }) => {
const { t } = useTranslation();
const { isOpen, isUnseen, version } = useWhatsNew();
const items = readItems(t('whatsNew.items', { returnObjects: true }));
@@ -86,6 +86,7 @@ export const WhatsNewDialog = () => {
placement="center"
scrollBehavior="inside"
size="lg"
+ onExitComplete={onExitComplete}
onFocusOutside={keepOpenOnFocusOutside}
onOpenChange={handleOpenChange}
>
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx
index a87a0a9644..e1f71d4b8f 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx
@@ -1,5 +1,6 @@
import type { LayoutPreset } from '@workbench/layoutContracts';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
import { getLayoutPresetSourceOptions } from '@workbench/layoutPresetRouting';
import { layoutPresets } from '@workbench/layoutPresets';
@@ -22,15 +23,17 @@ export const LayoutPresetAdminDialogs = () => {
const account = useWorkbenchSelector((snapshot) => snapshot.account);
const customPresets = account.customLayoutPresets ?? EMPTY_LAYOUT_PRESETS;
const { deletePresetId, editPresetId } = layoutPresetManagerStore.useSelector((snapshot) => snapshot);
+ const editDialog = useExitRetainedValue(editPresetId);
const editTarget = useMemo(() => {
- if (!editPresetId) {
+ if (!editDialog.value) {
return null;
}
- const exists = [...layoutPresets, ...customPresets].some((preset) => preset.id === editPresetId);
+ const presetId = editDialog.value;
+ const exists = [...layoutPresets, ...customPresets].some((preset) => preset.id === presetId);
- return exists ? resolveSavedLayoutPreset(account, editPresetId) : null;
- }, [account, customPresets, editPresetId]);
+ return exists ? resolveSavedLayoutPreset(account, presetId) : null;
+ }, [account, customPresets, editDialog.value]);
const deleteTarget = customPresets.find((preset) => preset.id === deletePresetId) ?? null;
const sourceOptions = useMemo(() => (editTarget ? getLayoutPresetSourceOptions(editTarget) : []), [editTarget]);
@@ -54,15 +57,16 @@ export const LayoutPresetAdminDialogs = () => {
<>
{editTarget ? (
<LayoutPresetDialog
- key={editTarget.id}
+ key={editDialog.generation}
defaultRoute={editTarget.defaultRoute}
iconId={editTarget.iconId}
- isOpen
+ isOpen={editDialog.isOpen}
name={editTarget.label}
sourceOptions={sourceOptions}
submitLabel={t('topbar.presets.save')}
title={t('topbar.presets.edit')}
onClose={closeLayoutPresetAdmin}
+ onExitComplete={editDialog.release}
onSubmit={submitEdit}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx
index 6d1cd7b478..20746d2977 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx
@@ -68,6 +68,7 @@ export const LayoutPresetDialog = ({
isOpen,
name: initialName,
onClose,
+ onExitComplete,
onSubmit,
sourceOptions,
submitLabel,
@@ -78,6 +79,8 @@ export const LayoutPresetDialog = ({
isOpen: boolean;
name: string;
onClose: () => void;
+ /** Called once the close animation finishes; hosts release the retained dialog here. */
+ onExitComplete?: () => void;
onSubmit: (value: LayoutPresetDialogValue) => void;
sourceOptions: readonly GraphWidgetSource[];
submitLabel: string;
@@ -167,7 +170,14 @@ export const LayoutPresetDialog = ({
}, []);
return (
- <Dialog.Root initialFocusEl={initialFocusEl} open={isOpen} lazyMount unmountOnExit onOpenChange={handleOpenChange}>
+ <Dialog.Root
+ initialFocusEl={initialFocusEl}
+ open={isOpen}
+ lazyMount
+ unmountOnExit
+ onExitComplete={onExitComplete}
+ onOpenChange={handleOpenChange}
+ >
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx
index fa032f0bbe..dad9e79d2a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx
@@ -1,3 +1,4 @@
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { lazy, Suspense } from 'react';
import { layoutPresetManagerStore } from './layoutPresetManagerStore';
@@ -9,10 +10,12 @@ const LazyLayoutPresetManagerDialogBody = lazy(() =>
export const LayoutPresetManagerDialog = () => {
const isOpen = layoutPresetManagerStore.useSelector((snapshot) => snapshot.isOpen);
+ // Stays mounted through the close animation instead of vanishing with the open state.
+ const dialog = useExitPresence(isOpen);
- return isOpen ? (
+ return dialog.isMounted ? (
<Suspense fallback={null}>
- <LazyLayoutPresetManagerDialogBody />
+ <LazyLayoutPresetManagerDialogBody isOpen={isOpen} onExitComplete={dialog.release} />
</Suspense>
) : null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx
index 660252e445..5dea3392a2 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx
@@ -1,4 +1,5 @@
import { ChakraProvider } from '@chakra-ui/react';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
import { createWorkbenchStore, type WorkbenchInternalStore } from '@workbench/workbenchStore';
import { act, useSyncExternalStore } from 'react';
@@ -30,12 +31,16 @@ vi.mock('@workbench/WorkbenchContext', () => ({
) => selector(useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot)),
}));
+import { LayoutPresetManagerDialog } from './LayoutPresetManagerDialog';
import { LayoutPresetManagerDialogBody } from './LayoutPresetManagerDialogBody';
+import { closeLayoutPresetManager, openLayoutPresetManager } from './layoutPresetManagerStore';
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 noop = () => {};
+
const renderManager = async () => {
host = document.createElement('div');
document.body.append(host);
@@ -44,7 +49,7 @@ const renderManager = async () => {
await act(async () => {
root?.render(
<ChakraProvider value={system}>
- <LayoutPresetManagerDialogBody />
+ <LayoutPresetManagerDialogBody isOpen onExitComplete={noop} />
</ChakraProvider>
);
await new Promise<void>((resolve) => {
@@ -78,6 +83,7 @@ beforeEach(() => {
});
afterEach(async () => {
+ closeLayoutPresetManager();
await act(() => root?.unmount());
host?.remove();
host = null;
@@ -85,6 +91,29 @@ afterEach(async () => {
});
describe('LayoutPresetManagerDialogBody', () => {
+ it('animates the lazily loaded manager out instead of unmounting it on close', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <LayoutPresetManagerDialog />
+ </ChakraProvider>
+ )
+ );
+ await act(() => openLayoutPresetManager());
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="dialog"]')!;
+ const done = Array.from(dialog.querySelectorAll('button')).find((button) => button.textContent === 'Done')!;
+
+ const frames = await recordDialogExit(dialog, () => act(() => userEvent.click(done)));
+
+ // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(closingFrames(frames)).not.toHaveLength(0);
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
it('renders one account-ordered list without preset descriptions', async () => {
await renderManager();
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx
index 035e51ed3b..83e0174537 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx
@@ -33,7 +33,13 @@ const KEYBOARD_SENSOR_OPTIONS = {
} satisfies KeyboardSensorOptions;
/** The account-wide layout preset editor, rendered lazily from the top bar. */
-export const LayoutPresetManagerDialogBody = () => {
+export const LayoutPresetManagerDialogBody = ({
+ isOpen,
+ onExitComplete,
+}: {
+ isOpen: boolean;
+ onExitComplete: () => void;
+}) => {
const { t } = useTranslation();
const { layout } = useWorkbenchCommands();
const account = useWorkbenchSelector((snapshot) => snapshot.account);
@@ -70,7 +76,7 @@ export const LayoutPresetManagerDialogBody = () => {
);
return (
- <Dialog.Root open lazyMount unmountOnExit onOpenChange={handleOpenChange}>
+ <Dialog.Root lazyMount open={isOpen} unmountOnExit onExitComplete={onExitComplete} onOpenChange={handleOpenChange}>
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx
index bd1c9008b0..d9aef24252 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx
@@ -1,6 +1,7 @@
import type * as LayoutPresetActivationModule from '@workbench/layoutPresetActivation';
import { ChakraProvider } from '@chakra-ui/react';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { system } from '@theme/system';
import { createWorkbenchStore, type WorkbenchInternalStore } from '@workbench/workbenchStore';
import { act, useSyncExternalStore } from 'react';
@@ -167,6 +168,29 @@ describe('LayoutPresetStrip', () => {
});
// The menu's layer must be gone before an admin dialog mounts, or zag dismisses the dialog as nested above it.
+ it.each(['save-as', 'edit'] as const)(
+ 'animates the %s dialog out instead of unmounting it on close',
+ async (kind) => {
+ await renderStrip({ withAdminDialogs: true });
+
+ if (kind === 'save-as') {
+ await act(() =>
+ userEvent.click(document.querySelector<HTMLElement>('[aria-label="Save this layout as a new preset"]')!)
+ );
+ } else {
+ await openPresetMenuItem('custom-1', 'edit-preset');
+ }
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="dialog"]')!;
+
+ const frames = await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}')));
+
+ // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
+ expect(closingFrames(frames)).not.toHaveLength(0);
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+ }
+ );
+
it('keeps the edit and delete dialogs opened from a preset menu', async () => {
await renderStrip({ withAdminDialogs: true });
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
index 86ccad0ef2..e226c7d890 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
@@ -21,6 +21,7 @@ import {
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { IconButton } from '@platform/ui/Button';
import { MenuContent } from '@platform/ui/Menu';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
@@ -78,6 +79,7 @@ export const LayoutPresetStrip = () => {
const { t } = useTranslation();
const { layout } = useWorkbenchCommands();
const [isSaveAsOpen, setIsSaveAsOpen] = useState(false);
+ const saveAsDialog = useExitPresence(isSaveAsOpen);
const [menuTarget, setMenuTarget] = useState<PresetMenuTarget | null>(null);
const menuTicket = useRef(0);
@@ -242,15 +244,17 @@ export const LayoutPresetStrip = () => {
/>
) : null}
- {isSaveAsOpen ? (
+ {saveAsDialog.isMounted ? (
<LayoutPresetDialog
+ key={saveAsDialog.generation}
defaultRoute={saveAsDefaultRoute}
- isOpen
+ isOpen={saveAsDialog.isOpen}
name={`${activePreset.label} copy`}
sourceOptions={sourceOptions}
submitLabel={t('topbar.presets.save')}
title={t('topbar.presets.saveAs')}
onClose={closeSaveAsDialog}
+ onExitComplete={saveAsDialog.release}
onSubmit={saveAsNewPreset}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx
index 4353a38db4..f7bb182380 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.browser.test.tsx
@@ -5,9 +5,11 @@ import { ChakraProvider } from '@chakra-ui/react';
import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
+import { closingFrames, recordDialogExit, type DialogExitFrame } from '@platform/ui/dialogExit.testing';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { createEmptyCanvasState } from '@workbench/canvasMigration';
+import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -98,6 +100,43 @@ it('groups affected layers, keeps a warning after dismissal, and reopens recover
await expect.element(page.getByRole('dialog')).toBeVisible();
});
+/** Every frame recovery showed while closing must still show its row, so it animated out whole. */
+const expectRowWhileClosing = (frames: readonly DialogExitFrame[]) => {
+ const closing = closingFrames(frames);
+ expect(closing).not.toHaveLength(0);
+ for (const frame of closing) {
+ expect(frame.text).toContain('Used by 3 text layers');
+ }
+};
+
+it('animates recovery out on dismissal and returns workbench hotkeys as it starts closing', async () => {
+ await render();
+ await expect.element(page.getByRole('dialog', { name: 'Missing fonts' })).toBeVisible();
+ expect(isHotkeyModalLayerActive()).toBe(true);
+
+ const frames = await recordDialogExit(document.querySelector('[role="dialog"]')!, async () => {
+ await act(() => page.getByRole('button', { name: 'Continue with previews' }).click());
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ });
+
+ expectRowWhileClosing(frames);
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+});
+
+it('animates out with its rows once a retry finds every font', async () => {
+ await render();
+ await expect.element(page.getByRole('dialog', { name: 'Missing fonts' })).toBeVisible();
+
+ api.getFont.mockResolvedValue({ ...missing });
+ const frames = await recordDialogExit(document.querySelector('[role="dialog"]')!, () =>
+ act(() => page.getByRole('button', { name: 'Retry', exact: true }).click())
+ );
+
+ expectRowWhileClosing(frames);
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+ expect(isHotkeyModalLayerActive()).toBe(false);
+});
+
it('replaces every use through the undoable Canvas capability with target axis limits', async () => {
await render();
await act(() => page.getByRole('combobox', { name: 'Replacement font' }).selectOptions('replacement'));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx
index 659ef0ddfb..1f986bf782 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/MissingFontsDialog.tsx
@@ -2,65 +2,92 @@ import type { CanvasEngine, CanvasFontCapability } from '@workbench/canvas-engin
import { Box, Dialog, Flex, Input, NativeSelect, Portal, Stack, Text } from '@chakra-ui/react';
import { fontKeys, fontsQueryOptions, getFont, uploadFont, type FontRecord } from '@features/fonts';
+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { useMountEffect } from '@platform/react/useMountEffect';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { Button, CloseButton } from '@platform/ui';
-import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
+import { useQueries, useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
import { useCallback, useDeferredValue, useMemo, useRef, useState, type ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
type FontGroup = ReturnType<CanvasFontCapability['collectReferences']>[number];
+/** Per font: `undefined` while checking, `null` when it cannot be fetched, else the stored content hash. */
+const storedContentHashes = (queries: readonly UseQueryResult<FontRecord>[]) =>
+ queries.map((query) => (query.isPending ? undefined : query.isError ? null : query.data.contentHash));
+
export const MissingFontsDialog = ({ engine, groups }: { engine: CanvasEngine; groups: readonly FontGroup[] }) => {
const { t } = useTranslation('fonts');
- const queries = useQueries({
+ // Combined results are structurally shared, so `unavailable` keeps its identity until a check's outcome changes.
+ const storedHashes = useQueries({
queries: groups.map(({ fontRef }) => ({
queryKey: fontKeys.detail(fontRef.id),
queryFn: ({ signal }: { signal: AbortSignal }) => getFont(fontRef.id, signal),
retry: false,
staleTime: 30_000,
})),
+ combine: storedContentHashes,
});
const unavailable = useMemo(
() =>
groups.filter((group, index) => {
- const query = queries[index];
- return query && !query.isPending && (query.isError || query.data?.contentHash !== group.fontRef.contentHash);
+ const stored = storedHashes[index];
+ return stored !== undefined && stored !== group.fontRef.contentHash;
}),
- [groups, queries]
+ [groups, storedHashes]
);
const signature = JSON.stringify(unavailable.map(({ fontRef }) => [fontRef.id, fontRef.contentHash]));
const [dismissed, setDismissed] = useState<string | null>(null);
const close = useCallback(() => setDismissed(signature), [signature]);
const reopen = useCallback(() => setDismissed(null), []);
- if (!unavailable.length) {
- return null;
- }
+ const isOpen = unavailable.length > 0 && dismissed !== signature;
+ // Resolving the last font closes the dialog; its exit keeps the rows it last showed instead of collapsing.
+ const recovery = useExitRetainedValue(isOpen ? unavailable : null);
return (
<>
- <Box position="absolute" top="2" left="50%" transform="translateX(-50%)" zIndex="2">
- <Button colorPalette="orange" onClick={reopen}>
- {t('fonts.missing.warning', { count: unavailable.length })}
- </Button>
- </Box>
- {dismissed !== signature ? <RecoveryDialog groups={unavailable} engine={engine} onClose={close} /> : null}
+ {unavailable.length ? (
+ <Box position="absolute" top="2" left="50%" transform="translateX(-50%)" zIndex="2">
+ <Button colorPalette="orange" onClick={reopen}>
+ {t('fonts.missing.warning', { count: unavailable.length })}
+ </Button>
+ </Box>
+ ) : null}
+ {recovery.value ? (
+ <RecoveryDialog
+ key={recovery.generation}
+ groups={recovery.value}
+ engine={engine}
+ isOpen={recovery.isOpen}
+ onClose={close}
+ onExitComplete={recovery.release}
+ />
+ ) : null}
</>
);
};
+/** Mounted only while recovery is open, so workbench hotkeys return as soon as it starts closing. */
+const RecoveryModalLayer = () => {
+ useMountEffect(() => registerHotkeyModalLayer('missing-fonts'));
+ return null;
+};
+
const RecoveryDialog = ({
groups,
engine,
+ isOpen,
onClose,
+ onExitComplete,
}: {
- groups: FontGroup[];
+ groups: readonly FontGroup[];
engine: CanvasEngine;
+ isOpen: boolean;
onClose: () => void;
+ onExitComplete: () => void;
}) => {
const { t } = useTranslation('fonts');
const queryClient = useQueryClient();
- useMountEffect(() => registerHotkeyModalLayer('missing-fonts'));
const onOpenChange = useCallback(
({ open }: { open: boolean }) => {
if (!open) {
@@ -73,7 +100,15 @@ const RecoveryDialog = ({
void queryClient.invalidateQueries({ queryKey: fontKeys.all });
}, [queryClient]);
return (
- <Dialog.Root open placement="center" size="lg" scrollBehavior="inside" onOpenChange={onOpenChange}>
+ <Dialog.Root
+ open={isOpen}
+ placement="center"
+ size="lg"
+ scrollBehavior="inside"
+ onExitComplete={onExitComplete}
+ onOpenChange={onOpenChange}
+ >
+ {isOpen ? <RecoveryModalLayer /> : null}
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 8d3c1eb45d..643d0bbe7a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -193,6 +193,8 @@ interface LayerMenuProps {
*/
dialogKind?: LayerMenuDialogKind | null;
onDialogKindChange?: (kind: LayerMenuDialogKind | null) => void;
+ /** After a sibling dialog's close animation; a controlling parent may stop retaining its target here. */
+ onDialogExitComplete?: () => void;
/** Canvas-only items composed immediately before the terminal danger section. */
beforeDangerItems?: ReactNode;
/** Adds the legacy layer and Canvas group labels on the canvas surface. */
@@ -215,6 +217,7 @@ const LayerMenu = ({
unmountOnExit,
dialogKind: controlledDialogKind,
onDialogKindChange,
+ onDialogExitComplete,
beforeDangerItems,
showGroupLabels,
}: LayerMenuProps) => {
@@ -532,6 +535,12 @@ const LayerMenu = ({
const openRename = useCallback(() => setDialogKind('rename'), [setDialogKind]);
const closeDialog = useCallback(() => setDialogKind(null), [setDialogKind]);
const openRunWorkflow = useCallback(() => setDialogKind('run-workflow'), [setDialogKind]);
+ // Each close remounts the run dialog, closed, so the next open starts from a fresh form.
+ const [runWorkflowGeneration, setRunWorkflowGeneration] = useState(0);
+ const handleRunWorkflowExitComplete = useCallback(() => {
+ setRunWorkflowGeneration((generation) => generation + 1);
+ onDialogExitComplete?.();
+ }, [onDialogExitComplete]);
// Operations present their controls in the Properties pane, so starting one must bring that pane into view.
const revealProperties = useCallback(
(layerId: string) => {
@@ -975,17 +984,20 @@ const LayerMenu = ({
submitLabel={t('widgets.layers.actions.rename')}
title={t('widgets.layers.actions.rename')}
onClose={closeDialog}
+ onExitComplete={onDialogExitComplete}
onSubmit={submitRename}
/>
- {dialogKind === 'run-workflow' ? (
- <RunLayerWorkflowDialog
- availability={workflowAvailability}
- engine={engine}
- isOpen
- layerId={layer.id}
- onClose={closeDialog}
- />
- ) : null}
+ {/* Mounted before it opens, like the rename dialog: a dialog that mounts open while the menu is closing is
+ dismissed as nested above the menu's departing layer. */}
+ <RunLayerWorkflowDialog
+ key={runWorkflowGeneration}
+ availability={workflowAvailability}
+ engine={engine}
+ isOpen={dialogKind === 'run-workflow'}
+ layerId={layer.id}
+ onClose={closeDialog}
+ onExitComplete={handleRunWorkflowExitComplete}
+ />
</>
);
};
@@ -1027,9 +1039,14 @@ export const CanvasLayerContextMenu = ({
showGroupLabels?: boolean;
onClose: () => void;
}) => {
- // The layer a pending sibling dialog is anchored to. Captured while the live
- // target still exists, then retained until the dialog closes.
- const [dialogState, setDialogState] = useState<LayerMenuDialogState | null>(null);
+ // The layer a sibling dialog is anchored to. Captured while the live target
+ // still exists, then retained until the dialog has animated out.
+ const [dialogState, setDialogState] = useState<(LayerMenuDialogState & { isOpen: boolean }) | null>(null);
+ // A menu for another layer remounts LayerMenu, cutting the retained dialog short before it reports its exit.
+ // Drop that dialog, or it would resurface as a hidden menu for its layer once this one closes.
+ if (target && dialogState && target.layerId !== dialogState.target.layerId) {
+ setDialogState(null);
+ }
const renderTarget = resolveMenuTargetForRender(target, dialogState);
const layerId = renderTarget?.layerId ?? null;
@@ -1056,10 +1073,19 @@ export const CanvasLayerContextMenu = ({
);
const handleDialogKindChange = useCallback(
(kind: LayerMenuDialogKind | null) => {
- setDialogState(kind && target ? { kind, target } : null);
+ setDialogState((current) => {
+ if (kind) {
+ return target ? { isOpen: true, kind, target } : null;
+ }
+ return current ? { ...current, isOpen: false } : null;
+ });
},
[target]
);
+ const handleDialogExitComplete = useCallback(
+ () => setDialogState((current) => (current?.isOpen ? current : null)),
+ []
+ );
if (!renderTarget || !layer) {
return null;
@@ -1070,7 +1096,7 @@ export const CanvasLayerContextMenu = ({
key={renderTarget.layerId}
beforeDangerItems={beforeDangerItems}
dispatch={dispatch}
- dialogKind={dialogState?.kind ?? null}
+ dialogKind={dialogState?.isOpen ? dialogState.kind : null}
engine={engine}
layer={layer}
lazyMount
@@ -1080,6 +1106,7 @@ export const CanvasLayerContextMenu = ({
showGroupLabels={showGroupLabels}
unmountOnExit
onOpenChange={handleOpenChange}
+ onDialogExitComplete={handleDialogExitComplete}
onDialogKindChange={handleDialogKindChange}
/>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
index 3da932611b..db5fe639bb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
@@ -36,7 +36,7 @@ import {
Trash2Icon,
UngroupIcon,
} from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { COLOR_LABEL_ITEMS } from './colorLabels';
@@ -84,7 +84,17 @@ export const LayerGroupContextMenu = ({
const projectId = useActiveProjectId();
const document = useActiveProjectSelector((project) => project.canvas.document);
const { selectedIds } = useLayerPanelState(projectId, document.selectedLayerId);
+ const [menuOpen, setMenuOpen] = useState(true);
const [renaming, setRenaming] = useState(false);
+ // Choosing Rename closes the menu; the host's surface must outlive it until the rename dialog has animated out.
+ const renameChosen = useRef(false);
+ // Every request brings a new anchor. One for this same group while its rename animates out keeps this instance
+ // mounted, so it must reopen the menu here.
+ const [requestAnchor, setRequestAnchor] = useState(anchor);
+ if (anchor !== requestAnchor) {
+ setRequestAnchor(anchor);
+ setMenuOpen(true);
+ }
const selection = useCallback(
(): readonly string[] => (selectedIds.includes(group.id) ? selectedIds : [group.id]),
@@ -102,7 +112,11 @@ export const LayerGroupContextMenu = ({
);
const handleOpenChange = useCallback(
(details: { open: boolean }) => {
- if (!details.open) {
+ if (details.open) {
+ return;
+ }
+ setMenuOpen(false);
+ if (!renameChosen.current) {
onClose();
}
},
@@ -121,8 +135,18 @@ export const LayerGroupContextMenu = ({
},
[patch, t]
);
- const openRename = useCallback(() => setRenaming(true), []);
+ const openRename = useCallback(() => {
+ renameChosen.current = true;
+ setRenaming(true);
+ }, []);
const closeRename = useCallback(() => setRenaming(false), []);
+ // A menu reopened while the rename animated out now owns the surface and closes it itself.
+ const handleRenameExitComplete = useCallback(() => {
+ renameChosen.current = false;
+ if (!menuOpen) {
+ onClose();
+ }
+ }, [menuOpen, onClose]);
const handleToggleEnabled = useCallback(
() => patch(t('widgets.layers.actions.toggleVisibility'), { isEnabled: !group.isEnabled }),
[group.isEnabled, patch, t]
@@ -370,7 +394,7 @@ export const LayerGroupContextMenu = ({
return (
<>
- <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
+ <Menu.Root lazyMount open={menuOpen} positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
<Portal>
<Menu.Positioner>{items}</Menu.Positioner>
</Portal>
@@ -382,6 +406,7 @@ export const LayerGroupContextMenu = ({
submitLabel={t('widgets.layers.actions.rename')}
title={t('widgets.layers.actions.rename')}
onClose={closeRename}
+ onExitComplete={handleRenameExitComplete}
onSubmit={handleRename}
/>
</>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
new file mode 100644
index 0000000000..ff3e789efd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
@@ -0,0 +1,222 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { CanvasNodeContract } from '@workbench/canvas-engine/api';
+import type { Project } from '@workbench/projectContracts';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { createDocumentModel } from '@workbench/canvas-engine/api';
+import {
+ groupContract,
+ layerContract,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createInstance } from 'i18next';
+import { act, createRef, useImperativeHandle, useState, type Ref } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import type { LayerRowCommands } from './layerRowCommands';
+import type * as RunLayerWorkflowDialogModule from './RunLayerWorkflowDialog';
+
+import { LayerSurfaceHost, type LayerSurfaceEngine, type LayerSurfaceRequest } from './LayerSurfaceHost';
+
+const PROJECT_ID = 'surface-project';
+const mocks = vi.hoisted(() => ({
+ commands: { notifications: { add: () => undefined }, widgets: { open: () => undefined } },
+ // Only a layer menu reads workflow availability, once per render, so its calls show a layer menu is mounted.
+ layerMenuRender: vi.fn(),
+ project: null as unknown as Project,
+}));
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
+ useActiveProjectId: () => PROJECT_ID,
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(mocks.project),
+ useOptionalWorkbenchCommands: () => mocks.commands,
+ useWorkbenchCommands: () => mocks.commands,
+}));
+// A workflow with an image input and output, so the layer menu offers Run workflow.
+vi.mock('./RunLayerWorkflowDialog', async (importOriginal) => {
+ const availability = {
+ canRunWorkflow: true,
+ document: { id: 'workflow-1' },
+ getRunnableInputs: () => [],
+ hasWorkflowBindings: true,
+ outputs: [],
+ };
+ return {
+ ...(await importOriginal<typeof RunLayerWorkflowDialogModule>()),
+ useLayerWorkflowAvailability: () => {
+ mocks.layerMenuRender();
+ return availability;
+ },
+ };
+});
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+
+const nodes: CanvasNodeContract[] = [
+ layerContract('layer', 'raster', { name: 'Layer' }),
+ groupContract('group', [layerContract('child', 'raster', { name: 'Child' })], { name: 'Group' }),
+];
+const engine = {
+ document: {
+ model: () => createDocumentModel(mocks.project.canvas.document, { editRevision: 0, projectId: PROJECT_ID }),
+ },
+ exports: { hasExportableLayerContent: () => true },
+ interaction: { get: () => false, subscribe: () => () => undefined },
+ layers: { commitPrepared: () => ({ status: 'committed' as const }) },
+ projectId: PROJECT_ID,
+} as unknown as LayerSurfaceEngine;
+const anchor = { height: 10, width: 10, x: 40, y: 40 };
+
+const rowCommands = {} as LayerRowCommands;
+type OpenSurface = (surface: LayerSurfaceRequest) => void;
+const openSurfaceRef = createRef<OpenSurface>();
+const openSurface: OpenSurface = (surface) => openSurfaceRef.current!(surface);
+const Harness = ({ ref }: { ref: Ref<OpenSurface> }) => {
+ const [surface, setSurface] = useState<LayerSurfaceRequest | null>(null);
+ useImperativeHandle(ref, () => setSurface, []);
+ return (
+ <LayerSurfaceHost
+ commands={rowCommands}
+ dispatch={() => true}
+ document={mocks.project.canvas.document}
+ editingLocked={false}
+ engine={engine}
+ surface={surface}
+ // The panel clears its surface as soon as the menu closes.
+ onClose={() => setSurface(null)}
+ />
+ );
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(async () => {
+ const initial = { ...createInitialWorkbenchState().projects[0]!, id: PROJECT_ID };
+ mocks.project = applyCanvasProjectMutation(initial, {
+ document: { ...createEmptyCanvasDocument(), selectedLayerId: null, stacks: stacksFrom(nodes) },
+ type: 'replaceCanvasDocument',
+ });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness ref={openSurfaceRef} />
+ </ChakraProvider>
+ </I18nextProvider>
+ </QueryClientProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+it.each([
+ ['layer', 'Rename layer', 'Rename layer'],
+ ['layer', 'Run workflow', 'Run workflow from layer'],
+ ['group', 'Rename layer', 'Rename layer'],
+] as const)(
+ 'opens the %s menu "%s" dialog after the menu closes and animates it out on close',
+ async (id, item, title) => {
+ await act(() => openSurface({ anchor, id, kind: 'menu' }));
+ await act(() => page.getByRole('menuitem', { name: item, exact: true }).click());
+
+ await expect.element(page.getByRole('dialog', { name: title })).toBeVisible();
+ const dialog = document.querySelector('[role="dialog"]')!;
+ // Still open once the menu has gone: a dialog dismissed by the menu's teardown would already be closing.
+ expect(dialog).toHaveAttribute('data-state', 'open');
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toContain(title);
+ }
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+ }
+);
+
+// A closed menu stays in the DOM until its own exit animation ends.
+const openMenu = () => document.querySelector('[role="menu"][data-state="open"]');
+
+/** Choose a menu's rename item, then dismiss the dialog, which is left animating out. */
+const renameThenDismiss = async (id: string) => {
+ await act(() => openSurface({ anchor, id, kind: 'menu' }));
+ await act(() => page.getByRole('menuitem', { name: 'Rename layer', exact: true }).click());
+ await expect.element(page.getByRole('dialog', { name: 'Rename layer' })).toBeVisible();
+ const dialog = document.querySelector('[role="dialog"]')!;
+ await act(() => userEvent.keyboard('{Escape}'));
+ expect(dialog.isConnected).toBe(true);
+ expect(dialog).toHaveAttribute('data-state', 'closed');
+ return dialog;
+};
+
+it('drops a layer rename still animating out when another layer opens its menu', async () => {
+ await renameThenDismiss('layer');
+ await act(() => openSurface({ anchor: { ...anchor }, id: 'child', kind: 'menu' }));
+ await expect.poll(openMenu).not.toBeNull();
+
+ mocks.layerMenuRender.mockClear();
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();
+
+ // With every surface closed, no layer menu may come back for the rename its successor cut short.
+ expect(mocks.layerMenuRender).not.toHaveBeenCalled();
+});
+
+it('opens a group menu requested while its rename animates out, and keeps it once that exit ends', async () => {
+ const dialog = await renameThenDismiss('group');
+
+ await act(() => openSurface({ anchor: { ...anchor }, id: 'group', kind: 'menu' }));
+ await expect.poll(openMenu).not.toBeNull();
+ await expect.poll(() => dialog.isConnected).toBe(false);
+
+ expect(openMenu()).not.toBeNull();
+ await act(() => page.getByRole('menuitem', { name: 'Rename layer', exact: true }).click());
+ await expect.element(page.getByRole('dialog', { name: 'Rename layer' })).toBeVisible();
+});
+
+it('starts each Run workflow open from a fresh form', async () => {
+ const openRunWorkflow = async () => {
+ await act(() => openSurface({ anchor, id: 'layer', kind: 'menu' }));
+ await act(() => page.getByRole('menuitem', { name: 'Run workflow', exact: true }).click());
+ await expect.element(page.getByRole('dialog', { name: 'Run workflow from layer' })).toBeVisible();
+ };
+ const destination = page.getByRole('combobox', { name: 'Destination' });
+
+ await openRunWorkflow();
+ await act(() => destination.click());
+ await act(() => page.getByRole('option', { name: 'Canvas staging' }).click());
+ await expect.element(destination).toHaveTextContent('Canvas staging');
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ await openRunWorkflow();
+ await expect.element(destination).toHaveTextContent('Gallery');
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
index 2d89dfff22..cb8a101c15 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
@@ -124,6 +124,8 @@ interface RunLayerWorkflowDialogProps {
isOpen: boolean;
layerId: string;
onClose(): void;
+ /** After the close animation; a host may remount the dialog here so its next open starts fresh. */
+ onExitComplete?(): void;
}
interface SelectionState {
@@ -193,6 +195,7 @@ export const RunLayerWorkflowDialog = ({
isOpen,
layerId,
onClose,
+ onExitComplete,
}: RunLayerWorkflowDialogProps) => {
const { t } = useTranslation();
const notify = useNotify();
@@ -458,7 +461,14 @@ export const RunLayerWorkflowDialog = ({
const canRun = engine !== null && !isRunning && readinessMessage === null;
return (
- <Dialog.Root lazyMount open={isOpen} size="sm" unmountOnExit onOpenChange={handleOpenChange}>
+ <Dialog.Root
+ lazyMount
+ open={isOpen}
+ size="sm"
+ unmountOnExit
+ onExitComplete={onExitComplete}
+ onOpenChange={handleOpenChange}
+ >
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
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.tsx
index f074954e53..3a56080249 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
@@ -1,12 +1,14 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
import type { GalleryImage, GalleryImageItem, GalleryItemsPage, GalleryVideoItem } from '@features/gallery';
import type { InvocationProgressEvent, QueueItem, QueueItemStatusChangedEvent } from '@features/queue/contracts';
+import type * as DeletionConfirmationModule from '@workbench/image-actions/useDeletionConfirmation';
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { ChakraProvider } from '@chakra-ui/react';
import { DndContext, useSensor, useSensors, type DndContextProps } from '@dnd-kit/core';
import { requestGalleryItemReveal } from '@features/gallery/contracts';
import { createQueueCoordinator, type QueueCoordinatorBackendPort } from '@features/queue/runtime/coordinator';
+import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { QueryClient, QueryClientProvider, type InfiniteData } from '@tanstack/react-query';
import { system } from '@theme/system';
import { HoldToDragSensor, PrimaryMouseSensor } from '@workbench/shell/holdToDragSensor';
@@ -15,6 +17,7 @@ import { act, useCallback } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import { LivePreviewFollowProvider, useLivePreviewFollow } from './livePreviewFollow';
@@ -127,6 +130,7 @@ const mocks = vi.hoisted(() => {
selectedItemKey: string | null;
};
onImagesDeleted?: (imageNames: string[]) => void;
+ requestDeletionConfirmation?: DeletionConfirmationModule.RequestDeletionConfirmation;
},
recentImages,
bridgeProgressImage: null as unknown,
@@ -236,7 +240,7 @@ vi.mock('@features/gallery/contracts', async (importOriginal) => ({
requestGalleryItemReveal: vi.fn(),
}));
-vi.mock('@workbench/image-actions', () => ({
+vi.mock('@workbench/image-actions', async () => ({
EMPTY_IMAGE_RECALL_CAPABILITIES: {},
ImageContextMenu: () => null,
RecallActionButtons: () => null,
@@ -252,10 +256,9 @@ vi.mock('@workbench/image-actions', () => ({
getImageRecallTitle: () => '',
getSelectedGalleryImage: () => null,
getSelectedGalleryImageFromValues: () => null,
- useDeletionConfirmation: () => ({
- dialog: null,
- requestDeletionConfirmation: (_itemRefs: unknown, executeDeletion: () => Promise<void>) => executeDeletion(),
- }),
+ useDeletionConfirmation: (
+ await vi.importActual<typeof DeletionConfirmationModule>('@workbench/image-actions/useDeletionConfirmation')
+ ).useDeletionConfirmation,
useImageActions: (options: typeof mocks.imageActionOptions) => {
mocks.imageActionOptions = options;
return {};
@@ -2243,3 +2246,39 @@ describe('preview keyboard navigation boundary', () => {
expect(host?.querySelector('[data-swipe-neighbor="previous"] img')).toBeNull();
});
});
+
+describe('preview deletion confirmation', () => {
+ it('stays open while a live session takes over the preview, then animates out on close', async () => {
+ await render();
+ await act(() => {
+ void mocks.imageActionOptions!.requestDeletionConfirmation!([{ kind: 'image', name: 'newest' }], () =>
+ Promise.resolve()
+ );
+ });
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+ const confirmation = dialog.textContent;
+
+ mocks.project.queue.items = [queueItem];
+ mocks.project.settings.showProgressImagesInViewer = true;
+ mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });
+ mocks.useProgressImage.mockReturnValue({
+ dataUrl: 'data:image/png;base64,',
+ height: 64,
+ target: { itemIndex: 1, queueItemId: 'queue-item-live' },
+ width: 64,
+ });
+ await rerender();
+ expect(host?.querySelector('img[src^="data:image/png"]')).not.toBeNull();
+ expect(dialog.isConnected).toBe(true);
+ expect(dialog).toHaveAttribute('data-state', 'open');
+
+ const frames = closingFrames(await recordDialogExit(dialog, () => act(() => userEvent.keyboard('{Escape}'))));
+
+ expect(frames).not.toHaveLength(0);
+ for (const frame of frames) {
+ expect(frame.text).toBe(confirmation);
+ }
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 50eaf04ef4..ef44410c6e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -648,11 +648,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
target={contextMenuTarget}
onClose={closeContextMenu}
/>
- {deletionConfirmationDialog}
</>
) : (
<EmptyPreview />
)}
+ {/* Outside the branches: deleting the shown item or a live session taking over must not unmount a pending
+ confirmation, nor cut its exit animation short. */}
+ {deletionConfirmationDialog}
</Stack>
</Box>
);