Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(gallery): add the gallery picker popover and media slot
Josh Corbettfc01e31de4f7
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex c2f23e812c..35a0aa177d 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3345,6 +3345,45 @@"oldest": "Oldest","otherProjectBoards": "Other projects' boards","pagination": "Pagination",+ "picker": {+ "addedItem": "{{name}} (added)",+ "boardCount_one": "{{count}} board",+ "boardCount_other": "{{count}} boards",+ "boardsLabel": "Boards",+ "changeBoardNamed": "Change board ({{name}})",+ "chooseImage": "Choose image",+ "chooseMedia": "Choose image or video",+ "chooseVideo": "Choose video",+ "dropHint": "or drop one from the Gallery",+ "dropImage": "Drop image",+ "dropMedia": "Drop image or video",+ "dropVideo": "Drop video",+ "empty": "Nothing in {{name}} yet",+ "findBoard": "Find a board…",+ "itemCount_one": "{{count}} item",+ "itemCount_other": "{{count}} items",+ "itemsLabel": "Gallery items",+ "matchCount_one": "{{count}} match",+ "matchCount_other": "{{count}} matches",+ "openGallery": "Open Gallery",+ "remainingCount_one": "{{count}} more can be added",+ "remainingCount_other": "{{count}} more can be added",+ "remainingNone": "Nothing more can be added",+ "removeImage": "Remove image",+ "removeMedia": "Remove",+ "removeVideo": "Remove video",+ "replaceHint": "Click to replace, or drop from the Gallery",+ "replaceImage": "Replace image",+ "replaceMedia": "Replace",+ "replaceVideo": "Replace video",+ "searchIn": "Search {{name}}…",+ "unsupportedImage": "Images can't be used here",+ "unsupportedVideo": "Videos can't be used here",+ "upload": "Upload",+ "uploadFailed": "The upload didn't go through. Check the notifications for details.",+ "windowLimit": "Showing the first {{count}} items. Narrow the search to reach the rest.",+ "working": "Working…"+ },"preparingDownload": "Preparing download","renameBoard": "Rename board","resizeBoardPanel": "Resize board panel",diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex c331773b61..cf8d089f21 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -5,7 +5,7 @@* To publish a new entry module, add it here and cover it in dependencyPolicy.test.ts.*/export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {- gallery: ['contracts', 'launchpad', 'paletteSearch', 'queries', 'react', 'utility', 'widget'],+ gallery: ['contracts', 'launchpad', 'paletteSearch', 'picker', 'queries', 'react', 'utility', 'widget'],generation: ['canvasGraph','components',diff --git a/invokeai/frontend/webv2/src/features/gallery/picker.ts b/invokeai/frontend/webv2/src/features/gallery/picker.tsnew file mode 100644index 0000000000..2e36419b7b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/picker.ts@@ -0,0 +1,11 @@+export {+ type GalleryPickerAccept,+ type GalleryPickerSelection,+ type GalleryPickerTileState,+} from './ui/picker/galleryPicker';+export { GalleryPickerPopover, type GalleryPickerPopoverProps } from './ui/picker/GalleryPickerPopover';+export {+ GalleryMediaSlot,+ type GalleryMediaSlotLabels,+ type GalleryMediaSlotValue,+} from './ui/picker/GalleryMediaSlot';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex 20af9a2dd8..06600d2081 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -296,7 +296,7 @@ const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; refe};/** Documents the closed date-token grammar the search box accepts. */-const GallerySearchHelp = () => {+export const GallerySearchHelp = () => {const { t } = useTranslation();return (diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsxindex 3376befbfa..7ac4191377 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx@@ -4,7 +4,7 @@ import { Box, Icon, Input } from '@chakra-ui/react';import { parseDateTokens } from '@platform/search/dateTokens';import { InputShell } from '@platform/ui/InputShell';import { SearchIcon } from 'lucide-react';-import { useCallback, useMemo, useRef, type ReactNode } from 'react';+import { useCallback, useMemo, useRef, type KeyboardEvent, type ReactNode, type Ref } from 'react';/** `key:value` runs the date grammar recognizes, matched against the raw value. */const TOKEN_PATTERN = /(?:^|\s)(?:from|to|date):\S*/gi;@@ -71,18 +71,25 @@ export const GallerySearchField = ({ariaLabel,describedById,endElement,+ inputProps,isInvalid,placeholder,+ ref,value,onChange,+ onKeyDown,}: {ariaLabel: string;describedById?: string;endElement?: ReactNode;+ /** Listbox wiring (`aria-controls`, `aria-activedescendant`) for hosts that drive a list from the field. */+ inputProps?: Pick<React.ComponentProps<typeof Input>, 'aria-activedescendant' | 'aria-controls' | 'role'>;isInvalid?: boolean;placeholder: string;+ ref?: Ref<HTMLInputElement>;value: string;onChange: (value: string) => void;+ onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;}) => {const mirrorRef = useRef<HTMLDivElement>(null);const segments = useMemo(() => getGallerySearchSegments(value, parseDateTokens(value)), [value]);@@ -140,6 +147,8 @@ export const GallerySearchField = ({)}</Box><Input+ ref={ref}+ {...inputProps}aria-describedby={describedById}aria-invalid={isInvalid || undefined}aria-label={ariaLabel}@@ -158,6 +167,7 @@ export const GallerySearchField = ({w="full"value={value}onChange={handleChange}+ onKeyDown={onKeyDown}onScroll={handleScroll}/></InputShell>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.tsnew file mode 100644index 0000000000..da4224837e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts@@ -0,0 +1,44 @@+import type { GalleryBoard } from '@features/gallery/core/types';+import type { TFunction } from 'i18next';++import { describe, expect, it } from 'vitest';++import { getGalleryUploadTargetLabel } from './GalleryUploadButton';++const t = ((key: string, values?: Record<string, unknown>) =>+ values && 'name' in values ? `${key}:${String(values.name)}` : key) as unknown as TFunction;++const board: GalleryBoard = {+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id: 'dogs',+ imageCount: 0,+ kind: 'board',+ name: 'Dogs',+ projectId: null,+ videoCount: 0,+};++describe('getGalleryUploadTargetLabel', () => {+ it('names the selected board', () => {+ expect(getGalleryUploadTargetLabel([board], 'dogs', t)).toEqual({+ isAvailable: true,+ label: 'widgets.gallery.uploadMediaToBoard:Dogs',+ });+ });++ it('falls back to a generic name for an unknown board', () => {+ expect(getGalleryUploadTargetLabel([board], 'missing', t)).toEqual({+ isAvailable: true,+ label: 'widgets.gallery.uploadMediaToBoard:widgets.gallery.selectedBoardFallback',+ });+ });++ it('marks date boards unavailable', () => {+ expect(getGalleryUploadTargetLabel([board], 'by_date:2026-09-04', t)).toEqual({+ isAvailable: false,+ label: 'widgets.gallery.uploadsUnavailableForDateBoards',+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsxindex 8b6c8e617b..8008c1541a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx@@ -1,4 +1,5 @@import type { GalleryBoard } from '@features/gallery/core/types';+import type { TFunction } from 'i18next';import { Icon } from '@chakra-ui/react';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';@@ -10,6 +11,26 @@ import { useTranslation } from 'react-i18next';import { useGalleryUploadInput } from './useGalleryUploadInput';+/** Tooltip/aria text for an upload control; null when the board cannot receive uploads. */+export const getGalleryUploadTargetLabel = (+ boards: readonly GalleryBoard[],+ selectedBoardId: string,+ t: TFunction+): { isAvailable: boolean; label: string } => {+ if (isDateBoardId(selectedBoardId)) {+ return { isAvailable: false, label: t('widgets.gallery.uploadsUnavailableForDateBoards') };+ }++ const selectedBoard = boards.find((board) => board.id === selectedBoardId);++ return {+ isAvailable: true,+ label: t('widgets.gallery.uploadMediaToBoard', {+ name: selectedBoard ? getGalleryBoardLabel(selectedBoard, t) : t('widgets.gallery.selectedBoardFallback'),+ }),+ };+};+export const GalleryUploadButton = ({boards,selectedBoardId,@@ -20,13 +41,7 @@ export const GalleryUploadButton = ({onUploadFiles: (files: File[]) => Promise<unknown>;}) => {const { t } = useTranslation();- const selectedBoard = boards.find((board) => board.id === selectedBoardId);- const isVirtualTarget = isDateBoardId(selectedBoardId);- const label = isVirtualTarget- ? t('widgets.gallery.uploadsUnavailableForDateBoards')- : t('widgets.gallery.uploadMediaToBoard', {- name: selectedBoard ? getGalleryBoardLabel(selectedBoard, t) : t('widgets.gallery.selectedBoardFallback'),- });+ const { isAvailable, label } = getGalleryUploadTargetLabel(boards, selectedBoardId, t);const { inputProps, openPicker } = useGalleryUploadInput(onUploadFiles);@@ -37,7 +52,7 @@ export const GalleryUploadButton = ({<IconButtonaria-label={label}color="fg.muted"- disabled={isVirtualTarget}+ disabled={!isAvailable}size="xs"variant="ghost"onClick={openPicker}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsxindex b1162888a3..218285bfff 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx@@ -1,4 +1,4 @@-import type { GalleryView } from '@features/gallery/core/types';+import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';import { Text } from '@chakra-ui/react';import { SegmentTabs } from '@platform/ui';@@ -14,31 +14,39 @@ const GALLERY_VIEW_TABS = [] satisfies { labelKey: string; value: GalleryView }[];/**- * Media / Assets, each carrying the selected board's count for that view so- * the split is legible before you switch. The same `SegmentTabs` strip the- * layer panes use; each layout shell wires the tabpanel by putting- * `segmentTabsPanelId(idBase)` on its grid container.+ * Media / Assets, each carrying `board`'s count for that view so the split is+ * legible before you switch. The same `SegmentTabs` strip the layer panes use;+ * the caller wires the tabpanel by putting `segmentTabsPanelId(idBase)` on its+ * grid container.*/-export const GalleryViewTabs = ({ idBase }: { idBase: string }) => {+export const GalleryViewSegmentTabs = ({+ activeView,+ board,+ idBase,+ onSelect,+}: {+ activeView: GalleryView;+ board: GalleryBoard | undefined;+ idBase: string;+ onSelect: (view: GalleryView) => void;+}) => {const { t } = useTranslation();- const { actions, gallery } = useGalleryWidget();- const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);// SegmentTabs re-fires selecting the active tab (its collapsible-toggle// affordance); a same-view write would only dirty the widget values.const handleViewChange = useCallback((value: GalleryView) => {- if (value !== gallery.galleryView) {- actions.setView(value);+ if (value !== activeView) {+ onSelect(value);}},- [actions, gallery.galleryView]+ [activeView, onSelect]);const tabs = useMemo(() =>GALLERY_VIEW_TABS.map(({ labelKey, value }) => {- const count = selectedBoard ? getGalleryCountForView(selectedBoard, value) : null;+ const count = board ? getGalleryCountForView(board, value) : null;return {id: value,@@ -56,12 +64,12 @@ export const GalleryViewTabs = ({ idBase }: { idBase: string }) => {),};}),- [selectedBoard, t]+ [board, t]);return (<SegmentTabs- activeId={gallery.galleryView}+ activeId={activeView}ariaLabel={t('common.view')}idBase={idBase}isCompact@@ -70,3 +78,17 @@ export const GalleryViewTabs = ({ idBase }: { idBase: string }) => {/>);};++export const GalleryViewTabs = ({ idBase }: { idBase: string }) => {+ const { actions, gallery } = useGalleryWidget();+ const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);++ return (+ <GalleryViewSegmentTabs+ activeView={gallery.galleryView}+ board={selectedBoard}+ idBase={idBase}+ onSelect={actions.setView}+ />+ );+};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.tsxnew file mode 100644index 0000000000..455e116d01--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx@@ -0,0 +1,349 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop */+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';+import type { GalleryBoard } from '@features/gallery/core/types';+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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { widgetCollisionDetection } from '@workbench/widgetDnd';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { GalleryMediaSlotValue } from './GalleryMediaSlot';++import { GalleryMediaSlot } from './GalleryMediaSlot';++const mocks = vi.hoisted(() => ({+ getGalleryItemByRef: vi.fn(),+ invalidateGallery: vi.fn(),+ uploadGalleryImage: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'en' },+ t: (key: string, values?: Record<string, unknown>) =>+ values && 'name' in values ? `${key}:${String(values.name)}` : key,+ }),+}));++vi.mock('@features/queue/react', () => ({+ useQueueItemProgress: () => null,+ useQueueItemProgressImage: () => null,+}));++vi.mock('@features/gallery/data/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ galleryBoardsOptions: () => ({+ queryFn: () => Promise.resolve([board]),+ queryKey: ['test-slot-boards'],+ staleTime: Infinity,+ }),+ galleryItemsInfiniteOptions: () => ({+ getNextPageParam: () => undefined,+ initialPageParam: 0,+ queryFn: () => Promise.resolve({ items: [image('a.png')], total: 1 }),+ queryKey: ['test-slot-items'],+ staleTime: Infinity,+ }),+}));++vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getGalleryItemByRef: (...args: unknown[]) => mocks.getGalleryItemByRef(...args),+ uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),+}));++vi.mock('@features/gallery/data/queryCache', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),+}));++const board: GalleryBoard = {+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id: 'dogs',+ imageCount: 1,+ kind: 'board',+ name: 'Dogs',+ projectId: null,+ videoCount: 0,+};++const image = (name: string): GalleryItem => ({+ boardId: 'dogs',+ category: 'general',+ createdAt: '2026-09-01T00:00:00.000Z',+ fullUrl: `/full/${name}`,+ height: 96,+ isIntermediate: false,+ kind: 'image',+ name,+ starred: false,+ thumbnailUrl: `/thumb/${name}`,+ width: 128,+});++const IMAGE_REF: GalleryItemRef = { kind: 'image', name: 'frame.png' };+const VIDEO_REF: GalleryItemRef = { kind: 'video', name: 'clip.mp4' };++const galleryCommands = { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() };+const notifications = { add: vi.fn(), reportError: vi.fn() };+const adapter = {+ gallery: galleryCommands,+ galleryValues: { galleryView: 'images', selectedBoardId: 'dogs' },+ notifications,+ projectName: 'Project',+ widgets: { openGallery: () => true, patchGalleryValues: vi.fn() },+} as unknown as GalleryUiAdapter;++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const onChange = vi.fn();++const interact = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 50);+ });+ });++const DraggableThumb = ({ data, id, left, testId }: { data: unknown; id: string; left: number; testId: string }) => {+ const { listeners, setNodeRef } = useDraggable({ data: data as never, id });++ return (+ <div+ ref={setNodeRef}+ {...listeners}+ data-testid={testId}+ style={{ height: 40, left, position: 'fixed', top: 20, width: 40 }}+ />+ );+};++const renderSlot = async (props: Partial<Parameters<typeof GalleryMediaSlot>[0]> = {}) => {+ const Harness = () => {+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));++ return (+ <ChakraProvider value={system}>+ <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"+ uploadBoardId="none"+ value={null}+ onChange={onChange}+ {...props}+ />+ </div>+ </DndContext>+ </GalleryUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ );+ };++ await interact(() => root?.render(<Harness />));+};++const trigger = () => host?.querySelector<HTMLButtonElement>('button[aria-label^="widgets.gallery.picker."]');+const actionButton = (key: string) =>+ [...(host?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find((button) => button.textContent?.includes(key));+const alertText = () => host?.querySelector('[role="alert"]')?.textContent ?? null;++const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {+ target.dispatchEvent(+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })+ );+};++const dragOntoSlot = async (testId: string) => {+ const thumb = document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)!;+ const rect = thumb.getBoundingClientRect();+ const slotRect = document.querySelector<HTMLElement>('[data-testid="slot"] button')!.getBoundingClientRect();+ const x = slotRect.left + slotRect.width / 2;+ const y = slotRect.top + slotRect.height / 2;++ await interact(() => pointer('pointerdown', thumb, rect.left + 20, rect.top + 20));+ await interact(() => pointer('pointermove', thumb.ownerDocument, rect.left + 50, rect.top + 50));+ await interact(() => pointer('pointermove', thumb.ownerDocument, x, y));+ await interact(() => pointer('pointerup', thumb.ownerDocument, x, y));+};++const changeFile = async (file: File) => {+ const input = host?.querySelector<HTMLInputElement>('input[type="file"]');++ Object.defineProperty(input, 'files', { configurable: true, value: [file] });+ await interact(() => input?.dispatchEvent(new Event('change', { bubbles: true })));+};++beforeEach(() => {+ vi.clearAllMocks();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ queryClient?.clear();+});++describe('GalleryMediaSlot', () => {+ it('opens the picker from the slot and hands back the picked item', async () => {+ await renderSlot();++ expect(trigger()?.getAttribute('aria-label')).toBe('widgets.gallery.picker.chooseImage');+ await interact(() => trigger()?.click());++ const dialog = document.querySelector<HTMLElement>('[role="dialog"][data-state="open"]');++ expect(dialog?.getAttribute('aria-label')).toBe('widgets.gallery.picker.chooseImage');+ await vi.waitFor(() => expect(dialog?.querySelector('[data-item-key="image:a.png"]')).not.toBeNull());+ await interact(() => dialog?.querySelector<HTMLElement>('[data-item-key="image:a.png"]')?.click());++ expect(onChange).toHaveBeenCalledExactlyOnceWith(image('a.png'));+ expect(document.querySelector('[role="dialog"][data-state="open"]')).toBeNull();+ });++ it('adopts a single image dropped from the gallery, resolving it first', async () => {+ let resolveItem: ((item: GalleryItem) => void) | undefined;++ mocks.getGalleryItemByRef.mockReturnValue(+ new Promise<GalleryItem>((resolve) => {+ resolveItem = resolve;+ })+ );+ await renderSlot();+ await dragOntoSlot('image-thumb');++ expect(mocks.getGalleryItemByRef).toHaveBeenCalledExactlyOnceWith(IMAGE_REF, expect.any(AbortSignal));+ expect(trigger()?.getAttribute('aria-busy')).toBe('true');++ await interact(() => resolveItem?.(image('frame.png')));++ expect(onChange).toHaveBeenCalledExactlyOnceWith(image('frame.png'));+ expect(trigger()?.getAttribute('aria-busy')).toBeNull();+ });++ it('reports a failed resolve inline', async () => {+ mocks.getGalleryItemByRef.mockRejectedValue(new Error('image vanished'));+ await renderSlot();+ await dragOntoSlot('image-thumb');++ expect(onChange).not.toHaveBeenCalled();+ expect(alertText()).toBe('image vanished');+ expect(notifications.reportError).toHaveBeenCalledWith(expect.objectContaining({ message: 'image vanished' }));+ });++ it('ignores multi-item and wrong-kind drags', async () => {+ await renderSlot();+ await dragOntoSlot('multi-thumb');+ await dragOntoSlot('video-thumb');++ expect(mocks.getGalleryItemByRef).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('uploads into the given board and adopts the result', async () => {+ mocks.uploadGalleryImage.mockResolvedValue({+ boardId: 'none',+ createdAt: '2026-09-09T00:00:00.000Z',+ height: 96,+ imageCategory: 'user',+ imageName: 'fresh.png',+ imageUrl: '/full/fresh.png',+ queuedAt: '2026-09-09T00:00:00.000Z',+ sourceQueueItemId: 'queue-1',+ starred: false,+ thumbnailUrl: '/thumb/fresh.png',+ width: 128,+ });+ await renderSlot();++ expect(host?.querySelector<HTMLInputElement>('input[type="file"]')?.multiple).toBe(false);+ await changeFile(new File(['image'], 'fresh.png', { type: 'image/png' }));++ expect(mocks.uploadGalleryImage).toHaveBeenCalledExactlyOnceWith(expect.any(File), 'none', expect.anything());+ expect(onChange).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'image', name: 'fresh.png' }));+ expect(alertText()).toBeNull();+ });++ it('refuses a file of a kind the slot cannot take and reports an upload that yields nothing', async () => {+ mocks.uploadGalleryImage.mockRejectedValue(new Error('storage offline'));+ await renderSlot();++ await changeFile(new File(['video'], 'clip.mp4', { type: 'video/mp4' }));++ expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();+ expect(alertText()).toBe('widgets.gallery.picker.unsupportedVideo');++ await changeFile(new File(['image'], 'photo.png', { type: 'image/png' }));++ expect(mocks.uploadGalleryImage).toHaveBeenCalledOnce();+ expect(onChange).not.toHaveBeenCalled();+ expect(alertText()).toBe('widgets.gallery.picker.uploadFailed');+ });++ it('shows the current value with a replace hint and clears it', async () => {+ const value: GalleryMediaSlotValue = { height: 96, kind: 'image', name: 'chosen.png', width: 128 };++ await renderSlot({ value });++ expect(trigger()?.getAttribute('aria-label')).toBe('widgets.gallery.picker.replaceImage');+ expect(host?.textContent).toContain('chosen.png');+ expect(host?.textContent).toContain('128 × 96');++ await interact(() => actionButton('widgets.gallery.picker.removeImage')?.click());++ expect(onChange).toHaveBeenCalledExactlyOnceWith(null);+ });++ it('stands down while disabled, showing the reason', async () => {+ await renderSlot({ disabled: true, disabledReason: 'Frames come from the video' });++ expect(trigger()?.disabled).toBe(true);+ expect(host?.textContent).toContain('Frames come from the video');+ expect(actionButton('widgets.gallery.picker.upload')).toBeUndefined();++ await dragOntoSlot('image-thumb');++ expect(mocks.getGalleryItemByRef).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsxnew file mode 100644index 0000000000..282b6bba68--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx@@ -0,0 +1,317 @@+import type { DragEndEvent } from '@dnd-kit/core';+import type { GalleryItem, GalleryItemKind, GalleryItemRef } from '@features/gallery/core/items';++import { Box, HStack, Icon, Image, Spinner, Stack, Text } from '@chakra-ui/react';+import { useDndMonitor } from '@dnd-kit/core';+import { classifyGalleryUpload, getGalleryItemByRef } from '@features/gallery/data/backend';+import { getGalleryImageThumbnailUrl } from '@features/gallery/data/imageUrls';+import { galleryBoardsOptions } from '@features/gallery/data/queries';+import { getGalleryVideoThumbnailUrl } from '@features/gallery/data/videoUrls';+import { isGalleryItemDragData, useGalleryItemDroppable } from '@features/gallery/ui/galleryDnd';+import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';+import { useGalleryUploadAction } from '@features/gallery/ui/useGalleryUploadAction';+import { getGalleryUploadAccept, useGalleryUploadInput } from '@features/gallery/ui/useGalleryUploadInput';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { Button } from '@platform/ui/Button';+import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';+import { DropZone } from '@platform/ui/DropZone';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { useQuery } from '@tanstack/react-query';+import { ChevronDownIcon, ImagePlusIcon, RefreshCwIcon, UploadIcon, XIcon } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { GalleryPickerAccept } from './galleryPicker';++import { GalleryPickerPopover } from './GalleryPickerPopover';++const EMPTY_BOARDS: never[] = [];+const DROP_ZONE_FOCUS_PROPS = {+ outlineColor: 'accent.focusRing',+ outlineOffset: '2px',+ outlineStyle: 'solid',+ outlineWidth: '2px',+};+const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };+const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };++export interface GalleryMediaSlotValue {+ height?: number;+ kind: GalleryItemKind;+ name: string;+ width?: number;+}++export interface GalleryMediaSlotLabels {+ choose: string;+ /** Overlay call-to-action while a compatible drag is in flight. */+ drop: string;+ remove: string;+ replace: string;+}++const getDefaultLabels = (accept: GalleryPickerAccept, t: (key: string) => string): GalleryMediaSlotLabels => {+ const noun = accept.length === 1 && accept[0] === 'video' ? 'Video' : accept.length === 1 ? 'Image' : 'Media';++ return {+ choose: t(`widgets.gallery.picker.choose${noun}`),+ drop: t(`widgets.gallery.picker.drop${noun}`),+ remove: t(`widgets.gallery.picker.remove${noun}`),+ replace: t(`widgets.gallery.picker.replace${noun}`),+ };+};++const getThumbnailUrl = (value: GalleryMediaSlotValue): string =>+ value.kind === 'video' ? getGalleryVideoThumbnailUrl(value.name) : getGalleryImageThumbnailUrl(value.name);++/**+ * A single-item media field: click opens the gallery picker, a gallery drag+ * can be dropped on it, and a file can be uploaded from its action row. Owns+ * the async resolve/upload work and its busy and error states; the consumer+ * only sees `onChange` with a full item (or null when cleared).+ */+export const GalleryMediaSlot = ({+ accept,+ disabled = false,+ disabledReason,+ dropId,+ labels: labelOverrides,+ uploadBoardId,+ value,+ onChange,+}: {+ accept: GalleryPickerAccept;+ disabled?: boolean;+ /** Shown in place of the affordances while disabled (e.g. a mutual exclusion). */+ disabledReason?: string;+ /** Unique droppable id; sibling slots must not share one. */+ dropId: string;+ labels?: Partial<GalleryMediaSlotLabels>;+ /** Where a file uploaded from the action row lands; a getter is read when the upload starts. */+ uploadBoardId: string | (() => string);+ value: GalleryMediaSlotValue | null;+ onChange: (item: GalleryItem | null) => void;+}) => {+ const { t } = useTranslation();+ const { notifications } = useGalleryUi();+ const { data: boards } = useQuery(galleryBoardsOptions());+ const [isBusy, setIsBusy] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const isInert = disabled || isBusy;+ const labels = useMemo(() => ({ ...getDefaultLabels(accept, t), ...labelOverrides }), [accept, labelOverrides, t]);++ // Advertise single drags of accepted kinds, but stay armed for any drag of+ // those kinds: a multi-item release must be a dead drop, not fall through.+ const { acceptsDrag, shieldsDrag } = useMemo(+ () => ({+ acceptsDrag: (data: unknown) =>+ isGalleryItemDragData(data) && data.items.length === 1 && accept.includes(data.items[0]!.kind),+ shieldsDrag: (data: unknown) =>+ isGalleryItemDragData(data) && data.items.some((ref) => accept.includes(ref.kind)),+ }),+ [accept]+ );+ const { acceptsActiveDrag, isOver, setNodeRef } = useGalleryItemDroppable(+ acceptsDrag,+ { data: { kind: dropId }, disabled: isInert, id: dropId },+ shieldsDrag+ );++ const fail = useCallback(+ (error: unknown) => {+ const message = error instanceof Error ? error.message : String(error);++ setErrorMessage(message);+ notifications.reportError({ area: 'gallery-media-slot', message, namespace: 'gallery' });+ },+ [notifications]+ );++ const adoptRef = useCallback(+ async (ref: GalleryItemRef) => {+ const owner = captureAccountScope();++ setErrorMessage(null);+ setIsBusy(true);++ try {+ const item = await getGalleryItemByRef(ref, owner.signal);++ assertAccountScopeCurrent(owner);+ onChange(item);+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ fail(error);+ }+ } finally {+ if (isAccountScopeCurrent(owner)) {+ setIsBusy(false);+ }+ }+ },+ [fail, onChange]+ );++ const handleDragEnd = useCallback(+ (event: DragEndEvent) => {+ const data = event.active.data.current;++ if (!isInert && event.over?.id === dropId && acceptsDrag(data) && isGalleryItemDragData(data)) {+ void adoptRef(data.items[0]!);+ }+ },+ [acceptsDrag, adoptRef, dropId, isInert]+ );++ useDndMonitor({ onDragEnd: handleDragEnd });++ const uploadFiles = useGalleryUploadAction({ boards: boards ?? EMPTY_BOARDS, selectedBoardId: uploadBoardId });+ const uploadOptions = useMemo(() => ({ accept: getGalleryUploadAccept(accept), multiple: false }), [accept]);+ const handleUpload = useCallback(+ ([file]: File[]) => {+ const kind = file ? classifyGalleryUpload(file)?.kind : undefined;++ setErrorMessage(null);++ // The input's `accept` is advisory ("All files" bypasses it); a kind the+ // slot cannot take must not be uploaded only to be dropped on the floor.+ if (!file || (kind && !accept.includes(kind))) {+ setErrorMessage(+ t(kind === 'video' ? 'widgets.gallery.picker.unsupportedVideo' : 'widgets.gallery.picker.unsupportedImage')+ );+ return;+ }++ setIsBusy(true);+ void uploadFiles([file])+ .then((uploaded) => {+ const item = uploaded.find((candidate) => accept.includes(candidate.kind));++ if (item) {+ onChange(item);+ } else {+ setErrorMessage(t('widgets.gallery.picker.uploadFailed'));+ }+ })+ .finally(() => setIsBusy(false));+ },+ [accept, onChange, t, uploadFiles]+ );+ const { inputProps: uploadInputProps, openPicker: openUploadPicker } = useGalleryUploadInput(+ handleUpload,+ uploadOptions+ );+ const handleClear = useCallback(() => onChange(null), [onChange]);+ const handlePick = useCallback(+ (item: GalleryItem) => {+ setErrorMessage(null);+ onChange(item);+ },+ [onChange]+ );++ return (+ <Stack gap="2">+ <Box ref={setNodeRef} position="relative">+ <GalleryPickerPopover accept={accept} label={labels.choose} onPick={handlePick}>+ <DropZone+ as="button"+ aria-busy={isBusy || undefined}+ aria-disabled={disabled || undefined}+ aria-label={value ? labels.replace : labels.choose}+ cursor={disabled ? 'not-allowed' : undefined}+ disabled={isInert}+ isDisabled={isInert}+ isOver={isOver}+ minH="20"+ overflow="hidden"+ textAlign="start"+ w="full"+ _disabled={DROP_ZONE_DISABLED_PROPS}+ _focusVisible={DROP_ZONE_FOCUS_PROPS}+ _hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}+ >+ {value ? (+ <HStack align="stretch" gap="3" h="20" p="2">+ <Box bg="blackAlpha.300" boxSize="16" flexShrink="0" overflow="hidden" rounded="sm">+ <Image+ alt=""+ boxSize="full"+ objectFit="contain"+ outline="1px solid"+ outlineColor="border.image"+ outlineOffset="-1px"+ rounded="sm"+ src={getThumbnailUrl(value)}+ />+ </Box>+ <Stack align="start" flex="1" gap="1" justify="center" minW="0">+ <MiddleTruncate color="fg" fontSize="xs" fontWeight="semibold" text={value.name} />+ {value.width && value.height ? (+ <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums">+ {value.width} × {value.height}+ </Text>+ ) : null}+ <HStack color="fg.subtle" 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>+ </HStack>+ </Stack>+ </HStack>+ ) : (+ <Stack align="center" color="fg.muted" gap="1.5" justify="center" minH="20" px="4">+ {isBusy ? (+ <Spinner size="sm" />+ ) : (+ <HStack color="fg" fontSize="xs" fontWeight="600" gap="1.5">+ <Icon as={ImagePlusIcon} boxSize="4" />+ {labels.choose}+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />+ </HStack>+ )}+ <Text color="fg.subtle" fontSize="2xs" textAlign="center">+ {disabled && disabledReason+ ? disabledReason+ : isBusy+ ? t('widgets.gallery.picker.working')+ : t('widgets.gallery.picker.dropHint')}+ </Text>+ </Stack>+ )}+ </DropZone>+ </GalleryPickerPopover>+ <DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={labels.drop} />+ </Box>+ <HStack justify="end">+ {disabled ? null : (+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={openUploadPicker}>+ <Icon as={UploadIcon} boxSize="3" />+ {t('widgets.gallery.picker.upload')}+ </Button>+ )}+ {value ? (+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={handleClear}>+ <Icon as={XIcon} boxSize="3" />+ {labels.remove}+ </Button>+ ) : null}+ </HStack>+ {errorMessage ? (+ <Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">+ {errorMessage}+ </Text>+ ) : null}+ <input {...uploadInputProps} />+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsxnew file mode 100644index 0000000000..185547999e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsx@@ -0,0 +1,127 @@+import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';++import { Badge, Box, Text } from '@chakra-ui/react';+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { BoardCover } from '@features/gallery/ui/GalleryBoardCover';+import { getGalleryCountForView } from '@features/gallery/ui/galleryBoardLabels';+import { GalleryBoardRowShell } from '@features/gallery/ui/GalleryBoardRowShell';+import { Scrollable } from '@platform/ui/Scrollable';+import { dropdownGroupLabel } from '@theme/recipes';+import { memo, useCallback, useMemo, type KeyboardEvent } from 'react';+import { useTranslation } from 'react-i18next';++export interface GalleryPickerBoardGroup {+ boards: GalleryBoard[];+ id: string;+ label: string;+}++const GalleryPickerBoardRow = memo(function GalleryPickerBoardRow({+ board,+ galleryView,+ isSelected,+ onSelect,+}: {+ board: GalleryBoard;+ galleryView: GalleryView;+ isSelected: boolean;+ onSelect: (boardId: string) => void;+}) {+ const { t } = useTranslation();+ const handleSelect = useCallback(() => onSelect(board.id), [board.id, onSelect]);+ const cover = useMemo(() => <BoardCover board={board} />, [board]);++ return (+ <GalleryBoardRowShell+ cover={cover}+ isSelected={isSelected}+ label={getGalleryBoardLabel(board, t)}+ onSelect={handleSelect}+ >+ <Badge flexShrink={0} fontVariantNumeric="tabular-nums" size="xs" variant="subtle">+ {getGalleryCountForView(board, galleryView)}+ </Badge>+ </GalleryBoardRowShell>+ );+});++/**+ * The grouped board list the picker swaps in for its grid. Arrow keys walk the+ * rows; leaving the top row hands focus back to the search field.+ */+export const GalleryPickerBoards = ({+ emptyMessage,+ galleryView,+ groups,+ id,+ label,+ selectedBoardId,+ onExitTop,+ onSelect,+}: {+ emptyMessage: string;+ galleryView: GalleryView;+ groups: GalleryPickerBoardGroup[];+ id: string;+ label: string;+ selectedBoardId: string;+ onExitTop: () => void;+ onSelect: (boardId: string) => void;+}) => {+ const viewportProps = useMemo(() => ({ id }), [id]);++ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') {+ return;+ }++ const rows = [...event.currentTarget.querySelectorAll<HTMLButtonElement>('button')];+ const index = rows.indexOf(document.activeElement as HTMLButtonElement);++ if (index === -1) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();++ if (event.key === 'ArrowUp' && index === 0) {+ onExitTop();+ return;+ }++ rows[Math.min(rows.length - 1, index + (event.key === 'ArrowDown' ? 1 : -1))]?.focus();+ },+ [onExitTop]+ );++ return (+ <Scrollable flex="1" label={label} minH="0" viewportProps={viewportProps}>+ <Box px="1" py="1" onKeyDown={handleKeyDown}>+ {groups.length === 0 ? (+ <Text color="fg.muted" fontSize="2xs" px="2" py="3" textAlign="center">+ {emptyMessage}+ </Text>+ ) : (+ groups.map((group) => (+ <Box key={group.id}>+ <Text css={dropdownGroupLabel} px="2" py="1">+ {group.label}+ </Text>+ {group.boards.map((board) => (+ <GalleryPickerBoardRow+ key={board.id}+ board={board}+ galleryView={galleryView}+ isSelected={board.id === selectedBoardId}+ onSelect={onSelect}+ />+ ))}+ </Box>+ ))+ )}+ </Box>+ </Scrollable>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsxnew file mode 100644index 0000000000..72904444ea--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx@@ -0,0 +1,280 @@+import type { SystemStyleObject } from '@chakra-ui/react';+import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';+import type { CSSProperties, MouseEvent } from 'react';++import { Box, Icon, Skeleton } from '@chakra-ui/react';+import { toGalleryItemKey } from '@features/gallery/core/items';+import { getGalleryColumnCountForCell } from '@features/gallery/ui/galleryGridLayout';+import { GalleryTileFrame } from '@features/gallery/ui/GalleryTileFrame';+import { Scrollable } from '@platform/ui/Scrollable';+import { CheckIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import {+ GALLERY_PICKER_CELL_PX,+ GALLERY_PICKER_MAX_COLUMNS,+ GALLERY_PICKER_MIN_COLUMNS,+ type GalleryPickerTileState,+} from './galleryPicker';++const GRID_GAP_PX = 4;+const SKELETON_TILE_COUNT = 8;++const IMG_STYLE: CSSProperties = {+ display: 'block',+ height: '100%',+ inset: 0,+ maxWidth: 'none',+ objectFit: 'cover',+ position: 'absolute',+ width: '100%',+};++const ACTIVE_TILE_CSS: SystemStyleObject = {+ outline: '2px solid {colors.accent.solid}',+ outlineOffset: '-4px',+};++const PICKABLE_TILE_CSS: SystemStyleObject = { cursor: 'pointer' };+const INERT_TILE_CSS: SystemStyleObject = { cursor: 'not-allowed', opacity: 0.35 };+const ADDED_TILE_CSS: SystemStyleObject = { cursor: 'default' };++const getTileCss = (state: GalleryPickerTileState, isActive: boolean): SystemStyleObject => {+ const base = state === 'pickable' ? PICKABLE_TILE_CSS : state === 'added' ? ADDED_TILE_CSS : INERT_TILE_CSS;++ return isActive ? { ...base, ...ACTIVE_TILE_CSS } : base;+};++export const galleryPickerOptionId = (idBase: string, key: GalleryItemKey): string => `${idBase}-${key}`;++const GalleryPickerTile = memo(function GalleryPickerTile({+ idBase,+ isActive,+ isCurrent,+ isMultiple,+ item,+ state,+}: {+ idBase: string;+ isActive: boolean;+ /** The Gallery widget's own selection, ringed so it reads as the default. */+ isCurrent: boolean;+ isMultiple: boolean;+ item: GalleryItem;+ state: GalleryPickerTileState;+}) {+ const { t } = useTranslation();+ const key = toGalleryItemKey(item);+ const css = useMemo(() => getTileCss(state, isActive), [isActive, state]);+ const unsupportedLabel =+ state === 'unsupported'+ ? t(item.kind === 'video' ? 'widgets.gallery.picker.unsupportedVideo' : 'widgets.gallery.picker.unsupportedImage')+ : undefined;++ // Ref callbacks re-run when `isActive` changes, so the keyboard highlight+ // stays in view without an effect; pointer hover never moves it.+ const scrollIntoView = useCallback(+ (node: HTMLDivElement | null) => {+ if (node && isActive) {+ node.scrollIntoView({ block: 'nearest' });+ }+ },+ [isActive]+ );++ return (+ <GalleryTileFrame+ ref={scrollIntoView}+ aria-disabled={state === 'pickable' ? undefined : true}+ aria-label={state === 'added' ? t('widgets.gallery.picker.addedItem', { name: item.name }) : item.name}+ // Single mode: selection follows the highlight (what Enter picks).+ // Multiple mode: selection is what has been added; the highlight is+ // carried by `aria-activedescendant` alone.+ aria-selected={isMultiple ? state === 'added' : isActive}+ css={css}+ data-item-key={key}+ id={galleryPickerOptionId(idBase, key)}+ isSelected={isCurrent || state === 'added'}+ item={item}+ role="option"+ title={unsupportedLabel}+ >+ <img+ alt=""+ decoding="async"+ draggable={false}+ loading="lazy"+ src={item.thumbnailUrl || item.fullUrl}+ style={IMG_STYLE}+ />+ {state === 'added' ? (+ <Box+ alignItems="center"+ bg="accent.solid"+ boxSize="4"+ color="accent.contrast"+ display="flex"+ insetInlineEnd="1"+ justifyContent="center"+ pointerEvents="none"+ position="absolute"+ rounded="full"+ top="1"+ zIndex="1"+ >+ <Icon as={CheckIcon} boxSize="2.5" strokeWidth="3" />+ </Box>+ ) : null}+ </GalleryTileFrame>+ );+});++/**+ * The picker's tile grid: the column count follows the measured width, one+ * delegated click serves every tile, and a sentinel at the end asks for the+ * next page. Not virtualized — the base infinite window bounds the rows and+ * lazy images keep the network idle until scrolled.+ */+export const GalleryPickerGrid = ({+ activeKey,+ columnCount,+ currentKey,+ getTileState,+ idBase,+ isMultiple,+ isStale,+ items,+ label,+ onActivate,+ onColumnCountChange,+ onLoadMore,+}: {+ activeKey: GalleryItemKey | null;+ columnCount: number;+ currentKey: GalleryItemKey | null;+ getTileState: (item: GalleryItem) => GalleryPickerTileState;+ idBase: string;+ isMultiple: boolean;+ /** `items` belong to the previous scope while the current one loads. */+ isStale: boolean;+ /** Null while nothing has loaded yet. */+ items: GalleryItem[] | null;+ label: string;+ onActivate: (item: GalleryItem) => void;+ onColumnCountChange: (columnCount: number) => void;+ onLoadMore: () => void;+}) => {+ const resizeObserverRef = useRef<ResizeObserver | null>(null);+ const loadMoreObserverRef = useRef<IntersectionObserver | null>(null);+ const itemsByKey = useMemo(() => new Map(items?.map((item) => [toGalleryItemKey(item), item])), [items]);++ const measureRef = useCallback(+ (node: HTMLDivElement | null) => {+ resizeObserverRef.current?.disconnect();+ resizeObserverRef.current = null;++ if (!node) {+ return;+ }++ const observer = new ResizeObserver(([entry]) => {+ const widthPx = entry?.contentRect.width ?? 0;++ if (widthPx > 0) {+ onColumnCountChange(+ getGalleryColumnCountForCell({+ max: GALLERY_PICKER_MAX_COLUMNS,+ min: GALLERY_PICKER_MIN_COLUMNS,+ targetCellPx: GALLERY_PICKER_CELL_PX,+ widthPx,+ })+ );+ }+ });++ observer.observe(node);+ resizeObserverRef.current = observer;+ },+ [onColumnCountChange]+ );++ // The scroll viewport is found from the DOM rather than a ref: the sentinel+ // can mount in the same commit as the viewport, before any parent ref is set.+ const sentinelRef = useCallback(+ (node: HTMLDivElement | null) => {+ loadMoreObserverRef.current?.disconnect();+ loadMoreObserverRef.current = null;++ if (!node) {+ return;+ }++ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry?.isIntersecting) {+ onLoadMore();+ }+ },+ { root: node.closest('[data-scope="scroll-area"][data-part="viewport"]'), rootMargin: '160px' }+ );++ observer.observe(node);+ loadMoreObserverRef.current = observer;+ },+ [onLoadMore]+ );++ const handleClick = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ const key = (event.target as HTMLElement).closest<HTMLElement>('[data-item-key]')?.dataset.itemKey;+ const item = key ? itemsByKey.get(key as GalleryItemKey) : undefined;++ if (item) {+ onActivate(item);+ }+ },+ [itemsByKey, onActivate]+ );++ return (+ <Scrollable flex="1" minH="0">+ <Box+ ref={measureRef}+ aria-busy={items === null || isStale || undefined}+ aria-label={label}+ aria-multiselectable={isMultiple || undefined}+ display="grid"+ gap={`${GRID_GAP_PX}px`}+ gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}+ id={idBase}+ opacity={isStale ? 0.6 : undefined}+ p="2"+ role="listbox"+ transition="opacity var(--wb-motion-duration-fast) ease"+ onClick={handleClick}+ >+ {items === null+ ? Array.from({ length: SKELETON_TILE_COUNT }, (_, index) => (+ <Skeleton key={index} aspectRatio={1} rounded="md" />+ ))+ : items.map((item) => {+ const key = toGalleryItemKey(item);++ return (+ <GalleryPickerTile+ key={key}+ idBase={idBase}+ isActive={key === activeKey}+ isCurrent={key === currentKey}+ isMultiple={isMultiple}+ item={item}+ state={getTileState(item)}+ />+ );+ })}+ </Box>+ {items && items.length > 0 && !isStale ? <Box ref={sentinelRef} aria-hidden="true" h="1px" /> : null}+ </Scrollable>+ );+};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.tsxnew file mode 100644index 0000000000..3a3b5edf36--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx@@ -0,0 +1,534 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop */+import type { GalleryItem } from '@features/gallery/core/items';+import type { GalleryBoard } from '@features/gallery/core/types';+import type { GalleryUiAdapter } from '@features/gallery/react';++import { ChakraProvider } from '@chakra-ui/react';+import { legacyGeneratedImageToGalleryItem } from '@features/gallery/core/items';+import { GalleryUiProvider } from '@features/gallery/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act, useCallback, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getGalleryPickerSelectionAfterPick, type GalleryPickerSelection } from './galleryPicker';+import { GalleryPickerPopover } from './GalleryPickerPopover';++const mocks = vi.hoisted(() => ({+ invalidateGallery: vi.fn(),+ listItems: vi.fn(),+ uploadGalleryImage: vi.fn(),+ uploadGalleryVideo: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'en' },+ t: (key: string, values?: Record<string, unknown>) =>+ values && 'name' in values ? `${key}:${String(values.name)}` : key,+ }),+}));++vi.mock('@features/queue/react', () => ({+ useQueueItemProgress: () => null,+ useQueueItemProgressImage: () => null,+}));++vi.mock('@features/gallery/data/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ galleryBoardsOptions: () => ({+ queryFn: () => Promise.resolve(boards),+ queryKey: ['test-picker-boards'],+ staleTime: Infinity,+ }),+ galleryItemsInfiniteOptions: (filter: { boardId: string; galleryView: string; searchTerm: string }) => ({+ getNextPageParam: () => undefined,+ initialPageParam: 0,+ queryFn: () => Promise.resolve(mocks.listItems(filter)),+ queryKey: ['test-picker-items', filter.boardId, filter.galleryView, filter.searchTerm],+ staleTime: Infinity,+ }),+}));++vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),+ uploadGalleryVideo: (...args: unknown[]) => mocks.uploadGalleryVideo(...args),+}));++vi.mock('@features/gallery/data/queryCache', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),+}));++const board: GalleryBoard = {+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id: 'dogs',+ imageCount: 3,+ kind: 'board',+ name: 'Dogs',+ projectId: null,+ videoCount: 1,+};+const uncategorized: GalleryBoard = {+ ...board,+ assetCount: 1,+ id: 'none',+ imageCount: 1,+ kind: 'uncategorized',+ name: '',+};+const boards = [board, uncategorized];++/** Newest first, matching the picker's DESC order. */+const ORDER = ['a.png', 'b.png', 'c.mp4', 'cat.png', 'e.png', 'f.png', 'loose.png'];++const image = (name: string, boardId = 'dogs'): GalleryItem => ({+ boardId,+ category: 'general',+ createdAt: `2026-09-0${9 - ORDER.indexOf(name)}T00:00:00.000Z`,+ fullUrl: `/full/${name}`,+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name,+ starred: false,+ thumbnailUrl: `/thumb/${name}`,+ width: 64,+});+const video = (name: string): GalleryItem => ({ ...image(name), durationSeconds: 4, kind: 'video' });++const dogItems: GalleryItem[] = [+ image('a.png'),+ image('b.png'),+ video('c.mp4'),+ image('cat.png'),+ image('e.png'),+ image('f.png'),+];+const uncategorizedItems: GalleryItem[] = [image('loose.png', 'none')];++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const galleryCommands = { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() };+const openGallery = vi.fn(() => true);+const notifications = { add: vi.fn(), reportError: vi.fn() };++const adapter = {+ gallery: galleryCommands,+ galleryValues: { galleryView: 'images', selectedBoardId: 'dogs', selectedImage: dogItems[1] },+ notifications,+ projectName: 'Project',+ widgets: { openGallery, patchGalleryValues: vi.fn() },+} as unknown as GalleryUiAdapter;++const onPick = vi.fn();++/** A consumer that records picks into `selection`, as every multi-add slot does. */+const MultiAddHost = ({ initialSelection }: { initialSelection: GalleryPickerSelection }) => {+ const [selection, setSelection] = useState(initialSelection);+ const handlePick = useCallback((item: GalleryItem) => {+ onPick(item);+ setSelection((current) => getGalleryPickerSelectionAfterPick(current, item));+ }, []);++ return (+ <GalleryPickerPopover accept={['image']} label="Add images" selection={selection} onPick={handlePick}>+ <button type="button">Add images</button>+ </GalleryPickerPopover>+ );+};++const OPEN_DIALOG = '[role="dialog"][data-state="open"]';++const settle = async () => {+ for (let round = 0; round < 6; round += 1) {+ await act(async () => {+ await new Promise((resolve) => {+ requestAnimationFrame(() => setTimeout(resolve, 0));+ });+ });+ }+};++const renderPicker = async (picker?: React.ReactElement) => {+ 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>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );++ const trigger = host?.querySelector<HTMLButtonElement>('button');++ if (!trigger) {+ throw new Error('trigger did not render');+ }++ return trigger;+};++const openPicker = async (picker?: React.ReactElement) => {+ const trigger = await renderPicker(picker);++ await act(() => trigger.click());+ await settle();++ const dialog = document.querySelector<HTMLElement>(OPEN_DIALOG);++ if (!dialog) {+ throw new Error('picker did not open');+ }++ return { dialog, trigger };+};++const getSearchInput = (dialog: HTMLElement) => {+ const input = dialog.querySelector<HTMLInputElement>('input:not([type="file"])');++ if (!input) {+ throw new Error('search input missing');+ }++ return input;+};++const getOptions = (dialog: HTMLElement) => [...dialog.querySelectorAll<HTMLElement>('[role="option"]')];+const getOption = (dialog: HTMLElement, key: string) => {+ const option = dialog.querySelector<HTMLElement>(`[data-item-key="${CSS.escape(key)}"]`);++ if (!option) {+ throw new Error(`option ${key} missing`);+ }++ return option;+};+const getActiveOption = (dialog: HTMLElement) =>+ document.getElementById(getSearchInput(dialog).getAttribute('aria-activedescendant') ?? '');+const getStatus = (dialog: HTMLElement) => dialog.querySelector('[role="status"]')?.textContent ?? '';+const getBoardsRegion = (dialog: HTMLElement) =>+ dialog.querySelector<HTMLElement>('[role="region"][aria-label="widgets.gallery.picker.boardsLabel"]');+const getBoardRow = (dialog: HTMLElement, text: string) =>+ [...(getBoardsRegion(dialog)?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find((row) =>+ row.textContent?.includes(text)+ );+const getColumnCount = (dialog: HTMLElement) =>+ getComputedStyle(dialog.querySelector('[role="listbox"]')!).gridTemplateColumns.split(' ').length;++const pressKey = async (target: HTMLElement, key: string) => {+ await act(() => target.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key })));+ await settle();+};++const typeSearch = async (input: HTMLInputElement, value: string) => {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;++ await act(() => {+ setter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await settle();+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.listItems.mockImplementation((filter: { boardId: string; searchTerm: string }) => {+ const items = filter.boardId === 'none' ? uncategorizedItems : dogItems;+ const matching = items.filter((item) => item.name.includes(filter.searchTerm));++ return { items: matching, total: matching.length };+ });+ host = document.createElement('div');+ document.body.appendChild(host);+ root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ queryClient?.clear();+});++describe('GalleryPickerPopover', () => {+ it('opens with the search focused and the gallery selection ready to pick with Enter', async () => {+ const { dialog, trigger } = await openPicker();+ const input = getSearchInput(dialog);++ await vi.waitFor(() => expect(document.activeElement).toBe(input));+ expect(dialog.getAttribute('aria-label')).toBe('Choose image');+ expect(getOptions(dialog)).toHaveLength(6);+ expect(getActiveOption(dialog)).toBe(getOption(dialog, 'image:b.png'));+ expect(getOption(dialog, 'image:b.png').getAttribute('aria-selected')).toBe('true');+ expect(getStatus(dialog)).toBe('widgets.gallery.picker.itemCount');++ const activeTab = dialog.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');++ expect(document.getElementById(activeTab?.getAttribute('aria-controls') ?? '')?.getAttribute('role')).toBe(+ 'tabpanel'+ );++ await pressKey(input, 'Enter');++ expect(onPick).toHaveBeenCalledExactlyOnceWith(dogItems[1]);+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ await vi.waitFor(() => expect(document.activeElement).toBe(trigger));+ });++ it('moves the highlight with the arrow keys, by column for up and down, and picks with a click', async () => {+ const { dialog } = await openPicker();+ const input = getSearchInput(dialog);+ const columns = getColumnCount(dialog);++ expect(columns).toBeGreaterThanOrEqual(3);++ await pressKey(input, 'ArrowLeft');+ expect(getActiveOption(dialog)).toBe(getOption(dialog, 'image:a.png'));++ await pressKey(input, 'ArrowDown');+ expect(getActiveOption(dialog)?.dataset.itemKey).toBe(`image:${ORDER[columns]}`);++ await pressKey(input, 'ArrowUp');+ await pressKey(input, 'ArrowRight');+ await pressKey(input, 'ArrowRight');+ expect(getActiveOption(dialog)).toBe(getOption(dialog, 'video:c.mp4'));+ expect(getStatus(dialog)).toBe('widgets.gallery.picker.unsupportedVideo');++ await pressKey(input, 'Enter');+ expect(onPick).not.toHaveBeenCalled();++ await act(() => getOption(dialog, 'image:cat.png').click());+ expect(onPick).toHaveBeenCalledExactlyOnceWith(dogItems[3]);+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ });++ it('closes on Escape and returns focus to the trigger', async () => {+ const { dialog, trigger } = await openPicker();++ await act(() =>+ getSearchInput(dialog).dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }))+ );+ await settle();++ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ expect(onPick).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(document.activeElement).toBe(trigger));+ });++ it('dims tiles the slot cannot take and ignores clicks on them', async () => {+ const { dialog } = await openPicker();+ const videoTile = getOption(dialog, 'video:c.mp4');++ expect(videoTile.getAttribute('aria-disabled')).toBe('true');+ expect(getComputedStyle(videoTile).opacity).toBe('0.35');++ await act(() => videoTile.click());++ expect(onPick).not.toHaveBeenCalled();+ expect(document.querySelector(OPEN_DIALOG)).not.toBeNull();+ });++ it('filters the board as you type and restarts the highlight at the first match', async () => {+ const { dialog } = await openPicker();++ await typeSearch(getSearchInput(dialog), 'cat');++ expect(mocks.listItems).toHaveBeenCalledWith(expect.objectContaining({ boardId: 'dogs', searchTerm: 'cat' }));+ expect(getOptions(dialog).map((option) => option.dataset.itemKey)).toEqual(['image:cat.png']);+ expect(getActiveOption(dialog)).toBe(getOption(dialog, 'image:cat.png'));+ expect(getStatus(dialog)).toBe('widgets.gallery.picker.matchCount');++ // With text in the field, Left/Right belong to the caret.+ const leftKey = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'ArrowLeft' });++ await act(() => getSearchInput(dialog).dispatchEvent(leftKey));+ expect(leftKey.defaultPrevented).toBe(false);+ expect(getActiveOption(dialog)).toBe(getOption(dialog, 'image:cat.png'));+ });++ it('switches to the Assets view from the tabs', async () => {+ const { dialog } = await openPicker();+ const assetsTab = [...dialog.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) =>+ tab.textContent?.includes('common.assets')+ );++ await act(() => assetsTab?.click());+ await settle();++ expect(mocks.listItems).toHaveBeenCalledWith(expect.objectContaining({ boardId: 'dogs', galleryView: 'assets' }));+ });++ it('keeps multi-add pickers open until every slot is filled', async () => {+ const selection: GalleryPickerSelection = {+ addedKeys: new Set(['image:a.png']),+ mode: 'multiple',+ remaining: { image: 2 },+ };+ const { dialog } = await openPicker(<MultiAddHost initialSelection={selection} />);++ expect(dialog.querySelector('[role="listbox"]')?.getAttribute('aria-multiselectable')).toBe('true');+ expect(getOption(dialog, 'image:a.png').getAttribute('aria-disabled')).toBe('true');+ expect(getOption(dialog, 'image:a.png').getAttribute('aria-selected')).toBe('true');+ expect(getOption(dialog, 'image:b.png').getAttribute('aria-selected')).toBe('false');+ expect(getStatus(dialog)).toBe('widgets.gallery.picker.remainingCount · widgets.gallery.picker.itemCount');+ expect(dialog.textContent).toContain('common.done');++ await act(() => getOption(dialog, 'image:a.png').click());+ expect(onPick).not.toHaveBeenCalled();++ await act(() => getOption(dialog, 'image:b.png').click());++ expect(onPick).toHaveBeenCalledExactlyOnceWith(dogItems[1]);+ expect(document.querySelector(OPEN_DIALOG)).not.toBeNull();+ expect(getOption(dialog, 'image:b.png').getAttribute('aria-disabled')).toBe('true');+ expect(getOption(dialog, 'image:b.png').getAttribute('aria-selected')).toBe('true');++ await act(() => getOption(dialog, 'image:cat.png').click());++ expect(onPick).toHaveBeenCalledTimes(2);+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ });++ it('switches boards from an in-place list and re-scopes the grid', async () => {+ const { dialog } = await openPicker();+ const input = getSearchInput(dialog);+ const boardButton = dialog.querySelector<HTMLButtonElement>('[aria-expanded]');++ await typeSearch(input, 'cat');+ await act(() => boardButton?.click());+ await settle();++ expect(boardButton?.getAttribute('aria-expanded')).toBe('true');+ expect(getOptions(dialog)).toHaveLength(0);+ expect(input.value).toBe('');+ expect(getStatus(dialog)).toBe('widgets.gallery.picker.boardCount');+ expect(getBoardRow(dialog, 'Dogs')?.getAttribute('aria-current')).toBe('true');++ // Enter with an empty search must not silently switch boards.+ await pressKey(input, 'Enter');+ expect(boardButton?.getAttribute('aria-expanded')).toBe('true');++ // ArrowDown hands focus to the first row; ArrowUp from it comes back.+ await pressKey(input, 'ArrowDown');+ const firstRow = getBoardsRegion(dialog)?.querySelector('button');++ expect(document.activeElement).toBe(firstRow);+ await pressKey(firstRow as HTMLElement, 'ArrowUp');+ expect(document.activeElement).toBe(input);++ await act(() => getBoardRow(dialog, 'widgets.gallery.uncategorized')?.click());+ await settle();++ expect(boardButton?.getAttribute('aria-expanded')).toBe('false');+ expect(mocks.listItems).toHaveBeenCalledWith(expect.objectContaining({ boardId: 'none' }));+ expect(getOptions(dialog).map((option) => option.dataset.itemKey)).toEqual(['image:loose.png']);+ expect(galleryCommands.selectBoard).not.toHaveBeenCalled();+ });++ it('uploads into the current board and picks the result', async () => {+ const uploaded = {+ boardId: 'dogs',+ createdAt: '2026-09-09T00:00:00.000Z',+ height: 64,+ imageCategory: 'user' as const,+ imageName: 'fresh.png',+ imageUrl: '/full/fresh.png',+ queuedAt: '2026-09-09T00:00:00.000Z',+ sourceQueueItemId: 'queue-1',+ starred: false,+ thumbnailUrl: '/thumb/fresh.png',+ width: 64,+ };++ mocks.uploadGalleryImage.mockResolvedValue(uploaded);++ const { dialog } = await openPicker();+ const fileInput = dialog.querySelector<HTMLInputElement>('input[type="file"]');++ expect(fileInput?.getAttribute('accept')).toBe('image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp');+ expect(fileInput?.multiple).toBe(false);++ Object.defineProperty(fileInput, 'files', {+ configurable: true,+ value: [new File(['image'], 'fresh.png', { type: 'image/png' })],+ });+ await act(() => fileInput?.dispatchEvent(new Event('change', { bubbles: true })));+ await settle();++ expect(mocks.uploadGalleryImage).toHaveBeenCalledWith(expect.any(File), 'dogs', expect.anything());+ expect(onPick).toHaveBeenCalledExactlyOnceWith(legacyGeneratedImageToGalleryItem(uploaded));+ expect(onPick.mock.calls[0]?.[0]).toMatchObject({ fullUrl: '/full/fresh.png', kind: 'image', name: 'fresh.png' });+ expect(galleryCommands.selectItem).not.toHaveBeenCalled();+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ });++ it('does not adopt an upload of a kind the slot cannot take', async () => {+ mocks.uploadGalleryVideo.mockResolvedValue(video('clip.mp4'));++ const { dialog } = await openPicker();+ const fileInput = dialog.querySelector<HTMLInputElement>('input[type="file"]');++ Object.defineProperty(fileInput, 'files', {+ configurable: true,+ value: [new File(['video'], 'clip.mp4', { type: 'video/mp4' })],+ });+ await act(() => fileInput?.dispatchEvent(new Event('change', { bubbles: true })));+ await settle();++ expect(mocks.uploadGalleryVideo).toHaveBeenCalledOnce();+ expect(onPick).not.toHaveBeenCalled();+ expect(document.querySelector(OPEN_DIALOG)).not.toBeNull();+ });++ it('hands off to the Gallery widget on the picker board', async () => {+ const { dialog } = await openPicker();++ await act(() => dialog.querySelector<HTMLButtonElement>('[aria-expanded]')?.click());+ await settle();+ await act(() => getBoardRow(dialog, 'widgets.gallery.uncategorized')?.click());+ await settle();++ const openButton = [...dialog.querySelectorAll<HTMLButtonElement>('button')].find((button) =>+ button.textContent?.includes('widgets.gallery.picker.openGallery')+ );++ await act(() => openButton?.click());++ expect(galleryCommands.selectBoard).toHaveBeenCalledExactlyOnceWith('none');+ expect(galleryCommands.setView).toHaveBeenCalledExactlyOnceWith('images');+ expect(openGallery).toHaveBeenCalledOnce();+ expect(document.querySelector(OPEN_DIALOG)).toBeNull();+ });++ it('leaves the Gallery board alone when it already matches, and stays open if the widget cannot open', async () => {+ openGallery.mockReturnValueOnce(false);++ const { dialog } = await openPicker();+ const openButton = [...dialog.querySelectorAll<HTMLButtonElement>('button')].find((button) =>+ button.textContent?.includes('widgets.gallery.picker.openGallery')+ );++ await act(() => openButton?.click());++ expect(galleryCommands.selectBoard).not.toHaveBeenCalled();+ expect(openGallery).toHaveBeenCalledOnce();+ expect(document.querySelector(OPEN_DIALOG)).not.toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsxnew file mode 100644index 0000000000..5b4d45bac3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx@@ -0,0 +1,76 @@+import type { GalleryItem } from '@features/gallery/core/items';+import type { ReactElement } from 'react';++import { Popover, Portal } from '@chakra-ui/react';+import { PopoverContent } from '@platform/ui/Popover';+import { useCallback, useRef, useState } from 'react';++import type { GalleryPickerAccept, GalleryPickerSelection } from './galleryPicker';++import { GalleryPickerView } from './GalleryPickerView';++const POSITIONING = { placement: 'bottom-start' } as const;+const SINGLE_SELECTION: GalleryPickerSelection = { mode: 'single' };++export interface GalleryPickerPopoverProps {+ accept: GalleryPickerAccept;+ /** The trigger element; must accept a ref and a click handler. */+ children: ReactElement;+ /** The dialog's accessible name, e.g. "Choose image". */+ label: string;+ selection?: GalleryPickerSelection;+ onPick: (item: GalleryItem) => void;+}++/**+ * A compact gallery anchored to an image slot. The view mounts on open and+ * unmounts on close, so every open starts from the Gallery widget's scope.+ */+export const GalleryPickerPopover = ({+ accept,+ children,+ label,+ selection = SINGLE_SELECTION,+ onPick,+}: GalleryPickerPopoverProps) => {+ const [isOpen, setIsOpen] = useState(false);+ const searchInputRef = useRef<HTMLInputElement>(null);++ const handleOpenChange = useCallback(({ open }: { open: boolean }) => setIsOpen(open), []);+ const close = useCallback(() => setIsOpen(false), []);+ const getInitialFocusEl = useCallback(() => searchInputRef.current, []);++ return (+ <Popover.Root+ initialFocusEl={getInitialFocusEl}+ lazyMount+ open={isOpen}+ positioning={POSITIONING}+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Popover.Trigger asChild>{children}</Popover.Trigger>+ <Portal>+ <Popover.Positioner>+ <PopoverContent+ aria-label={label}+ display="flex"+ flexDirection="column"+ maxH="min(26rem, var(--available-height))"+ overflow="hidden"+ p="0"+ w="clamp(18rem, var(--reference-width), 28rem)"+ >+ <GalleryPickerView+ accept={accept}+ searchInputRef={searchInputRef}+ selection={selection}+ onClose={close}+ onPick={onPick}+ />+ </PopoverContent>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxnew file mode 100644index 0000000000..cd7843571a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -0,0 +1,468 @@+import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';+import type { KeyboardEvent, RefObject } from 'react';++import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { 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 { getGalleryProjectBoardId, getGallerySelectedBoardId } from '@features/gallery/ui/galleryStateView';+import { useGalleryUi } 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';+import { getGalleryUploadAccept, useGalleryUploadInput } from '@features/gallery/ui/useGalleryUploadInput';+import { Button, CloseButton, IconButton } from '@platform/ui/Button';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';+import { Tooltip } from '@platform/ui/Tooltip';+import { ChevronsDownUpIcon, ChevronsUpDownIcon, ExternalLinkIcon, ImageIcon, UploadIcon } from 'lucide-react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ GALLERY_PICKER_MIN_COLUMNS,+ getGalleryPickerDefaultIndex,+ getGalleryPickerNeighborIndex,+ getGalleryPickerRemaining,+ getGalleryPickerSelectionAfterPick,+ getGalleryPickerStatus,+ getGalleryPickerTileState,+ isGalleryPickerFull,+ isGalleryPickerNavKey,+ isGalleryPickerNavKeyForField,+ type GalleryPickerAccept,+ type GalleryPickerSelection,+} from './galleryPicker';+import { GalleryPickerBoards, type GalleryPickerBoardGroup } from './GalleryPickerBoards';+import { galleryPickerOptionId, GalleryPickerGrid } from './GalleryPickerGrid';+import { useGalleryPickerScope } from './useGalleryPickerScope';++const BOARD_BUTTON_EXPANDED_PROPS = { bg: 'bg.emphasized' } as const;++/** Unseeded until the first page loads; then the Gallery's selection if it is on that page, else nothing. */+type ActiveKeyState = GalleryItemKey | null | undefined;++export const GalleryPickerView = ({+ accept,+ searchInputRef,+ selection,+ onClose,+ onPick,+}: {+ accept: GalleryPickerAccept;+ searchInputRef: RefObject<HTMLInputElement | null>;+ selection: GalleryPickerSelection;+ onClose: () => void;+ onPick: (item: GalleryItem) => void;+}) => {+ const { t } = useTranslation();+ const { gallery: galleryCommands, galleryValues, projectName, widgets } = useGalleryUi();+ const { data, gallerySelectedItem, scope, selectBoard, setSearchTerm, setView, settings, togglePane } =+ useGalleryPickerScope();+ const idBase = useId();+ const listboxId = `${idBase}-options`;+ const boardsId = `${idBase}-boards`;+ const isMultiple = selection.mode === 'multiple';+ const isSearching = scope.searchTerm.trim() !== '';+ const currentKey = gallerySelectedItem ? toGalleryItemKey(gallerySelectedItem) : null;+ const seedKey = gallerySelectedItem && accept.includes(gallerySelectedItem.kind) ? currentKey : null;++ const [activeKey, setActiveKey] = useState<ActiveKeyState>(undefined);+ const [columnCount, setColumnCount] = useState(GALLERY_PICKER_MIN_COLUMNS);+ const [isUploading, setIsUploading] = useState(false);+ // Live read ports: an upload resolves after an await and must judge capacity+ // against the selection as it stands then; the sentinel observer wants one+ // stable callback rather than a rebuild per fetched page.+ const selectionRef = useRef(selection);+ const loadMoreRef = useRef(data.loadMore);+ // The previous scope's items stay on screen, dimmed, while a new board or+ // search loads; skeletons only ever show before anything has loaded.+ const [lastItems, setLastItems] = useState<GalleryItem[] | null>(null);++ // eslint-disable-next-line react/react-compiler+ selectionRef.current = selection;+ // eslint-disable-next-line react/react-compiler+ loadMoreRef.current = data.loadMore;++ if (data.items !== null && data.items !== lastItems) {+ setLastItems(data.items);+ }++ const isStale = data.items === null && lastItems !== null;+ const items = data.items ?? lastItems;++ // Seed once the first page is in, so a selection past it never yanks the+ // highlight (and the scroll) when a later page happens to contain it.+ if (activeKey === undefined && data.items !== null) {+ setActiveKey(seedKey && data.items.some((item) => toGalleryItemKey(item) === seedKey) ? seedKey : null);+ }++ const activeIndex = activeKey && items ? items.findIndex((item) => toGalleryItemKey(item) === activeKey) : -1;+ const resolvedActiveIndex =+ activeIndex >= 0 ? activeIndex : items ? getGalleryPickerDefaultIndex(items, accept, selection) : -1;+ const activeItem = resolvedActiveIndex >= 0 ? items?.[resolvedActiveIndex] : undefined;+ const resolvedActiveKey = activeItem ? toGalleryItemKey(activeItem) : null;+ const selectedBoard = data.boards.find((board) => board.id === data.selectedBoardId);+ const boardName = selectedBoard ? getGalleryBoardLabel(selectedBoard, t) : t('widgets.gallery.selectedBoardFallback');+ const uploadTarget = getGalleryUploadTargetLabel(data.boards, data.selectedBoardId, t);+ const showsGrid = scope.pane === 'items' && (items === null || items.length > 0);++ const getTileState = useCallback(+ (item: GalleryItem) => getGalleryPickerTileState(item, accept, selection),+ [accept, selection]+ );++ const pickItem = useCallback(+ (item: GalleryItem) => {+ const current = selectionRef.current;++ if (getGalleryPickerTileState(item, accept, current) !== 'pickable') {+ return;+ }++ onPick(item);++ if (current.mode === 'single' || isGalleryPickerFull(accept, getGalleryPickerSelectionAfterPick(current, item))) {+ onClose();+ }+ },+ [accept, onClose, onPick]+ );++ const uploadFiles = useGalleryUploadAction({ boards: data.boards, selectedBoardId: data.selectedBoardId });+ const adoptUploads = useCallback(+ (uploaded: GalleryItem[]) => {+ let current = selectionRef.current;+ let picked = false;++ for (const item of uploaded) {+ if (getGalleryPickerTileState(item, accept, current) !== 'pickable') {+ continue;+ }++ onPick(item);+ picked = true;+ current = getGalleryPickerSelectionAfterPick(current, item);+ }++ if (picked && (current.mode === 'single' || isGalleryPickerFull(accept, current))) {+ onClose();+ }+ },+ [accept, onClose, onPick]+ );+ const handleUpload = useCallback(+ (files: File[]) => {+ setIsUploading(true);++ return uploadFiles(files)+ .then(adoptUploads)+ .finally(() => setIsUploading(false));+ },+ [adoptUploads, uploadFiles]+ );+ const uploadOptions = useMemo(+ () => ({ accept: getGalleryUploadAccept(accept), multiple: isMultiple }),+ [accept, isMultiple]+ );+ const { inputProps: uploadInputProps, openPicker: openUploadPicker } = useGalleryUploadInput(+ handleUpload,+ uploadOptions+ );++ const boardGroups = useMemo<GalleryPickerBoardGroup[]>(() => {+ const groups = getGalleryBoardGroups({+ boards: data.boards,+ projectBoardId: getGalleryProjectBoardId(galleryValues),+ projectName,+ searchTerm: scope.searchTerm,+ showArchived: settings.showArchivedBoards,+ showDates: settings.showDateBoards,+ showOtherProjects: settings.showOtherProjectBoards,+ t,+ });++ return [+ { boards: groups.yourBoards, id: 'boards', label: t('widgets.gallery.boardGroups.boards') },+ { boards: groups.dateBoards, id: 'dates', label: t('widgets.gallery.boardGroups.byDate') },+ { boards: groups.archivedBoards, id: 'archived', label: t('common.archived') },+ ].filter((group) => group.boards.length > 0);+ }, [+ data.boards,+ galleryValues,+ projectName,+ scope.searchTerm,+ settings.showArchivedBoards,+ settings.showDateBoards,+ settings.showOtherProjectBoards,+ t,+ ]);+ const visibleBoardCount = boardGroups.reduce((count, group) => count + group.boards.length, 0);++ const focusSearch = useCallback(() => searchInputRef.current?.focus(), [searchInputRef]);+ // The clicked row unmounts with the pane; without this, focus falls to the+ // body and the next keystrokes reach the workbench hotkeys.+ const handleSelectBoard = useCallback(+ (boardId: string) => {+ selectBoard(boardId);+ focusSearch();+ },+ [focusSearch, selectBoard]+ );++ const handleSearchKeyDown = useCallback(+ (event: KeyboardEvent<HTMLInputElement>) => {+ if (event.nativeEvent.isComposing) {+ return;+ }++ if (scope.pane === 'boards') {+ if (event.key === 'ArrowDown') {+ event.preventDefault();+ event.stopPropagation();+ document.getElementById(boardsId)?.querySelector('button')?.focus();+ } else if (event.key === 'Enter' && isSearching) {+ const first = boardGroups[0]?.boards[0];++ event.preventDefault();+ event.stopPropagation();++ if (first) {+ handleSelectBoard(first.id);+ }+ }++ return;+ }++ if (!items) {+ return;+ }++ if (isGalleryPickerNavKey(event.key) && isGalleryPickerNavKeyForField(event.key, event.currentTarget.value)) {+ const next = items[getGalleryPickerNeighborIndex(resolvedActiveIndex, items.length, columnCount, event.key)];++ event.preventDefault();+ event.stopPropagation();++ if (next) {+ setActiveKey(toGalleryItemKey(next));+ }+ } else if (event.key === 'Enter') {+ event.preventDefault();+ event.stopPropagation();++ if (activeItem) {+ pickItem(activeItem);+ }+ }+ },+ [+ activeItem,+ boardGroups,+ boardsId,+ columnCount,+ handleSelectBoard,+ isSearching,+ items,+ pickItem,+ resolvedActiveIndex,+ scope.pane,+ ]+ );++ const handleActivate = useCallback(+ (item: GalleryItem) => {+ setActiveKey(toGalleryItemKey(item));+ pickItem(item);+ },+ [pickItem]+ );+ const handleLoadMore = useCallback(() => loadMoreRef.current(), []);+ const handleClearSearch = useCallback(() => setSearchTerm(''), [setSearchTerm]);++ const openGallery = useCallback(() => {+ if (data.selectedBoardId !== getGallerySelectedBoardId(galleryValues, data.boards)) {+ galleryCommands.selectBoard(data.selectedBoardId);+ }++ galleryCommands.setView(scope.galleryView);++ if (widgets.openGallery()) {+ onClose();+ }+ }, [data.boards, data.selectedBoardId, galleryCommands, galleryValues, onClose, scope.galleryView, widgets]);++ const status = getGalleryPickerStatus({+ accept,+ activeItem,+ isSearching,+ isWindowTruncated: data.isWindowTruncated,+ loadedCount: items?.length ?? 0,+ pane: scope.pane,+ remaining: getGalleryPickerRemaining(accept, selection),+ total: data.total,+ visibleBoardCount,+ })+ .map((part) => t(`widgets.gallery.picker.${part.kind}`, 'count' in part ? { count: part.count } : undefined))+ .join(' · ');++ const searchEndElement = useMemo(+ () => (+ <HStack flexShrink={0} gap="0">+ {scope.searchTerm ? (+ <CloseButton aria-label={t('common.clearSearch')} size="2xs" onClick={handleClearSearch} />+ ) : null}+ {scope.pane === 'items' ? <GallerySearchHelp /> : null}+ </HStack>+ ),+ [handleClearSearch, scope.pane, scope.searchTerm, t]+ );+ const searchInputProps = useMemo(+ () =>+ scope.pane === 'boards'+ ? { 'aria-controls': boardsId }+ : showsGrid+ ? {+ 'aria-activedescendant': resolvedActiveKey+ ? galleryPickerOptionId(listboxId, resolvedActiveKey)+ : undefined,+ 'aria-controls': listboxId,+ }+ : undefined,+ [boardsId, listboxId, resolvedActiveKey, scope.pane, showsGrid]+ );+ const searchLabel =+ scope.pane === 'boards'+ ? t('widgets.gallery.picker.findBoard')+ : t('widgets.gallery.picker.searchIn', { name: boardName });++ return (+ <Stack flex="1" gap="0" minH="0">+ <input {...uploadInputProps} />+ <HStack gap="1" minW="0" pt="2" px="2">+ <Button+ _expanded={BOARD_BUTTON_EXPANDED_PROPS}+ aria-controls={scope.pane === 'boards' ? boardsId : undefined}+ aria-expanded={scope.pane === 'boards'}+ aria-label={t('widgets.gallery.picker.changeBoardNamed', { name: boardName })}+ flex="1"+ justifyContent="flex-start"+ minW="0"+ size="xs"+ variant="ghost"+ onClick={togglePane}+ >+ {selectedBoard ? <BoardCover board={selectedBoard} /> : <BoardCoverIcon icon={ImageIcon} />}+ <MiddleTruncate fontWeight="600" minW="0" text={boardName} />+ <Icon+ as={scope.pane === 'boards' ? ChevronsDownUpIcon : ChevronsUpDownIcon}+ boxSize="3"+ color="fg.subtle"+ flexShrink={0}+ />+ </Button>+ <GalleryViewSegmentTabs+ activeView={scope.galleryView}+ board={selectedBoard}+ idBase={idBase}+ onSelect={setView}+ />+ <Tooltip content={uploadTarget.label}>+ <IconButton+ aria-busy={isUploading || undefined}+ aria-label={uploadTarget.label}+ color="fg.muted"+ disabled={!uploadTarget.isAvailable || isUploading}+ size="xs"+ variant="ghost"+ onClick={openUploadPicker}+ >+ <Icon as={UploadIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ </HStack>+ <Box pt="1.5" px="2">+ <GallerySearchField+ ref={searchInputRef}+ ariaLabel={searchLabel}+ endElement={searchEndElement}+ inputProps={searchInputProps}+ placeholder={searchLabel}+ value={scope.searchTerm}+ onChange={setSearchTerm}+ onKeyDown={handleSearchKeyDown}+ />+ </Box>+ <Stack+ aria-labelledby={segmentTabsTabId(idBase, scope.galleryView)}+ flex="1"+ gap="0"+ id={segmentTabsPanelId(idBase)}+ minH="0"+ role="tabpanel"+ >+ {scope.pane === 'boards' ? (+ <GalleryPickerBoards+ emptyMessage={t('widgets.gallery.noBoardsMatchSearch')}+ galleryView={scope.galleryView}+ groups={boardGroups}+ id={boardsId}+ label={t('widgets.gallery.picker.boardsLabel')}+ selectedBoardId={data.selectedBoardId}+ onExitTop={focusSearch}+ onSelect={handleSelectBoard}+ />+ ) : showsGrid ? (+ <GalleryPickerGrid+ activeKey={resolvedActiveKey}+ columnCount={columnCount}+ currentKey={currentKey}+ getTileState={getTileState}+ idBase={listboxId}+ isMultiple={isMultiple}+ isStale={isStale}+ items={items}+ label={t('widgets.gallery.picker.itemsLabel')}+ onActivate={handleActivate}+ onColumnCountChange={setColumnCount}+ onLoadMore={handleLoadMore}+ />+ ) : (+ <Stack align="center" color="fg.muted" gap="2" justify="center" minH="7rem" px="4" py="6">+ <Icon as={ImageIcon} boxSize="4" color="fg.subtle" />+ <Text fontSize="xs" textAlign="center" textWrap="pretty">+ {isSearching+ ? t('widgets.gallery.noImagesMatch')+ : t('widgets.gallery.picker.empty', { name: boardName })}+ </Text>+ {!isSearching && uploadTarget.isAvailable ? (+ <Button disabled={isUploading} size="xs" variant="outline" onClick={openUploadPicker}>+ <Icon as={UploadIcon} boxSize="3.5" />+ {t('widgets.gallery.picker.upload')}+ </Button>+ ) : null}+ </Stack>+ )}+ </Stack>+ <HStack borderColor="border.subtle" borderTopWidth="1px" gap="2" justify="space-between" pe="1" ps="2" py="1">+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums" minW="0" role="status" truncate>+ {status}+ </Text>+ {isMultiple ? (+ <Button flexShrink={0} size="2xs" variant="subtle" onClick={onClose}>+ {t('common.done')}+ </Button>+ ) : (+ <Button color="fg.muted" flexShrink={0} size="2xs" variant="ghost" onClick={openGallery}>+ {t('widgets.gallery.picker.openGallery')}+ <Icon as={ExternalLinkIcon} boxSize="3" />+ </Button>+ )}+ </HStack>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.test.tsnew file mode 100644index 0000000000..e378ec14cd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.test.ts@@ -0,0 +1,262 @@+import type { GalleryItem } from '@features/gallery/core/items';++import { describe, expect, it } from 'vitest';++import {+ getGalleryPickerDefaultIndex,+ getGalleryPickerNeighborIndex,+ getGalleryPickerRemaining,+ getGalleryPickerSelectionAfterPick,+ getGalleryPickerStatus,+ getGalleryPickerTileState,+ isGalleryPickerFull,+ isGalleryPickerNavKey,+ isGalleryPickerNavKeyForField,+ type GalleryPickerSelection,+} from './galleryPicker';++const image = (name: string): GalleryItem => ({+ boardId: 'board',+ category: 'general',+ createdAt: '2026-09-01T00:00:00.000Z',+ fullUrl: `/full/${name}`,+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name,+ starred: false,+ thumbnailUrl: `/thumb/${name}`,+ width: 64,+});++const video = (name: string): GalleryItem => ({+ boardId: 'board',+ category: 'general',+ createdAt: '2026-09-01T00:00:00.000Z',+ durationSeconds: 3,+ fps: 24,+ fullUrl: `/video/${name}`,+ height: 64,+ isIntermediate: false,+ kind: 'video',+ name,+ starred: false,+ thumbnailUrl: `/video-thumb/${name}`,+ width: 64,+});++const single: GalleryPickerSelection = { mode: 'single' };++describe('getGalleryPickerTileState', () => {+ it('marks kinds the slot cannot take as unsupported before anything else', () => {+ const selection: GalleryPickerSelection = {+ addedKeys: new Set(['video:v.mp4']),+ mode: 'multiple',+ remaining: { image: 0 },+ };++ expect(getGalleryPickerTileState(video('v.mp4'), ['image'], selection)).toBe('unsupported');+ expect(getGalleryPickerTileState(video('v.mp4'), ['image'], single)).toBe('unsupported');+ });++ it('is always pickable in single mode', () => {+ expect(getGalleryPickerTileState(image('a.png'), ['image'], single)).toBe('pickable');+ });++ it('reports added, then full, then pickable in multiple mode', () => {+ const selection: GalleryPickerSelection = {+ addedKeys: new Set(['image:a.png']),+ mode: 'multiple',+ remaining: { image: 0, video: 2 },+ };++ expect(getGalleryPickerTileState(image('a.png'), ['image', 'video'], selection)).toBe('added');+ expect(getGalleryPickerTileState(image('b.png'), ['image', 'video'], selection)).toBe('full');+ expect(getGalleryPickerTileState(video('v.mp4'), ['image', 'video'], selection)).toBe('pickable');+ });++ it('treats a kind without a remaining count as unlimited', () => {+ const selection: GalleryPickerSelection = { addedKeys: new Set(), mode: 'multiple', remaining: {} };++ expect(getGalleryPickerTileState(image('a.png'), ['image'], selection)).toBe('pickable');+ });+});++describe('isGalleryPickerFull', () => {+ it('never reports single mode as full', () => {+ expect(isGalleryPickerFull(['image'], single)).toBe(false);+ });++ it('is full only when every accepted kind is exhausted', () => {+ const halfFull: GalleryPickerSelection = { addedKeys: new Set(), mode: 'multiple', remaining: { image: 0 } };++ expect(isGalleryPickerFull(['image'], halfFull)).toBe(true);+ expect(isGalleryPickerFull(['image', 'video'], halfFull)).toBe(false);+ expect(+ isGalleryPickerFull(['image', 'video'], {+ addedKeys: new Set(),+ mode: 'multiple',+ remaining: { image: 0, video: 0 },+ })+ ).toBe(true);+ });+});++describe('getGalleryPickerSelectionAfterPick', () => {+ it('returns single mode untouched', () => {+ expect(getGalleryPickerSelectionAfterPick(single, image('a.png'))).toBe(single);+ });++ it('adds the key and decrements only the picked kind, never below zero', () => {+ const before: GalleryPickerSelection = {+ addedKeys: new Set(['image:a.png']),+ mode: 'multiple',+ remaining: { image: 1, video: 0 },+ };+ const after = getGalleryPickerSelectionAfterPick(before, image('b.png'));++ expect(after).toEqual({+ addedKeys: new Set(['image:a.png', 'image:b.png']),+ mode: 'multiple',+ remaining: { image: 0, video: 0 },+ });+ expect(before.addedKeys.has('image:b.png')).toBe(false);+ expect(getGalleryPickerSelectionAfterPick(after, image('c.png'))).toMatchObject({ remaining: { image: 0 } });+ });++ it('leaves an unlimited kind unlimited', () => {+ const after = getGalleryPickerSelectionAfterPick(+ { addedKeys: new Set(), mode: 'multiple', remaining: { video: 1 } },+ image('a.png')+ );++ expect(after).toMatchObject({ remaining: { video: 1 } });+ expect(isGalleryPickerFull(['image', 'video'], after)).toBe(false);+ });+});++describe('getGalleryPickerNeighborIndex', () => {+ // 4 columns, 10 tiles: rows [0..3] [4..7] [8,9]+ const count = 10;+ const columns = 4;++ it('walks reading order across row ends and clamps at both ends', () => {+ expect(getGalleryPickerNeighborIndex(3, count, columns, 'ArrowRight')).toBe(4);+ expect(getGalleryPickerNeighborIndex(4, count, columns, 'ArrowLeft')).toBe(3);+ expect(getGalleryPickerNeighborIndex(0, count, columns, 'ArrowLeft')).toBe(0);+ expect(getGalleryPickerNeighborIndex(9, count, columns, 'ArrowRight')).toBe(9);+ });++ it('moves by a column up and down and holds still over a ragged row', () => {+ expect(getGalleryPickerNeighborIndex(1, count, columns, 'ArrowDown')).toBe(5);+ expect(getGalleryPickerNeighborIndex(5, count, columns, 'ArrowUp')).toBe(1);+ expect(getGalleryPickerNeighborIndex(6, count, columns, 'ArrowDown')).toBe(6);+ expect(getGalleryPickerNeighborIndex(2, count, columns, 'ArrowUp')).toBe(2);+ });++ it('jumps with Home and End', () => {+ expect(getGalleryPickerNeighborIndex(5, count, columns, 'Home')).toBe(0);+ expect(getGalleryPickerNeighborIndex(5, count, columns, 'End')).toBe(9);+ });++ it('enters the grid at an edge when nothing is active, and yields -1 for an empty grid', () => {+ expect(getGalleryPickerNeighborIndex(-1, count, columns, 'ArrowDown')).toBe(0);+ expect(getGalleryPickerNeighborIndex(-1, count, columns, 'End')).toBe(9);+ expect(getGalleryPickerNeighborIndex(42, count, columns, 'ArrowUp')).toBe(0);+ expect(getGalleryPickerNeighborIndex(0, 0, columns, 'ArrowDown')).toBe(-1);+ });+});++describe('isGalleryPickerNavKey', () => {+ it('recognises the six navigation keys only', () => {+ expect(isGalleryPickerNavKey('ArrowDown')).toBe(true);+ expect(isGalleryPickerNavKey('Home')).toBe(true);+ expect(isGalleryPickerNavKey('Enter')).toBe(false);+ expect(isGalleryPickerNavKey('PageDown')).toBe(false);+ });+});++describe('getGalleryPickerRemaining', () => {+ it('sums the accepted kinds and treats an unlimited kind or single mode as null', () => {+ const selection: GalleryPickerSelection = {+ addedKeys: new Set(),+ mode: 'multiple',+ remaining: { image: 2, video: 1 },+ };++ expect(getGalleryPickerRemaining(['image', 'video'], selection)).toBe(3);+ expect(getGalleryPickerRemaining(['image'], selection)).toBe(2);+ expect(getGalleryPickerRemaining(['image'], { addedKeys: new Set(), mode: 'multiple', remaining: {} })).toBeNull();+ expect(getGalleryPickerRemaining(['image'], single)).toBeNull();+ });+});++describe('getGalleryPickerDefaultIndex', () => {+ it('prefers the first pickable tile and falls back to the first tile', () => {+ const items = [video('v.mp4'), image('a.png'), image('b.png')];++ expect(getGalleryPickerDefaultIndex(items, ['image'], single)).toBe(1);+ expect(getGalleryPickerDefaultIndex(items, ['video'], single)).toBe(0);+ expect(getGalleryPickerDefaultIndex([video('v.mp4')], ['image'], single)).toBe(0);+ expect(getGalleryPickerDefaultIndex([], ['image'], single)).toBe(-1);+ expect(+ getGalleryPickerDefaultIndex(items, ['image'], {+ addedKeys: new Set(['image:a.png']),+ mode: 'multiple',+ remaining: { image: 1 },+ })+ ).toBe(2);+ });+});++describe('getGalleryPickerStatus', () => {+ const base = {+ accept: ['image'] as const,+ activeItem: image('a.png'),+ isSearching: false,+ isWindowTruncated: false,+ loadedCount: 12,+ pane: 'items' as const,+ remaining: null,+ total: 48,+ visibleBoardCount: 3,+ };++ it('counts boards on the boards pane regardless of anything else', () => {+ expect(getGalleryPickerStatus({ ...base, pane: 'boards', remaining: 0 })).toEqual([+ { count: 3, kind: 'boardCount' },+ ]);+ });++ it('explains an unsupported highlight before capacity or counts', () => {+ expect(getGalleryPickerStatus({ ...base, activeItem: video('v.mp4'), remaining: 0 })).toEqual([+ { kind: 'unsupportedVideo' },+ ]);+ expect(getGalleryPickerStatus({ ...base, accept: ['video'], activeItem: image('a.png') })).toEqual([+ { kind: 'unsupportedImage' },+ ]);+ });++ it('composes capacity with the window cap or the listing count', () => {+ expect(getGalleryPickerStatus({ ...base, remaining: 2 })).toEqual([+ { count: 2, kind: 'remainingCount' },+ { count: 48, kind: 'itemCount' },+ ]);+ expect(getGalleryPickerStatus({ ...base, isSearching: true, remaining: 0 })).toEqual([+ { kind: 'remainingNone' },+ { count: 48, kind: 'matchCount' },+ ]);+ expect(getGalleryPickerStatus({ ...base, isWindowTruncated: true })).toEqual([{ count: 12, kind: 'windowLimit' }]);+ expect(getGalleryPickerStatus({ ...base, total: null })).toEqual([]);+ });+});++describe('isGalleryPickerNavKeyForField', () => {+ it('leaves the caret keys to the field once it has text', () => {+ expect(isGalleryPickerNavKeyForField('ArrowLeft', '')).toBe(true);+ expect(isGalleryPickerNavKeyForField('ArrowLeft', 'cat')).toBe(false);+ expect(isGalleryPickerNavKeyForField('Home', 'cat')).toBe(false);+ expect(isGalleryPickerNavKeyForField('ArrowDown', 'cat')).toBe(true);+ expect(isGalleryPickerNavKeyForField('ArrowUp', 'cat')).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.tsnew file mode 100644index 0000000000..f0150fb229--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.ts@@ -0,0 +1,212 @@+import type { GalleryItem, GalleryItemKey, GalleryItemKind } from '@features/gallery/core/items';++import { toGalleryItemKey } from '@features/gallery/core/items';++export type GalleryPickerAccept = readonly GalleryItemKind[];++export type GalleryPickerSelection =+ | { mode: 'single' }+ | {+ mode: 'multiple';+ addedKeys: ReadonlySet<GalleryItemKey>;+ /** Slots left per kind; a kind absent here is unlimited. */+ remaining: Partial<Record<GalleryItemKind, number>>;+ };++export type GalleryPickerTileState = 'added' | 'full' | 'pickable' | 'unsupported';++export const GALLERY_PICKER_CELL_PX = 72;+export const GALLERY_PICKER_MIN_COLUMNS = 3;+export const GALLERY_PICKER_MAX_COLUMNS = 8;++const getRemaining = (selection: Extract<GalleryPickerSelection, { mode: 'multiple' }>, kind: GalleryItemKind) =>+ selection.remaining[kind] ?? Number.POSITIVE_INFINITY;++export const getGalleryPickerTileState = (+ item: GalleryItem,+ accept: GalleryPickerAccept,+ selection: GalleryPickerSelection+): GalleryPickerTileState => {+ if (!accept.includes(item.kind)) {+ return 'unsupported';+ }++ if (selection.mode === 'single') {+ return 'pickable';+ }++ if (selection.addedKeys.has(toGalleryItemKey(item))) {+ return 'added';+ }++ return getRemaining(selection, item.kind) <= 0 ? 'full' : 'pickable';+};++/** True once no accepted kind has a slot left. */+export const isGalleryPickerFull = (accept: GalleryPickerAccept, selection: GalleryPickerSelection): boolean =>+ selection.mode === 'multiple' && accept.every((kind) => getRemaining(selection, kind) <= 0);++/** The selection as it will stand once `item` is added, so a pick can decide to close without waiting on props. */+export const getGalleryPickerSelectionAfterPick = (+ selection: GalleryPickerSelection,+ item: GalleryItem+): GalleryPickerSelection => {+ if (selection.mode === 'single') {+ return selection;+ }++ const remainingForKind = selection.remaining[item.kind];++ return {+ ...selection,+ addedKeys: new Set(selection.addedKeys).add(toGalleryItemKey(item)),+ remaining:+ remainingForKind === undefined+ ? selection.remaining+ : { ...selection.remaining, [item.kind]: Math.max(0, remainingForKind - 1) },+ };+};++/** Slots left across the accepted kinds; null when any accepted kind is unlimited or in single mode. */+export const getGalleryPickerRemaining = (+ accept: GalleryPickerAccept,+ selection: GalleryPickerSelection+): number | null => {+ if (selection.mode !== 'multiple') {+ return null;+ }++ let total = 0;++ for (const kind of accept) {+ const remaining = selection.remaining[kind];++ if (remaining === undefined) {+ return null;+ }++ total += remaining;+ }++ return total;+};++/** Where the keyboard highlight lands when nothing is active: the first tile Enter could pick, else the first tile. */+export const getGalleryPickerDefaultIndex = (+ items: readonly GalleryItem[],+ accept: GalleryPickerAccept,+ selection: GalleryPickerSelection+): number => {+ if (items.length === 0) {+ return -1;+ }++ const pickable = items.findIndex((item) => getGalleryPickerTileState(item, accept, selection) === 'pickable');++ return pickable >= 0 ? pickable : 0;+};++export type GalleryPickerStatusPart =+ | { count: number; kind: 'boardCount' | 'itemCount' | 'matchCount' | 'remainingCount' | 'windowLimit' }+ | { kind: 'remainingNone' | 'unsupportedImage' | 'unsupportedVideo' };++/**+ * The footer line, most specific first: the boards pane counts boards; a+ * highlighted tile the slot cannot take explains itself; otherwise capacity,+ * then either the window cap or the listing size.+ */+export const getGalleryPickerStatus = ({+ accept,+ activeItem,+ isSearching,+ isWindowTruncated,+ loadedCount,+ pane,+ remaining,+ total,+ visibleBoardCount,+}: {+ accept: GalleryPickerAccept;+ activeItem: GalleryItem | undefined;+ isSearching: boolean;+ isWindowTruncated: boolean;+ loadedCount: number;+ pane: 'boards' | 'items';+ remaining: number | null;+ total: number | null;+ visibleBoardCount: number;+}): GalleryPickerStatusPart[] => {+ if (pane === 'boards') {+ return [{ count: visibleBoardCount, kind: 'boardCount' }];+ }++ if (activeItem && !accept.includes(activeItem.kind)) {+ return [{ kind: activeItem.kind === 'video' ? 'unsupportedVideo' : 'unsupportedImage' }];+ }++ const parts: GalleryPickerStatusPart[] = [];++ if (remaining !== null) {+ parts.push(remaining > 0 ? { count: remaining, kind: 'remainingCount' } : { kind: 'remainingNone' });+ }++ if (isWindowTruncated) {+ parts.push({ count: loadedCount, kind: 'windowLimit' });+ } else if (total !== null) {+ parts.push({ count: total, kind: isSearching ? 'matchCount' : 'itemCount' });+ }++ return parts;+};++export type GalleryPickerNavKey = 'ArrowDown' | 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'End' | 'Home';++/** Left/Right/Home/End belong to the caret while the field has text; Up/Down always move the grid. */+export const isGalleryPickerNavKeyForField = (key: GalleryPickerNavKey, fieldValue: string): boolean =>+ key === 'ArrowUp' || key === 'ArrowDown' || fieldValue === '';++const NAV_KEYS: ReadonlySet<string> = new Set<GalleryPickerNavKey>([+ 'ArrowDown',+ 'ArrowLeft',+ 'ArrowRight',+ 'ArrowUp',+ 'End',+ 'Home',+]);++export const isGalleryPickerNavKey = (key: string): key is GalleryPickerNavKey => NAV_KEYS.has(key);++/**+ * Keyboard movement over a row-major grid. Left/right walk reading order+ * across row ends; up/down stay in the column and hold still when no tile+ * sits there (a ragged last row). No active tile resolves to an edge.+ */+export const getGalleryPickerNeighborIndex = (+ index: number,+ count: number,+ columnCount: number,+ key: GalleryPickerNavKey+): number => {+ if (count <= 0) {+ return -1;+ }++ if (index < 0 || index >= count) {+ return key === 'End' ? count - 1 : 0;+ }++ switch (key) {+ case 'Home':+ return 0;+ case 'End':+ return count - 1;+ case 'ArrowLeft':+ return Math.max(0, index - 1);+ case 'ArrowRight':+ return Math.min(count - 1, index + 1);+ case 'ArrowUp':+ return index - columnCount >= 0 ? index - columnCount : index;+ case 'ArrowDown':+ return index + columnCount < count ? index + columnCount : index;+ }+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.tsnew file mode 100644index 0000000000..656fd710ec--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts@@ -0,0 +1,71 @@+import type { GallerySettings } from '@features/gallery/core/settings';+import type { GalleryView } from '@features/gallery/core/types';++import { getSelectedGalleryItemFromValues } from '@features/gallery/core/selection';+import { getGallerySettings } from '@features/gallery/core/settings';+import {+ getGalleryProjectBoardId,+ getGalleryRawSelectedBoardId,+ getGalleryView,+} from '@features/gallery/ui/galleryStateView';+import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';+import { useGalleryData } from '@features/gallery/ui/useGalleryData';+import { useCallback, useDeferredValue, useMemo, useState } from 'react';++export type GalleryPickerPane = 'boards' | 'items';++const NO_RECENT_IMAGES: never[] = [];++export interface GalleryPickerScope {+ boardId: string | null;+ galleryView: GalleryView;+ pane: GalleryPickerPane;+ searchTerm: string;+}++/**+ * The picker's local view of the gallery: seeded from the Gallery widget's+ * values when the picker mounts (the popover unmounts on close, so mounting is+ * opening) and never written back. The search field serves whichever pane is+ * showing, so a pane switch clears it.+ */+export const useGalleryPickerScope = () => {+ const { galleryValues } = useGalleryUi();+ const [scope, setScope] = useState<GalleryPickerScope>(() => ({+ boardId: getGalleryRawSelectedBoardId(galleryValues),+ galleryView: getGalleryView(galleryValues),+ pane: 'items',+ searchTerm: '',+ }));+ const deferredSearchTerm = useDeferredValue(scope.searchTerm);+ const settings = useMemo<GallerySettings>(+ () => ({ ...getGallerySettings(galleryValues), paginationMode: 'infinite', starredFirst: true }),+ [galleryValues]+ );+ const data = useGalleryData({+ galleryView: scope.galleryView,+ page: 0,+ projectBoardId: getGalleryProjectBoardId(galleryValues),+ // No recents overlay: `items` must stay null until the first page lands,+ // so the loading, seeding and stale states have one unambiguous signal.+ recentImages: NO_RECENT_IMAGES,+ searchTerm: scope.pane === 'items' ? deferredSearchTerm : '',+ selectedBoardId: scope.boardId,+ semanticQuery: null,+ settings,+ });+ const gallerySelectedItem = useMemo(() => getSelectedGalleryItemFromValues(galleryValues), [galleryValues]);++ const setSearchTerm = useCallback((searchTerm: string) => setScope((current) => ({ ...current, searchTerm })), []);+ const setView = useCallback((galleryView: GalleryView) => setScope((current) => ({ ...current, galleryView })), []);+ const selectBoard = useCallback(+ (boardId: string) => setScope((current) => ({ ...current, boardId, pane: 'items', searchTerm: '' })),+ []+ );+ const togglePane = useCallback(+ () => setScope((current) => ({ ...current, pane: current.pane === 'items' ? 'boards' : 'items', searchTerm: '' })),+ []+ );++ return { data, gallerySelectedItem, scope, selectBoard, setSearchTerm, setView, settings, togglePane };+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 7647f5e3e5..ffd48e25cf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -386,6 +386,18 @@ describe('focused gallery upload action', () => {expect(mocks.notificationsAdd).not.toHaveBeenCalled();});+ it('trusts a board id the loaded list does not name', async () => {+ mocks.uploadGalleryImage.mockResolvedValue(imageUpload('photo.png', '2026-07-30T12:00:04.000Z', 'board-9'));++ selectedBoardId = 'board-9';+ await renderProbe();+ await act(async () => {+ await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);+ });++ expect(mocks.uploadGalleryImage).toHaveBeenCalledExactlyOnceWith(expect.any(File), 'board-9', expect.anything());+ });+it('rejects unsupported files without a request and resolves empty', async () => {await act(async () => {await expect(diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.tsindex 1814d2414d..3110a62d3c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts@@ -29,11 +29,13 @@ const toErrorMessage = (error: unknown): string => (error instanceof Error ? errexport const useGalleryUploadAction = ({boards,getCurrentGalleryLocation,- selectedBoardId,+ selectedBoardId: selectedBoardIdOrGetter,}: {boards: GalleryBoard[];- getCurrentGalleryLocation: () => { galleryView: GalleryView; selectedBoardId: string };- selectedBoardId: string;+ /** Where the gallery is showing on completion; the newest upload visible there gets selected. Omit to leave the selection alone. */+ 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 queryClient = useQueryClient();@@ -42,6 +44,8 @@ export const useGalleryUploadAction = ({return useCallback(async (files) => {const owner = captureAccountScope();+ const selectedBoardId =+ typeof selectedBoardIdOrGetter === 'function' ? selectedBoardIdOrGetter() : selectedBoardIdOrGetter;if (isDateBoardId(selectedBoardId)) {notifications.reportError({@@ -78,7 +82,9 @@ export const useGalleryUploadAction = ({notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });try {- const targetBoardId = selectedBoard?.kind === 'board' ? selectedBoardId : 'none';+ // Only a board known to be virtual is demoted; an id the (possibly+ // narrower or still-loading) list does not name is trusted as given.+ const targetBoardId = selectedBoard && selectedBoard.kind !== 'board' ? 'none' : selectedBoardId;const imageUploads = accepted.filter((upload) => upload.kind === 'image');const videoUploads = accepted.filter((upload) => upload.kind === 'video');const imageResultsPromise = Promise.allSettled(@@ -128,14 +134,16 @@ export const useGalleryUploadAction = ({return [];}- const currentGalleryLocation = getCurrentGalleryLocation();- const visibleUploads = uploadedItems.filter(- (item) =>- item.boardId === currentGalleryLocation.selectedBoardId &&- (currentGalleryLocation.galleryView === 'images'- ? item.category === 'general'- : item.category === 'control' || item.category === 'mask' || item.category === 'user')- );+ const currentGalleryLocation = getCurrentGalleryLocation?.();+ const visibleUploads = currentGalleryLocation+ ? uploadedItems.filter(+ (item) =>+ item.boardId === currentGalleryLocation.selectedBoardId &&+ (currentGalleryLocation.galleryView === 'images'+ ? item.category === 'general'+ : item.category === 'control' || item.category === 'mask' || item.category === 'user')+ )+ : [];const newestVisibleUpload = visibleUploads.reduce<GalleryItem | undefined>((newest, item) =>newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,@@ -173,6 +181,6 @@ export const useGalleryUploadAction = ({return [];}},- [boards, gallery, getCurrentGalleryLocation, notifications, queryClient, selectedBoardId, t]+ [boards, gallery, getCurrentGalleryLocation, notifications, queryClient, selectedBoardIdOrGetter, t]);};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadInput.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadInput.tsindex aff6b59b45..ee2a0e8004 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadInput.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadInput.ts@@ -1,10 +1,24 @@+import type { GalleryItemKind } from '@features/gallery/core/items';+import { useCallback, useRef, type ChangeEvent } from 'react';-export const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp,video/mp4,.png,.jpg,.jpeg,.webp,.mp4';+const UPLOAD_ACCEPT_BY_KIND: Record<GalleryItemKind, string> = {+ image: 'image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp',+ video: 'video/mp4,.mp4',+};++/** The file input `accept` list for the given kinds. */+export const getGalleryUploadAccept = (kinds: readonly GalleryItemKind[]): string =>+ kinds.map((kind) => UPLOAD_ACCEPT_BY_KIND[kind]).join(',');++export const ACCEPTED_UPLOAD_EXTENSIONS = getGalleryUploadAccept(['image', 'video']);export const UPLOAD_INPUT_STYLE = { display: 'none' } as const;/** The hidden-input picker every gallery upload trigger shares: change extracts files, resets the input (so re-picking the same file fires), and forwards. */-export const useGalleryUploadInput = (onUploadFiles: (files: File[]) => Promise<unknown> | void) => {+export const useGalleryUploadInput = (+ onUploadFiles: (files: File[]) => Promise<unknown> | void,+ { accept = ACCEPTED_UPLOAD_EXTENSIONS, multiple = true }: { accept?: string; multiple?: boolean } = {}+) => {const inputRef = useRef<HTMLInputElement | null>(null);const onChange = useCallback(@@ -24,8 +38,8 @@ export const useGalleryUploadInput = (onUploadFiles: (files: File[]) => Promise<return {inputProps: {- accept: ACCEPTED_UPLOAD_EXTENSIONS,- multiple: true as const,+ accept,+ multiple,onChange,ref: inputRef,style: UPLOAD_INPUT_STYLE,diff --git a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsxindex bb8dc45dd2..9ebd081c20 100644--- a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx@@ -8,6 +8,8 @@ const DROP_ZONE_TRANSITION ='background var(--wb-motion-duration-fast) ease, border-color var(--wb-motion-duration-fast) ease, opacity var(--wb-motion-duration-fast) ease, box-shadow var(--wb-motion-duration-fast) ease';export interface DropZoneProps extends BoxProps {+ /** Native `disabled`, for zones rendered `as="button"`. */+ disabled?: boolean;/** The zone cannot accept input right now; the hover preview stands down. */isDisabled?: boolean;/** A compatible drag is hovering the zone. */