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.

feat(webv2): choose model covers from the gallery picker

Josh Corbettd796e8e4ef2d
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index c60df6d169..34d1e96da3 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -89,15 +89,15 @@ The mixed-folder rules are longest-prefix rules in the manifest, so the Backend,
The target dependency graph intentionally records the current migration cycle: Workbench and the eight destination Features are one transitional strongly connected component. That is evidence for the cycle-breaking sequence, not permission for the destination architecture to retain the cycle. The migration must replace implementation imports with public module interfaces or composition-root adapters until the only direction is `app -> workbench/features -> platform`.
-Feature interfaces remain ordinary module interfaces unless two adapters add leverage. Queue's backend port has production transport/realtime and test adapters; Identity's token/session port has browser-session and test adapters; Models and Nodes use production event/transport adapters; their sinks (model-load activity, node execution) are injected into Queue's runtime at the App composition root, with test doubles in Queue's runtime tests. Gallery, Generation, Workflow, and Upscale keep their compilation and UI seams internal until their feature tickets demonstrate another independent adapter. Workbench image actions likewise remain internal rather than becoming a shallow Image Feature.
+Feature interfaces remain ordinary module interfaces unless two adapters add leverage. Queue's backend port has production transport/realtime and test adapters; Identity's token/session port has browser-session and test adapters; Models and Nodes use production event/transport adapters; their sinks (model-load activity, node execution) are injected into Queue's runtime at the App composition root, with test doubles in Queue's runtime tests. Gallery, Generation, Workflow, and Upscale keep their compilation and UI seams internal until their feature tickets demonstrate another independent adapter. Workbench image actions likewise remain internal rather than becoming a shallow Image Feature. Gallery's picker and media slots read a narrow `GalleryHost` (gallery scope, notifications, an optional Gallery-widget reveal): the workbench derives it from the Gallery UI adapter, and the Launchpad's model manager, which has no workbench, supplies one itself. Media slots accept dragged gallery items only inside `GalleryDragScope`, which the workbench shell provides with its drag context; widget dialog hosts and the Launchpad sit outside it.
| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |
-| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |
+| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads and Gallery's public picker; descriptors/capabilities, catalog/load commands and manager contribution |
| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |
| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |
-| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |
+| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Models, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |
| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |
| Workflow | Workflow document, validation, compilation, preview/editor/library and explicit publication; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |
| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 78a0f8d93f..5dc3c67c05 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 893510,
+ "brotliBytes": 893586,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 892809,
+ "gzipBytes": 892942,
"imageRawBytes": 156376,
- "initialRawBytes": 2118301,
+ "initialRawBytes": 2118609,
"largestAssetRawBytes": 749035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 93111,
+ "ownedRawBytes": 93082,
"requestCount": 36,
"scriptRequestCount": 20,
"sourceOwners": [
@@ -334,17 +334,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1242105,
+ "brotliBytes": 1243382,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1236729,
+ "gzipBytes": 1237668,
"imageRawBytes": 156376,
- "initialRawBytes": 3202228,
+ "initialRawBytes": 3203516,
"largestAssetRawBytes": 749035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 144143,
- "requestCount": 77,
- "scriptRequestCount": 61,
+ "ownedRawBytes": 144128,
+ "requestCount": 74,
+ "scriptRequestCount": 58,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -511,6 +511,7 @@
"source:src/features/gallery/ui/GalleryDragCursor.tsx",
"source:src/features/gallery/ui/GalleryItemSearch.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
+ "source:src/features/gallery/ui/GallerySearchHelp.tsx",
"source:src/features/gallery/ui/GalleryTileFrame.tsx",
"source:src/features/gallery/ui/GalleryUiContext.tsx",
"source:src/features/gallery/ui/GalleryUploadButton.tsx",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 95723202ce..536ed05daa 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -919,6 +919,7 @@
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
+ "source:src/features/gallery/ui/GallerySearchHelp.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryStarredFilterToggle.tsx",
@@ -1978,6 +1979,7 @@
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
+ "source:src/features/gallery/ui/GallerySearchHelp.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryStarredFilterToggle.tsx",
@@ -3207,6 +3209,7 @@
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
+ "source:src/features/gallery/ui/GallerySearchHelp.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryStarredFilterToggle.tsx",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 085d84e39f..f212e8033e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1043,7 +1043,6 @@
"accessTokenPlaceholder": "Only needed for protected sources",
"accessTokenRequiredMessage": "This source needs an access token. Add one to continue.",
"actions": "Model actions",
- "addImage": "Add image",
"addModels": "Add Models",
"addModelsResults": "Add models results",
"addToken": "Add token",
@@ -1343,8 +1342,6 @@
"repoVariant": "Repo Variant",
"relatedModels": "Related Models",
"relatedModelsHelp": "Link the models that pair well with this one - they are suggested together elsewhere in the app.",
- "removeImage": "Remove image",
- "removeModelImage": "Remove model image",
"removeTriggerPhrase": "Remove trigger phrase {{phrase}}",
"resetBaseFilters": "Reset base filters",
"restartFileFailed": "Restart file failed",
@@ -1432,7 +1429,6 @@
"unlinkNamed": "Unlink {{name}}",
"updatePath": "Update path",
"updatePathDescription": "If the model file moved on disk, point Invoke at its new location. The file is not moved or copied.",
- "uploadCoverImageFor": "Upload cover image for {{name}}",
"useSupportedImage": "Use a PNG, JPEG, or WebP image.",
"variant": "Variant",
"variantHelp": "Architecture variant, e.g. inpaint or dev.",
@@ -3901,6 +3897,7 @@
"removeMedia": "Remove",
"removeVideo": "Remove video",
"replaceHint": "Click to replace, or drop from the Gallery",
+ "replaceClickHint": "Click to replace",
"replaceImage": "Replace image",
"replaceMedia": "Replace",
"replaceVideo": "Replace video",
diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
index e87dd7102d..06c7af5d62 100644
--- a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
@@ -119,9 +119,15 @@ if (uncoveredRoutes.length > 0) {
const failures = measurements.flatMap((measurement) => checkRouteBudget(measurement, budgets[measurement.routeId]));
const launchpad = measurements.find((measurement) => measurement.routeId === 'launchpad');
const editor = measurements.find((measurement) => measurement.routeId === 'editor');
-// Shared settings metadata must not turn Launchpad overlays into editor boot paths.
+// Launchpad overlays and pages load lazily, but must still never pull in (and run) the editor: loading its modules
+// ahead of the /app route mis-orders their start-up. Shared gallery and settings code is where that creeps in.
for (const source of [
+ 'src/features/fonts/ui/FontsPage.tsx',
+ 'src/features/gallery/ui/picker/GalleryPickerView.tsx',
+ 'src/features/models/ui/ModelManagerView.tsx',
+ 'src/features/nodes/ui/NodeManagerView.tsx',
'src/workbench/palette/LaunchpadCommandPaletteDialog.tsx',
+ 'src/workbench/settings/PreferencesPage.tsx',
'src/workbench/settings/SettingsDialog.tsx',
]) {
const overlay = measureRouteBuild(manifest, chunkSourceManifest, source, source, (file) => assetCache.get(file));
diff --git a/invokeai/frontend/webv2/src/features/gallery/picker.ts b/invokeai/frontend/webv2/src/features/gallery/picker.ts
index 6fdfe82b15..e3a9745b6f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/picker.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/picker.ts
@@ -6,3 +6,4 @@ export {
type GalleryPickerTileState,
} from './ui/picker/galleryPicker';
export { GalleryPickerPopover, type GalleryPickerPopoverProps } from './ui/picker/GalleryPickerPopover';
+export { GalleryHostProvider, type GalleryHost } from './ui/GalleryUiContext';
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx
index c646b26599..50c2b97d48 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx
@@ -1,38 +1,28 @@
import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';
-import { Box, Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';
+import { Box, HStack, Icon, Text } from '@chakra-ui/react';
import { semanticReferenceFromDataTransfer } from '@features/gallery/core/semanticImageQuery';
import { imageIndexAvailabilityOptions } from '@features/gallery/data/queries';
import { useMountEffect } from '@platform/react/useMountEffect';
import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';
-import { CloseButton, IconButton, ToggleIconButton } from '@platform/ui/Button';
+import { CloseButton, ToggleIconButton } from '@platform/ui/Button';
import { InputShell } from '@platform/ui/InputShell';
-import { PopoverContent } from '@platform/ui/Popover';
import { useQuery } from '@tanstack/react-query';
-import { CircleHelpIcon, ImageIcon, MapIcon, SparklesIcon } from 'lucide-react';
+import { ImageIcon, MapIcon, SparklesIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import { flushSync } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { GALLERY_SEMANTIC_SEARCH_DROP_ID, useGalleryImageDroppable } from './galleryDnd';
import { GallerySearchField } from './GallerySearchField';
+import { GallerySearchHelp } from './GallerySearchHelp';
import { useGalleryUi } from './GalleryUiContext';
import { useGalleryWidget } from './GalleryWidgetContext';
const SEARCH_HINT_ID = 'gallery-search-hint';
-const HELP_POSITIONING = { placement: 'bottom-end' } as const;
-
/** Debounce typing because each semantic commit embeds and reranks on the server. */
export const SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS = 300;
-/** The `key:value` forms `parseDateTokens` accepts, as shown in the help popover. */
-const DATE_TOKEN_EXAMPLES = [
- { descriptionKey: 'widgets.gallery.searchHelpFrom', key: 'from:2026-07-14' },
- { descriptionKey: 'widgets.gallery.searchHelpTo', key: 'to:yesterday' },
- { descriptionKey: 'widgets.gallery.searchHelpDate', key: 'date:today' },
- { descriptionKey: 'widgets.gallery.searchHelpRelative', key: 'from:7d' },
-] as const;
-
/** The full identity of the reference, surfaced as the chip's hover title. */
const getSemanticReferenceTitle = (reference: GallerySemanticReference): string => {
switch (reference.kind) {
@@ -427,44 +417,3 @@ const GallerySemanticChip = ({
</InputShell>
);
};
-
-/** Documents the closed date-token grammar the search box accepts. */
-export const GallerySearchHelp = () => {
- const { t } = useTranslation();
-
- return (
- <Popover.Root positioning={HELP_POSITIONING}>
- <Popover.Trigger asChild>
- <IconButton aria-label={t('widgets.gallery.searchHelpTitle')} color="fg.subtle" size="2xs" variant="ghost">
- <Icon as={CircleHelpIcon} boxSize="3.5" />
- </IconButton>
- </Popover.Trigger>
- <Portal>
- <Popover.Positioner>
- <PopoverContent maxW="18rem" p="3">
- <Stack gap="2">
- <Text fontSize="xs" fontWeight="600">
- {t('widgets.gallery.searchHelpTitle')}
- </Text>
- <Text color="fg.muted" fontSize="2xs">
- {t('widgets.gallery.searchHelpIntro')}
- </Text>
- <Stack gap="1.5">
- {DATE_TOKEN_EXAMPLES.map(({ descriptionKey, key }) => (
- <HStack key={key} align="start" gap="2">
- <Code flexShrink={0} fontSize="2xs" px="1">
- {key}
- </Code>
- <Text color="fg.muted" fontSize="2xs">
- {t(descriptionKey)}
- </Text>
- </HStack>
- ))}
- </Stack>
- </Stack>
- </PopoverContent>
- </Popover.Positioner>
- </Portal>
- </Popover.Root>
- );
-};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchHelp.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchHelp.tsx
new file mode 100644
index 0000000000..7f14932ef2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchHelp.tsx
@@ -0,0 +1,56 @@
+import { Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';
+import { IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { CircleHelpIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+const HELP_POSITIONING = { placement: 'bottom-end' } as const;
+
+/** The `key:value` forms `parseDateTokens` accepts, as shown in the help popover. */
+const DATE_TOKEN_EXAMPLES = [
+ { descriptionKey: 'widgets.gallery.searchHelpFrom', key: 'from:2026-07-14' },
+ { descriptionKey: 'widgets.gallery.searchHelpTo', key: 'to:yesterday' },
+ { descriptionKey: 'widgets.gallery.searchHelpDate', key: 'date:today' },
+ { descriptionKey: 'widgets.gallery.searchHelpRelative', key: 'from:7d' },
+] as const;
+
+/** Documents the closed date-token grammar the search box accepts. */
+export const GallerySearchHelp = () => {
+ const { t } = useTranslation();
+
+ return (
+ <Popover.Root positioning={HELP_POSITIONING}>
+ <Popover.Trigger asChild>
+ <IconButton aria-label={t('widgets.gallery.searchHelpTitle')} color="fg.subtle" size="2xs" variant="ghost">
+ <Icon as={CircleHelpIcon} boxSize="3.5" />
+ </IconButton>
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent maxW="18rem" p="3">
+ <Stack gap="2">
+ <Text fontSize="xs" fontWeight="600">
+ {t('widgets.gallery.searchHelpTitle')}
+ </Text>
+ <Text color="fg.muted" fontSize="2xs">
+ {t('widgets.gallery.searchHelpIntro')}
+ </Text>
+ <Stack gap="1.5">
+ {DATE_TOKEN_EXAMPLES.map(({ descriptionKey, key }) => (
+ <HStack key={key} align="start" gap="2">
+ <Code flexShrink={0} fontSize="2xs" px="1">
+ {key}
+ </Code>
+ <Text color="fg.muted" fontSize="2xs">
+ {t(descriptionKey)}
+ </Text>
+ </HStack>
+ ))}
+ </Stack>
+ </Stack>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
index 2e75da8be4..9d67b987de 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
@@ -3,7 +3,7 @@ import type { GallerySettings } from '@features/gallery/core/settings';
import type { GalleryBoard, GalleryBoardDeletionResult, GalleryImage, GalleryView } from '@features/gallery/core/types';
import type { QueueProgressSession } from '@features/queue/contracts';
-import { createContext, use, type ComponentType, type ReactNode } from 'react';
+import { createContext, use, useMemo, type ComponentType, type ReactNode } from 'react';
export interface GalleryItemActions {
deleteItems(items: GalleryItemRef[]): Promise<void>;
@@ -155,3 +155,52 @@ export const useGalleryUi = (): GalleryUiAdapter => {
return adapter;
};
+
+/** For hooks shared with hosts that have no workbench; they use it only for Gallery widget side effects. */
+export const useOptionalGalleryUi = (): GalleryUiAdapter | null => use(GalleryUiContext);
+
+/**
+ * What gallery surfaces outside the Gallery widget (the picker, media slots) need from their host. The workbench
+ * derives it from its UI adapter; a host without a workbench (the Launchpad) supplies one with GalleryHostProvider.
+ */
+export interface GalleryHost {
+ galleryValues: Record<string, unknown>;
+ notifications: GalleryNotificationsPort;
+ projectName: string;
+ /** Shows the Gallery widget at a view, switching board when one is given; absent where there is no widget. */
+ revealInGallery?: (location: { boardId: string | null; view: GalleryView }) => boolean;
+}
+
+const GalleryHostContext = createContext<GalleryHost | null>(null);
+
+export const GalleryHostProvider = ({ children, host }: { children: ReactNode; host: GalleryHost }) => (
+ <GalleryHostContext value={host}>{children}</GalleryHostContext>
+);
+
+export const useGalleryHost = (): GalleryHost => {
+ const host = use(GalleryHostContext);
+ const adapter = use(GalleryUiContext);
+ const derived = useMemo<GalleryHost | null>(
+ () =>
+ adapter && {
+ galleryValues: adapter.galleryValues,
+ notifications: adapter.notifications,
+ projectName: adapter.projectName,
+ revealInGallery: ({ boardId, view }) => {
+ if (boardId !== null) {
+ adapter.gallery.selectBoard(boardId);
+ }
+ adapter.gallery.setView(view);
+ return adapter.widgets.openGallery();
+ },
+ },
+ [adapter]
+ );
+ const resolved = host ?? derived;
+
+ if (!resolved) {
+ throw new Error('Gallery surfaces require a GalleryHostProvider or an App-composed GalleryUiProvider.');
+ }
+
+ return resolved;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
index ad602d6b6c..cf9cf8bd34 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
@@ -3,6 +3,7 @@ import type { GalleryBoardKind } from '@features/gallery/core/types';
import { useDndContext, useDroppable, type UseDroppableArguments } from '@dnd-kit/core';
import { toGalleryItemKey } from '@features/gallery/core/items';
+import { createContext } from 'react';
export interface GalleryItemDragData {
kind: 'gallery-item';
@@ -41,6 +42,12 @@ export const getGalleryItemDragId = (
scope?: string
): GalleryItemDragId => `${source}${scope ? `#${scope}` : ''}:${toGalleryItemKey(item)}`;
+/**
+ * True inside the drag context that gallery items are dragged in (the workbench shell). dnd-kit cannot say whether a
+ * DndContext is mounted, and surfaces outside it (widget dialog hosts, the Launchpad) still render gallery drop targets.
+ */
+export const GalleryDragScope = createContext(false);
+
export const getGalleryBoardDropId = (boardId: string): string => `gallery-board:${boardId}`;
/** Real boards and Uncategorized hold items; date boards are views and accept no moves. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
index c160f5a679..08c6667915 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
@@ -6,7 +6,7 @@ import type { GalleryUiAdapter } from '@features/gallery/react';
import { ChakraProvider } from '@chakra-ui/react';
import { DndContext, PointerSensor, useDraggable, useSensor, useSensors } from '@dnd-kit/core';
import { GalleryUiProvider } from '@features/gallery/react';
-import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/ui/galleryDnd';
+import { GalleryDragScope, getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/ui/galleryDnd';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { widgetCollisionDetection } from '@workbench/widgetDnd';
@@ -140,27 +140,30 @@ const renderSlot = async (props: Partial<Parameters<typeof GalleryMediaSlot>[0]>
<QueryClientProvider client={queryClient!}>
<GalleryUiProvider adapter={adapter}>
<DndContext collisionDetection={widgetCollisionDetection} sensors={sensors}>
- <DraggableThumb
- data={getGalleryItemDragData([IMAGE_REF])}
- id={getGalleryItemDragId(IMAGE_REF, 'preview-frame')}
- left={10}
- testId="image-thumb"
- />
- <DraggableThumb
- data={getGalleryItemDragData([VIDEO_REF])}
- id={getGalleryItemDragId(VIDEO_REF, 'preview-frame')}
- left={60}
- testId="video-thumb"
- />
- <DraggableThumb
- data={getGalleryItemDragData([IMAGE_REF, { kind: 'image', name: 'second.png' }])}
- id="multi-image-drag"
- left={110}
- testId="multi-thumb"
- />
- <div data-testid="slot" style={{ left: 200, position: 'fixed', top: 200, width: 320 }}>
- <GalleryMediaSlot accept={['image']} dropId="test-slot" value={null} onChange={onChange} {...props} />
- </div>
+ {/* As in the workbench shell, gallery drags are scoped to the drag context that carries them. */}
+ <GalleryDragScope value>
+ <DraggableThumb
+ data={getGalleryItemDragData([IMAGE_REF])}
+ id={getGalleryItemDragId(IMAGE_REF, 'preview-frame')}
+ left={10}
+ testId="image-thumb"
+ />
+ <DraggableThumb
+ data={getGalleryItemDragData([VIDEO_REF])}
+ id={getGalleryItemDragId(VIDEO_REF, 'preview-frame')}
+ left={60}
+ testId="video-thumb"
+ />
+ <DraggableThumb
+ data={getGalleryItemDragData([IMAGE_REF, { kind: 'image', name: 'second.png' }])}
+ id="multi-image-drag"
+ left={110}
+ testId="multi-thumb"
+ />
+ <div data-testid="slot" style={{ left: 200, position: 'fixed', top: 200, width: 320 }}>
+ <GalleryMediaSlot accept={['image']} dropId="test-slot" value={null} onChange={onChange} {...props} />
+ </div>
+ </GalleryDragScope>
</DndContext>
</GalleryUiProvider>
</QueryClientProvider>
@@ -385,4 +388,62 @@ describe('GalleryMediaSlot', () => {
expect(mocks.getGalleryItemByRef).not.toHaveBeenCalled();
});
+
+ it('renders outside any drag context, as in widget dialog hosts and on the Launchpad', async () => {
+ await interact(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient!}>
+ <GalleryUiProvider adapter={adapter}>
+ <GalleryMediaSlot accept={['image']} dropId="outside-slot" value={null} onChange={onChange} />
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+
+ expect(trigger()).not.toBeNull();
+ expect(alertText()).toBeNull();
+ // Nothing can be dragged in here, so neither face may promise a drop.
+ expect(host?.textContent).not.toContain('widgets.gallery.picker.dropHint');
+ });
+
+ it('lays out a square tile with the icon above its label and its actions overlaid, outside the drag scope', async () => {
+ const renderTile = (value: GalleryMediaSlotValue | null) =>
+ interact(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient!}>
+ <GalleryUiProvider adapter={adapter}>
+ <div style={{ width: 112 }}>
+ <GalleryMediaSlot
+ accept={['image']}
+ dropId="tile-slot"
+ layout="tile"
+ value={value}
+ onChange={onChange}
+ />
+ </div>
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+
+ await renderTile(null);
+ const face = trigger()!;
+ expect(face.getBoundingClientRect().height).toBe(face.getBoundingClientRect().width);
+ expect(face.textContent).toBe('widgets.gallery.picker.chooseImage');
+ const [icon, label] = [face.querySelector('svg')!, [...face.querySelectorAll('p')].at(-1)!];
+ expect(icon.getBoundingClientRect().bottom).toBeLessThanOrEqual(label.getBoundingClientRect().top);
+
+ await renderTile({ kind: 'image', name: 'cover.png' });
+ const remove = host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.picker.removeImage"]');
+ expect(remove).not.toBeNull();
+ // Beside the face, never inside it.
+ expect(trigger()?.contains(remove!)).toBe(false);
+ await interact(() => remove!.click());
+ expect(onChange).toHaveBeenCalledWith(null);
+ expect(document.activeElement).toBe(trigger());
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
index 8ed3e64fd3..4b69cf7135 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
@@ -8,20 +8,21 @@ import { getGalleryItemByRef } from '@features/gallery/data/backend';
import { getGalleryImageThumbnailUrl } from '@features/gallery/data/imageUrls';
import { getGalleryVideoThumbnailUrl } from '@features/gallery/data/videoUrls';
import { FindInGalleryThumbnailButton } from '@features/gallery/ui/FindInGalleryButton';
-import { isGalleryItemDragData, useGalleryItemDroppable } from '@features/gallery/ui/galleryDnd';
-import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';
+import { GalleryDragScope, isGalleryItemDragData, useGalleryItemDroppable } from '@features/gallery/ui/galleryDnd';
+import { useGalleryHost } from '@features/gallery/ui/GalleryUiContext';
import { useGalleryUploadInput } from '@features/gallery/ui/useGalleryUploadInput';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
-import { Button } from '@platform/ui/Button';
+import { Button, IconButton } from '@platform/ui/Button';
import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';
import { DropZone } from '@platform/ui/DropZone';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
+import { Tooltip } from '@platform/ui/Tooltip';
import { ChevronDownIcon, ImagePlusIcon, RefreshCwIcon, UploadIcon, XIcon } from 'lucide-react';
-import { useCallback, useMemo, useState, type ReactNode } from 'react';
+import { use, useCallback, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { GalleryPickerAccept } from './galleryPicker';
@@ -36,6 +37,8 @@ const DROP_ZONE_FOCUS_PROPS = {
};
const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };
const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };
+const TILE_ACTIONS_SHOWN = { opacity: 1, pointerEvents: 'auto' } as const;
+const preventClick = (event: MouseEvent) => event.preventDefault();
export interface GalleryMediaSlotValue {
height?: number;
@@ -66,12 +69,20 @@ const getDefaultLabels = (accept: GalleryPickerAccept, t: (key: string) => strin
const getThumbnailUrl = (value: GalleryMediaSlotValue): string =>
value.kind === 'video' ? getGalleryVideoThumbnailUrl(value.name) : getGalleryImageThumbnailUrl(value.name);
+/** Registered only inside the gallery drag scope; outside it (dialog hosts, the Launchpad) nothing can be dragged in. */
+const GalleryDragEndMonitor = ({ onDragEnd }: { onDragEnd: (event: DragEndEvent) => void }) => {
+ useDndMonitor({ onDragEnd });
+ return null;
+};
+
/**
* Own async resolution and report complete items through onChange. onUploadFile and custom thumbnails support
* media stored outside the gallery.
*/
export const GalleryMediaSlot = ({
accept,
+ busy = false,
+ layout = 'row',
disabled = false,
disabledReason,
dropId,
@@ -83,6 +94,13 @@ export const GalleryMediaSlot = ({
onUploadFile,
}: {
accept: GalleryPickerAccept;
+ /** The consumer is still acting on a pick (storing it elsewhere, say); the slot shows it working and waits. */
+ busy?: boolean;
+ /**
+ * `row` (the default) names the value beside its thumbnail with actions below; `tile` is a square face for a cover
+ * image, filling the width it is given, with its actions overlaid. Size a tile with its container.
+ */
+ layout?: 'row' | 'tile';
disabled?: boolean;
/** Shown in place of the affordances while disabled (e.g. a mutual exclusion). */
disabledReason?: string;
@@ -99,8 +117,11 @@ export const GalleryMediaSlot = ({
onUploadFile?: (file: File) => void;
}) => {
const { t } = useTranslation();
- const { notifications } = useGalleryUi();
- const [isBusy, setIsBusy] = useState(false);
+ const { notifications } = useGalleryHost();
+ const isInDragScope = use(GalleryDragScope);
+ const [isResolving, setIsResolving] = useState(false);
+ const triggerRef = useRef<HTMLDivElement | null>(null);
+ const isBusy = isResolving || busy;
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const isInert = disabled || isBusy;
const labels = useMemo(() => ({ ...getDefaultLabels(accept, t), ...labelOverrides }), [accept, labelOverrides, t]);
@@ -137,7 +158,7 @@ export const GalleryMediaSlot = ({
const owner = captureAccountScope();
setErrorMessage(null);
- setIsBusy(true);
+ setIsResolving(true);
try {
const item = await getGalleryItemByRef(ref, owner.signal);
@@ -150,7 +171,7 @@ export const GalleryMediaSlot = ({
}
} finally {
if (isAccountScopeCurrent(owner)) {
- setIsBusy(false);
+ setIsResolving(false);
}
}
},
@@ -168,8 +189,6 @@ export const GalleryMediaSlot = ({
[acceptsDrag, adoptRef, dropId, isInert]
);
- useDndMonitor({ onDragEnd: handleDragEnd });
-
const uploadOptions = useMemo(() => ({ accept: getGalleryUploadAccept(accept), multiple: false }), [accept]);
const handleUpload = useCallback(
([file]: File[]) => {
@@ -194,7 +213,11 @@ export const GalleryMediaSlot = ({
handleUpload,
uploadOptions
);
- const handleClear = useCallback(() => onChange(null), [onChange]);
+ // Remove unmounts with the value; hand focus to the slot rather than letting it fall to the page.
+ const handleClear = useCallback(() => {
+ triggerRef.current?.focus();
+ onChange(null);
+ }, [onChange]);
const handlePick = useCallback(
(item: GalleryItem) => {
setErrorMessage(null);
@@ -203,43 +226,118 @@ export const GalleryMediaSlot = ({
[onChange]
);
+ const isTile = layout === 'tile';
+ // Drops only arrive inside the gallery drag scope; elsewhere the hints must not promise them.
+ const emptyHint = disabled && disabledReason ? disabledReason : isBusy ? t('widgets.gallery.picker.working') : null;
+ const valueHint =
+ emptyHint ??
+ (isInDragScope ? t('widgets.gallery.picker.replaceHint') : t('widgets.gallery.picker.replaceClickHint'));
+ const valueThumbnail = value
+ ? (thumbnail ?? (
+ <Image
+ alt=""
+ boxSize="full"
+ objectFit={isTile ? 'cover' : 'contain'}
+ outline="1px solid"
+ outlineColor="border.image"
+ outlineOffset="-1px"
+ rounded="sm"
+ src={getThumbnailUrl(value)}
+ />
+ ))
+ : null;
+ const removeAction = value ? (
+ isTile ? (
+ <Tooltip content={labels.remove}>
+ <IconButton aria-label={labels.remove} disabled={isBusy} size="2xs" variant="solid" onClick={handleClear}>
+ <XIcon />
+ </IconButton>
+ </Tooltip>
+ ) : (
+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={handleClear}>
+ <Icon as={XIcon} boxSize="3" />
+ {labels.remove}
+ </Button>
+ )
+ ) : null;
+ const uploadAction =
+ onUploadFile && !disabled ? (
+ isTile ? (
+ <Tooltip content={t('widgets.gallery.picker.upload')}>
+ <IconButton
+ aria-label={t('widgets.gallery.picker.upload')}
+ disabled={isBusy}
+ size="2xs"
+ variant="solid"
+ onClick={openUploadPicker}
+ >
+ <UploadIcon />
+ </IconButton>
+ </Tooltip>
+ ) : (
+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={openUploadPicker}>
+ <Icon as={UploadIcon} boxSize="3" />
+ {t('widgets.gallery.picker.upload')}
+ </Button>
+ )
+ ) : null;
+
return (
<Stack gap="2">
<Box ref={setNodeRef} className="group" position="relative">
<GalleryPickerPopover accept={accept} label={labels.choose} onPick={handlePick}>
<DropZone
+ ref={triggerRef}
as="button"
aria-busy={isBusy || undefined}
- aria-disabled={disabled || undefined}
+ aria-disabled={isInert || undefined}
aria-label={value ? labels.replace : labels.choose}
+ aspectRatio={isTile ? 1 : undefined}
cursor={disabled ? 'not-allowed' : undefined}
- disabled={isInert}
+ // Busy stays focusable (`aria-disabled`): Remove hands focus here while the action runs.
+ disabled={disabled}
isDisabled={isInert}
+ onClickCapture={isBusy ? preventClick : undefined}
isInvalid={errorMessage !== null}
isOver={isOver}
- minH="20"
+ minH={isTile ? undefined : '20'}
overflow="hidden"
+ position="relative"
textAlign="start"
w="full"
_disabled={DROP_ZONE_DISABLED_PROPS}
_focusVisible={DROP_ZONE_FOCUS_PROPS}
_hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}
>
- {value ? (
+ {isTile ? (
+ <>
+ {valueThumbnail ? (
+ <Box inset="0" position="absolute">
+ {valueThumbnail}
+ </Box>
+ ) : (
+ <Stack align="center" color="fg.muted" gap="1.5" h="full" justify="center" px="2" textAlign="center">
+ <Icon as={ImagePlusIcon} boxSize="5" />
+ <Text color="fg" fontSize="xs" fontWeight="600">
+ {labels.choose}
+ </Text>
+ {emptyHint && !isBusy ? (
+ <Text color="fg.muted" fontSize="2xs">
+ {emptyHint}
+ </Text>
+ ) : null}
+ </Stack>
+ )}
+ {isBusy ? (
+ <Stack align="center" bg="bg.muted/85" inset="0" justify="center" position="absolute">
+ <Spinner size="sm" />
+ </Stack>
+ ) : null}
+ </>
+ ) : value ? (
<HStack align="stretch" gap="3" h="20" p="2">
<Box bg="blackAlpha.300" boxSize="16" flexShrink="0" overflow="hidden" rounded="sm">
- {thumbnail ?? (
- <Image
- alt=""
- boxSize="full"
- objectFit="contain"
- outline="1px solid"
- outlineColor="border.image"
- outlineOffset="-1px"
- rounded="sm"
- src={getThumbnailUrl(value)}
- />
- )}
+ {valueThumbnail}
</Box>
<Stack align="start" flex="1" gap="1" justify="center" minW="0">
<MiddleTruncate color="fg" fontSize="xs" fontWeight="semibold" text={value.name} />
@@ -250,13 +348,7 @@ export const GalleryMediaSlot = ({
) : null}
<HStack color="fg.muted" gap="1">
{isBusy ? <Spinner size="xs" /> : <Icon as={RefreshCwIcon} boxSize="2.5" />}
- <Text fontSize="2xs">
- {disabled && disabledReason
- ? disabledReason
- : isBusy
- ? t('widgets.gallery.picker.working')
- : t('widgets.gallery.picker.replaceHint')}
- </Text>
+ <Text fontSize="2xs">{valueHint}</Text>
</HStack>
</Stack>
</HStack>
@@ -271,44 +363,56 @@ export const GalleryMediaSlot = ({
<Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />
</HStack>
)}
- <Text color="fg.muted" fontSize="2xs" textAlign="center">
- {disabled && disabledReason
- ? disabledReason
- : isBusy
- ? t('widgets.gallery.picker.working')
- : t('widgets.gallery.picker.dropHint')}
- </Text>
+ {emptyHint || isInDragScope ? (
+ <Text color="fg.muted" fontSize="2xs" textAlign="center">
+ {emptyHint ?? t('widgets.gallery.picker.dropHint')}
+ </Text>
+ ) : null}
</Stack>
)}
</DropZone>
</GalleryPickerPopover>
{value && onFind ? (
- /*
- * Keep the badge beside the button face to avoid nested buttons; matching row metrics align it without
- * measurement.
- */
- <HStack gap="3" h="20" insetInline="0" p="2" pointerEvents="none" position="absolute" top="0">
- <Box boxSize="16" flexShrink="0" position="relative">
+ isTile ? (
+ <Box left="1" position="absolute" top="1">
<FindInGalleryThumbnailButton name={value.name} onFind={onFind} />
</Box>
+ ) : (
+ /*
+ * Keep the badge beside the button face to avoid nested buttons; matching row metrics align it without
+ * measurement.
+ */
+ <HStack gap="3" h="20" insetInline="0" p="2" pointerEvents="none" position="absolute" top="0">
+ <Box boxSize="16" flexShrink="0" position="relative">
+ <FindInGalleryThumbnailButton name={value.name} onFind={onFind} />
+ </Box>
+ </HStack>
+ )
+ ) : null}
+ {isTile && (removeAction || uploadAction) ? (
+ // Siblings of the trigger, not children: a button must not nest inside another.
+ <HStack
+ gap="0.5"
+ opacity={0}
+ pointerEvents="none"
+ position="absolute"
+ right="1"
+ top="1"
+ transition="opacity var(--wb-motion-duration-fast) ease"
+ _groupFocusWithin={TILE_ACTIONS_SHOWN}
+ _groupHover={TILE_ACTIONS_SHOWN}
+ >
+ {uploadAction}
+ {removeAction}
</HStack>
) : null}
<DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={labels.drop} />
+ {isInDragScope ? <GalleryDragEndMonitor onDragEnd={handleDragEnd} /> : null}
</Box>
- {(onUploadFile && !disabled) || value ? (
+ {!isTile && (uploadAction || removeAction) ? (
<HStack justify="end">
- {onUploadFile && !disabled ? (
- <Button disabled={isBusy} size="xs" variant="ghost" onClick={openUploadPicker}>
- <Icon as={UploadIcon} boxSize="3" />
- {t('widgets.gallery.picker.upload')}
- </Button>
- ) : null}
- {value ? (
- <Button disabled={isBusy} size="xs" variant="ghost" onClick={handleClear}>
- <Icon as={XIcon} boxSize="3" />
- {labels.remove}
- </Button>
- ) : null}
+ {uploadAction}
+ {removeAction}
</HStack>
) : null}
{errorMessage ? (
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
index 93eae1219c..16d21497d9 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
@@ -2,10 +2,12 @@
import type { GalleryItem } from '@features/gallery/core/items';
import type { GalleryBoard } from '@features/gallery/core/types';
import type { GalleryUiAdapter } from '@features/gallery/react';
+import type { GalleryHost } from '@features/gallery/ui/GalleryUiContext';
import { ChakraProvider } from '@chakra-ui/react';
import { getGalleryUploadAccept, legacyGeneratedImageToGalleryItem } from '@features/gallery/core/items';
import { GalleryUiProvider } from '@features/gallery/react';
+import { GalleryHostProvider } from '@features/gallery/ui/GalleryUiContext';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act, useCallback, useState } from 'react';
@@ -159,18 +161,24 @@ const settle = async () => {
}
};
-const renderPicker = async (picker?: React.ReactElement) => {
+/** A host without a workbench (the Launchpad): no Gallery widget scope to seed from or reveal. */
+const launchpadHost: GalleryHost = { galleryValues: {}, notifications, projectName: '' };
+
+const renderPicker = async (picker?: React.ReactElement, { withoutWorkbench = false } = {}) => {
+ const content = picker ?? (
+ <GalleryPickerPopover accept={['image']} label="Choose image" onPick={onPick}>
+ <button type="button">Choose image</button>
+ </GalleryPickerPopover>
+ );
await act(() =>
root?.render(
<ChakraProvider value={system}>
<QueryClientProvider client={queryClient!}>
- <GalleryUiProvider adapter={adapter}>
- {picker ?? (
- <GalleryPickerPopover accept={['image']} label="Choose image" onPick={onPick}>
- <button type="button">Choose image</button>
- </GalleryPickerPopover>
- )}
- </GalleryUiProvider>
+ {withoutWorkbench ? (
+ <GalleryHostProvider host={launchpadHost}>{content}</GalleryHostProvider>
+ ) : (
+ <GalleryUiProvider adapter={adapter}>{content}</GalleryUiProvider>
+ )}
</QueryClientProvider>
</ChakraProvider>
)
@@ -185,8 +193,8 @@ const renderPicker = async (picker?: React.ReactElement) => {
return trigger;
};
-const openPicker = async (picker?: React.ReactElement) => {
- const trigger = await renderPicker(picker);
+const openPicker = async (picker?: React.ReactElement, options?: { withoutWorkbench?: boolean }) => {
+ const trigger = await renderPicker(picker, options);
await act(() => trigger.click());
await settle();
@@ -556,4 +564,21 @@ describe('GalleryPickerPopover', () => {
expect(openGallery).toHaveBeenCalledOnce();
expect(document.querySelector(OPEN_DIALOG)).not.toBeNull();
});
+
+ it('picks without a workbench and offers no hand-off to a Gallery widget there', async () => {
+ const { dialog } = await openPicker(undefined, { withoutWorkbench: true });
+ const [first] = getOptions(dialog);
+
+ expect(first).toBeDefined();
+ expect(
+ [...dialog.querySelectorAll('button')].some((button) =>
+ button.textContent?.includes('widgets.gallery.picker.openGallery')
+ )
+ ).toBe(false);
+
+ await act(() => first!.click());
+
+ expect(onPick).toHaveBeenCalledOnce();
+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx
index 6900376f3d..daa6c36dab 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx
@@ -6,10 +6,10 @@ import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
import { getGalleryUploadAccept, toGalleryItemKey } from '@features/gallery/core/items';
import { BoardCover, BoardCoverIcon } from '@features/gallery/ui/GalleryBoardCover';
import { getGalleryBoardGroups } from '@features/gallery/ui/galleryBoardGroups';
-import { GallerySearchHelp } from '@features/gallery/ui/GalleryItemSearch';
import { GallerySearchField } from '@features/gallery/ui/GallerySearchField';
+import { GallerySearchHelp } from '@features/gallery/ui/GallerySearchHelp';
import { getGalleryProjectBoardId, getGallerySelectedBoardId } from '@features/gallery/ui/galleryStateView';
-import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';
+import { useGalleryHost } from '@features/gallery/ui/GalleryUiContext';
import { getGalleryUploadTargetLabel } from '@features/gallery/ui/GalleryUploadButton';
import { GalleryViewSegmentTabs } from '@features/gallery/ui/GalleryViewTabs';
import { useGalleryUploadAction } from '@features/gallery/ui/useGalleryUploadAction';
@@ -59,7 +59,7 @@ export const GalleryPickerView = ({
onPick: (item: GalleryItem) => void;
}) => {
const { t } = useTranslation();
- const { gallery: galleryCommands, galleryValues, projectName, widgets } = useGalleryUi();
+ const { galleryValues, projectName, revealInGallery } = useGalleryHost();
const { data, gallerySelectedItem, scope, selectBoard, setSearchTerm, setView, settings, togglePane } =
useGalleryPickerScope();
const idBase = useId();
@@ -291,16 +291,13 @@ export const GalleryPickerView = ({
const handleClearSearch = useCallback(() => setSearchTerm(''), [setSearchTerm]);
const openGallery = useCallback(() => {
- if (data.selectedBoardId !== getGallerySelectedBoardId(galleryValues, data.boards)) {
- galleryCommands.selectBoard(data.selectedBoardId);
- }
-
- galleryCommands.setView(scope.galleryView);
+ const boardId =
+ data.selectedBoardId !== getGallerySelectedBoardId(galleryValues, data.boards) ? data.selectedBoardId : null;
- if (widgets.openGallery()) {
+ if (revealInGallery?.({ boardId, view: scope.galleryView })) {
onClose();
}
- }, [data.boards, data.selectedBoardId, galleryCommands, galleryValues, onClose, scope.galleryView, widgets]);
+ }, [data.boards, data.selectedBoardId, galleryValues, onClose, revealInGallery, scope.galleryView]);
const status = getGalleryPickerStatus({
accept,
@@ -465,12 +462,12 @@ export const GalleryPickerView = ({
<Button flexShrink={0} size="2xs" variant="subtle" onClick={onClose}>
{t('common.done')}
</Button>
- ) : (
+ ) : revealInGallery ? (
<Button color="fg.muted" flexShrink={0} size="2xs" variant="ghost" onClick={openGallery}>
{t('widgets.gallery.picker.openGallery')}
<Icon as={ExternalLinkIcon} boxSize="3" />
</Button>
- )}
+ ) : null}
</HStack>
</Stack>
);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts
index dd4af68437..35864698d5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts
@@ -8,7 +8,7 @@ import {
getGalleryRawSelectedBoardId,
getGalleryView,
} from '@features/gallery/ui/galleryStateView';
-import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';
+import { useGalleryHost } from '@features/gallery/ui/GalleryUiContext';
import { useGalleryData } from '@features/gallery/ui/useGalleryData';
import { useCallback, useDeferredValue, useMemo, useState } from 'react';
@@ -28,7 +28,7 @@ export interface GalleryPickerScope {
* differently.
*/
export const useGalleryPickerScope = () => {
- const { galleryValues } = useGalleryUi();
+ const { galleryValues } = useGalleryHost();
const [scope, setScope] = useState<GalleryPickerScope>(() => ({
boardId: getGalleryRawSelectedBoardId(galleryValues),
galleryView: getGalleryView(galleryValues),
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts
index 236bb3320d..c7573394e7 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts
@@ -22,7 +22,7 @@ import { useTranslation } from 'react-i18next';
import type { GalleryActions } from './GalleryWidgetContext';
-import { useGalleryUi } from './GalleryUiContext';
+import { useGalleryHost, useOptionalGalleryUi } from './GalleryUiContext';
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const uploadLogger = createLogger({ area: 'upload', namespace: 'gallery' });
@@ -33,12 +33,16 @@ export const useGalleryUploadAction = ({
selectedBoardId: selectedBoardIdOrGetter,
}: {
boards: GalleryBoard[];
- /** Where the gallery is showing on completion; the newest upload visible there gets selected. Omit to leave the selection alone. */
+ /**
+ * Where the Gallery widget is showing on completion; the newest upload visible there gets selected. Omit to leave
+ * the selection alone, as hosts without a workbench must.
+ */
getCurrentGalleryLocation?: () => { galleryView: GalleryView; selectedBoardId: string };
/** A getter is read when the upload starts, for hosts that must not re-render on board changes. */
selectedBoardId: string | (() => string);
}): GalleryActions['uploadFiles'] => {
- const { gallery, notifications } = useGalleryUi();
+ const { notifications } = useGalleryHost();
+ const gallery = useOptionalGalleryUi()?.gallery;
const queryClient = useQueryClient();
const { t } = useTranslation();
@@ -171,7 +175,7 @@ export const useGalleryUploadAction = ({
);
if (newestVisibleUpload) {
- gallery.selectItem(newestVisibleUpload);
+ gallery?.selectItem(newestVisibleUpload);
}
void invalidateGallery(queryClient);
diff --git a/invokeai/frontend/webv2/src/features/gallery/utility.ts b/invokeai/frontend/webv2/src/features/gallery/utility.ts
index d731d919c6..4c5081ea97 100644
--- a/invokeai/frontend/webv2/src/features/gallery/utility.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/utility.ts
@@ -1,4 +1,5 @@
export {
+ GalleryDragScope,
getGalleryBoardDropData,
getGalleryBoardDropId,
getGalleryItemDragData,
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx
index 1bbb05368d..7eb9ede802 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx
@@ -1,7 +1,7 @@
import { ChakraProvider } from '@chakra-ui/react';
import { type AccountScope, accountLifecycle } from '@platform/state/accountLifecycle';
import { system } from '@theme/system';
-import { act } from 'react';
+import { act, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
@@ -26,6 +26,24 @@ vi.mock('@features/models/data/modelsStore', () => ({
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+/** The picker's own view is covered by its tests; a pick here hands over an item whose full image is a data URL. */
+const PICKED_PNG =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
+vi.mock('@features/gallery/ui/picker/GalleryPickerPopover', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ GalleryPickerPopover: ({ children, onPick }: { children: ReactNode; onPick: (item: unknown) => void }) => (
+ <>
+ {children}
+ <button
+ aria-label="Pick"
+ data-gallery-pick
+ type="button"
+ onClick={() => onPick({ fullUrl: PICKED_PNG, kind: 'image', name: 'picked.png' })}
+ />
+ </>
+ ),
+}));
+
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const deferred = <Value,>() => {
@@ -74,32 +92,35 @@ describe('ModelImageUpload account ownership', () => {
accountLifecycle.invalidate();
});
- const upload = async (file: File): Promise<void> => {
- const input = host.querySelector<HTMLInputElement>('input[type="file"]')!;
-
- Object.defineProperty(input, 'files', { configurable: true, value: [file] });
- input.dispatchEvent(new Event('change', { bubbles: true }));
- await Promise.resolve();
- };
+ const pick = () => act(() => host.querySelector<HTMLButtonElement>('[data-gallery-pick]')!.click());
- it('commits an upload only while its account lifetime is current', async () => {
- const file = new File(['image'], 'cover.png', { type: 'image/png' });
-
- await act(() => upload(file));
+ it('sets a gallery image as the cover from its full image, only while its account lifetime is current', async () => {
+ await pick();
await vi.waitFor(() => expect(onUpdated).toHaveBeenCalledOnce());
- expect(dependencies.updateModelImage).toHaveBeenCalledWith(model.key, file, owner.signal);
+ const [key, file, signal] = dependencies.updateModelImage.mock.calls[0] as [string, File, AbortSignal];
+ expect(key).toBe(model.key);
+ expect(file).toBeInstanceOf(File);
+ expect(file.name).toBe('picked.png');
+ expect(file.type).toBe('image/png');
+ expect(signal).toBe(owner.signal);
expect(dependencies.markCoverImageChanged).toHaveBeenCalledWith(model.key, true);
expect(onError).not.toHaveBeenCalled();
});
- it('quietly drops an account A upload that resolves after account B activates', async () => {
+ it('offers no separate upload: new files arrive through the gallery picker', () => {
+ expect(host.querySelector('input[type="file"]')).toBeNull();
+ expect([...host.querySelectorAll('button')].map((button) => button.textContent)).not.toContain(
+ 'widgets.gallery.picker.upload'
+ );
+ });
+
+ it('quietly drops an account A cover that resolves after account B activates', async () => {
const request = deferred<void>();
- const file = new File(['image'], 'cover.png', { type: 'image/png' });
dependencies.updateModelImage.mockReturnValueOnce(request.promise);
- await act(() => upload(file));
- expect(dependencies.updateModelImage).toHaveBeenCalledWith(model.key, file, owner.signal);
+ await pick();
+ await vi.waitFor(() => expect(dependencies.updateModelImage).toHaveBeenCalled());
await act(async () => {
accountLifecycle.activate('model-image-b', ':user:model-image-b');
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
index 44a7246295..2dc43197db 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
@@ -1,20 +1,24 @@
-/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type { GalleryItem } from '@features/gallery';
+import type { GalleryHost, GalleryPickerAccept } from '@features/gallery/picker';
import type { ModelConfig } from '@features/models/core/types';
-import { Box, Flex, Icon, Image, Stack, Text } from '@chakra-ui/react';
+import { Box, Image } from '@chakra-ui/react';
+import { GalleryMediaSlot } from '@features/gallery/mediaSlot';
+import { GalleryHostProvider } from '@features/gallery/picker';
import { deleteModelImage, getModelImageUrl, updateModelImage } from '@features/models/data/api';
import { markCoverImageChanged, useModelsSelector } from '@features/models/data/modelsStore';
+import { useNotify } from '@features/models/ui/useModelsNotify';
import { useScopedAction } from '@platform/react/useScopedAction';
import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
-import { DropZone, IconButton, Tooltip } from '@platform/ui';
-import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';
-import { useRef, useState, type DragEvent } from 'react';
+import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
-
-const dragContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');
+const IMAGE_ONLY: GalleryPickerAccept = ['image'];
+/** The model manager lives on the Launchpad: no project board to seed from and no Gallery widget to reveal. */
+const NO_GALLERY_VALUES: Record<string, unknown> = {};
interface ModelImageUploadProps {
model: Pick<ModelConfig, 'cover_image' | 'key' | 'name'>;
@@ -26,35 +30,67 @@ export const ModelImageUpload = (props: ModelImageUploadProps) => (
<ModelImageUploadForModel key={`${props.model.key}:${props.model.cover_image ?? ''}`} {...props} />
);
+/** The cover is chosen like any image slot, as a square tile: from the gallery, where the picker also uploads files. */
const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploadProps) => {
const { t } = useTranslation();
- const inputRef = useRef<HTMLInputElement | null>(null);
- const dragDepthRef = useRef(0);
const imageVersion = useModelsSelector((snapshot) => snapshot.coverImageVersions[model.key]);
const [hasImage, setHasImage] = useState(Boolean(model.cover_image));
- const [isDropActive, setIsDropActive] = useState(false);
- // Upload and delete share one busy flag: the tile hosts one action at a time.
+ // Setting and removing share one busy flag: the slot hosts one action at a time.
const { isBusy, run } = useScopedAction();
+ const notify = useNotify();
+ const galleryHost = useMemo<GalleryHost>(
+ () => ({
+ galleryValues: NO_GALLERY_VALUES,
+ notifications: {
+ add: ({ kind, message, title }) => notify[kind](title, message),
+ reportError: ({ message }) => notify.error(message),
+ },
+ projectName: '',
+ }),
+ [notify]
+ );
+ const value = useMemo(
+ () => (hasImage ? { kind: 'image' as const, name: t('models.modelCoverAlt', { name: model.name }) } : null),
+ [hasImage, model.name, t]
+ );
+ const thumbnail = useMemo(
+ () => (
+ <Image
+ alt=""
+ boxSize="full"
+ fit="cover"
+ src={getModelImageUrl(model.key, imageVersion ? String(imageVersion) : undefined)}
+ onError={() => setHasImage(false)}
+ />
+ ),
+ [imageVersion, model.key]
+ );
- const handleFile = async (file: File | undefined) => {
- if (!file) {
- return;
- }
-
- if (!ACCEPTED_TYPES.has(file.type)) {
- onError(t('models.useSupportedImage'));
- return;
- }
-
+ // The server keeps the full image as the cover, so take the original rather than the gallery thumbnail.
+ const setCover = (item: GalleryItem) => {
const modelKey = model.key;
- await run(
+ void run(
async (owner) => {
- await updateModelImage(modelKey, file, owner.signal);
+ const response = await fetch(item.fullUrl, { signal: owner.signal });
+
+ if (!response.ok) {
+ throw new Error(`${response.status} ${response.statusText}`);
+ }
+
+ const blob = await response.blob();
+
+ assertAccountScopeCurrent(owner);
+ if (!ACCEPTED_TYPES.has(blob.type)) {
+ onError(t('models.useSupportedImage'));
+ return;
+ }
+
+ await updateModelImage(modelKey, new File([blob], item.name, { type: blob.type }), owner.signal);
assertAccountScopeCurrent(owner);
setHasImage(true);
- // Bumps the cache-bust version so this tile and list thumbnails reload.
+ // Bumps the cache-bust version so this slot and list thumbnails reload.
markCoverImageChanged(modelKey, true);
onUpdated();
},
@@ -62,10 +98,10 @@ const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploa
);
};
- const handleDelete = async () => {
+ const removeCover = () => {
const modelKey = model.key;
- await run(
+ void run(
async (owner) => {
await deleteModelImage(modelKey, owner.signal);
@@ -79,132 +115,18 @@ const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploa
};
return (
- <DropZone
- aria-busy={isBusy || undefined}
- aria-label={t('models.uploadCoverImageFor', { name: model.name })}
- bg={isDropActive ? 'accent.muted' : 'bg.emphasized'}
- borderStyle={hasImage ? 'solid' : 'dashed'}
- boxSize="24"
- flexShrink={0}
- isOver={isDropActive}
- overflow="hidden"
- position="relative"
- role="button"
- tabIndex={0}
- className="group"
- _focusVisible={{ outline: '2px solid {colors.accent.solid}', outlineOffset: '2px' }}
- onClick={() => {
- if (!isBusy) {
- inputRef.current?.click();
- }
- }}
- onKeyDown={(event) => {
- if ((event.key === 'Enter' || event.key === ' ') && !isBusy) {
- event.preventDefault();
- inputRef.current?.click();
- }
- }}
- onDragEnter={(event) => {
- if (!dragContainsFiles(event)) {
- return;
- }
-
- event.preventDefault();
- dragDepthRef.current += 1;
- setIsDropActive(true);
- }}
- onDragLeave={(event) => {
- if (!dragContainsFiles(event)) {
- return;
- }
-
- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
-
- if (dragDepthRef.current === 0) {
- setIsDropActive(false);
- }
- }}
- onDragOver={(event) => {
- if (dragContainsFiles(event)) {
- event.preventDefault();
- }
- }}
- onDrop={(event) => {
- if (!dragContainsFiles(event)) {
- return;
- }
-
- event.preventDefault();
- dragDepthRef.current = 0;
- setIsDropActive(false);
- void handleFile(event.dataTransfer.files[0]);
- }}
- >
- <input
- ref={inputRef}
- accept="image/png,image/jpeg,image/webp"
- hidden
- type="file"
- onChange={(event) => {
- void handleFile(event.currentTarget.files?.[0] ?? undefined);
- event.currentTarget.value = '';
- }}
- onClick={(event) => event.stopPropagation()}
- />
- {hasImage ? (
- <Image
- alt={t('models.modelCoverAlt', { name: model.name })}
- boxSize="full"
- fit="cover"
- src={getModelImageUrl(model.key, imageVersion ? String(imageVersion) : undefined)}
- onError={() => setHasImage(false)}
+ <GalleryHostProvider host={galleryHost}>
+ <Box flexShrink={0} w="28">
+ <GalleryMediaSlot
+ accept={IMAGE_ONLY}
+ busy={isBusy}
+ dropId={`model-cover:${model.key}`}
+ layout="tile"
+ thumbnail={thumbnail}
+ value={value}
+ onChange={(item) => (item ? setCover(item) : removeCover())}
/>
- ) : (
- <Stack align="center" boxSize="full" color="fg.subtle" gap="1" justify="center">
- <Icon as={ImageIcon} boxSize="5" />
- <Text fontSize="2xs">{t('models.addImage')}</Text>
- </Stack>
- )}
- {isDropActive ? (
- <Flex
- align="center"
- bg="bg.muted/85"
- boxSize="full"
- inset="0"
- justify="center"
- pointerEvents="none"
- position="absolute"
- >
- <Icon as={UploadIcon} boxSize="5" color="accent.solid" />
- </Flex>
- ) : null}
- {hasImage && !isDropActive ? (
- <Box
- opacity={0}
- pointerEvents="none"
- position="absolute"
- right="1"
- top="1"
- transition="opacity var(--wb-motion-duration-fast) ease"
- _groupFocusWithin={{ opacity: 1, pointerEvents: 'auto' }}
- _groupHover={{ opacity: 1, pointerEvents: 'auto' }}
- >
- <Tooltip content={t('models.removeImage')}>
- <IconButton
- aria-label={t('models.removeModelImage')}
- colorPalette="red"
- size="2xs"
- variant="solid"
- onClick={(event) => {
- event.stopPropagation();
- void handleDelete();
- }}
- >
- <Icon as={XIcon} boxSize="3" />
- </IconButton>
- </Tooltip>
- </Box>
- ) : null}
- </DropZone>
+ </Box>
+ </GalleryHostProvider>
);
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUploadPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUploadPicker.browser.test.tsx
new file mode 100644
index 0000000000..6e64812cf9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUploadPicker.browser.test.tsx
@@ -0,0 +1,89 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+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 { ModelImageUpload } from './ModelImageUpload';
+
+const dependencies = vi.hoisted(() => ({ deleteModelImage: vi.fn() }));
+
+vi.mock('@features/models/data/api', () => ({
+ deleteModelImage: dependencies.deleteModelImage,
+ getModelImageUrl: () => '/model-image.png',
+ updateModelImage: vi.fn(),
+}));
+vi.mock('@features/models/data/modelsStore', () => ({
+ markCoverImageChanged: vi.fn(),
+ useModelsSelector: (selector: (snapshot: { coverImageVersions: Record<string, number> }) => unknown) =>
+ selector({ coverImageVersions: {} }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const model = { cover_image: 'cover.png', key: 'model-a', name: 'Model A' };
+const NOOP = () => {};
+
+/** The real picker trigger on the Launchpad: no workbench, so the tile supplies its own gallery host. */
+describe('ModelImageUpload gallery picker', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ dependencies.deleteModelImage.mockReset();
+ accountLifecycle.activate('model-image-picker', ':user:model-image-picker');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <ModelImageUpload model={model} onError={NOOP} onUpdated={NOOP} />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ // The slot button opens the picker; its name switches between choose and replace with the cover it shows.
+ const tile = () => host.querySelector<HTMLElement>('button[aria-haspopup="dialog"]')!;
+ const picker = () => document.querySelector('[role="dialog"][aria-label="widgets.gallery.picker.chooseImage"]');
+
+ it('opens the gallery picker from the keyboard', async () => {
+ await act(() => tile().focus());
+ await userEvent.keyboard('{Enter}');
+
+ await vi.waitFor(() => expect(picker()).not.toBeNull());
+ expect(tile().getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('keeps focus on the tile and does not open the picker while the cover is being removed', async () => {
+ dependencies.deleteModelImage.mockReturnValue(new Promise(NOOP));
+ const remove = host.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.picker.removeImage"]')!;
+
+ await act(() => remove.click());
+ await vi.waitFor(() => expect(tile().getAttribute('aria-busy')).toBe('true'));
+ // Remove handed focus to the tile; busy must not disable it out from under that focus (fixed up next frame).
+ await new Promise(requestAnimationFrame);
+ await new Promise(requestAnimationFrame);
+ expect(document.activeElement).toBe(tile());
+
+ await act(() => tile().click());
+
+ expect(picker()).toBeNull();
+ expect(tile().getAttribute('aria-expanded')).toBe('false');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index d91fc74c1a..d89c255343 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -12,7 +12,7 @@ import {
} from '@dnd-kit/core';
import { restrictToWindowEdges } from '@dnd-kit/modifiers';
import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
-import { GalleryDragCursor } from '@features/gallery/utility';
+import { GalleryDragCursor, GalleryDragScope } from '@features/gallery/utility';
import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { useMountEffect } from '@platform/react/useMountEffect';
import { FocusRegionProvider } from '@workbench/focusRegions';
@@ -291,61 +291,63 @@ export const WorkbenchShell = () => {
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
>
- <Flex direction="column" h="100vh" w="100vw">
- <WorkbenchNotificationToaster />
- <DocumentTitleProgress />
- <TopBar />
- <ProjectConflictBanner />
- <QueueRecoveryBanner />
+ <GalleryDragScope value>
+ <Flex direction="column" h="100vh" w="100vw">
+ <WorkbenchNotificationToaster />
+ <DocumentTitleProgress />
+ <TopBar />
+ <ProjectConflictBanner />
+ <QueueRecoveryBanner />
- <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">
- <VisuallyHidden as="h1" id="workbench-project-heading">
- {projectName}
- </VisuallyHidden>
- {/* Use a named content region: the project switcher is no longer a tablist. */}
- <Flex
- aria-labelledby="workbench-project-heading"
- flex="1"
- id={PROJECT_CONTENT_PANEL_ID}
- minH="0"
- overflow="hidden"
- role="region"
- >
- <WidgetBar
- edgeRegion={isLeftPanelShown ? 'left' : 'center'}
- groups={leftRailGroups}
- menuItems={leftMenuItems}
- side="left"
- onSelect={handleSelect}
- onToggle={handleToggleLeft}
- />
- {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}
- <CenterArea />
- {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}
- <WidgetBar
- edgeRegion={isRightPanelShown ? 'right' : 'center'}
- groups={rightRailGroups}
- menuItems={rightMenuItems}
- side="right"
- onSelect={handleSelect}
- onToggle={handleToggleRight}
- />
+ <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">
+ <VisuallyHidden as="h1" id="workbench-project-heading">
+ {projectName}
+ </VisuallyHidden>
+ {/* Use a named content region: the project switcher is no longer a tablist. */}
+ <Flex
+ aria-labelledby="workbench-project-heading"
+ flex="1"
+ id={PROJECT_CONTENT_PANEL_ID}
+ minH="0"
+ overflow="hidden"
+ role="region"
+ >
+ <WidgetBar
+ edgeRegion={isLeftPanelShown ? 'left' : 'center'}
+ groups={leftRailGroups}
+ menuItems={leftMenuItems}
+ side="left"
+ onSelect={handleSelect}
+ onToggle={handleToggleLeft}
+ />
+ {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}
+ <CenterArea />
+ {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}
+ <WidgetBar
+ edgeRegion={isRightPanelShown ? 'right' : 'center'}
+ groups={rightRailGroups}
+ menuItems={rightMenuItems}
+ side="right"
+ onSelect={handleSelect}
+ onToggle={handleToggleRight}
+ />
+ </Flex>
</Flex>
- </Flex>
- <BottomPanel />
- <StatusBar dropState={bottomDropState} />
- </Flex>
- <FloatingWidgetLayer />
- <GalleryDragCursor />
- <PasteMediaRuntime />
- {/*
- * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch
- * handlers.
- */}
- <DragOverlay style={DRAG_OVERLAY_STYLE}>
- {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}
- </DragOverlay>
+ <BottomPanel />
+ <StatusBar dropState={bottomDropState} />
+ </Flex>
+ <FloatingWidgetLayer />
+ <GalleryDragCursor />
+ <PasteMediaRuntime />
+ {/*
+ * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch
+ * handlers.
+ */}
+ <DragOverlay style={DRAG_OVERLAY_STYLE}>
+ {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}
+ </DragOverlay>
+ </GalleryDragScope>
</DndContext>
</FocusRegionProvider>
);
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index b50b13b02f..d070c9240b 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -83,23 +83,8 @@ const ROUTE_SHARED_MODULES = [
// Group dependencies shared by the editor shell and lazy widgets to reduce boot requests.
const EDITOR_BOOT_SHARED_MODULES = [
- '/app/GalleryUiAdapter.tsx',
- '/features/gallery/picker.ts',
- '/features/gallery/ui/GalleryBoardCover.tsx',
- '/features/gallery/ui/GalleryBoardRowShell.tsx',
'/features/gallery/ui/GalleryItemSearch.tsx',
- '/features/gallery/ui/GallerySearchField.tsx',
- '/features/gallery/ui/GalleryTileFrame.tsx',
- '/features/gallery/ui/GalleryUploadButton.tsx',
- '/features/gallery/ui/GalleryViewTabs.tsx',
- '/features/gallery/ui/GalleryWidgetContext.tsx',
- '/features/gallery/ui/galleryBoardGroups.ts',
- '/features/gallery/ui/galleryBoardLabels.ts',
- '/features/gallery/ui/galleryGridLayout.ts',
- '/features/gallery/ui/picker/GalleryPickerPopover.tsx',
- '/features/gallery/ui/useGalleryData.ts',
- '/features/gallery/ui/useGalleryUploadAction.ts',
- '/features/gallery/ui/useGalleryUploadInput.ts',
+ '/app/GalleryUiAdapter.tsx',
'/features/generation/core/prompt/ast.ts',
'/features/generation/core/prompt/attention.ts',
'/features/generation/data/architectureCapabilitiesApi.ts',
@@ -159,6 +144,37 @@ const WIDGET_METADATA_MODULES = [
'/workbench/widgets/preview/previewSettings.ts',
] as const;
+// The gallery picker and the pieces its view shares with the Gallery widget. The Launchpad's model manager uses the
+// picker, so it cannot sit in editor-boot-shared (which imports the editor itself: loading that early mis-orders the
+// editor's modules) nor in gallery-state (which the Launchpad home loads, so it would pay for the picker there).
+// Its query and drag modules join it, so the editor trades their separate chunks for this one; backend.ts stays out because
+// the Launchpad home reads it for recent outputs.
+const GALLERY_PICKER_MODULES = [
+ '/features/gallery/ui/galleryDnd.ts',
+ '/features/gallery/utility.ts',
+ '/features/gallery/ui/GalleryDragCursor.tsx',
+ '/features/gallery/core/boardLabels.ts',
+ '/features/gallery/data/queries.ts',
+ '/features/gallery/data/queryCache.ts',
+ '/features/gallery/ui/GallerySearchHelp.tsx',
+ '/platform/state/compareAndSwapRollback.ts',
+ '/features/gallery/picker.ts',
+ '/features/gallery/ui/GalleryBoardCover.tsx',
+ '/features/gallery/ui/GalleryBoardRowShell.tsx',
+ '/features/gallery/ui/GallerySearchField.tsx',
+ '/features/gallery/ui/GalleryTileFrame.tsx',
+ '/features/gallery/ui/GalleryUploadButton.tsx',
+ '/features/gallery/ui/GalleryViewTabs.tsx',
+ '/features/gallery/ui/GalleryWidgetContext.tsx',
+ '/features/gallery/ui/galleryBoardGroups.ts',
+ '/features/gallery/ui/galleryBoardLabels.ts',
+ '/features/gallery/ui/galleryGridLayout.ts',
+ '/features/gallery/ui/picker/GalleryPickerPopover.tsx',
+ '/features/gallery/ui/useGalleryData.ts',
+ '/features/gallery/ui/useGalleryUploadAction.ts',
+ '/features/gallery/ui/useGalleryUploadInput.ts',
+] as const;
+
// Gallery's shared state projection and UI port travel together.
const GALLERY_STATE_MODULES = [
'/features/gallery/core/items.ts',
@@ -307,6 +323,12 @@ export default defineConfig({
priority: 30,
test: (id) => matchesAnySuffix(id, CANVAS_LAYER_SHARED_MODULES),
},
+ {
+ includeDependenciesRecursively: false,
+ name: 'gallery-picker',
+ priority: 30,
+ test: (id) => matchesAnySuffix(id, GALLERY_PICKER_MODULES),
+ },
{
includeDependenciesRecursively: false,
name: 'gallery-state',