Skip to content

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

feat(gallery): rebuild the gallery widget

joshistoast6d50049c3fc8
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c990f0b5d8..b9430df38d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2194,16 +2194,16 @@
"assetCount_one": "{{count}} asset",
"assetCount_other": "{{count}} assets",
"boardActionsForBoard": "Board actions for {{name}}",
+ "boardArchived": "Archived board \"{{name}}\"",
"boardArchivePreparing_one": "Preparing an image archive of \"{{name}}\". {{count}} video will be omitted.",
"boardArchivePreparing_other": "Preparing an image archive of \"{{name}}\". {{count}} videos will be omitted.",
- "boardArchived": "Archived board \"{{name}}\"",
+ "boardCountsBreakdown": "{{media}} media, {{assets}} assets",
"boardCreated": "Created board \"{{name}}\"",
"boardGroups": {
"boards": "Boards",
"byDate": "By Date"
},
"boardItemCounts": "{{images}} · {{videos}} · {{assets}}",
- "boardMediaCountBreakdown": "{{images}} · {{videos}}",
"boardName": "Board name",
"boardRenamed": "Renamed board to \"{{name}}\"",
"boardUnarchived": "Unarchived board \"{{name}}\"",
@@ -2217,6 +2217,7 @@
"selectAllOnPage": "Select all gallery images on page",
"toggleStarImage": "Toggle gallery image star"
},
+ "createBoard": "Create board",
"createBoardNamed": "Create board \"{{name}}\"",
"dateFilterDay": "{{date}}",
"dateFilterFrom": "From {{date}}",
@@ -2232,20 +2233,30 @@
"deleteBoardPartialTitle": "Deleted board \"{{name}}\" with partial media cleanup",
"deleteBoardQuestion": "Delete board \"{{name}}\"?",
"deleteBoardSuccessTitle": "Deleted board \"{{name}}\"",
+ "deleteConfirmLabel": "Delete",
+ "deleteImagesConfirmBody_one": "This permanently deletes the image from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.",
+ "deleteImagesConfirmBody_other": "This permanently deletes these images from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.",
+ "deleteImagesConfirmTitle_one": "Delete image?",
+ "deleteImagesConfirmTitle_other": "Delete {{count}} images?",
+ "deleteItemsConfirmBody_one": "This permanently deletes the item from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.",
+ "deleteItemsConfirmBody_other": "This permanently deletes these items from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.",
+ "deleteItemsConfirmTitle_one": "Delete item?",
+ "deleteItemsConfirmTitle_other": "Delete {{count}} items?",
+ "deleteSelection": "Delete selection",
"downloadBoard": "Download Board",
"downloadBoardWithOmission_one": "Download Board ({{count}} video omitted)",
"downloadBoardWithOmission_other": "Download Board ({{count}} videos omitted)",
"downloadReady": "Download ready",
+ "downloadSelection": "Download selection",
"dropMediaToUploadToBoard": "Drop images or videos to upload to {{name}}",
"generationProgress": "Generation progress",
"generationProgressPercent": "Generation {{percentage}}%",
"hideArchivedBoards": "Hide archived boards",
"hideDateBoards": "Hide date boards",
- "imageDensity": "Image density",
"imageCount_one": "{{count}} image",
"imageCount_other": "{{count}} images",
+ "imageSize": "Image size",
"imageSort": "Image Sort",
- "itemsAriaLabel": "Gallery items",
"infinite": "Infinite",
"itemActions": {
"delete": {
@@ -2281,8 +2292,10 @@
"success_other": "Unstarred {{count}} items."
}
},
+ "itemsAriaLabel": "Gallery items",
"loadingBackendGallery": "Loading backend gallery...",
"loadingBoard": "Loading board...",
+ "moveSelectionToBoard": "Move selection to board",
"newest": "Newest",
"noBoardsMatchSearch": "No boards match this search.",
"noImagesMatch": "No items match this board, tab, or search.",
@@ -2291,28 +2304,45 @@
"preparingDownload": "Preparing download",
"projectBoardCreated": "Created project board \"{{name}}\"",
"renameBoard": "Rename board",
+ "resizeBoardPanel": "Resize board panel",
+ "searchHelpDate": "A single day.",
+ "searchHelpFrom": "On or after this day.",
+ "searchHelpIntro": "Combine plain text with date tokens. Values accept YYYY-MM-DD, today, yesterday, or relative values such as 7d, 2w, and 1m.",
+ "searchHelpRelative": "Relative: days (d), weeks (w), or months (m) ago.",
+ "searchHelpTitle": "Search syntax",
+ "searchHelpTo": "On or before this day.",
"searchImagesAriaLabel": "Search gallery items",
"searchImagesPlaceholder": "Search items",
"searchOrCreateBoards": "Search or create boards",
+ "selectedBoardFallback": "selected board",
"selectImageForPreview": "Select {{name}} for preview",
+ "selectionActions": "Selection actions",
+ "selectionCount_one": "{{count}} selected",
+ "selectionCount_other": "{{count}} selected",
"selectVideoForPreview": "Select video {{name}}, duration {{duration}}, for preview",
- "selectedBoardFallback": "selected board",
"settings": "Gallery settings",
- "settingsGridDensity": "Grid Density",
+ "settingsGridSize": "Grid Size",
"settingsThumbnails": "Thumbnails",
"showArchivedBoards": "Show archived boards",
"showDateBoards": "Show date boards",
"showPendingItems": "Show pending items",
"showStarredImagesFirst": "Show starred images first",
+ "sortBoards": "Sort boards",
"sortBoardsAscending": "Sort boards ascending",
+ "sortBoardsBy": "Sort by",
"sortBoardsDescending": "Sort boards descending",
"starImage": "Star {{name}}",
+ "starSelection": "Star selection",
+ "statusChip_one": "Gallery: {{count}} item",
+ "statusChip_other": "Gallery: {{count}} items",
"thumbnailFitAspect": "Aspect",
"thumbnailFitSquare": "Square",
+ "toggleBoardsNamed": "Toggle boards, currently {{name}}",
"unarchiveBoard": "Unarchive Board",
"uncategorized": "Uncategorized",
"unknownBoard": "Unknown board",
"unstarImage": "Unstar {{name}}",
+ "unstarSelection": "Unstar selection",
"uploadDateBoardUnavailable": "Uploads are unavailable for date boards.",
"uploadFailed": "No files uploaded. {{failed}} failed.",
"uploadMediaToBoard": "Upload images or videos to {{name}}",
@@ -2321,13 +2351,11 @@
"uploadSuccessTitle_one": "Uploaded {{count}} file",
"uploadSuccessTitle_other": "Uploaded {{count}} files",
"uploadSummary": "{{images}} and {{videos}} uploaded to {{board}}. {{failed}} failed.",
- "uploadUnsupported": "No supported media files to upload (PNG, JPEG, WebP, or MP4).",
"uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards",
+ "uploadUnsupported": "No supported media files to upload (PNG, JPEG, WebP, or MP4).",
"videoCount_one": "{{count}} video",
"videoCount_other": "{{count}} videos",
- "windowLimit": "Showing the first {{count}} items. Narrow the search or switch to Pages to reach the rest.",
- "statusChip_one": "Gallery: {{count}} item",
- "statusChip_other": "Gallery: {{count}} items"
+ "windowLimit": "Showing the first {{count}} items. Narrow the search or switch to Pages to reach the rest."
},
"serverStatus": {
"connected": "Connected to Server",
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index a030d43c1e..4d76802ff4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
@@ -10,6 +10,7 @@ export type {
GalleryView,
GeneratedImageContract,
} from './core/types';
+export { getGalleryBoardLabel, type GalleryBoardTranslate } from './core/boardLabels';
export { normalizeGalleryImage } from './core/image';
export {
assertNeverGalleryItem,
@@ -19,6 +20,7 @@ export {
isGalleryImageItem,
legacyGeneratedImageToGalleryItem,
parseGalleryItemKey,
+ shouldStarSelection,
toGalleryItemKey,
toGalleryItemRef,
type GalleryImageItem,
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
new file mode 100644
index 0000000000..cb78cb2910
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import type { GalleryBoard } from './types';
+
+import { getGalleryBoardLabel } from './boardLabels';
+
+const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
+ archived: false,
+ assetCount: 3,
+ id: 'dogs',
+ imageCount: 50,
+ kind: 'board',
+ name: 'dogs',
+ videoCount: 4,
+ ...overrides,
+});
+
+const t = (key: string) => (key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key);
+
+describe('getGalleryBoardLabel', () => {
+ it('uses the stored name for real boards', () => {
+ expect(getGalleryBoardLabel(createBoard(), t)).toBe('dogs');
+ });
+
+ it('translates the synthesized uncategorized board instead of trusting its name', () => {
+ expect(getGalleryBoardLabel(createBoard({ kind: 'uncategorized', name: '' }), t)).toBe('Uncategorized');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts
new file mode 100644
index 0000000000..8ba9b97735
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts
@@ -0,0 +1,7 @@
+import type { GalleryBoard } from './types';
+
+export type GalleryBoardTranslate = (key: string) => string;
+
+/** Resolves the localized display label for synthesized and stored boards. */
+export const getGalleryBoardLabel = (board: GalleryBoard, t: GalleryBoardTranslate): string =>
+ board.kind === 'uncategorized' ? t('widgets.gallery.uncategorized') : board.name;
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts
index d0ac80ae13..ba9d1e865a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts
@@ -9,11 +9,26 @@ import {
isGalleryImageItem,
legacyGeneratedImageToGalleryItem,
parseGalleryItemKey,
+ shouldStarSelection,
toGalleryItemKey,
toGalleryItemRef,
type GalleryImageItem,
} from './items';
+const galleryItem = (name: string, starred: boolean): GalleryImageItem => ({
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-07-30T12:00:00.000Z',
+ fullUrl: `/images/${name}/full`,
+ height: 512,
+ isIntermediate: false,
+ kind: 'image',
+ name,
+ starred,
+ thumbnailUrl: `/images/${name}/thumbnail`,
+ width: 768,
+});
+
const generatedImage: GeneratedImageContract = {
height: 512,
imageName: 'legacy.png',
@@ -57,6 +72,43 @@ describe('gallery item keys', () => {
});
});
+describe('selection starring policy', () => {
+ const starred = galleryItem('starred.png', true);
+ const unstarred = galleryItem('unstarred.png', false);
+
+ it('does not star an empty selection', () => {
+ expect(shouldStarSelection([starred], [])).toBe(false);
+ });
+
+ it('unstars only when every selected item is loaded and starred', () => {
+ expect(shouldStarSelection([starred], [{ kind: 'image', name: starred.name }])).toBe(false);
+ });
+
+ it('stars when any selected item is loaded and unstarred', () => {
+ expect(
+ shouldStarSelection(
+ [starred, unstarred],
+ [
+ { kind: 'image', name: starred.name },
+ { kind: 'image', name: unstarred.name },
+ ]
+ )
+ ).toBe(true);
+ });
+
+ it('stars when any selected item has not been loaded', () => {
+ expect(
+ shouldStarSelection(
+ [starred],
+ [
+ { kind: 'image', name: starred.name },
+ { kind: 'video', name: 'not-loaded.mp4' },
+ ]
+ )
+ ).toBe(true);
+ });
+});
+
describe('gallery item compatibility', () => {
it('normalizes missing legacy gallery context when adapting a generated image', () => {
expect(legacyGeneratedImageToGalleryItem(generatedImage)).toEqual({
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
index 2b94ed0383..8cc0430747 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
@@ -51,6 +51,15 @@ export interface GalleryItemMutationResult {
export const toGalleryItemKey = ({ kind, name }: GalleryItemRef): GalleryItemKey => `${kind}:${name}`;
+export const shouldStarSelection = (items: readonly GalleryItem[], refs: readonly GalleryItemRef[]): boolean => {
+ if (refs.length === 0) {
+ return false;
+ }
+
+ const loadedItemsByKey = new Map(items.map((item) => [toGalleryItemKey(item), item]));
+ return refs.some((ref) => !loadedItemsByKey.get(toGalleryItemKey(ref))?.starred);
+};
+
export const parseGalleryItemKey = (key: string): GalleryItemRef => {
const separatorIndex = key.indexOf(':');
const kind = key.slice(0, separatorIndex);
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
index 8207f8bf02..05f807579d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
@@ -4,6 +4,18 @@ export type GalleryThumbnailFit = 'square' | 'aspect';
export type GalleryPaginationMode = 'infinite' | 'paginated';
+/** The collapsible groups in the board panel, in render order. */
+export const GALLERY_BOARD_SECTION_IDS = ['boards', 'dates', 'archived'] as const;
+
+export type GalleryBoardSectionId = (typeof GALLERY_BOARD_SECTION_IDS)[number];
+
+/** Height in the stacked layout, width in the wide one — stored separately. */
+export const GALLERY_BOARD_PANEL_MIN_HEIGHT_PX = 120;
+export const GALLERY_BOARD_PANEL_MAX_HEIGHT_PX = 600;
+export const GALLERY_MIN_GRID_HEIGHT_PX = 128;
+export const GALLERY_BOARD_PANEL_MIN_WIDTH_PX = 180;
+export const GALLERY_BOARD_PANEL_MAX_WIDTH_PX = 420;
+
/**
* User-tunable gallery settings. Persisted as plain entries in the gallery
* widget's `values` record so they survive workbench autosave/hydration.
@@ -11,6 +23,11 @@ export type GalleryPaginationMode = 'infinite' | 'paginated';
export interface GallerySettings {
boardOrderBy: GalleryBoardOrderBy;
boardOrderDir: GalleryOrderDir;
+ /** Board panel disclosure controlled by the region-independent widget header. */
+ boardPanelCollapsed: boolean;
+ boardPanelHeightPx: number;
+ boardPanelWidthPx: number;
+ collapsedBoardSections: GalleryBoardSectionId[];
imageDensityPercent: number;
imageOrderDir: GalleryOrderDir;
paginationMode: GalleryPaginationMode;
@@ -25,6 +42,10 @@ export interface GallerySettings {
export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {
boardOrderBy: 'created_at',
boardOrderDir: 'DESC',
+ boardPanelCollapsed: false,
+ boardPanelHeightPx: 280,
+ boardPanelWidthPx: 240,
+ collapsedBoardSections: [],
imageDensityPercent: 50,
imageOrderDir: 'DESC',
paginationMode: 'infinite',
@@ -41,9 +62,41 @@ const isOrderDir = (value: unknown): value is GalleryOrderDir => value === 'ASC'
const isBoardOrderBy = (value: unknown): value is GalleryBoardOrderBy =>
value === 'created_at' || value === 'board_name';
+const isBoardSectionId = (value: unknown): value is GalleryBoardSectionId =>
+ GALLERY_BOARD_SECTION_IDS.includes(value as GalleryBoardSectionId);
+
+const getBoundedSize = (
+ value: unknown,
+ { fallback, max, min }: { fallback: number; max: number; min: number }
+): number =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
+
+/** Filtered to known ids: a stale one would close a section with no way back. */
+const getCollapsedBoardSections = (value: unknown): GalleryBoardSectionId[] =>
+ Array.isArray(value)
+ ? GALLERY_BOARD_SECTION_IDS.filter((sectionId) =>
+ value.some((entry) => isBoardSectionId(entry) && entry === sectionId)
+ )
+ : DEFAULT_GALLERY_SETTINGS.collapsedBoardSections;
+
export const getGallerySettings = (values: Record<string, unknown>): GallerySettings => ({
boardOrderBy: isBoardOrderBy(values.boardOrderBy) ? values.boardOrderBy : DEFAULT_GALLERY_SETTINGS.boardOrderBy,
boardOrderDir: isOrderDir(values.boardOrderDir) ? values.boardOrderDir : DEFAULT_GALLERY_SETTINGS.boardOrderDir,
+ boardPanelCollapsed:
+ typeof values.boardPanelCollapsed === 'boolean'
+ ? values.boardPanelCollapsed
+ : DEFAULT_GALLERY_SETTINGS.boardPanelCollapsed,
+ boardPanelHeightPx: getBoundedSize(values.boardPanelHeightPx, {
+ fallback: DEFAULT_GALLERY_SETTINGS.boardPanelHeightPx,
+ max: GALLERY_BOARD_PANEL_MAX_HEIGHT_PX,
+ min: GALLERY_BOARD_PANEL_MIN_HEIGHT_PX,
+ }),
+ boardPanelWidthPx: getBoundedSize(values.boardPanelWidthPx, {
+ fallback: DEFAULT_GALLERY_SETTINGS.boardPanelWidthPx,
+ max: GALLERY_BOARD_PANEL_MAX_WIDTH_PX,
+ min: GALLERY_BOARD_PANEL_MIN_WIDTH_PX,
+ }),
+ collapsedBoardSections: getCollapsedBoardSections(values.collapsedBoardSections),
imageDensityPercent:
typeof values.imageDensityPercent === 'number' && Number.isFinite(values.imageDensityPercent)
? Math.min(100, Math.max(0, values.imageDensityPercent))
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 72d0de1e65..829c43f73a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -378,7 +378,9 @@ export const listGalleryBoards = async ({
id: 'none',
imageCount: uncategorizedImageCount,
kind: 'uncategorized',
- name: 'Uncategorized',
+ // Synthesized, not stored: `kind` is the durable fact and the UI resolves
+ // the label from it, so no untranslatable name crosses the transport.
+ name: '',
videoCount: uncategorizedVideoCount,
},
...boards.filter((board) => includeArchived || !board.archived).map(mapBoard),
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
index a49d19ed3c..ca99414242 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -97,7 +97,7 @@ describe('Gallery item query read model', () => {
it('coalesces board readers through one query key and includes requested virtual boards', async () => {
const queryClient = createQueryClient();
- const board = { id: 'none', kind: 'uncategorized', name: 'Uncategorized' };
+ const board = { id: 'none', kind: 'uncategorized', name: '' };
const dateBoard = { id: 'by_date:2026-07-18', kind: 'date', name: 'July 18' };
const options = galleryBoardsOptions({ includeDateBoards: true, orderDir: 'DESC' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx
new file mode 100644
index 0000000000..0ee21b84ab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx
@@ -0,0 +1,58 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { Flex, Icon, Image } from '@chakra-ui/react';
+import { CalendarIcon, ImageIcon, PlayIcon, type LucideIcon } from 'lucide-react';
+
+/** Square swatch shown at the start of every board row and in the stacked header. */
+export const BoardCoverIcon = ({ icon }: { icon: LucideIcon }) => (
+ <Flex
+ align="center"
+ bg="bg.emphasized"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="5"
+ color="fg.subtle"
+ flexShrink={0}
+ justify="center"
+ rounded="sm"
+ >
+ <Icon as={icon} boxSize="3" />
+ </Flex>
+);
+
+export const BoardCover = ({ board }: { board: GalleryBoard }) => {
+ if (board.coverThumbnailUrl) {
+ return (
+ <Flex boxSize="5" flexShrink={0} position="relative">
+ <Image
+ alt=""
+ bg="bg.emphasized"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="5"
+ objectFit="cover"
+ rounded="sm"
+ src={board.coverThumbnailUrl}
+ />
+ {board.coverVideoName ? (
+ <Flex
+ align="center"
+ aria-hidden="true"
+ bg="blackAlpha.700"
+ bottom="0"
+ boxSize="2.5"
+ color="white"
+ justify="center"
+ position="absolute"
+ right="0"
+ rounded="full"
+ >
+ <Icon as={PlayIcon} boxSize="1.5" fill="currentColor" />
+ </Flex>
+ ) : null}
+ </Flex>
+ );
+ }
+
+ return <BoardCoverIcon icon={board.kind === 'date' ? CalendarIcon : ImageIcon} />;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.browser.test.tsx
new file mode 100644
index 0000000000..a5b1ce40cb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.browser.test.tsx
@@ -0,0 +1,144 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GalleryBoardDragMonitor } from './GalleryBoardDragMonitor';
+import { getGalleryBoardDropData, getGalleryItemDragData } from './galleryDnd';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+const dnd = vi.hoisted(() => ({ monitor: null as null | Record<string, (event: never) => void> }));
+
+vi.mock('@dnd-kit/core', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useDndMonitor: (monitor: Record<string, (event: never) => void>) => {
+ dnd.monitor = monitor;
+ },
+}));
+
+const updateSettings = vi.fn();
+const moveItemsToBoard = vi.fn(async () => {});
+const draggedRef = { kind: 'image' as const, name: 'dragged.png' };
+const draggedItem = {
+ boardId: 'source-board',
+ category: 'general' as const,
+ createdAt: '2026-07-30T12:00:00.000Z',
+ fullUrl: '/images/dragged.png/full',
+ height: 64,
+ isIntermediate: false,
+ kind: 'image' as const,
+ name: 'dragged.png',
+ starred: false,
+ thumbnailUrl: '/images/dragged.png/thumbnail',
+ width: 64,
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderMonitor = async (boardPanelCollapsed: boolean) => {
+ const contextValue = {
+ actions: { updateSettings },
+ gallery: {
+ items: [draggedItem],
+ settings: { boardPanelCollapsed },
+ },
+ itemActions: { moveItemsToBoard },
+ } as unknown as GalleryWidgetContextValue;
+
+ await act(() => {
+ root?.render(
+ <GalleryWidgetContext value={contextValue}>
+ <GalleryBoardDragMonitor />
+ </GalleryWidgetContext>
+ );
+ });
+};
+
+const dragStart = (data: unknown) =>
+ act(() => dnd.monitor?.onDragStart?.({ active: { data: { current: data } } } as never));
+
+const dragEnd = (activeData: unknown, overData?: unknown) =>
+ act(() =>
+ dnd.monitor?.onDragEnd?.({
+ active: { data: { current: activeData } },
+ over: overData ? { data: { current: overData } } : null,
+ } as never)
+ );
+
+const dragCancel = () => act(() => dnd.monitor?.onDragCancel?.({} as never));
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ dnd.monitor = null;
+ vi.clearAllMocks();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GalleryBoardDragMonitor', () => {
+ it('temporarily expands a collapsed panel, forwards the drop, and restores collapse', async () => {
+ await renderMonitor(true);
+ const dragData = getGalleryItemDragData([draggedRef]);
+
+ dragStart(dragData);
+ expect(updateSettings).toHaveBeenNthCalledWith(1, { boardPanelCollapsed: false });
+
+ dragEnd(dragData, getGalleryBoardDropData('target-board', 'board'));
+
+ expect(moveItemsToBoard).toHaveBeenCalledExactlyOnceWith([draggedRef], 'target-board');
+ expect(updateSettings).toHaveBeenNthCalledWith(2, { boardPanelCollapsed: true });
+ });
+
+ it('leaves a panel that was already expanded open', async () => {
+ await renderMonitor(false);
+ const dragData = getGalleryItemDragData([draggedRef]);
+
+ dragStart(dragData);
+ dragEnd(dragData, getGalleryBoardDropData('target-board', 'board'));
+
+ expect(moveItemsToBoard).toHaveBeenCalledOnce();
+ expect(updateSettings).not.toHaveBeenCalled();
+ });
+
+ it('ignores non-gallery drags', async () => {
+ await renderMonitor(true);
+
+ dragStart({ kind: 'workflow-node' });
+ dragEnd({ kind: 'workflow-node' }, getGalleryBoardDropData('target-board', 'board'));
+
+ expect(updateSettings).not.toHaveBeenCalled();
+ expect(moveItemsToBoard).not.toHaveBeenCalled();
+ });
+
+ it('restores collapse after an invalid drop', async () => {
+ await renderMonitor(true);
+ const dragData = getGalleryItemDragData([draggedRef]);
+
+ dragStart(dragData);
+ dragEnd(dragData, getGalleryBoardDropData('target-date', 'date'));
+
+ expect(moveItemsToBoard).not.toHaveBeenCalled();
+ expect(updateSettings).toHaveBeenLastCalledWith({ boardPanelCollapsed: true });
+ });
+
+ it('restores collapse after cancellation', async () => {
+ await renderMonitor(true);
+
+ dragStart(getGalleryItemDragData([draggedRef]));
+ dragCancel();
+
+ expect(updateSettings).toHaveBeenLastCalledWith({ boardPanelCollapsed: true });
+ expect(moveItemsToBoard).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx
new file mode 100644
index 0000000000..655b7a0c22
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx
@@ -0,0 +1,56 @@
+import { useDndMonitor, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';
+import { useCallback, useRef } from 'react';
+
+import { forwardGalleryBoardDrop, isGalleryItemDragData } from './galleryDnd';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+/**
+ * Owns board-drop forwarding and the temporary disclosure needed to make
+ * board targets available when an item drag begins from a collapsed gallery.
+ */
+export const GalleryBoardDragMonitor = () => {
+ const { actions, gallery, itemActions } = useGalleryWidget();
+ const dragOpenedPanelRef = useRef(false);
+
+ const restoreDisclosure = useCallback(() => {
+ if (!dragOpenedPanelRef.current) {
+ return;
+ }
+
+ dragOpenedPanelRef.current = false;
+ actions.updateSettings({ boardPanelCollapsed: true });
+ }, [actions]);
+
+ const handleDragStart = useCallback(
+ (event: DragStartEvent) => {
+ if (!gallery.settings.boardPanelCollapsed || !isGalleryItemDragData(event.active.data.current)) {
+ return;
+ }
+
+ dragOpenedPanelRef.current = true;
+ actions.updateSettings({ boardPanelCollapsed: false });
+ },
+ [actions, gallery.settings.boardPanelCollapsed]
+ );
+
+ const handleDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ forwardGalleryBoardDrop({
+ activeData: event.active.data.current,
+ loadedItems: gallery.items,
+ moveItemsToBoard: (items, boardId) => void itemActions.moveItemsToBoard(items, boardId),
+ overData: event.over?.data.current,
+ });
+ restoreDisclosure();
+ },
+ [gallery.items, itemActions, restoreDisclosure]
+ );
+
+ useDndMonitor({
+ onDragCancel: restoreDisclosure,
+ onDragEnd: handleDragEnd,
+ onDragStart: handleDragStart,
+ });
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx
new file mode 100644
index 0000000000..55c125febc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx
@@ -0,0 +1,158 @@
+import type { GalleryBoardOrderBy, GalleryOrderDir } from '@features/gallery/core/types';
+
+import { HStack, Icon, Input, InputGroup, Menu, Portal } from '@chakra-ui/react';
+import { CloseButton, IconButton, ToggleIconButton } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { ArchiveIcon, ArrowUpDownIcon, CalendarIcon, SearchIcon } from 'lucide-react';
+import { useCallback, useMemo, type ChangeEvent, type KeyboardEvent, type Ref } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useMenuTriggerIds } from './galleryMenuIds';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const SEARCH_START_ELEMENT = <Icon as={SearchIcon} size="xs" />;
+const SORT_MENU_POSITIONING = { placement: 'bottom-end' } as const;
+
+/**
+ * Board search plus the three list controls. All three are icon-only in both
+ * layouts — the wide sidebar has no room for labels, and giving the stacked
+ * layout labelled variants would be exactly the size-conditional behaviour this
+ * redesign exists to remove.
+ */
+export const GalleryBoardFilters = ({
+ ref,
+ searchTerm,
+ onSearchChange,
+ onSubmitSearch,
+}: {
+ /** The panel focuses the field when "+" is pressed with nothing typed. */
+ ref?: Ref<HTMLInputElement>;
+ searchTerm: string;
+ onSearchChange: (searchTerm: string) => void;
+ /** Enter on the field; the panel decides whether that means "create". */
+ onSubmitSearch: () => void;
+}) => {
+ const { t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+ const { boardOrderBy, boardOrderDir, showArchivedBoards, showDateBoards } = gallery.settings;
+ const sortTriggerIds = useMenuTriggerIds();
+
+ const handleSearchChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => onSearchChange(event.currentTarget.value),
+ [onSearchChange]
+ );
+
+ const handleClearSearch = useCallback(() => onSearchChange(''), [onSearchChange]);
+
+ const handleSearchKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ event.stopPropagation();
+
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ onSubmitSearch();
+ }
+ },
+ [onSubmitSearch]
+ );
+
+ const handleToggleDateBoards = useCallback(
+ (showDateBoards: boolean) => actions.updateSettings({ showDateBoards }),
+ [actions]
+ );
+
+ const handleToggleArchivedBoards = useCallback(
+ (showArchivedBoards: boolean) => actions.updateSettings({ showArchivedBoards }),
+ [actions]
+ );
+
+ const handleOrderByChange = useCallback(
+ (event: { value: string }) => actions.updateSettings({ boardOrderBy: event.value as GalleryBoardOrderBy }),
+ [actions]
+ );
+
+ const handleOrderDirChange = useCallback(
+ (event: { value: string }) => actions.updateSettings({ boardOrderDir: event.value as GalleryOrderDir }),
+ [actions]
+ );
+
+ const clearSearchButton = useMemo(
+ () =>
+ searchTerm ? (
+ <CloseButton aria-label={t('common.clearSearch')} me="-2" size="2xs" onClick={handleClearSearch} />
+ ) : null,
+ [searchTerm, handleClearSearch, t]
+ );
+
+ return (
+ <HStack gap="1">
+ <InputGroup endElement={clearSearchButton} flex="1" minW="0" startElement={SEARCH_START_ELEMENT}>
+ <Input
+ ref={ref}
+ aria-label={t('widgets.gallery.searchOrCreateBoards')}
+ placeholder={t('widgets.gallery.searchOrCreateBoards')}
+ size="xs"
+ value={searchTerm}
+ onChange={handleSearchChange}
+ onKeyDown={handleSearchKeyDown}
+ />
+ </InputGroup>
+ <ToggleIconButton
+ checked={showDateBoards}
+ icon={CalendarIcon}
+ size="xs"
+ label={showDateBoards ? t('widgets.gallery.hideDateBoards') : t('widgets.gallery.showDateBoards')}
+ onCheckedChange={handleToggleDateBoards}
+ />
+ <ToggleIconButton
+ checked={showArchivedBoards}
+ icon={ArchiveIcon}
+ size="xs"
+ label={showArchivedBoards ? t('widgets.gallery.hideArchivedBoards') : t('widgets.gallery.showArchivedBoards')}
+ onCheckedChange={handleToggleArchivedBoards}
+ />
+ <Menu.Root ids={sortTriggerIds} positioning={SORT_MENU_POSITIONING}>
+ <Tooltip content={t('widgets.gallery.sortBoards')} ids={sortTriggerIds}>
+ <Menu.Trigger asChild>
+ <IconButton aria-label={t('widgets.gallery.sortBoards')} color="fg.muted" size="xs" variant="ghost">
+ <Icon as={ArrowUpDownIcon} boxSize="3.5" />
+ </IconButton>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="9rem">
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel>{t('widgets.gallery.sortBoardsBy')}</Menu.ItemGroupLabel>
+ <Menu.RadioItemGroup value={boardOrderBy} onValueChange={handleOrderByChange}>
+ <Menu.RadioItem value="created_at">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('common.created')}</Menu.ItemText>
+ </Menu.RadioItem>
+ <Menu.RadioItem value="board_name">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('common.name')}</Menu.ItemText>
+ </Menu.RadioItem>
+ </Menu.RadioItemGroup>
+ </Menu.ItemGroup>
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ <Menu.RadioItemGroup value={boardOrderDir} onValueChange={handleOrderDirChange}>
+ <Menu.RadioItem value="DESC">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('widgets.gallery.sortBoardsDescending')}</Menu.ItemText>
+ </Menu.RadioItem>
+ <Menu.RadioItem value="ASC">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('widgets.gallery.sortBoardsAscending')}</Menu.ItemText>
+ </Menu.RadioItem>
+ </Menu.RadioItemGroup>
+ </Menu.ItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 94ca5db917..be8f5efd1f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -2,15 +2,14 @@
import type { GalleryBoard } from '@features/gallery/core/types';
import { Dialog, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';
-import { Button } from '@platform/ui';
+import { Button } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
import { ArchiveIcon, DownloadIcon, PencilIcon, Trash2Icon, type LucideIcon } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useGalleryWidget } from './GalleryWidgetContext';
-const MENU_CONTENT_PADDING_X = '0';
-
export interface GalleryBoardMenuTarget {
board: GalleryBoard;
x: number;
@@ -140,17 +139,17 @@ export const GalleryBoardMenu = ({
<Portal>
<Menu.Positioner>
{board && (
- <Menu.Content minW="12rem" py="1" px={MENU_CONTENT_PADDING_X}>
+ <MenuContent minW="12rem">
<BoardDownloadMenuItem board={board} />
{isManagedBoard && (
<>
<BoardRenameMenuItem board={board} onRename={setRenameTarget} onRenameValue={setRenameValue} />
<BoardArchiveMenuItem archived={board.archived} boardId={board.id} />
- <Menu.Separator borderColor="border.subtle" />
+ <Menu.Separator />
<BoardDeleteMenuItem board={board} onDelete={setDeleteTarget} />
</>
)}
- </Menu.Content>
+ </MenuContent>
)}
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
new file mode 100644
index 0000000000..7ebce54ead
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
@@ -0,0 +1,165 @@
+import type { GalleryItemKey } from '@features/gallery/core/items';
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { Badge, Box, Text } from '@chakra-ui/react';
+import { useDndContext, useDroppable } from '@dnd-kit/core';
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { toGalleryItemKey } from '@features/gallery/core/items';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { MoreVerticalIcon } from 'lucide-react';
+import { useCallback, useMemo, type MouseEvent, type PointerEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { BoardCover } from './GalleryBoardCover';
+import { GalleryBoardRowShell } from './GalleryBoardRowShell';
+import { getGalleryBoardDropData, getGalleryBoardDropId, isGalleryItemDragData } from './galleryDnd';
+import { getBoardCounts } from './galleryStateView';
+
+export const GalleryBoardRow = ({
+ board,
+ isMenuOpen,
+ isProjectBoard,
+ isSelected,
+ loadedItemBoardIds,
+ onOpenMenu,
+ onSelectBoard,
+}: {
+ board: GalleryBoard;
+ /** Its own menu is showing, so the trigger must not fade out from under it. */
+ isMenuOpen?: boolean;
+ isProjectBoard: boolean;
+ isSelected: boolean;
+ loadedItemBoardIds: ReadonlyMap<GalleryItemKey, string>;
+ /** Omitted for date rows, which have no board actions. */
+ onOpenMenu?: (board: GalleryBoard, x: number, y: number) => void;
+ onSelectBoard: (boardId: string) => void;
+}) => {
+ const { t } = useTranslation();
+ const { active } = useDndContext();
+ const dragData = active?.data.current;
+ const boardLabel = getGalleryBoardLabel(board, t);
+
+ const canDropItems =
+ board.kind === 'board' &&
+ isGalleryItemDragData(dragData) &&
+ dragData.items.some((ref) => loadedItemBoardIds.get(toGalleryItemKey(ref)) !== board.id);
+
+ const { isOver, setNodeRef } = useDroppable({
+ data: getGalleryBoardDropData(board.id, board.kind),
+ disabled: !canDropItems,
+ id: getGalleryBoardDropId(board.id),
+ });
+
+ const counts = getBoardCounts(board);
+ const mediaCount = counts.imageCount + counts.videoCount;
+ const countsBreakdown = t('widgets.gallery.boardCountsBreakdown', {
+ assets: counts.assetCount,
+ media: mediaCount,
+ });
+
+ const handleSelect = useCallback(() => onSelectBoard(board.id), [board.id, onSelectBoard]);
+
+ const handleContextMenu = useCallback(
+ (event: MouseEvent) => {
+ if (!onOpenMenu) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenMenu(board, event.clientX, event.clientY);
+ },
+ [board, onOpenMenu]
+ );
+
+ const handleActionsClick = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ if (!onOpenMenu) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const rect = event.currentTarget.getBoundingClientRect();
+
+ onOpenMenu(board, rect.left, rect.bottom);
+ },
+ [board, onOpenMenu]
+ );
+
+ const stopPropagation = useCallback((event: MouseEvent | PointerEvent) => event.stopPropagation(), []);
+
+ const cover = useMemo(() => <BoardCover board={board} />, [board]);
+ const subtitle = useMemo(
+ () =>
+ board.ownerName ? (
+ <Text color={isSelected ? 'inherit' : 'fg.muted'} fontSize="2xs" lineHeight="shorter" minW="0" truncate>
+ {board.ownerName}
+ </Text>
+ ) : null,
+ [board.ownerName, isSelected]
+ );
+ const actions = useMemo(
+ () =>
+ onOpenMenu ? (
+ <IconButton
+ aria-label={t('widgets.gallery.boardActionsForBoard', { name: boardLabel })}
+ className="board-row-actions"
+ flexShrink={0}
+ // Its menu anchors to this button, so it must not fade out beneath it.
+ opacity={isMenuOpen ? 1 : 0}
+ // 24px: the target-size floor, and short enough for the 28px row.
+ size="2xs"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="ghost"
+ onClick={handleActionsClick}
+ onPointerDown={stopPropagation}
+ onPointerUp={stopPropagation}
+ >
+ <MoreVerticalIcon />
+ </IconButton>
+ ) : null,
+ [boardLabel, handleActionsClick, isMenuOpen, onOpenMenu, stopPropagation, t]
+ );
+
+ return (
+ <Box
+ // An outline rather than a border, so the drop affordance never reflows the list.
+ bg={isOver ? 'accent.muted' : undefined}
+ outline={canDropItems ? '1px dashed' : undefined}
+ outlineColor={canDropItems ? 'accent.solid' : undefined}
+ rounded="sm"
+ w="full"
+ >
+ <GalleryBoardRowShell
+ ref={setNodeRef}
+ actions={actions}
+ cover={cover}
+ isSelected={isSelected}
+ label={boardLabel}
+ subtitle={subtitle}
+ onContextMenu={onOpenMenu ? handleContextMenu : undefined}
+ onSelect={handleSelect}
+ >
+ {isProjectBoard ? (
+ <Badge colorPalette={isSelected ? undefined : 'accent'} flexShrink={0} size="xs" variant="subtle">
+ {t('common.project')}
+ </Badge>
+ ) : null}
+ <Tooltip content={countsBreakdown}>
+ <Badge
+ aria-label={countsBreakdown}
+ flexShrink={0}
+ fontVariantNumeric="tabular-nums"
+ size="xs"
+ variant="subtle"
+ >
+ {mediaCount} | {counts.assetCount}
+ </Badge>
+ </Tooltip>
+ </GalleryBoardRowShell>
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx
new file mode 100644
index 0000000000..7c25c22e65
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx
@@ -0,0 +1,82 @@
+import { HStack, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';
+import { Row } from '@platform/ui/Row';
+import { useMemo, type MouseEvent, type ReactNode, type Ref } from 'react';
+
+/** On the container, not the row button: the `⋮` sibling must share the fill. */
+const ROW_CONTAINER_CSS = {
+ '&:hover .board-row-actions, &:focus-within .board-row-actions': { opacity: 1 },
+ '&:hover .board-row-hover, &:focus-within .board-row-hover': { opacity: 1 },
+ _hover: { bg: 'bg.muted' },
+ borderRadius: 'sm',
+ transition: 'background var(--wb-motion-duration-fast) ease',
+} as const;
+
+/** The active row is filled, matching `rowRecipe`'s own `active="accent"` variant. */
+const SELECTED_CONTAINER_CSS: SystemStyleObject = {
+ ...ROW_CONTAINER_CSS,
+ _hover: { bg: 'accent.solid' },
+ bg: 'accent.solid',
+ color: 'accent.contrast',
+} as const;
+
+/** The container owns the fill, so the button contributes only its focus ring. */
+const ROW_BUTTON_CSS = { _hover: { bg: 'transparent' }, bg: 'transparent' } as const;
+
+/**
+ * The one row shape every board-panel entry uses. `actions` is a flex sibling
+ * of the row button, never a child: nested buttons are invalid markup, and an
+ * overlaid one carves the row's touch target into unhittable slivers.
+ */
+export const GalleryBoardRowShell = ({
+ actions,
+ ariaLabel,
+ children,
+ cover,
+ isSelected = false,
+ label,
+ labelWeight,
+ subtitle,
+ ref,
+ onContextMenu,
+ onSelect,
+}: {
+ /** Hover-revealed trailing controls, outside the row button. */
+ actions?: ReactNode;
+ ariaLabel?: string;
+ /** Trailing metadata rendered inside the row button (dates, counts, badges). */
+ children?: ReactNode;
+ cover: ReactNode;
+ isSelected?: boolean;
+ label: string;
+ labelWeight?: string;
+ subtitle?: ReactNode;
+ ref?: Ref<HTMLDivElement>;
+ onContextMenu?: (event: MouseEvent) => void;
+ onSelect: () => void;
+}) => {
+ const containerCss = useMemo(() => (isSelected ? SELECTED_CONTAINER_CSS : ROW_CONTAINER_CSS), [isSelected]);
+
+ return (
+ <HStack ref={ref} css={containerCss} gap="0" pe="1" w="full">
+ <Row active="none" asChild css={ROW_BUTTON_CSS} flex="1" gap="2" minH="7" minW="0" px="1" py="1">
+ <button
+ aria-current={isSelected ? 'true' : undefined}
+ aria-label={ariaLabel}
+ type="button"
+ onClick={onSelect}
+ onContextMenu={onContextMenu}
+ >
+ {cover}
+ <Stack align="stretch" flex="1" gap="0" minW="0" textAlign="start">
+ <Text fontSize="xs" fontWeight={labelWeight ?? (isSelected ? '600' : '500')} minW="0" truncate>
+ {label}
+ </Text>
+ {subtitle}
+ </Stack>
+ {children}
+ </button>
+ </Row>
+ {actions}
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx
new file mode 100644
index 0000000000..45a47418ff
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx
@@ -0,0 +1,72 @@
+import type { GalleryBoardSectionId } from '@features/gallery/core/settings';
+
+import { Collapsible, HStack, Stack, Text } from '@chakra-ui/react';
+import { ChevronRightIcon } from 'lucide-react';
+import { useCallback, type ReactNode } from 'react';
+
+const INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' } as const;
+const TRIGGER_HOVER_STYLES = { color: 'fg' } as const;
+
+/**
+ * One collapsible group in the board panel. The trailing `action` is a sibling
+ * of the disclosure trigger rather than a child, so the "+" button is not a
+ * <button> nested inside another one.
+ */
+export const GalleryBoardSection = ({
+ action,
+ children,
+ isOpen,
+ label,
+ sectionId,
+ onToggle,
+}: {
+ action?: ReactNode;
+ children: ReactNode;
+ isOpen: boolean;
+ label: string;
+ sectionId: GalleryBoardSectionId;
+ onToggle: (sectionId: GalleryBoardSectionId, isOpen: boolean) => void;
+}) => {
+ const handleOpenChange = useCallback(
+ ({ open }: { open: boolean }) => onToggle(sectionId, open),
+ [sectionId, onToggle]
+ );
+
+ return (
+ <Collapsible.Root open={isOpen} onOpenChange={handleOpenChange}>
+ <HStack gap="1" minH="6" pe="1" ps="1">
+ <Collapsible.Trigger
+ alignItems="center"
+ color="fg.muted"
+ display="flex"
+ flex="1"
+ gap="1"
+ minW="0"
+ transition="color var(--wb-motion-duration-fast) ease"
+ _hover={TRIGGER_HOVER_STYLES}
+ >
+ <Collapsible.Indicator _open={INDICATOR_OPEN_STYLES} transition="transform var(--wb-motion-duration-medium)">
+ <ChevronRightIcon size="12" />
+ </Collapsible.Indicator>
+ <Text
+ as="span"
+ fontSize="2xs"
+ fontWeight="600"
+ letterSpacing="wide"
+ lineHeight="1"
+ textTransform="uppercase"
+ truncate
+ >
+ {label}
+ </Text>
+ </Collapsible.Trigger>
+ {action}
+ </HStack>
+ <Collapsible.Content>
+ <Stack gap="0.5" pb="1">
+ {children}
+ </Stack>
+ </Collapsible.Content>
+ </Collapsible.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx
deleted file mode 100644
index 06c6ed8db3..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.browser.test.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { ChakraProvider } from '@chakra-ui/react';
-import { system } from '@theme/system';
-import { act } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { BoardCover, BoardOptionContent } from './GalleryBoardSelect';
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string, values?: Record<string, unknown>) => {
- if (key === 'widgets.gallery.imageCount') {
- return `${String(values?.count)} images`;
- }
- if (key === 'widgets.gallery.videoCount') {
- return `${String(values?.count)} videos`;
- }
- if (key === 'widgets.gallery.boardMediaCountBreakdown') {
- return `${String(values?.images)} · ${String(values?.videos)}`;
- }
-
- return key;
- },
- }),
-}));
-
-const board = {
- archived: false,
- assetCount: 2,
- coverImageName: null,
- coverThumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=',
- coverVideoName: 'clip.mp4',
- id: 'video-only',
- imageCount: 0,
- kind: 'board',
- name: 'Video only',
- videoCount: 5,
-} as const;
-
-let host: HTMLDivElement | null = null;
-let root: Root | null = null;
-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-beforeEach(() => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(async () => {
- await act(() => root?.unmount());
- host?.remove();
- host = null;
- root = null;
-});
-
-describe('board mixed-media presentation', () => {
- it('renders video-only boards with a mixed total, localized breakdown tooltip, and tabular numerals', async () => {
- await act(() =>
- root?.render(
- <ChakraProvider value={system}>
- <BoardOptionContent board={board} isSelected={false} />
- </ChakraProvider>
- )
- );
-
- await vi.waitFor(() => {
- expect(document.body.textContent).toContain('5 | 2');
- });
-
- const countBadge = Array.from(document.querySelectorAll('[aria-label]')).find(
- (element) => element.getAttribute('aria-label') === '0 images · 5 videos'
- );
-
- expect(countBadge).toBeDefined();
- expect(countBadge ? getComputedStyle(countBadge).fontVariantNumeric : '').toContain('tabular-nums');
- expect(countBadge?.getAttribute('data-scope')).toBe('tooltip');
- expect(countBadge?.getAttribute('data-part')).toBe('trigger');
- });
-
- it('overlays a decorative play glyph on static video covers', async () => {
- await act(() =>
- root?.render(
- <ChakraProvider value={system}>
- <BoardCover board={board} />
- </ChakraProvider>
- )
- );
-
- await vi.waitFor(() => {
- expect(document.querySelector('img')?.getAttribute('src')).toContain('data:image/gif');
- });
- expect(document.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
- expect(document.querySelector('video')).toBeNull();
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.ts
deleted file mode 100644
index 836527cae0..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { GalleryItem } from '@features/gallery/contracts';
-
-import { describe, expect, it, vi } from 'vitest';
-
-import { forwardGalleryBoardDrop } from './GalleryBoardSelect';
-import { getGalleryBoardDropData, getGalleryItemDragData } from './galleryDnd';
-
-const createItem = (kind: GalleryItem['kind'], name: string, boardId: string): GalleryItem => {
- const base = {
- boardId,
- category: 'general' as const,
- createdAt: '2026-07-30T00:00:00.000Z',
- fullUrl: `/full/${name}`,
- height: 64,
- isIntermediate: false,
- name,
- starred: false,
- thumbnailUrl: `/thumbnail/${name}`,
- width: 64,
- };
-
- return kind === 'video' ? { ...base, durationSeconds: 8, kind } : { ...base, kind };
-};
-
-describe('forwardGalleryBoardDrop', () => {
- it('forwards the full ordered mixed resolution without stripping video refs', () => {
- const moveItemsToBoard = vi.fn();
- const dragData = getGalleryItemDragData([
- { kind: 'video', name: 'shared' },
- { kind: 'image', name: 'image.png' },
- { kind: 'image', name: 'shared' },
- ]);
- const loadedItems = [
- createItem('image', 'shared', 'board-b'),
- createItem('video', 'shared', 'board-a'),
- createItem('image', 'image.png', 'none'),
- ];
-
- expect(
- forwardGalleryBoardDrop({
- activeData: dragData,
- loadedItems,
- moveItemsToBoard,
- overData: getGalleryBoardDropData('board-b', 'board'),
- })
- ).toBe(true);
- expect(moveItemsToBoard).toHaveBeenCalledOnce();
- expect(moveItemsToBoard).toHaveBeenCalledWith(
- [
- { kind: 'video', name: 'shared' },
- { kind: 'image', name: 'image.png' },
- ],
- 'board-b'
- );
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
deleted file mode 100644
index b1beab526c..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
+++ /dev/null
@@ -1,677 +0,0 @@
-import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/core/items';
-import type { GalleryBoard } from '@features/gallery/core/types';
-
-import {
- Badge,
- Flex,
- HStack,
- Icon,
- Image,
- Input,
- InputGroup,
- Menu,
- Portal,
- ScrollArea,
- Stack,
- Text,
-} from '@chakra-ui/react';
-import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';
-import { toGalleryItemKey } from '@features/gallery/core/items';
-import { Button, CloseButton, IconButton, Tooltip } from '@platform/ui';
-import {
- ArchiveIcon,
- ArrowDownAZIcon,
- ArrowUpAZIcon,
- CalendarIcon,
- ChevronDownIcon,
- ImageIcon,
- MoreVerticalIcon,
- PinIcon,
- PlayIcon,
- PlusIcon,
- type LucideIcon,
- SearchIcon,
- XIcon,
-} from 'lucide-react';
-import {
- useCallback,
- useMemo,
- useRef,
- useState,
- type ChangeEvent,
- type KeyboardEvent,
- type MouseEvent,
- type PointerEvent,
-} from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenu';
-import {
- getGalleryBoardDropData,
- getGalleryBoardDropId,
- isGalleryItemDragData,
- resolveGalleryBoardDrop,
-} from './galleryDnd';
-import { getBoardCounts } from './galleryStateView';
-import { useGalleryWidget } from './GalleryWidgetContext';
-
-export const forwardGalleryBoardDrop = ({
- activeData,
- loadedItems,
- moveItemsToBoard,
- overData,
-}: {
- activeData: unknown;
- loadedItems: readonly GalleryItem[];
- moveItemsToBoard: (items: GalleryItemRef[], boardId: string) => void;
- overData: unknown;
-}): boolean => {
- const resolution = resolveGalleryBoardDrop(activeData, overData, loadedItems);
-
- if (!resolution) {
- return false;
- }
-
- moveItemsToBoard(resolution.items, resolution.boardId);
- return true;
-};
-
-export const GalleryBoardSelect = () => {
- const { t } = useTranslation();
- const { actions, gallery, itemActions, projectName } = useGalleryWidget();
- const { active } = useDndContext();
- const [isOpen, setIsOpen] = useState(false);
- const [boardSearchTerm, setBoardSearchTerm] = useState('');
- const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);
- const boardMenuActiveRef = useRef(false);
- const dragOpenedMenuRef = useRef(false);
- const isGalleryItemDragActive = isGalleryItemDragData(active?.data.current);
- const loadedItemBoardIds = useMemo(
- () => new Map<GalleryItemKey, string>(gallery.items.map((item) => [toGalleryItemKey(item), item.boardId])),
- [gallery.items]
- );
- const trimmedSearchTerm = boardSearchTerm.trim();
- const normalizedSearchTerm = trimmedSearchTerm.toLowerCase();
- const matchesSearch = useCallback(
- (name: string) => !normalizedSearchTerm || name.toLowerCase().includes(normalizedSearchTerm),
- [normalizedSearchTerm]
- );
-
- const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId) ?? null;
- const uncategorizedBoard = gallery.boards.find((board) => board.kind === 'uncategorized') ?? null;
- const projectBoard = gallery.projectBoardId
- ? (gallery.boards.find((board) => board.id === gallery.projectBoardId) ?? null)
- : null;
- const projectRowName = projectBoard?.name ?? projectName;
- const dateBoards = gallery.boards.filter((board) => board.kind === 'date' && matchesSearch(board.name));
- const regularBoards = gallery.boards.filter(
- (board) => board.kind === 'board' && board.id !== gallery.projectBoardId && matchesSearch(board.name)
- );
- const showProjectRow = matchesSearch(projectRowName);
- const showUncategorizedRow = uncategorizedBoard !== null && matchesSearch(uncategorizedBoard.name);
- const hasAnyMatch = showProjectRow || showUncategorizedRow || dateBoards.length > 0 || regularBoards.length > 0;
- const hasExactMatch =
- gallery.boards.some((board) => board.name.toLowerCase() === normalizedSearchTerm) ||
- projectRowName.toLowerCase() === normalizedSearchTerm;
- const canCreateFromSearch = trimmedSearchTerm.length > 0 && !hasExactMatch;
-
- const closeAndReset = useCallback(() => {
- setIsOpen(false);
- setBoardSearchTerm('');
- }, []);
-
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- const dragData = event.active.data.current;
- const dropData = event.over?.data.current;
-
- forwardGalleryBoardDrop({
- activeData: dragData,
- loadedItems: gallery.items,
- moveItemsToBoard: (items, boardId) => void itemActions.moveItemsToBoard(items, boardId),
- overData: dropData,
- });
-
- if (dragOpenedMenuRef.current) {
- dragOpenedMenuRef.current = false;
- closeAndReset();
- }
- },
- [closeAndReset, gallery.items, itemActions]
- );
-
- const handleDragCancel = useCallback(() => {
- if (dragOpenedMenuRef.current) {
- dragOpenedMenuRef.current = false;
- closeAndReset();
- }
- }, [closeAndReset]);
-
- const handleDragStart = useCallback((event: DragStartEvent) => {
- if (!isGalleryItemDragData(event.active.data.current)) {
- return;
- }
-
- dragOpenedMenuRef.current = true;
- setBoardMenuTarget(null);
- setBoardSearchTerm('');
- setIsOpen(true);
- }, []);
-
- useDndMonitor({
- onDragCancel: handleDragCancel,
- onDragEnd: handleDragEnd,
- onDragStart: handleDragStart,
- });
-
- const createBoardFromSearch = useCallback(() => {
- if (!canCreateFromSearch) {
- return;
- }
-
- closeAndReset();
- void actions.createBoard(trimmedSearchTerm);
- }, [actions, canCreateFromSearch, closeAndReset, trimmedSearchTerm]);
-
- const openBoardMenu = useCallback((board: GalleryBoard, x: number, y: number) => {
- setBoardMenuTarget({ board, x, y });
- }, []);
-
- const clearSearch = useCallback(() => {
- setBoardSearchTerm('');
- }, []);
-
- const clearSearchButton = useMemo(
- () =>
- boardSearchTerm ? (
- <CloseButton aria-label={t('common.clearSearch')} size="2xs" onClick={clearSearch} me="-2">
- <XIcon />
- </CloseButton>
- ) : null,
- [boardSearchTerm, clearSearch, t]
- );
-
- const searchStartElement = useMemo(() => <Icon as={SearchIcon} size="xs" />, []);
- const menuPositioning = useMemo(() => ({ placement: 'bottom-start' as const }), []);
-
- const handleOpenChange = useCallback(
- (event: { open: boolean }) => {
- if (event.open) {
- setIsOpen(true);
- return;
- }
-
- if (boardMenuActiveRef.current || isGalleryItemDragActive) {
- return;
- }
-
- closeAndReset();
- },
- [closeAndReset, isGalleryItemDragActive]
- );
-
- const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
- setBoardSearchTerm(event.currentTarget.value);
- }, []);
-
- const handleSearchKeyDown = useCallback(
- (event: KeyboardEvent<HTMLInputElement>) => {
- event.stopPropagation();
-
- if (event.key === 'Enter' && !hasAnyMatch) {
- event.preventDefault();
- createBoardFromSearch();
- }
- },
- [createBoardFromSearch, hasAnyMatch]
- );
-
- const handleSelectProjectBoard = useCallback(() => {
- closeAndReset();
- void actions.selectProjectBoard();
- }, [actions, closeAndReset]);
-
- const handleBoardMenuActiveChange = useCallback((isActive: boolean) => {
- boardMenuActiveRef.current = isActive;
- }, []);
-
- const handleBoardMenuClose = useCallback(() => setBoardMenuTarget(null), []);
-
- return (
- <>
- <Menu.Root open={isOpen} positioning={menuPositioning} onOpenChange={handleOpenChange}>
- <Menu.Trigger asChild>
- <Button minW="0" size="sm" variant="outline" w="full" px="1">
- {selectedBoard ? (
- <BoardOptionContent
- badge={selectedBoard.id === gallery.projectBoardId ? t('common.project') : undefined}
- badgeColor={selectedBoard.id === gallery.projectBoardId ? 'blue' : undefined}
- board={selectedBoard}
- isSelected={false}
- />
- ) : (
- <Text fontSize="xs" me="auto">
- {t('widgets.gallery.loadingBoard')}
- </Text>
- )}
- <Icon as={ChevronDownIcon} boxSize="3" flexShrink={0} />
- </Button>
- </Menu.Trigger>
- <Portal>
- <Menu.Positioner>
- <Menu.Content
- maxH="min(30rem, calc(100vh - 6rem))"
- minW="min(22rem, calc(100vw - 2rem))"
- overflow="hidden"
- p="0"
- >
- <Stack gap="2" p="2">
- <InputGroup startElement={searchStartElement} endElement={clearSearchButton}>
- <Input
- aria-label={t('widgets.gallery.searchOrCreateBoards')}
- placeholder={t('widgets.gallery.searchOrCreateBoards')}
- size="sm"
- value={boardSearchTerm}
- onChange={handleSearchChange}
- onKeyDown={handleSearchKeyDown}
- />
- </InputGroup>
- <BoardListControls />
- </Stack>
- <Menu.Separator borderColor="border.subtle" m="0" />
- <ScrollArea.Root maxH="20rem" size="xs" variant="hover" w="full">
- <ScrollArea.Viewport maxH="inherit" w="full">
- <ScrollArea.Content py="1">
- {showProjectRow &&
- (projectBoard ? (
- <BoardRow
- badge={t('common.project')}
- badgeColor="blue"
- board={projectBoard}
- isSelected={projectBoard.id === gallery.selectedBoardId}
- loadedItemBoardIds={loadedItemBoardIds}
- onOpenMenu={openBoardMenu}
- onSelectBoard={actions.selectBoard}
- onSelectComplete={closeAndReset}
- />
- ) : (
- <Menu.Item value="__project-board__" onClick={handleSelectProjectBoard}>
- <HStack gap="2" minW="0" w="full">
- <BoardCoverIcon icon={PinIcon} />
- <Text flex="1" fontSize="xs" fontWeight="500" minW="0" truncate>
- {projectRowName}
- </Text>
- <Badge colorPalette="blue" flexShrink={0} size="xs" variant="subtle">
- {t('common.project')}
- </Badge>
- </HStack>
- </Menu.Item>
- ))}
- {showUncategorizedRow && uncategorizedBoard && (
- <BoardRow
- board={uncategorizedBoard}
- isSelected={uncategorizedBoard.id === gallery.selectedBoardId}
- loadedItemBoardIds={loadedItemBoardIds}
- onOpenMenu={openBoardMenu}
- onSelectBoard={actions.selectBoard}
- onSelectComplete={closeAndReset}
- />
- )}
- {dateBoards.length > 0 && (
- <>
- <BoardGroupLabel>{t('widgets.gallery.boardGroups.byDate')}</BoardGroupLabel>
- {dateBoards.map((board) => (
- <BoardRow
- key={board.id}
- board={board}
- isSelected={board.id === gallery.selectedBoardId}
- loadedItemBoardIds={loadedItemBoardIds}
- onSelectBoard={actions.selectBoard}
- onSelectComplete={closeAndReset}
- />
- ))}
- </>
- )}
- {(regularBoards.length > 0 || canCreateFromSearch) && (
- <BoardGroupLabel>{t('widgets.gallery.boardGroups.boards')}</BoardGroupLabel>
- )}
- {regularBoards.map((board) => (
- <BoardRow
- key={board.id}
- badge={board.archived ? t('common.archived') : undefined}
- badgeColor="gray"
- board={board}
- isSelected={board.id === gallery.selectedBoardId}
- loadedItemBoardIds={loadedItemBoardIds}
- onOpenMenu={openBoardMenu}
- onSelectBoard={actions.selectBoard}
- onSelectComplete={closeAndReset}
- />
- ))}
- {!hasAnyMatch && !canCreateFromSearch && (
- <Text color="fg.subtle" fontSize="2xs" px="3" py="2">
- {t('widgets.gallery.noBoardsMatchSearch')}
- </Text>
- )}
- {canCreateFromSearch && (
- <Menu.Item value="__create-board__" onClick={createBoardFromSearch}>
- <HStack gap="2" minW="0" w="full">
- <BoardCoverIcon icon={PlusIcon} />
- <Text flex="1" fontSize="xs" fontWeight="600" minW="0" truncate>
- {t('widgets.gallery.createBoardNamed', { name: trimmedSearchTerm })}
- </Text>
- </HStack>
- </Menu.Item>
- )}
- </ScrollArea.Content>
- </ScrollArea.Viewport>
- <ScrollArea.Scrollbar>
- <ScrollArea.Thumb />
- </ScrollArea.Scrollbar>
- </ScrollArea.Root>
- </Menu.Content>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
- <GalleryBoardMenu
- target={boardMenuTarget}
- onActiveChange={handleBoardMenuActiveChange}
- onClose={handleBoardMenuClose}
- />
- </>
- );
-};
-
-const BoardListControls = () => {
- const { t } = useTranslation();
- const { actions, gallery } = useGalleryWidget();
- const { boardOrderBy, boardOrderDir, showArchivedBoards, showDateBoards } = gallery.settings;
- const isAscending = boardOrderDir === 'ASC';
- const handleOrderByName = useCallback(() => actions.updateSettings({ boardOrderBy: 'board_name' }), [actions]);
- const handleOrderByCreated = useCallback(() => actions.updateSettings({ boardOrderBy: 'created_at' }), [actions]);
-
- const handleToggleOrderDir = useCallback(
- () => actions.updateSettings({ boardOrderDir: isAscending ? 'DESC' : 'ASC' }),
- [actions, isAscending]
- );
-
- const handleToggleDateBoards = useCallback(
- () => actions.updateSettings({ showDateBoards: !showDateBoards }),
- [actions, showDateBoards]
- );
-
- const handleToggleArchivedBoards = useCallback(
- () => actions.updateSettings({ showArchivedBoards: !showArchivedBoards }),
- [actions, showArchivedBoards]
- );
-
- return (
- <HStack gap="1" justify="space-between">
- <HStack gap="1">
- <Button size="2xs" variant={boardOrderBy === 'board_name' ? 'solid' : 'outline'} onClick={handleOrderByName}>
- {t('common.name')}
- </Button>
- <Button size="2xs" variant={boardOrderBy === 'created_at' ? 'solid' : 'outline'} onClick={handleOrderByCreated}>
- {t('common.created')}
- </Button>
- <IconButton
- aria-label={
- isAscending ? t('widgets.gallery.sortBoardsDescending') : t('widgets.gallery.sortBoardsAscending')
- }
- size="2xs"
- variant="outline"
- onClick={handleToggleOrderDir}
- >
- {isAscending ? <ArrowUpAZIcon /> : <ArrowDownAZIcon />}
- </IconButton>
- </HStack>
- <HStack gap="1">
- <IconButton
- aria-label={showDateBoards ? t('widgets.gallery.hideDateBoards') : t('widgets.gallery.showDateBoards')}
- aria-pressed={showDateBoards}
- size="2xs"
- title={showDateBoards ? t('widgets.gallery.hideDateBoards') : t('widgets.gallery.showDateBoards')}
- variant={showDateBoards ? 'solid' : 'outline'}
- onClick={handleToggleDateBoards}
- >
- <CalendarIcon />
- </IconButton>
- <IconButton
- aria-label={
- showArchivedBoards ? t('widgets.gallery.hideArchivedBoards') : t('widgets.gallery.showArchivedBoards')
- }
- aria-pressed={showArchivedBoards}
- size="2xs"
- title={showArchivedBoards ? t('widgets.gallery.hideArchivedBoards') : t('widgets.gallery.showArchivedBoards')}
- variant={showArchivedBoards ? 'solid' : 'outline'}
- onClick={handleToggleArchivedBoards}
- >
- <ArchiveIcon />
- </IconButton>
- </HStack>
- </HStack>
- );
-};
-
-const BoardGroupLabel = ({ children }: { children: string }) => (
- <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="3" pb="0.5" pt="2" textTransform="uppercase">
- {children}
- </Text>
-);
-
-const BoardRow = ({
- badge,
- badgeColor,
- board,
- isSelected,
- loadedItemBoardIds,
- onOpenMenu,
- onSelectBoard,
- onSelectComplete,
-}: {
- badge?: string;
- badgeColor?: 'blue' | 'gray';
- board: GalleryBoard;
- isSelected: boolean;
- loadedItemBoardIds: ReadonlyMap<GalleryItemKey, string>;
- onOpenMenu?: (board: GalleryBoard, x: number, y: number) => void;
- onSelectBoard: (boardId: string) => void;
- onSelectComplete: () => void;
-}) => {
- const { t } = useTranslation();
- const { active } = useDndContext();
- const dragData = active?.data.current;
-
- const canDropItems =
- board.kind === 'board' &&
- isGalleryItemDragData(dragData) &&
- dragData.items.some((ref) => loadedItemBoardIds.get(toGalleryItemKey(ref)) !== board.id);
-
- const { isOver, setNodeRef } = useDroppable({
- data: getGalleryBoardDropData(board.id, board.kind),
- disabled: !canDropItems,
- id: getGalleryBoardDropId(board.id),
- });
-
- const hoverCss = useMemo(
- () => (onOpenMenu ? { '&:hover .board-row-actions': { opacity: 1 } } : undefined),
- [onOpenMenu]
- );
-
- const handleSelect = useCallback(() => {
- onSelectComplete();
- onSelectBoard(board.id);
- }, [board.id, onSelectBoard, onSelectComplete]);
-
- const handleContextMenu = useCallback(
- (event: MouseEvent) => {
- if (!onOpenMenu) {
- return;
- }
-
- event.preventDefault();
- event.stopPropagation();
- onOpenMenu(board, event.clientX, event.clientY);
- },
- [board, onOpenMenu]
- );
-
- const handleActionsClick = useCallback(
- (event: MouseEvent<HTMLButtonElement>) => {
- if (!onOpenMenu) {
- return;
- }
-
- event.preventDefault();
- event.stopPropagation();
-
- const rect = event.currentTarget.getBoundingClientRect();
-
- onOpenMenu(board, rect.left, rect.bottom);
- },
- [board, onOpenMenu]
- );
-
- const stopPropagation = useCallback((event: MouseEvent | PointerEvent) => event.stopPropagation(), []);
-
- return (
- <Menu.Item
- ref={setNodeRef}
- // DropZone tokens without the DropZone component: an outline (not a border) so the drop affordance never shifts menu layout.
- bg={isOver ? 'accent.muted' : undefined}
- css={hoverCss}
- outline={canDropItems ? '1px dashed' : undefined}
- outlineColor={canDropItems ? 'accent.solid' : undefined}
- value={board.id}
- onClick={handleSelect}
- onContextMenu={onOpenMenu ? handleContextMenu : undefined}
- >
- <BoardOptionContent badge={badge} badgeColor={badgeColor} board={board} isSelected={isSelected} showOwner />
- {onOpenMenu && (
- <IconButton
- aria-label={t('widgets.gallery.boardActionsForBoard', { name: board.name })}
- className="board-row-actions"
- flexShrink={0}
- opacity={0}
- size="2xs"
- transition="opacity var(--wb-motion-duration-medium) ease"
- variant="ghost"
- onClick={handleActionsClick}
- onPointerDown={stopPropagation}
- onPointerUp={stopPropagation}
- >
- <MoreVerticalIcon />
- </IconButton>
- )}
- </Menu.Item>
- );
-};
-
-export const BoardOptionContent = ({
- badge,
- badgeColor = 'gray',
- board,
- isSelected,
- showOwner = false,
-}: {
- badge?: string;
- badgeColor?: 'blue' | 'gray';
- board: GalleryBoard;
- isSelected: boolean;
- /** Render the owner line (admins on multi-user backends); off in the compact trigger. */
- showOwner?: boolean;
-}) => {
- const { t } = useTranslation();
- const counts = getBoardCounts(board);
- const mediaCountBreakdown = t('widgets.gallery.boardMediaCountBreakdown', {
- images: t('widgets.gallery.imageCount', { count: counts.imageCount }),
- videos: t('widgets.gallery.videoCount', { count: counts.videoCount }),
- });
-
- return (
- <HStack gap="2" minW="0" w="full">
- <BoardCover board={board} />
- <Stack gap="1" minW="0">
- <Text fontSize="xs" fontWeight={isSelected ? '700' : '500'} minW="0" lineHeight={1} truncate>
- {board.name}
- </Text>
- {showOwner && board.ownerName ? (
- <Text color="fg.subtle" fontSize="2xs" minW="0" lineHeight={1} truncate>
- {board.ownerName}
- </Text>
- ) : null}
- </Stack>
- <Flex ms="auto">
- {badge && (
- <Badge colorPalette={badgeColor} flexShrink={0} size="xs" variant="subtle">
- {badge}
- </Badge>
- )}
- <Tooltip content={mediaCountBreakdown}>
- <Badge
- aria-label={mediaCountBreakdown}
- flexShrink={0}
- fontVariantNumeric="tabular-nums"
- size="xs"
- variant={isSelected ? 'solid' : 'subtle'}
- >
- {counts.imageCount + counts.videoCount} | {counts.assetCount}
- </Badge>
- </Tooltip>
- </Flex>
- </HStack>
- );
-};
-
-const BoardCoverIcon = ({ icon }: { icon: LucideIcon }) => (
- <Flex
- align="center"
- bg="bg.emphasized"
- borderWidth="1px"
- borderColor="border.subtle"
- boxSize="7"
- color="fg.subtle"
- flexShrink={0}
- justify="center"
- rounded="md"
- >
- <Icon as={icon} boxSize="4" />
- </Flex>
-);
-
-export const BoardCover = ({ board }: { board: GalleryBoard }) => {
- if (board.coverThumbnailUrl) {
- return (
- <Flex boxSize="7" flexShrink={0} position="relative">
- <Image
- alt=""
- bg="bg.emphasized"
- borderWidth="1px"
- borderColor="border.subtle"
- boxSize="7"
- objectFit="cover"
- rounded="md"
- src={board.coverThumbnailUrl}
- />
- {board.coverVideoName ? (
- <Flex
- align="center"
- aria-hidden="true"
- bg="blackAlpha.700"
- bottom="0.5"
- boxSize="3"
- color="white"
- justify="center"
- position="absolute"
- right="0.5"
- rounded="full"
- >
- <Icon as={PlayIcon} boxSize="2" fill="currentColor" />
- </Flex>
- ) : null}
- </Flex>
- );
- }
-
- return <BoardCoverIcon icon={board.kind === 'date' ? CalendarIcon : ImageIcon} />;
-};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
new file mode 100644
index 0000000000..9fb4eebcf5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
@@ -0,0 +1,341 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { DEFAULT_GALLERY_SETTINGS, type GallerySettings } from '@features/gallery/core/settings';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryStateView } from './galleryStateView';
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GalleryBoardsPanel } from './GalleryBoardsPanel';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en' },
+ t: (key: string, values?: Record<string, unknown>) => {
+ if (key === 'widgets.gallery.createBoardNamed') {
+ return `Create board "${String(values?.name)}"`;
+ }
+ if (key === 'widgets.gallery.boardGroups.boards') {
+ return 'Your boards';
+ }
+ if (key === 'widgets.gallery.boardGroups.byDate') {
+ return 'Dates';
+ }
+ if (key === 'common.archived') {
+ return 'Archived';
+ }
+ if (key === 'widgets.gallery.uncategorized') {
+ return 'Uncategorized';
+ }
+
+ return key;
+ },
+ }),
+}));
+
+const actions = {
+ createBoard: vi.fn(async () => {}),
+ selectBoard: vi.fn(),
+ selectProjectBoard: vi.fn(async () => {}),
+ updateSettings: vi.fn(),
+};
+
+const itemActions = { moveItemsToBoard: vi.fn(async () => {}) };
+
+const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
+ archived: false,
+ assetCount: 3,
+ imageCount: 50,
+ kind: 'board',
+ videoCount: 0,
+ ...overrides,
+});
+
+const boards = [
+ createBoard({ id: 'dogs', name: 'dogs' }),
+ createBoard({ id: 'cats', imageCount: 56, name: 'Cats', ownerName: 'Alice Example' }),
+ createBoard({ assetCount: 1, id: 'none', imageCount: 1, kind: 'uncategorized', name: '' }),
+ createBoard({ archived: true, id: 'gorl', imageCount: 1, name: 'GORL' }),
+ createBoard({ id: 'by_date:2026-07-30', imageCount: 12, kind: 'date', name: 'Today' }),
+];
+
+const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateView =>
+ ({
+ boards,
+ compareImageKey: null,
+ currentItem: null,
+ galleryView: 'images',
+ isLoading: false,
+ items: [],
+ pendingPlaceholders: [],
+ projectBoardId: null,
+ searchTerm: '',
+ selectedBoardId: 'dogs',
+ selectedItemKey: null,
+ selectedItemKeys: [],
+ settings: { ...DEFAULT_GALLERY_SETTINGS, showArchivedBoards: true, showDateBoards: true, ...settings },
+ ...({} as Record<string, never>),
+ }) as GalleryStateView;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderPanel = async (gallery: GalleryStateView = createGallery()) => {
+ const contextValue = {
+ actions,
+ gallery,
+ itemActions,
+ projectName: 'Project',
+ } as unknown as GalleryWidgetContextValue;
+
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GalleryWidgetContext value={contextValue}>
+ <DndContext>
+ <GalleryBoardsPanel />
+ </DndContext>
+ </GalleryWidgetContext>
+ </ChakraProvider>
+ )
+ );
+};
+
+const getBoardRows = (): HTMLElement[] =>
+ Array.from(host?.querySelectorAll<HTMLElement>('[data-part="content"] button[type="button"]') ?? []);
+
+const getSearchInput = (): HTMLInputElement => {
+ const input = host?.querySelector<HTMLInputElement>('input');
+
+ if (!input) {
+ throw new Error('board search input did not render');
+ }
+
+ return input;
+};
+
+const type = async (input: HTMLInputElement, value: string) => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+
+ await act(async () => {
+ setter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+};
+
+const click = async (element: HTMLElement) => {
+ await act(async () => {
+ element.click();
+ await Promise.resolve();
+ });
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ host.style.cssText = 'height:480px;left:20px;position:fixed;top:20px;width:280px;';
+ document.body.append(host);
+ root = createRoot(host);
+ Object.values(actions).forEach((mock) => mock.mockClear());
+ itemActions.moveItemsToBoard.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GalleryBoardsPanel', () => {
+ it('renders boards, dates, and archived as separate sections', async () => {
+ await renderPanel();
+
+ const text = host?.textContent ?? '';
+
+ expect(text).toContain('Your boards');
+ expect(text).toContain('Dates');
+ expect(text).toContain('Archived');
+ expect(text).toContain('GORL');
+ });
+
+ it('keeps archived boards out of the main list', async () => {
+ await renderPanel();
+
+ const sections = Array.from(host?.querySelectorAll('[data-scope="collapsible"]') ?? []);
+ const boardsSection = sections[0];
+
+ expect(boardsSection?.textContent).toContain('dogs');
+ expect(boardsSection?.textContent).not.toContain('GORL');
+ });
+
+ it('marks the project board with a Project badge', async () => {
+ // The fixture project used by the visual harness has no project board, so
+ // this path is only reachable here.
+ await renderPanel({ ...createGallery(), projectBoardId: 'cats' } as GalleryStateView);
+
+ const catsRow = getBoardRows().find((row) => row.textContent?.includes('Cats'));
+
+ expect(catsRow?.textContent).toContain('common.project');
+ });
+
+ it('shows media and asset counts together, so the row does not change meaning with the tab', async () => {
+ await renderPanel();
+
+ const catsRow = getBoardRows().find((row) => row.textContent?.includes('Cats'));
+
+ // Cats has 56 images, 0 videos, 3 assets.
+ expect(catsRow?.textContent).toContain('56 | 3');
+ });
+
+ it('does not spend row width on creation dates', async () => {
+ await renderPanel();
+
+ expect(host?.textContent).not.toMatch(/\b\d{1,2} [A-Z][a-z]{2}\b/);
+ });
+
+ it('marks the selected board for assistive tech', async () => {
+ await renderPanel();
+
+ const current = host?.querySelector('[aria-current="true"]');
+
+ expect(current?.textContent).toContain('dogs');
+ });
+
+ it('renders owner subtitles only when the backend supplies an owner', async () => {
+ await renderPanel();
+
+ const catsRow = getBoardRows().find((row) => row.textContent?.includes('Cats'));
+ const dogsRow = getBoardRows().find((row) => row.textContent?.includes('dogs'));
+
+ expect(catsRow?.textContent).toContain('Alice Example');
+ expect(dogsRow?.textContent).not.toContain('Alice Example');
+ });
+
+ it('keeps the owner subtitle truncated and changes it from muted to selected contrast styling', async () => {
+ await renderPanel();
+
+ const unselectedOwner = Array.from(host?.querySelectorAll<HTMLElement>('*') ?? []).find(
+ (element) => element.childElementCount === 0 && element.textContent === 'Alice Example'
+ );
+
+ expect(unselectedOwner).toBeDefined();
+ expect(getComputedStyle(unselectedOwner!).overflow).toBe('hidden');
+ expect(getComputedStyle(unselectedOwner!).textOverflow).toBe('ellipsis');
+ const unselectedColor = getComputedStyle(unselectedOwner!).color;
+
+ await renderPanel({ ...createGallery(), selectedBoardId: 'cats' } as GalleryStateView);
+ const selectedOwner = Array.from(host?.querySelectorAll<HTMLElement>('*') ?? []).find(
+ (element) => element.childElementCount === 0 && element.textContent === 'Alice Example'
+ );
+
+ expect(selectedOwner).toBeDefined();
+ expect(getComputedStyle(selectedOwner!).color).not.toBe(unselectedColor);
+ expect(host?.querySelector('[aria-current="true"]')?.textContent).toContain('Alice Example');
+ });
+
+ it('shows the count for the active view and switches with the tab', async () => {
+ await renderPanel();
+ expect(host?.textContent).toContain('50');
+
+ await renderPanel({ ...createGallery(), galleryView: 'assets' } as GalleryStateView);
+ expect(host?.textContent).toContain('3');
+ });
+
+ it('selects a board and clears the search on click', async () => {
+ await renderPanel();
+ await type(getSearchInput(), 'cat');
+
+ const catsRow = getBoardRows().find((row) => row.textContent?.includes('Cats'));
+
+ await click(catsRow!);
+
+ expect(actions.selectBoard).toHaveBeenCalledWith('cats');
+ expect(getSearchInput().value).toBe('');
+ });
+
+ it('filters the list and offers to create an unmatched name', async () => {
+ await renderPanel();
+ await type(getSearchInput(), 'birds');
+
+ expect(host?.textContent).toContain('Create board "birds"');
+
+ const createRow = getBoardRows().find((row) => row.textContent?.includes('Create board'));
+
+ await click(createRow!);
+
+ expect(actions.createBoard).toHaveBeenCalledWith('birds');
+ });
+
+ it('creates on Enter only when nothing matched', async () => {
+ await renderPanel();
+ const input = getSearchInput();
+
+ await type(input, 'dog');
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
+ await Promise.resolve();
+ });
+ expect(actions.createBoard).not.toHaveBeenCalled();
+
+ await type(input, 'birds');
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
+ await Promise.resolve();
+ });
+ expect(actions.createBoard).toHaveBeenCalledWith('birds');
+ });
+
+ it('persists a collapsed section', async () => {
+ await renderPanel();
+
+ const trigger = host?.querySelector<HTMLElement>('[data-scope="collapsible"] [data-part="trigger"]');
+
+ await click(trigger!);
+
+ expect(actions.updateSettings).toHaveBeenCalledWith({ collapsedBoardSections: ['boards'] });
+ });
+
+ it('reopens a section that was persisted as collapsed', async () => {
+ await renderPanel(createGallery({ collapsedBoardSections: ['boards'] }));
+
+ const trigger = host?.querySelector<HTMLElement>('[data-scope="collapsible"] [data-part="trigger"]');
+
+ await click(trigger!);
+
+ expect(actions.updateSettings).toHaveBeenCalledWith({ collapsedBoardSections: [] });
+ });
+
+ it('toggles the date and archived board queries from the filter row', async () => {
+ await renderPanel();
+
+ const dateToggle = host?.querySelector<HTMLElement>('button[aria-label="widgets.gallery.hideDateBoards"]');
+
+ await click(dateToggle!);
+ expect(actions.updateSettings).toHaveBeenCalledWith({ showDateBoards: false });
+
+ const archiveToggle = host?.querySelector<HTMLElement>('button[aria-label="widgets.gallery.hideArchivedBoards"]');
+
+ await click(archiveToggle!);
+ expect(actions.updateSettings).toHaveBeenCalledWith({ showArchivedBoards: false });
+ });
+
+ it('reports no matches when the only board named is one the filters are hiding', async () => {
+ // Reachable while the archived toggle has flipped but the refetch that
+ // drops archived boards has not landed: the name is taken, so creating is
+ // refused, yet no section will show it.
+ await renderPanel(createGallery({ showArchivedBoards: false }));
+ await type(getSearchInput(), 'GORL');
+
+ expect(host?.textContent).toContain('widgets.gallery.noBoardsMatchSearch');
+ expect(host?.textContent).not.toContain('Create board');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx
new file mode 100644
index 0000000000..bf0b63960f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx
@@ -0,0 +1,244 @@
+import type { GalleryItemKey } from '@features/gallery/core/items';
+import type { GalleryBoardSectionId } from '@features/gallery/core/settings';
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { Badge, HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';
+import { toGalleryItemKey } from '@features/gallery/core/items';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { PinIcon, PlusIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { BoardCoverIcon } from './GalleryBoardCover';
+import { GalleryBoardFilters } from './GalleryBoardFilters';
+import { getGalleryBoardGroups } from './galleryBoardGroups';
+import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenu';
+import { GalleryBoardRow } from './GalleryBoardRow';
+import { GalleryBoardRowShell } from './GalleryBoardRowShell';
+import { GalleryBoardSection } from './GalleryBoardSection';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const SCROLL_CONTENT_PROPS = { py: '1' } as const;
+const PROJECT_ROW_COVER = <BoardCoverIcon icon={PinIcon} />;
+const CREATE_ROW_COVER = <BoardCoverIcon icon={PlusIcon} />;
+
+/**
+ * The board browser: search and list controls above a grouped, collapsible
+ * list of boards. Identical in both layouts — the shells only decide whether it
+ * sits above the items area or beside it.
+ */
+export const GalleryBoardsPanel = () => {
+ const { t } = useTranslation();
+ const { actions, gallery, projectName } = useGalleryWidget();
+ const [searchTerm, setSearchTerm] = useState('');
+ const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);
+ const searchInputRef = useRef<HTMLInputElement>(null);
+
+ const { collapsedBoardSections, showArchivedBoards, showDateBoards } = gallery.settings;
+
+ const groups = useMemo(
+ () =>
+ getGalleryBoardGroups({
+ boards: gallery.boards,
+ projectBoardId: gallery.projectBoardId,
+ projectName,
+ searchTerm,
+ showArchived: showArchivedBoards,
+ showDates: showDateBoards,
+ t,
+ }),
+ [gallery.boards, gallery.projectBoardId, projectName, searchTerm, showArchivedBoards, showDateBoards, t]
+ );
+
+ const loadedItemBoardIds = useMemo(
+ () => new Map<GalleryItemKey, string>(gallery.items.map((item) => [toGalleryItemKey(item), item.boardId])),
+ [gallery.items]
+ );
+
+ const trimmedSearchTerm = searchTerm.trim();
+
+ const createBoardFromSearch = useCallback(() => {
+ if (!groups.canCreateFromSearch) {
+ return;
+ }
+
+ setSearchTerm('');
+ void actions.createBoard(trimmedSearchTerm);
+ }, [actions, groups.canCreateFromSearch, trimmedSearchTerm]);
+
+ // Enter only creates when nothing matched; with matches on screen it would
+ // be far too easy to make a near-duplicate board by reflex.
+ const handleSubmitSearch = useCallback(() => {
+ if (!groups.hasAnyMatch) {
+ createBoardFromSearch();
+ }
+ }, [createBoardFromSearch, groups.hasAnyMatch]);
+
+ // "+" creates straight away when the field already names the board; with an
+ // empty field there is nothing to name it, so it hands over the caret.
+ const handleAddBoard = useCallback(() => {
+ if (groups.canCreateFromSearch) {
+ createBoardFromSearch();
+ return;
+ }
+
+ searchInputRef.current?.focus();
+ }, [createBoardFromSearch, groups.canCreateFromSearch]);
+
+ const handleSelectBoard = useCallback(
+ (boardId: string) => {
+ setSearchTerm('');
+ actions.selectBoard(boardId);
+ },
+ [actions]
+ );
+
+ const handleSelectProjectBoard = useCallback(() => {
+ setSearchTerm('');
+ void actions.selectProjectBoard();
+ }, [actions]);
+
+ const openBoardMenu = useCallback((board: GalleryBoard, x: number, y: number) => {
+ setBoardMenuTarget({ board, x, y });
+ }, []);
+
+ const handleBoardMenuClose = useCallback(() => setBoardMenuTarget(null), []);
+
+ const handleToggleSection = useCallback(
+ (sectionId: GalleryBoardSectionId, isOpen: boolean) => {
+ const nextSections = isOpen
+ ? collapsedBoardSections.filter((entry) => entry !== sectionId)
+ : [...collapsedBoardSections, sectionId];
+
+ actions.updateSettings({ collapsedBoardSections: nextSections });
+ },
+ [actions, collapsedBoardSections]
+ );
+
+ const isSectionOpen = (sectionId: GalleryBoardSectionId) => !collapsedBoardSections.includes(sectionId);
+
+ const addBoardAction = useMemo(
+ () => (
+ <Tooltip content={t('widgets.gallery.createBoard')}>
+ <IconButton
+ aria-label={t('widgets.gallery.createBoard')}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={handleAddBoard}
+ >
+ <Icon as={PlusIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ ),
+ [handleAddBoard, t]
+ );
+
+ return (
+ <Stack flex="1" gap="1" minH="0" minW="0">
+ <GalleryBoardFilters
+ ref={searchInputRef}
+ searchTerm={searchTerm}
+ onSearchChange={setSearchTerm}
+ onSubmitSearch={handleSubmitSearch}
+ />
+ <ScrollArea.Root flex="1" minH="0" size="xs" variant="hover" w="full">
+ <ScrollArea.Viewport h="full" w="full">
+ <ScrollArea.Content {...SCROLL_CONTENT_PROPS}>
+ <GalleryBoardSection
+ action={addBoardAction}
+ isOpen={isSectionOpen('boards')}
+ label={t('widgets.gallery.boardGroups.boards')}
+ sectionId="boards"
+ onToggle={handleToggleSection}
+ >
+ {groups.hasProjectBoardPlaceholder ? (
+ <GalleryBoardRowShell cover={PROJECT_ROW_COVER} label={projectName} onSelect={handleSelectProjectBoard}>
+ <Badge colorPalette="accent" flexShrink={0} size="xs" variant="subtle">
+ {t('common.project')}
+ </Badge>
+ </GalleryBoardRowShell>
+ ) : null}
+ {groups.yourBoards.map((board) => (
+ <GalleryBoardRow
+ key={board.id}
+ board={board}
+ isMenuOpen={boardMenuTarget?.board.id === board.id}
+ isProjectBoard={board.id === gallery.projectBoardId}
+ isSelected={board.id === gallery.selectedBoardId}
+ loadedItemBoardIds={loadedItemBoardIds}
+ onOpenMenu={openBoardMenu}
+ onSelectBoard={handleSelectBoard}
+ />
+ ))}
+ {groups.canCreateFromSearch ? (
+ <GalleryBoardRowShell
+ cover={CREATE_ROW_COVER}
+ label={t('widgets.gallery.createBoardNamed', { name: trimmedSearchTerm })}
+ labelWeight="600"
+ onSelect={createBoardFromSearch}
+ />
+ ) : null}
+ </GalleryBoardSection>
+
+ {groups.dateBoards.length > 0 ? (
+ <GalleryBoardSection
+ isOpen={isSectionOpen('dates')}
+ label={t('widgets.gallery.boardGroups.byDate')}
+ sectionId="dates"
+ onToggle={handleToggleSection}
+ >
+ {groups.dateBoards.map((board) => (
+ <GalleryBoardRow
+ key={board.id}
+ board={board}
+ isMenuOpen={boardMenuTarget?.board.id === board.id}
+ isProjectBoard={false}
+ isSelected={board.id === gallery.selectedBoardId}
+ loadedItemBoardIds={loadedItemBoardIds}
+ onSelectBoard={handleSelectBoard}
+ />
+ ))}
+ </GalleryBoardSection>
+ ) : null}
+
+ {groups.archivedBoards.length > 0 ? (
+ <GalleryBoardSection
+ isOpen={isSectionOpen('archived')}
+ label={t('common.archived')}
+ sectionId="archived"
+ onToggle={handleToggleSection}
+ >
+ {groups.archivedBoards.map((board) => (
+ <GalleryBoardRow
+ key={board.id}
+ board={board}
+ isMenuOpen={boardMenuTarget?.board.id === board.id}
+ isProjectBoard={false}
+ isSelected={board.id === gallery.selectedBoardId}
+ loadedItemBoardIds={loadedItemBoardIds}
+ onOpenMenu={openBoardMenu}
+ onSelectBoard={handleSelectBoard}
+ />
+ ))}
+ </GalleryBoardSection>
+ ) : null}
+
+ {!groups.hasAnyMatch && !groups.canCreateFromSearch ? (
+ <HStack justify="center" py="3">
+ <Text color="fg.muted" fontSize="2xs">
+ {t('widgets.gallery.noBoardsMatchSearch')}
+ </Text>
+ </HStack>
+ ) : null}
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar>
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ </ScrollArea.Root>
+ <GalleryBoardMenu target={boardMenuTarget} onClose={handleBoardMenuClose} />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index ef819fd024..9a2ccdd2bb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -1,5 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */
import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryItemsFilter } from '@features/gallery/data/queries';
import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';
import { ChakraProvider } from '@chakra-ui/react';
@@ -16,6 +17,7 @@ import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';
import { isGalleryImageDragData } from '@features/gallery/utility';
+import { parseDateTokens } from '@platform/search/dateTokens';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -113,11 +115,13 @@ void i18n.use(initReactI18next).init({
itemsAriaLabel: 'Gallery items',
loadingBackendGallery: 'Loading gallery',
noImagesMatch: 'No items',
+ dropMediaToUploadToBoard: 'Drop media to {{name}}',
selectImageForPreview: 'Select {{name}} for preview',
selectVideoForPreview: 'Select video {{name}}, duration {{duration}}, for preview',
selectedBoardFallback: 'selected board',
starImage: 'Star {{name}}',
unstarImage: 'Unstar {{name}}',
+ uncategorized: 'Uncategorized',
windowLimit: 'Limited to {{count}}',
},
preview: {
@@ -173,6 +177,21 @@ const board = {
videoCount: 1,
} as const;
+/** Mirrors how `useGalleryData` derives the filter the widget publishes on context. */
+const createFilter = (gallery: GalleryStateView): GalleryItemsFilter => {
+ const parse = parseDateTokens(gallery.searchTerm);
+
+ return {
+ boardId: gallery.selectedBoardId,
+ ...(parse.range?.from ? { createdFrom: parse.range.from } : {}),
+ ...(parse.range?.to ? { createdTo: parse.range.to } : {}),
+ galleryView: gallery.galleryView,
+ orderDir: gallery.settings.imageOrderDir,
+ searchTerm: parse.text,
+ starredFirst: gallery.settings.starredFirst,
+ };
+};
+
const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateView => {
const items = overrides.items ?? [
createItem('image', 'first.png'),
@@ -334,10 +353,12 @@ const Harness = ({
);
const contextValue: GalleryWidgetContextValue = {
actions: createActions(),
+ filter: createFilter(gallery),
gallery,
itemActions: imageActionMocks,
isWindowTruncated: false,
projectName: 'Project',
+ region: 'right',
runtime,
} as unknown as GalleryWidgetContextValue;
@@ -349,7 +370,7 @@ const Harness = ({
<GalleryWidgetContext value={contextValue}>
<DndContext sensors={sensors}>
<DragMonitor />
- <GalleryImageGrid layout="wide" />
+ <GalleryImageGrid />
{coMountPreviewSources ? (
<>
<PreviewFrame
@@ -478,7 +499,7 @@ describe('GalleryImageGrid mixed item cells', () => {
expect(onDragStart).toHaveBeenCalledWith({
data: { items: [{ kind: 'video', name: 'shared' }], kind: 'gallery-item' },
- id: 'gallery-grid:video:shared',
+ id: 'gallery-grid#right:video:shared',
});
// dnd-kit briefly suppresses the click following a completed drag. Let
@@ -526,7 +547,7 @@ describe('GalleryImageGrid mixed item cells', () => {
],
kind: 'gallery-item',
},
- id: 'gallery-grid:image:loaded.png',
+ id: 'gallery-grid#right:image:loaded.png',
});
expect(isGalleryImageDragData(drag?.data)).toBe(false);
});
@@ -760,6 +781,22 @@ describe('GalleryImageGrid range selection', () => {
});
});
+describe('GalleryImageGrid upload drop zone', () => {
+ it('uses the localized label for the Uncategorized upload target', async () => {
+ const uncategorizedBoard = { ...board, id: 'none', kind: 'uncategorized' as const, name: '' };
+
+ await renderGallery(createGallery({ boards: [uncategorizedBoard], selectedBoardId: 'none' }));
+
+ const gridRoot = host?.querySelector('[role="list"]')?.closest('[data-scope="scroll-area"]')?.parentElement;
+ const dataTransfer = new DataTransfer();
+ dataTransfer.items.add(new File(['image'], 'image.png', { type: 'image/png' }));
+
+ await interact(() => gridRoot?.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })));
+
+ expect(host?.textContent).toContain('Drop media to Uncategorized');
+ });
+});
+
describe('GalleryImageGrid virtualization', () => {
it('keeps external-store option callbacks stable across equivalent renders', async () => {
const gallery = createGallery({ items: [createItem('video', 'clip.mp4')] });
@@ -784,8 +821,15 @@ describe('GalleryImageGrid virtualization', () => {
);
await vi.waitFor(() => expect(actionMocks.loadMore).toHaveBeenCalled());
+ // Columns follow the measured viewport width now, so pinning a row count
+ // would just re-encode the harness width. The invariant that matters is
+ // that the rows the virtualizer is asked for cover every cell exactly once.
+ const renderedRows = host?.querySelectorAll('[role="list"] [role="presentation"]').length ?? 0;
+ const renderedCells = host?.querySelectorAll('[role="listitem"]').length ?? 0;
+
const options = mocks.virtualizerOptions.at(-1);
- expect(options?.count).toBe(7);
+ expect(options?.count).toBe(renderedRows);
+ expect(renderedCells).toBe(items.length);
expect(options?.overscan).toBe(4);
expect(options?.estimateSize()).toBe(options?.estimateSize());
expect(host?.querySelector('[role="listitem"]')).toHaveStyle({ aspectRatio: '1 / 1' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 1e6c841ef0..cab03efd28 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -1,26 +1,8 @@
-import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';
-import type { GalleryThumbnailFit } from '@features/gallery/core/settings';
-
-import { Badge, Box, Flex, ProgressCircle, ScrollArea, Skeleton, Spinner, Text } from '@chakra-ui/react';
-import { useDraggable } from '@dnd-kit/core';
-import { CSS } from '@dnd-kit/utilities';
-import {
- formatGalleryVideoDuration,
- isGalleryImageItem,
- parseGalleryItemKey,
- toGalleryItemKey,
- toGalleryItemRef,
-} from '@features/gallery/core/items';
-import { isDateBoardId, type GalleryItemNames } from '@features/gallery/data/backend';
-import { galleryItemNamesOptions, type GalleryItemsFilter } from '@features/gallery/data/queries';
-import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';
-import { parseDateTokens } from '@platform/search/dateTokens';
-import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
-import { DropZone, IconButton } from '@platform/ui';
-import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';
-import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';
-import { useQueryClient } from '@tanstack/react-query';
-import { PlayIcon, StarIcon, UploadIcon } from 'lucide-react';
+import { Box, Flex, ScrollArea, Spinner, Text } from '@chakra-ui/react';
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { toGalleryItemKey, type GalleryItem } from '@features/gallery/core/items';
+import { DropZone } from '@platform/ui';
+import { UploadIcon } from 'lucide-react';
import {
useCallback,
useEffect,
@@ -30,97 +12,72 @@ import {
useRef,
useState,
type DragEvent,
- type KeyboardEvent,
- type MouseEvent,
} from 'react';
import { useVirtualizer } from 'react-hook-tanstack-virtual';
import { useTranslation } from 'react-i18next';
import type { GalleryQueuePlaceholder } from './galleryStateView';
-import type { GalleryItemContextMenuTarget } from './GalleryUiContext';
-import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';
+import { GALLERY_GRID_GAP_PX, getGalleryCellSizePx, getGalleryColumnCount } from './galleryGridLayout';
+import { GalleryQueuePlaceholderCell } from './GalleryQueuePlaceholderCell';
import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';
+import { GalleryThumbnailCell } from './GalleryThumbnail';
import { useGalleryUi } from './GalleryUiContext';
import { useGalleryWidget } from './GalleryWidgetContext';
+import { useGalleryGridHotkeys } from './useGalleryGridHotkeys';
+import { useGalleryGridSelection } from './useGalleryGridSelection';
-const GRID_GAP_PX = 4;
-const THUMBNAIL_HOVER_CSS = {
- '&:hover .gallery-thumb-overlay, &:focus-within .gallery-thumb-overlay': { opacity: 1 },
- '&:focus-within': { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' },
-} as const;
-const THUMBNAIL_BUTTON_STYLE = {
- background: 'transparent',
- border: 0,
- cursor: 'pointer',
- display: 'block',
- height: '100%',
- inset: 0,
- minWidth: 0,
- outline: 'none',
- padding: 0,
- position: 'absolute',
- width: '100%',
-} as const;
-
-const viewportWidthCache = new Map<'stacked' | 'wide', number>();
-
-const getGalleryColumnCount = (imageDensityPercent: number, layout: 'stacked' | 'wide'): number => {
- const min = 2;
- const max = layout === 'wide' ? 10 : 6;
- const percent = Math.min(100, Math.max(0, imageDensityPercent));
-
- return Math.round(min + ((max - min) * percent) / 100);
-};
+/**
+ * Seeds the measured width per region so remounting the gallery in a placement
+ * it has already been shown in does not paint one frame of fallback-sized
+ * tiles before the ResizeObserver reports.
+ */
+const viewportWidthCache = new Map<string, number>();
const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');
-const getGalleryItemRange = (
- orderedRefs: readonly GalleryItemRef[],
- anchorItemKey: string,
- targetItemKey: string
-): GalleryItemRef[] | null => {
- const anchorIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === anchorItemKey);
- const targetIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === targetItemKey);
-
- if (anchorIndex === -1 || targetIndex === -1) {
- return null;
- }
-
- const start = Math.min(anchorIndex, targetIndex);
- const end = Math.max(anchorIndex, targetIndex);
-
- return orderedRefs.slice(start, end + 1);
-};
-
type GridCell =
| { kind: 'item'; item: GalleryItem; itemIndex: number }
| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };
-export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {
+/**
+ * The virtualized thumbnail grid. Column count comes from the measured
+ * viewport width, so the grid is layout-blind: both shells render it the same
+ * way and it simply fills whatever box it is handed.
+ */
+export const GalleryImageGrid = () => {
const { t } = useTranslation();
- const { actions, gallery, isWindowTruncated, itemActions, runtime } = useGalleryWidget();
- const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();
- const queryClient = useQueryClient();
- const [contextMenuTarget, setContextMenuTarget] = useState<GalleryItemContextMenuTarget | null>(null);
+ const { actions, gallery, isWindowTruncated, itemActions, region } = useGalleryWidget();
+ const { account, antialiasProgressImages, ImageContextMenu } = useGalleryUi();
const [isDropActive, setIsDropActive] = useState(false);
- const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(layout) ?? 0);
+ const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(region) ?? 0);
const dragDepthRef = useRef(0);
const viewportRef = useRef<HTMLDivElement | null>(null);
const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =
gallery.settings;
- const columnCount = getGalleryColumnCount(imageDensityPercent, layout);
- const selectedItemKeys = useMemo(() => new Set(gallery.selectedItemKeys), [gallery.selectedItemKeys]);
- const selectedItemRefs = useMemo(() => gallery.selectedItemKeys.map(parseGalleryItemKey), [gallery.selectedItemKeys]);
+
+ const {
+ actionSelectionRefs,
+ activeContextMenuTarget,
+ getDragItems,
+ handleCloseContextMenu,
+ handleThumbnailClick,
+ handleThumbnailContextMenu,
+ selectedItemKeys,
+ syncRangeInteractionContext,
+ } = useGalleryGridSelection();
+
+ const columnCount = getGalleryColumnCount({ imageDensityPercent, widthPx: viewportWidth });
const isFollowingLive = gallery.currentItem?.kind === 'placeholder';
const isComparisonActive =
gallery.selectedItemKey?.startsWith('image:') === true &&
gallery.compareImageKey !== null &&
gallery.selectedItemKey !== null &&
gallery.compareImageKey !== gallery.selectedItemKey;
- const selectedBoardName =
- gallery.boards.find((board) => board.id === gallery.selectedBoardId)?.name ??
- t('widgets.gallery.selectedBoardFallback');
+ const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);
+ const selectedBoardName = selectedBoard
+ ? getGalleryBoardLabel(selectedBoard, t)
+ : t('widgets.gallery.selectedBoardFallback');
const isEmpty = gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0;
const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(gallery.items, imageOrderDir, starredFirst);
@@ -143,15 +100,9 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
];
}, [gallery.items, gallery.pendingPlaceholders, placeholderInsertionIndex]);
- const getCellIndexForItem = (itemIndex: number): number =>
- itemIndex >= placeholderInsertionIndex ? itemIndex + gallery.pendingPlaceholders.length : itemIndex;
-
const rowCount = Math.ceil(cells.length / columnCount);
-
- const cellSizePx =
- viewportWidth > 0 ? Math.max(1, (viewportWidth - GRID_GAP_PX * (columnCount - 1)) / columnCount) : 96;
-
- const rowHeightPx = cellSizePx + GRID_GAP_PX;
+ const cellSizePx = getGalleryCellSizePx({ columnCount, widthPx: viewportWidth });
+ const rowHeightPx = cellSizePx + GALLERY_GRID_GAP_PX;
const estimateRowSize = useCallback(() => rowHeightPx, [rowHeightPx]);
const getScrollElement = useCallback(() => viewportRef.current, []);
@@ -166,6 +117,19 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
virtualizer.measure();
});
+ // Deliberately unmemoized: the hotkey hook only ever calls this from inside
+ // an effect event, which always sees the latest render's closure, so a stable
+ // identity would buy nothing and pinning the mutable virtualizer into a
+ // dependency array defeats the compiler's own memoization.
+ const scrollToItemIndex = (itemIndex: number) => {
+ const cellIndex =
+ itemIndex >= placeholderInsertionIndex ? itemIndex + gallery.pendingPlaceholders.length : itemIndex;
+
+ virtualizer.scrollToIndex(Math.floor(cellIndex / columnCount));
+ };
+
+ useGalleryGridHotkeys({ actionSelectionRefs, columnCount, scrollToItemIndex });
+
useLayoutEffect(() => {
const viewport = viewportRef.current;
@@ -178,7 +142,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
return;
}
- viewportWidthCache.set(layout, width);
+ viewportWidthCache.set(region, width);
setViewportWidth((currentWidth) => (currentWidth === width ? currentWidth : width));
};
@@ -194,7 +158,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
observer.observe(viewport);
return () => observer.disconnect();
- }, [isEmpty, layout]);
+ }, [isEmpty, region]);
useEffect(() => {
measureVirtualizer();
@@ -209,167 +173,6 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
}
}, [actions, lastVisibleRowIndex, paginationMode, rowCount]);
- const parsedSearch = useMemo(() => parseDateTokens(gallery.searchTerm), [gallery.searchTerm]);
- const itemNamesFilter = useMemo<GalleryItemsFilter>(
- () => ({
- boardId: gallery.selectedBoardId,
- ...(parsedSearch.range?.from ? { createdFrom: parsedSearch.range.from } : {}),
- ...(parsedSearch.range?.to ? { createdTo: parsedSearch.range.to } : {}),
- galleryView: gallery.galleryView,
- orderDir: imageOrderDir,
- searchTerm: parsedSearch.text,
- starredFirst,
- }),
- [gallery.galleryView, gallery.selectedBoardId, imageOrderDir, parsedSearch.range, parsedSearch.text, starredFirst]
- );
- const itemNamesFilterIdentity = useMemo(() => JSON.stringify(itemNamesFilter), [itemNamesFilter]);
- const rangeInteractionContextRef = useRef({
- filterIdentity: itemNamesFilterIdentity,
- selectedItemKey: gallery.selectedItemKey,
- });
- const syncRangeInteractionContext = useCallback(
- (node: HTMLDivElement | null) => {
- if (node) {
- rangeInteractionContextRef.current = {
- filterIdentity: itemNamesFilterIdentity,
- selectedItemKey: gallery.selectedItemKey,
- };
- }
- },
- [gallery.selectedItemKey, itemNamesFilterIdentity]
- );
-
- const activeContextMenuTarget = useMemo(() => {
- const primaryTargetItem = contextMenuTarget?.items[0];
-
- if (!primaryTargetItem) {
- return contextMenuTarget;
- }
-
- const primaryTargetItemKey = toGalleryItemKey(primaryTargetItem);
-
- return gallery.items.some((item) => toGalleryItemKey(item) === primaryTargetItemKey) ? contextMenuTarget : null;
- }, [contextMenuTarget, gallery.items]);
-
- const selectItemRange = useCallback(
- async (item: GalleryItem) => {
- const owner = captureAccountScope();
- const capturedContext = rangeInteractionContextRef.current;
- const anchorItemKey = capturedContext.selectedItemKey;
- const targetItemKey = toGalleryItemKey(item);
-
- if (!anchorItemKey) {
- actions.selectItem(item);
- return;
- }
-
- const isInteractionCurrent = () =>
- isAccountScopeCurrent(owner) &&
- rangeInteractionContextRef.current.filterIdentity === capturedContext.filterIdentity &&
- rangeInteractionContextRef.current.selectedItemKey === capturedContext.selectedItemKey;
- const selectFromRefs = (refs: readonly GalleryItemRef[]): boolean => {
- const range = getGalleryItemRange(refs, anchorItemKey, targetItemKey);
-
- if (!range) {
- return false;
- }
-
- actions.selectItemRange(range, item);
- return true;
- };
- const materializedRefs = gallery.items.map(toGalleryItemRef);
- const namesOptions = galleryItemNamesOptions(itemNamesFilter);
-
- try {
- const orderedRefs = isDateBoardId(itemNamesFilter.boardId)
- ? queryClient.getQueryData<GalleryItemNames>(namesOptions.queryKey)?.items
- : (await queryClient.fetchQuery(namesOptions)).items;
-
- if (!isInteractionCurrent()) {
- return;
- }
-
- if (orderedRefs && selectFromRefs(orderedRefs)) {
- return;
- }
- } catch {
- if (!isInteractionCurrent()) {
- return;
- }
- }
-
- if (!selectFromRefs(materializedRefs)) {
- actions.selectItem(item);
- }
- },
- [actions, gallery.items, itemNamesFilter, queryClient]
- );
-
- const handleThumbnailClick = useCallback(
- (item: GalleryItem, event: MouseEvent) => {
- if (event.shiftKey) {
- void selectItemRange(item);
- return;
- }
-
- if (event.altKey && isGalleryImageItem(item)) {
- actions.setCompareItem(item);
- return;
- }
-
- if (event.ctrlKey || event.metaKey) {
- const itemKey = toGalleryItemKey(item);
- const remainingItemKeys = gallery.selectedItemKeys.filter((key) => key !== itemKey);
- const nextPrimaryItem =
- gallery.selectedItemKey === itemKey
- ? (gallery.items.find(
- (candidate) => toGalleryItemKey(candidate) === remainingItemKeys[remainingItemKeys.length - 1]
- ) ?? null)
- : null;
-
- actions.toggleItemInSelection(item, nextPrimaryItem);
- } else {
- actions.selectItem(item);
- }
- },
- [actions, gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys, selectItemRange]
- );
-
- const handleThumbnailContextMenu = useCallback(
- (item: GalleryItem, x: number, y: number) => {
- const itemKey = toGalleryItemKey(item);
-
- if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {
- const itemRefs = selectedItemRefs;
- const selectionItems = [
- item,
- ...gallery.items.filter(
- (candidate) => toGalleryItemKey(candidate) !== itemKey && selectedItemKeys.has(toGalleryItemKey(candidate))
- ),
- ];
-
- setContextMenuTarget({ itemRefs, items: selectionItems, x, y });
- return;
- }
-
- setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y });
- },
- [gallery.items, selectedItemKeys, selectedItemRefs]
- );
-
- const getDragItems = useCallback(
- (item: GalleryItem): GalleryItemRef[] => {
- const itemKey = toGalleryItemKey(item);
-
- if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {
- return selectedItemRefs;
- }
-
- return [toGalleryItemRef(item)];
- },
- [selectedItemKeys, selectedItemRefs]
- );
-
const handleDragEnter = useCallback((event: DragEvent) => {
if (!dragEventContainsFiles(event)) {
return;
@@ -418,108 +221,10 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
}, [account]);
const handleToggleStarred = useCallback(
- (item: GalleryItem) => void itemActions.setItemsStarred([toGalleryItemRef(item)], !item.starred),
+ (item: GalleryItem) => void itemActions.setItemsStarred([{ kind: item.kind, name: item.name }], !item.starred),
[itemActions]
);
- const handleCloseContextMenu = useCallback(() => setContextMenuTarget(null), []);
-
- const actionSelectionRefs = useMemo(
- () =>
- selectedItemRefs.length > 0
- ? selectedItemRefs
- : gallery.selectedItemKey
- ? [parseGalleryItemKey(gallery.selectedItemKey)]
- : [],
- [gallery.selectedItemKey, selectedItemRefs]
- );
-
- const navigate = useEffectEvent((direction: 'down' | 'left' | 'right' | 'up') => {
- const itemCount = gallery.items.length;
-
- if (itemCount === 0) {
- return;
- }
-
- const selectedIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === gallery.selectedItemKey);
- const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;
- const delta =
- direction === 'right' ? 1 : direction === 'left' ? -1 : direction === 'down' ? columnCount : -columnCount;
- const nextIndex = Math.min(itemCount - 1, Math.max(0, fallbackIndex + delta));
- const nextItem = gallery.items[nextIndex];
-
- if (nextItem && (nextIndex !== selectedIndex || selectedIndex === -1)) {
- actions.selectItem(nextItem);
- virtualizer.scrollToIndex(Math.floor(getCellIndexForItem(nextIndex) / columnCount));
- }
- });
-
- const executeGalleryHotkey = useEffectEvent((commandId: string) => {
- if (commandId === 'gallery.selectAllOnPage') {
- const primaryItem = gallery.items[0];
-
- if (primaryItem) {
- actions.selectItemRange(gallery.items.map(toGalleryItemRef), primaryItem);
- }
- return;
- }
-
- if (commandId === 'gallery.clearSelection') {
- widgets.patchGalleryValues({
- selectedImage: null,
- selectedImageName: null,
- selectedImageNames: [],
- });
- return;
- }
-
- if (commandId === 'gallery.deleteSelection' && actionSelectionRefs.length > 0) {
- void itemActions.deleteItems(actionSelectionRefs);
- return;
- }
-
- if (commandId === 'gallery.starImage' && actionSelectionRefs.length > 0) {
- const loadedItemsByKey = new Map(gallery.items.map((item) => [toGalleryItemKey(item), item]));
- const shouldStar = actionSelectionRefs.some((ref) => !loadedItemsByKey.get(toGalleryItemKey(ref))?.starred);
-
- void itemActions.setItemsStarred(actionSelectionRefs, shouldStar);
- }
- });
-
- useEffect(() => {
- const directions = [
- ['gallery.selectAllOnPage', t('widgets.gallery.commands.selectAllOnPage'), null, ['mod+a']],
- ['gallery.clearSelection', t('widgets.gallery.commands.clearSelection'), null, ['esc']],
- ['gallery.galleryNavUp', t('widgets.gallery.commands.navigationUp'), 'up', ['arrowup']],
- ['gallery.galleryNavRight', t('widgets.gallery.commands.navigationRight'), 'right', ['arrowright']],
- ['gallery.galleryNavDown', t('widgets.gallery.commands.navigationDown'), 'down', ['arrowdown']],
- ['gallery.galleryNavLeft', t('widgets.gallery.commands.navigationLeft'), 'left', ['arrowleft']],
- ['gallery.galleryNavUpAlt', t('widgets.gallery.commands.navigationUp'), 'up', ['alt+arrowup']],
- ['gallery.galleryNavRightAlt', t('widgets.gallery.commands.navigationRight'), 'right', ['alt+arrowright']],
- ['gallery.galleryNavDownAlt', t('widgets.gallery.commands.navigationDown'), 'down', ['alt+arrowdown']],
- ['gallery.galleryNavLeftAlt', t('widgets.gallery.commands.navigationLeft'), 'left', ['alt+arrowleft']],
- ['gallery.deleteSelection', t('widgets.gallery.commands.deleteSelection'), null, ['delete', 'backspace']],
- ['gallery.starImage', t('widgets.gallery.commands.toggleStarImage'), null, ['.']],
- ] as const;
- const disposers = directions.flatMap(([id, title, direction, defaultKeys]) => [
- runtime.commands.register({
- handler: () => (direction ? navigate(direction) : executeGalleryHotkey(id)),
- id,
- title,
- }),
- runtime.hotkeys.register({
- commandId: id,
- defaultKeys: [...defaultKeys],
- id,
- title,
- }),
- ]);
-
- return () => {
- disposers.forEach((dispose) => dispose());
- };
- }, [runtime.commands, runtime.hotkeys, t]);
-
return (
<Box
ref={syncRangeInteractionContext}
@@ -542,14 +247,14 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
</Flex>
) : (
<ScrollArea.Root h="full" minH="0" size="xs" variant="hover" w="full">
- <ScrollArea.Viewport ref={viewportRef} h="full" w="full" outline="none">
+ <ScrollArea.Viewport ref={viewportRef} h="full" outline="none" w="full">
<ScrollArea.Content aria-label={t('widgets.gallery.itemsAriaLabel')} role="list">
<Box h={`${virtualizer.totalSize}px`} position="relative" w="full">
{virtualRows.map((virtualRow) => (
<Box
key={virtualRow.key}
display="grid"
- gap={`${GRID_GAP_PX}px`}
+ gap={`${GALLERY_GRID_GAP_PX}px`}
gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}
left="0"
position="absolute"
@@ -577,6 +282,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
<GalleryThumbnailCell
key={toGalleryItemKey(cell.item)}
alwaysShowDimensions={showImageDimensions}
+ dragScope={region}
compareRole={
isComparisonActive && toGalleryItemKey(cell.item) === gallery.selectedItemKey
? t('widgets.preview.viewing')
@@ -586,9 +292,9 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
}
fit={thumbnailFit}
getDragItems={getDragItems}
- item={cell.item}
isPrimary={!isFollowingLive && toGalleryItemKey(cell.item) === gallery.selectedItemKey}
isSelected={!isFollowingLive && selectedItemKeys.has(toGalleryItemKey(cell.item))}
+ item={cell.item}
onClick={handleThumbnailClick}
onContextMenu={handleThumbnailContextMenu}
onToggleStarred={handleToggleStarred}
@@ -641,288 +347,3 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
</Box>
);
};
-
-const GalleryQueuePlaceholderCell = ({
- antialiasProgressImages,
- fit,
- isSelected,
- onClick,
- placeholder,
-}: {
- antialiasProgressImages: boolean;
- fit: GalleryThumbnailFit;
- isSelected: boolean;
- onClick: () => void;
- placeholder: GalleryQueuePlaceholder;
-}) => {
- const { t } = useTranslation();
- const progressImage = useQueueItemProgressImage(placeholder.queueItemId, placeholder.itemIndex);
- const progress = useQueueItemProgress(placeholder.queueItemId);
- const isActive = progress?.activeItemIndex === placeholder.itemIndex;
- const percentage = typeof progress?.percentage === 'number' ? Math.round(progress.percentage * 100) : null;
-
- return (
- <Box aspectRatio={1} minW="0" role="listitem" w="full">
- <Box
- as="button"
- aria-label={t('widgets.preview.showInProgressDiffusion')}
- aria-pressed={isSelected}
- bg="bg"
- borderColor={isSelected ? 'accent.solid' : 'border.subtle'}
- borderWidth={isSelected ? '2px' : '1px'}
- cursor="pointer"
- h="full"
- overflow="hidden"
- position="relative"
- rounded="md"
- w="full"
- onClick={onClick}
- >
- <StreamingImageFrame
- fit={fit === 'aspect' ? 'contain' : 'cover'}
- h="full"
- liveImage={progressImageToStreamingSource(progressImage)}
- shouldAntialiasLiveImage={antialiasProgressImages}
- w="full"
- >
- <Skeleton h="full" w="full" />
- </StreamingImageFrame>
- {isActive ? <GalleryPlaceholderCircularProgress percentage={percentage} /> : null}
- </Box>
- </Box>
- );
-};
-
-const GalleryPlaceholderCircularProgress = ({ percentage }: { percentage: number | null }) => {
- const { t } = useTranslation();
-
- return (
- <Flex
- align="center"
- justify="center"
- alignItems="center"
- pointerEvents="none"
- position="absolute"
- inset="0"
- zIndex="1"
- >
- <ProgressCircle.Root
- aria-label={
- percentage === null
- ? t('widgets.gallery.generationProgress')
- : t('widgets.gallery.generationProgressPercent', { percentage })
- }
- bg="bg/85"
- borderWidth={1}
- p={0.5}
- rounded="full"
- size="xs"
- value={percentage}
- >
- <ProgressCircle.Circle>
- <ProgressCircle.Track />
- <ProgressCircle.Range />
- </ProgressCircle.Circle>
- </ProgressCircle.Root>
- </Flex>
- );
-};
-
-const GalleryThumbnail = ({
- alwaysShowDimensions,
- compareRole,
- dragItems,
- fit,
- item,
- isPrimary,
- isSelected,
- onClick,
- onContextMenu,
- onToggleStarred,
-}: {
- alwaysShowDimensions: boolean;
- compareRole: string | null;
- dragItems: GalleryItemRef[];
- fit: GalleryThumbnailFit;
- item: GalleryItem;
- isPrimary: boolean;
- isSelected: boolean;
- onClick: (item: GalleryItem, event: MouseEvent) => void;
- onContextMenu: (item: GalleryItem, x: number, y: number) => void;
- onToggleStarred: (item: GalleryItem) => void;
-}) => {
- const { t } = useTranslation();
- const isCompared = compareRole !== null;
- const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;
-
- const { isDragging, listeners, setNodeRef, transform } = useDraggable({
- data: getGalleryItemDragData(dragItems),
- id: getGalleryItemDragId(toGalleryItemRef(item), 'gallery-grid'),
- });
-
- const containerStyle = useMemo(() => ({ transform: CSS.Transform.toString(transform) }), [transform]);
-
- const imageStyle = useMemo(
- () =>
- ({
- display: 'block',
- height: '100%',
- inset: 0,
- maxWidth: 'none',
- objectFit: fit === 'aspect' ? 'contain' : 'cover',
- position: 'absolute',
- width: '100%',
- }) as const,
- [fit]
- );
-
- const handleContextMenu = useCallback(
- (event: MouseEvent) => {
- event.preventDefault();
- onContextMenu(item, event.clientX, event.clientY);
- },
- [item, onContextMenu]
- );
-
- const handleClick = useCallback((event: MouseEvent) => onClick(item, event), [item, onClick]);
- const handleActivationKeyDown = useCallback((event: KeyboardEvent<HTMLButtonElement>) => {
- if (event.key === 'Enter' || event.key === ' ') {
- event.stopPropagation();
- }
- }, []);
-
- const handleToggleStarred = useCallback(
- (event: MouseEvent<HTMLButtonElement>) => {
- event.stopPropagation();
-
- onToggleStarred(item);
- },
- [item, onToggleStarred]
- );
-
- return (
- <Box
- ref={setNodeRef}
- {...listeners}
- aspectRatio={1}
- bg="bg"
- borderWidth="2px"
- borderColor={isSelected || isCompared ? 'accent.solid' : 'border.subtle'}
- boxShadow={isCompared ? 'inset 0 0 0 1px {colors.accent.solid}' : undefined}
- css={THUMBNAIL_HOVER_CSS}
- minW="0"
- opacity={isDragging ? 0.55 : undefined}
- overflow="hidden"
- role="listitem"
- position="relative"
- rounded="md"
- style={containerStyle}
- touchAction="none"
- w="full"
- zIndex={isDragging ? 2 : undefined}
- onContextMenu={handleContextMenu}
- >
- <button
- aria-current={isPrimary ? 'true' : undefined}
- aria-label={
- item.kind === 'video'
- ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })
- : t('widgets.gallery.selectImageForPreview', { name: item.name })
- }
- aria-pressed={isSelected}
- style={THUMBNAIL_BUTTON_STYLE}
- type="button"
- onClick={handleClick}
- onKeyDown={handleActivationKeyDown}
- >
- <img
- alt={item.name}
- decoding={item.kind === 'video' ? 'async' : undefined}
- draggable={false}
- src={item.thumbnailUrl || item.fullUrl}
- style={imageStyle}
- />
- </button>
- {compareRole && (
- <Badge
- insetInlineStart="1"
- pointerEvents="none"
- position="absolute"
- size="xs"
- top="1"
- variant="solid"
- zIndex="1"
- >
- {compareRole}
- </Badge>
- )}
- <IconButton
- aria-label={
- item.starred
- ? t('widgets.gallery.unstarImage', { name: item.name })
- : t('widgets.gallery.starImage', { name: item.name })
- }
- className="gallery-thumb-overlay"
- colorPalette={item.starred ? 'yellow' : 'gray'}
- insetInlineEnd="1"
- opacity={item.starred ? 1 : 0}
- position="absolute"
- size="2xs"
- top="1"
- transition="opacity var(--wb-motion-duration-medium) ease"
- variant="solid"
- zIndex="1"
- onClick={handleToggleStarred}
- >
- <StarIcon fill={item.starred ? 'currentColor' : 'none'} />
- </IconButton>
- {item.kind === 'image' && item.width > 0 && item.height > 0 && (
- <Badge
- bottom="1"
- className="gallery-thumb-overlay"
- insetInlineStart="1"
- opacity={alwaysShowDimensions ? 1 : 0}
- pointerEvents="none"
- position="absolute"
- size="xs"
- transition="opacity var(--wb-motion-duration-medium) ease"
- variant="solid"
- zIndex="1"
- >
- {item.width}x{item.height}
- </Badge>
- )}
- {duration !== null && (
- <Badge
- bottom="1"
- display="flex"
- fontVariantNumeric="tabular-nums"
- gap="1"
- insetInlineStart="1"
- opacity={1}
- pointerEvents="none"
- position="absolute"
- size="xs"
- transition="opacity var(--wb-motion-duration-medium) ease"
- variant="solid"
- zIndex="1"
- >
- <PlayIcon aria-hidden="true" fill="currentColor" />
- {duration}
- </Badge>
- )}
- </Box>
- );
-};
-
-const GalleryThumbnailCell = ({
- item,
- getDragItems,
- ...props
-}: Omit<Parameters<typeof GalleryThumbnail>[0], 'dragItems'> & {
- getDragItems: (item: GalleryItem) => GalleryItemRef[];
-}) => {
- const dragItems = useMemo(() => getDragItems(item), [getDragItems, item]);
-
- return <GalleryThumbnail {...props} dragItems={dragItems} item={item} />;
-};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx
new file mode 100644
index 0000000000..2a0a0ee74a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx
@@ -0,0 +1,70 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GalleryItemSearch } from './GalleryItemSearch';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en' },
+ t: (key: string) => key,
+ }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderSearch = async () => {
+ const contextValue = {
+ actions: { setSearchTerm: vi.fn() },
+ gallery: { searchTerm: '' },
+ } as unknown as GalleryWidgetContextValue;
+
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <GalleryWidgetContext value={contextValue}>
+ <GalleryItemSearch />
+ </GalleryWidgetContext>
+ </ChakraProvider>
+ );
+ });
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ document.querySelectorAll('[data-scope="popover"][data-part="positioner"]').forEach((element) => element.remove());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GalleryItemSearch help', () => {
+ it('shows the relative value in a valid prefixed token', async () => {
+ await renderSearch();
+ const trigger = host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.searchHelpTitle"]');
+
+ await act(async () => {
+ trigger?.click();
+ await Promise.resolve();
+ });
+
+ const examples = Array.from(document.querySelectorAll('code')).map((element) => element.textContent);
+
+ expect(examples).toContain('from:7d');
+ expect(examples).not.toContain('7d');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx
new file mode 100644
index 0000000000..e80d1283a1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx
@@ -0,0 +1,152 @@
+import { Box, Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';
+import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';
+import { CloseButton, IconButton } from '@platform/ui/Button';
+import { CircleHelpIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GallerySearchField } from './GallerySearchField';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const SEARCH_DATE_HINT_ID = 'gallery-search-date-hint';
+const HELP_POSITIONING = { placement: 'bottom-end' } as const;
+
+/** The `key:value` forms `parseDateTokens` accepts, as shown in the help popover. */
+const DATE_TOKEN_EXAMPLES = [
+ { descriptionKey: 'widgets.gallery.searchHelpFrom', key: 'from:2026-07-14' },
+ { descriptionKey: 'widgets.gallery.searchHelpTo', key: 'to:yesterday' },
+ { descriptionKey: 'widgets.gallery.searchHelpDate', key: 'date:today' },
+ { descriptionKey: 'widgets.gallery.searchHelpRelative', key: 'from:7d' },
+] as const;
+
+export const GalleryItemSearch = () => {
+ const { i18n, t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+
+ const handleClearSearch = useCallback(() => actions.setSearchTerm(''), [actions]);
+
+ // Valid tokens are legible as chips in the field itself, so only the failure
+ // case still needs words — and it is positioned out of flow. As a sibling it
+ // grew the field's row and knocked the wide header out of vertical centre.
+ const invalidHint = useMemo(() => {
+ const parse = parseDateTokens(gallery.searchTerm);
+ const invalid = findInvalidDateToken(gallery.searchTerm, parse);
+
+ return invalid ? t('widgets.gallery.dateFilterInvalid', { value: invalid.raw }) : null;
+ }, [gallery.searchTerm, t]);
+
+ // The chips show which text is a filter, not what it resolved to, so the
+ // resolved range stays available to assistive tech.
+ const appliedRange = useMemo(() => {
+ const parse = parseDateTokens(gallery.searchTerm);
+ const shape = parse.range ? describeDateRange(parse.range) : null;
+
+ if (!shape) {
+ return null;
+ }
+
+ const locale = i18n.language;
+
+ switch (shape.kind) {
+ case 'day':
+ return t('widgets.gallery.dateFilterDay', { date: formatIsoDate(shape.date, locale) });
+ case 'range':
+ return t('widgets.gallery.dateFilterRange', {
+ from: formatIsoDate(shape.from, locale),
+ to: formatIsoDate(shape.to, locale),
+ });
+ case 'from':
+ return t('widgets.gallery.dateFilterFrom', { date: formatIsoDate(shape.date, locale) });
+ case 'through':
+ return t('widgets.gallery.dateFilterThrough', { date: formatIsoDate(shape.date, locale) });
+ }
+ }, [gallery.searchTerm, i18n.language, t]);
+
+ const endElement = useMemo(
+ () => (
+ <HStack flexShrink={0} gap="0">
+ {gallery.searchTerm ? (
+ <CloseButton aria-label={t('common.clearSearch')} size="2xs" onClick={handleClearSearch} />
+ ) : null}
+ <GallerySearchHelp />
+ </HStack>
+ ),
+ [gallery.searchTerm, handleClearSearch, t]
+ );
+
+ return (
+ <Box minW="0" position="relative" w="full">
+ <GallerySearchField
+ ariaLabel={t('widgets.gallery.searchImagesAriaLabel')}
+ describedById={invalidHint ? SEARCH_DATE_HINT_ID : undefined}
+ endElement={endElement}
+ isInvalid={invalidHint !== null}
+ placeholder={t('widgets.gallery.searchImagesPlaceholder')}
+ value={gallery.searchTerm}
+ onChange={actions.setSearchTerm}
+ />
+ {invalidHint ? (
+ <Text
+ color="fg.error"
+ fontSize="2xs"
+ id={SEARCH_DATE_HINT_ID}
+ insetInlineStart="0"
+ // Out of flow and inert: it must never shift the header row, nor
+ // swallow clicks meant for the grid it now floats over.
+ pointerEvents="none"
+ position="absolute"
+ role="status"
+ top="100%"
+ >
+ {invalidHint}
+ </Text>
+ ) : null}
+ {appliedRange ? (
+ <Text role="status" srOnly>
+ {appliedRange}
+ </Text>
+ ) : null}
+ </Box>
+ );
+};
+
+/** Documents the closed date-token grammar the search box accepts. */
+const GallerySearchHelp = () => {
+ const { t } = useTranslation();
+
+ return (
+ <Popover.Root positioning={HELP_POSITIONING}>
+ <Popover.Trigger asChild>
+ <IconButton aria-label={t('widgets.gallery.searchHelpTitle')} color="fg.subtle" size="2xs" variant="ghost">
+ <Icon as={CircleHelpIcon} boxSize="3.5" />
+ </IconButton>
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content maxW="18rem" p="3">
+ <Stack gap="2">
+ <Text fontSize="xs" fontWeight="600">
+ {t('widgets.gallery.searchHelpTitle')}
+ </Text>
+ <Text color="fg.muted" fontSize="2xs">
+ {t('widgets.gallery.searchHelpIntro')}
+ </Text>
+ <Stack gap="1.5">
+ {DATE_TOKEN_EXAMPLES.map(({ descriptionKey, key }) => (
+ <HStack key={key} align="start" gap="2">
+ <Code flexShrink={0} fontSize="2xs" px="1">
+ {key}
+ </Code>
+ <Text color="fg.muted" fontSize="2xs">
+ {t(descriptionKey)}
+ </Text>
+ </HStack>
+ ))}
+ </Stack>
+ </Stack>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx
new file mode 100644
index 0000000000..edcbefadbc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx
@@ -0,0 +1,79 @@
+import type { GalleryOrderDir } from '@features/gallery/core/types';
+
+import { Icon, Menu, Portal } from '@chakra-ui/react';
+import { Button } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { ChevronDownIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const SORT_POSITIONING = { placement: 'bottom-end' } as const;
+
+/**
+ * Grid ordering, promoted out of the settings popover: which end of the board
+ * you are looking at is a decision made constantly, not a preference set once.
+ */
+export const GalleryItemSortMenu = () => {
+ const { t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+ const { imageOrderDir, starredFirst } = gallery.settings;
+
+ const handleOrderDirChange = useCallback(
+ (event: { value: string }) => actions.updateSettings({ imageOrderDir: event.value as GalleryOrderDir }),
+ [actions]
+ );
+
+ const handleStarredFirstChange = useCallback(
+ (starredFirst: boolean) => actions.updateSettings({ starredFirst }),
+ [actions]
+ );
+
+ return (
+ <Menu.Root positioning={SORT_POSITIONING}>
+ <Menu.Trigger asChild>
+ <Button
+ aria-label={t('widgets.gallery.imageSort')}
+ color="fg.muted"
+ flexShrink={0}
+ fontSize="xs"
+ gap="1"
+ size="xs"
+ variant="ghost"
+ >
+ {imageOrderDir === 'DESC' ? t('widgets.gallery.newest') : t('widgets.gallery.oldest')}
+ <Icon as={ChevronDownIcon} boxSize="3" />
+ </Button>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="11rem">
+ <Menu.RadioItemGroup value={imageOrderDir} onValueChange={handleOrderDirChange}>
+ <Menu.RadioItem value="DESC">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('widgets.gallery.newest')}</Menu.ItemText>
+ </Menu.RadioItem>
+ <Menu.RadioItem value="ASC">
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('widgets.gallery.oldest')}</Menu.ItemText>
+ </Menu.RadioItem>
+ </Menu.RadioItemGroup>
+ <Menu.Separator />
+ {/* A real checkbox item rather than a Switch smuggled into a menu
+ item, which needed closeOnSelect + a click-swallower to behave. */}
+ <Menu.CheckboxItem
+ checked={starredFirst}
+ closeOnSelect={false}
+ value="starred-first"
+ onCheckedChange={handleStarredFirstChange}
+ >
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('widgets.gallery.showStarredImagesFirst')}</Menu.ItemText>
+ </Menu.CheckboxItem>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
new file mode 100644
index 0000000000..da953a9cfb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
@@ -0,0 +1,310 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryBoard } from '@features/gallery/core/types';
+import type { GalleryUiAdapter } from '@features/gallery/react';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
+import { GalleryUiProvider } from '@features/gallery/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryStateView } from './galleryStateView';
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GalleryStackedLayout } from './GalleryStackedLayout';
+import { GalleryWideLayout } from './GalleryWideLayout';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+vi.mock('@features/queue/react', () => ({
+ useQueueItemProgress: () => null,
+ useQueueItemProgressImage: () => null,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en' },
+ t: (key: string, values?: Record<string, unknown>) =>
+ key === 'widgets.gallery.selectionCount' ? `${String(values?.count)} selected` : key,
+ }),
+}));
+
+const board: GalleryBoard = {
+ archived: false,
+ assetCount: 3,
+ id: 'dogs',
+ imageCount: 50,
+ kind: 'board',
+ name: 'dogs',
+ videoCount: 0,
+};
+
+const createItem = (name: string) => ({
+ boardId: 'dogs',
+ category: 'general',
+ createdAt: '2026-07-30T00:00:00.000Z',
+ fullUrl: `/full/${name}`,
+ height: 64,
+ isIntermediate: false,
+ kind: 'image',
+ name,
+ starred: false,
+ thumbnailUrl: `/thumb/${name}`,
+ width: 64,
+});
+
+const createGallery = (overrides: Partial<GalleryStateView> = {}) =>
+ ({
+ boards: [board],
+ compareImageKey: null,
+ currentItem: null,
+ galleryView: 'images',
+ isLoading: false,
+ items: [createItem('a.png'), createItem('b.png')],
+ pendingPlaceholders: [],
+ projectBoardId: null,
+ searchTerm: '',
+ selectedBoardId: 'dogs',
+ selectedItemKey: 'image:a.png',
+ selectedItemKeys: ['image:a.png', 'image:b.png'],
+ settings: DEFAULT_GALLERY_SETTINGS,
+ ...overrides,
+ }) as unknown as GalleryStateView;
+
+const gallery = createGallery();
+
+let region: GalleryWidgetContextValue['region'] = 'center';
+let activeGallery: GalleryStateView = gallery;
+
+const setRegion = (next: GalleryWidgetContextValue['region']) => {
+ region = next;
+};
+
+const setGallery = (next: GalleryStateView) => {
+ activeGallery = next;
+};
+
+const createContextValue = () =>
+ ({
+ ...contextBase,
+ gallery: activeGallery,
+ region,
+ }) as unknown as GalleryWidgetContextValue;
+
+const contextBase = {
+ actions: {
+ createBoard: vi.fn(),
+ loadMore: vi.fn(),
+ selectBoard: vi.fn(),
+ selectProjectBoard: vi.fn(),
+ setSearchTerm: vi.fn(),
+ setView: vi.fn(),
+ updateSettings: vi.fn(),
+ uploadFiles: vi.fn(),
+ },
+ filter: { boardId: 'dogs', galleryView: 'images', searchTerm: '' },
+ gallery,
+ isWindowTruncated: false,
+ itemActions: {
+ deleteItems: vi.fn(),
+ downloadItems: vi.fn(),
+ moveItemsToBoard: vi.fn(),
+ setItemsStarred: vi.fn(),
+ },
+ projectName: 'Project',
+ runtime: {
+ commands: { register: () => () => undefined },
+ hotkeys: { register: () => () => undefined },
+ },
+};
+
+const adapter = {
+ ImageContextMenu: () => null,
+ account: { enableLiveFollow: vi.fn() },
+ antialiasProgressImages: false,
+ widgets: { 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 renderLayout = async (Layout: typeof GalleryStackedLayout | typeof GalleryWideLayout) => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient!}>
+ <GalleryUiProvider adapter={adapter}>
+ <GalleryWidgetContext value={createContextValue()}>
+ <DndContext>
+ <Layout />
+ </DndContext>
+ </GalleryWidgetContext>
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+};
+
+/**
+ * The slots every shell owes, identified the way a user would find them. If a
+ * shell drops one, the redesign's central promise — same components, different
+ * arrangement — has been broken.
+ */
+const findSlots = () => ({
+ boardSearch: host?.querySelector('input[aria-label="widgets.gallery.searchOrCreateBoards"]') ?? null,
+ boardsSection: host?.querySelector('[data-scope="collapsible"]') ?? null,
+ grid: host?.querySelector('[role="list"]') ?? null,
+ itemSearch: host?.querySelector('input[aria-label="widgets.gallery.searchImagesAriaLabel"]') ?? null,
+ selectionBar: host?.querySelector('[role="toolbar"]') ?? null,
+ sort: host?.querySelector('button[aria-label="widgets.gallery.imageSort"]') ?? null,
+ tabs: host?.querySelector('[role="radiogroup"]') ?? null,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setRegion('center');
+ setGallery(gallery);
+ host = document.createElement('div');
+ host.style.cssText = 'height:600px;left:0;position:fixed;top:0;width:900px;';
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ queryClient = null;
+});
+
+describe('gallery layout shells', () => {
+ it('renders every slot in the stacked shell', async () => {
+ await renderLayout(GalleryStackedLayout);
+
+ for (const [name, element] of Object.entries(findSlots())) {
+ expect(element, `stacked shell is missing the ${name} slot`).not.toBeNull();
+ }
+ });
+
+ it('renders every slot in the wide shell', async () => {
+ await renderLayout(GalleryWideLayout);
+
+ for (const [name, element] of Object.entries(findSlots())) {
+ expect(element, `wide shell is missing the ${name} slot`).not.toBeNull();
+ }
+ });
+
+ it('gives each shell a resize handle for the axis it splits on', async () => {
+ await renderLayout(GalleryStackedLayout);
+ expect(host?.querySelector('[role="separator"]')?.getAttribute('aria-orientation')).toBe('horizontal');
+
+ await renderLayout(GalleryWideLayout);
+ expect(host?.querySelector('[role="separator"]')?.getAttribute('aria-orientation')).toBe('vertical');
+ });
+
+ it('keeps a long board list inside the board panel instead of spilling it over the grid', async () => {
+ const boards = Array.from({ length: 40 }, (_, index) => ({
+ ...board,
+ id: `board-${index}`,
+ name: `Board ${index}`,
+ }));
+
+ setGallery(createGallery({ boards, selectedBoardId: 'board-0' }));
+ await renderLayout(GalleryStackedLayout);
+
+ const viewport = host?.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]');
+
+ if (!viewport) {
+ throw new Error('board panel viewport did not render');
+ }
+
+ // The panel has a definite height, so 40 boards have to scroll rather than
+ // push the list past its box and over the grid below it.
+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);
+ expect(viewport.getBoundingClientRect().height).toBeLessThanOrEqual(DEFAULT_GALLERY_SETTINGS.boardPanelHeightPx);
+
+ const grid = host?.querySelector('[role="list"]');
+ const panelBottom = viewport.getBoundingClientRect().bottom;
+
+ expect(grid?.getBoundingClientRect().top).toBeGreaterThanOrEqual(panelBottom);
+ });
+
+ it('clamps a persisted tall stacked panel to preserve the grid, then restores it without rewriting settings', async () => {
+ host!.style.height = '480px';
+ setGallery(createGallery({ settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelHeightPx: 600 } }));
+ await renderLayout(GalleryStackedLayout);
+
+ const separator = host?.querySelector<HTMLElement>('[role="separator"]');
+ const gridWrapper = host?.querySelector<HTMLElement>('[data-gallery-grid-wrapper]');
+
+ await vi.waitFor(() => expect(Number(separator?.getAttribute('aria-valuemax'))).toBeLessThan(600));
+ const shortMaximum = Number(separator?.getAttribute('aria-valuemax'));
+
+ expect(Number(separator?.getAttribute('aria-valuenow'))).toBe(shortMaximum);
+ expect(gridWrapper?.getBoundingClientRect().height).toBeGreaterThanOrEqual(128);
+ expect(contextBase.actions.updateSettings).not.toHaveBeenCalled();
+
+ host!.style.height = '1000px';
+
+ await vi.waitFor(() => expect(separator?.getAttribute('aria-valuenow')).toBe('600'));
+ expect(contextBase.actions.updateSettings).not.toHaveBeenCalled();
+ });
+
+ it('bounds stacked pointer and keyboard resizing by the measured maximum', async () => {
+ host!.style.height = '480px';
+ setGallery(createGallery({ settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelHeightPx: 600 } }));
+ await renderLayout(GalleryStackedLayout);
+
+ const separator = host?.querySelector<HTMLElement>('[role="separator"]');
+
+ await vi.waitFor(() => expect(Number(separator?.getAttribute('aria-valuemax'))).toBeLessThan(600));
+ const measuredMaximum = Number(separator?.getAttribute('aria-valuemax'));
+
+ await act(() => separator?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'End' })));
+ expect(contextBase.actions.updateSettings).toHaveBeenLastCalledWith({ boardPanelHeightPx: measuredMaximum });
+
+ contextBase.actions.updateSettings.mockClear();
+ await act(() => {
+ separator?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientY: 0 }));
+ window.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, clientY: 5_000 }));
+ window.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, clientY: 5_000 }));
+ });
+
+ expect(contextBase.actions.updateSettings).toHaveBeenLastCalledWith({ boardPanelHeightPx: measuredMaximum });
+ });
+
+ it('never renders upload or settings in the body, in either shell or any region', async () => {
+ // The widget frame owns them now (see GalleryWidgetChrome). Rendering them
+ // here too would double the controls in every placement.
+ for (const region of ['center', 'right'] as const) {
+ for (const Layout of [GalleryStackedLayout, GalleryWideLayout]) {
+ setRegion(region);
+ await renderLayout(Layout);
+
+ expect(host?.querySelector('button[aria-label^="widgets.gallery.upload"]'), region).toBeNull();
+ expect(host?.querySelector('button[aria-label="widgets.gallery.settings"]'), region).toBeNull();
+ expect(host?.querySelector('[role="radiogroup"]'), 'the rest of the row still renders').not.toBeNull();
+ }
+ }
+ });
+
+ it('hides the board column and its handle in both shells when collapsed', async () => {
+ setGallery(createGallery({ settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelCollapsed: true } }));
+
+ for (const Layout of [GalleryStackedLayout, GalleryWideLayout]) {
+ await renderLayout(Layout);
+
+ expect(host?.querySelector('input[aria-label="widgets.gallery.searchOrCreateBoards"]')).toBeNull();
+ expect(host?.querySelector('[role="separator"]')).toBeNull();
+ expect(host?.querySelector('[role="list"]'), 'the grid still renders').not.toBeNull();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx
new file mode 100644
index 0000000000..b4293435d1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx
@@ -0,0 +1,23 @@
+import { Box } from '@chakra-ui/react';
+
+import type { GalleryWidgetProps } from './GalleryUiContext';
+
+import { useGalleryLayout } from './galleryDensity';
+import { GalleryStackedLayout } from './GalleryStackedLayout';
+import { GalleryWideLayout } from './GalleryWideLayout';
+
+/**
+ * The single place in the gallery that knows how much room it has. Everything
+ * below is layout-blind: the two shells arrange one identical set of slot
+ * components, so swapping between them is a rendering decision rather than a
+ * behavioural one.
+ */
+export const GalleryLayout = ({ region }: { region: GalleryWidgetProps['region'] }) => {
+ const { layout, rootRef } = useGalleryLayout(region);
+
+ return (
+ <Box ref={rootRef} h="full" maxW="full" minH="0" minW="0" w="full">
+ {layout === 'wide' ? <GalleryWideLayout /> : <GalleryStackedLayout />}
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryPanelContent.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryPanelContent.tsx
deleted file mode 100644
index f1a32d9c4c..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryPanelContent.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { Stack } from '@chakra-ui/react';
-
-import { GalleryImageGrid } from './GalleryImageGrid';
-import { GalleryToolbar } from './GalleryToolbar';
-
-/**
- * The center region floats its chrome over the work surface and publishes the
- * clearance as `--wb-center-chrome-inset`. The gallery toolbar is top-anchored
- * and full width, so it adds that clearance to its own padding; every other
- * placement leaves the variable undefined and resolves to the plain padding.
- */
-export const GalleryPanelContent = ({ layout }: { layout: 'stacked' | 'wide' }) => {
- const padding = layout === 'stacked' ? '2' : '3';
-
- return (
- <Stack
- gap="3"
- p={padding}
- paddingTop={`calc(var(--chakra-spacing-${padding}) + var(--wb-center-chrome-inset, 0px))`}
- h="full"
- maxW="full"
- minH="0"
- minW="0"
- w="full"
- >
- <GalleryToolbar layout={layout} />
- <GalleryImageGrid layout={layout} />
- </Stack>
- );
-};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx
new file mode 100644
index 0000000000..0af92e3f3c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx
@@ -0,0 +1,96 @@
+import type { GalleryThumbnailFit } from '@features/gallery/core/settings';
+
+import { Box, Flex, ProgressCircle, Skeleton } from '@chakra-ui/react';
+import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';
+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';
+import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';
+import { useTranslation } from 'react-i18next';
+
+import type { GalleryQueuePlaceholder } from './galleryStateView';
+
+/** Grid tile standing in for an in-flight queue item bound for the current board. */
+export const GalleryQueuePlaceholderCell = ({
+ antialiasProgressImages,
+ fit,
+ isSelected,
+ placeholder,
+ onClick,
+}: {
+ antialiasProgressImages: boolean;
+ fit: GalleryThumbnailFit;
+ isSelected: boolean;
+ placeholder: GalleryQueuePlaceholder;
+ onClick: () => void;
+}) => {
+ const { t } = useTranslation();
+ const progressImage = useQueueItemProgressImage(placeholder.queueItemId, placeholder.itemIndex);
+ const progress = useQueueItemProgress(placeholder.queueItemId);
+ const isActive = progress?.activeItemIndex === placeholder.itemIndex;
+ const percentage = typeof progress?.percentage === 'number' ? Math.round(progress.percentage * 100) : null;
+
+ return (
+ <Box aspectRatio={1} minW="0" role="listitem" w="full">
+ <Box
+ as="button"
+ aria-label={t('widgets.preview.showInProgressDiffusion')}
+ aria-pressed={isSelected}
+ bg="bg"
+ borderColor={isSelected ? 'accent.solid' : 'border.subtle'}
+ borderWidth={isSelected ? '2px' : '1px'}
+ cursor="pointer"
+ h="full"
+ overflow="hidden"
+ position="relative"
+ rounded="md"
+ w="full"
+ onClick={onClick}
+ >
+ <StreamingImageFrame
+ fit={fit === 'aspect' ? 'contain' : 'cover'}
+ h="full"
+ liveImage={progressImageToStreamingSource(progressImage)}
+ shouldAntialiasLiveImage={antialiasProgressImages}
+ w="full"
+ >
+ <Skeleton h="full" w="full" />
+ </StreamingImageFrame>
+ {isActive ? <GalleryPlaceholderCircularProgress percentage={percentage} /> : null}
+ </Box>
+ </Box>
+ );
+};
+
+const GalleryPlaceholderCircularProgress = ({ percentage }: { percentage: number | null }) => {
+ const { t } = useTranslation();
+
+ return (
+ <Flex
+ align="center"
+ alignItems="center"
+ inset="0"
+ justify="center"
+ pointerEvents="none"
+ position="absolute"
+ zIndex="1"
+ >
+ <ProgressCircle.Root
+ aria-label={
+ percentage === null
+ ? t('widgets.gallery.generationProgress')
+ : t('widgets.gallery.generationProgressPercent', { percentage })
+ }
+ bg="bg/85"
+ borderWidth={1}
+ p={0.5}
+ rounded="full"
+ size="xs"
+ value={percentage}
+ >
+ <ProgressCircle.Circle>
+ <ProgressCircle.Track />
+ <ProgressCircle.Range />
+ </ProgressCircle.Circle>
+ </ProgressCircle.Root>
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx
new file mode 100644
index 0000000000..38a82d68c7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx
@@ -0,0 +1,161 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { parseDateTokens } from '@platform/search/dateTokens';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GallerySearchField, getGallerySearchSegments } from './GallerySearchField';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const onChange = vi.fn();
+
+const renderField = async (value: string, isInvalid = false) => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GallerySearchField
+ ariaLabel="Search gallery items"
+ isInvalid={isInvalid}
+ placeholder="Search items"
+ value={value}
+ onChange={onChange}
+ />
+ </ChakraProvider>
+ )
+ );
+};
+
+const getInput = (): HTMLInputElement => {
+ const input = host?.querySelector('input');
+
+ if (!input) {
+ throw new Error('search input did not render');
+ }
+
+ return input;
+};
+
+const getField = (): HTMLElement => host?.firstElementChild as HTMLElement;
+
+/** The mirror is the input's own sibling; the search icon is also aria-hidden. */
+const getMirror = (): HTMLElement => {
+ const mirror = getInput().previousElementSibling;
+
+ if (!(mirror instanceof HTMLElement) || mirror.getAttribute('aria-hidden') !== 'true') {
+ throw new Error('mirror layer not found beside the input');
+ }
+
+ return mirror;
+};
+
+const getChips = (): HTMLElement[] =>
+ Array.from(getMirror().querySelectorAll<HTMLElement>('span')).filter(
+ (span) => getComputedStyle(span).backgroundColor !== 'rgba(0, 0, 0, 0)'
+ );
+
+beforeEach(() => {
+ host = document.createElement('div');
+ host.style.cssText = 'left:0;position:fixed;top:0;width:320px;';
+ document.body.append(host);
+ root = createRoot(host);
+ onChange.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('getGallerySearchSegments', () => {
+ it('reproduces the value exactly, so the mirror stays in register with the input', () => {
+ for (const value of ['', 'sunset', 'from:7d sunset', ' from:today to:2026-01-02 x', 'from:nope tail']) {
+ const segments = getGallerySearchSegments(value, parseDateTokens(value));
+
+ expect(segments.map((segment) => segment.text).join(''), value).toBe(value);
+ }
+ });
+
+ it('chips only the token, never the space in front of it', () => {
+ const value = 'a from:7d';
+ const segments = getGallerySearchSegments(value, parseDateTokens(value));
+
+ expect(segments.filter((segment) => segment.kind === 'chip').map((segment) => segment.text)).toEqual(['from:7d']);
+ });
+
+ it('marks tokens the grammar rejected', () => {
+ const value = 'from:nope';
+ const [chip] = getGallerySearchSegments(value, parseDateTokens(value)).filter((s) => s.kind === 'chip');
+
+ expect(chip?.isInvalid).toBe(true);
+ });
+
+ it('leaves plain text unchipped', () => {
+ const value = 'just words';
+
+ expect(getGallerySearchSegments(value, parseDateTokens(value)).every((s) => s.kind === 'text')).toBe(true);
+ });
+});
+
+describe('GallerySearchField', () => {
+ it('keeps the field the same height when a token is added', async () => {
+ // The regression: the parsed-range hint used to render as a sibling, so
+ // typing a date grew the field and knocked the wide header row off centre.
+ await renderField('sunset');
+ const plainHeight = getField().getBoundingClientRect().height;
+
+ await renderField('from:7d sunset');
+
+ expect(getField().getBoundingClientRect().height).toBe(plainHeight);
+ });
+
+ it('paints the value through the mirror rather than the input', async () => {
+ await renderField('from:7d sunset');
+
+ expect(getComputedStyle(getInput()).color).toBe('rgba(0, 0, 0, 0)');
+ expect(getMirror().textContent).toBe('from:7d sunset');
+ });
+
+ it('renders a chip for the token and leaves the rest plain', async () => {
+ await renderField('from:7d sunset');
+
+ expect(getChips().map((chip) => chip.textContent)).toEqual(['from:7d']);
+ });
+
+ it('aligns the mirror with the input so glyphs sit on top of each other', async () => {
+ await renderField('from:7d sunset');
+
+ const inputRect = getInput().getBoundingClientRect();
+ const mirrorRect = getMirror().getBoundingClientRect();
+
+ expect(Math.abs(mirrorRect.left - inputRect.left)).toBeLessThanOrEqual(1);
+ // Vertical centres must agree, or every glyph is off by the difference.
+ expect(
+ Math.abs(mirrorRect.top + mirrorRect.height / 2 - (inputRect.top + inputRect.height / 2))
+ ).toBeLessThanOrEqual(1);
+ });
+
+ it('reports invalid input to assistive tech', async () => {
+ await renderField('from:nope', true);
+
+ expect(getInput().getAttribute('aria-invalid')).toBe('true');
+ });
+
+ it('reports typing back to the owner', async () => {
+ await renderField('');
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+
+ await act(async () => {
+ setter?.call(getInput(), 'from:today');
+ getInput().dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(onChange).toHaveBeenCalledWith('from:today');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx
new file mode 100644
index 0000000000..2b819faa49
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx
@@ -0,0 +1,182 @@
+import type { DateTokenParse } from '@platform/search/dateTokens';
+
+import { Box, Icon, Input } from '@chakra-ui/react';
+import { parseDateTokens } from '@platform/search/dateTokens';
+import { formControlInteraction } from '@theme/recipes';
+import { SearchIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, type ReactNode } from 'react';
+
+/** `key:value` runs the date grammar recognizes, matched against the raw value. */
+const TOKEN_PATTERN = /(?:^|\s)(?:from|to|date):\S*/gi;
+
+export interface GallerySearchSegment {
+ kind: 'chip' | 'text';
+ /** Chips only: the grammar rejected this value, so it filters nothing. */
+ isInvalid?: boolean;
+ text: string;
+}
+
+/**
+ * Splits the value into plain runs and token chips. Concatenating the segments
+ * must reproduce the value exactly — a dropped character shifts every glyph
+ * after it out of register with the input behind.
+ */
+export const getGallerySearchSegments = (value: string, parse: DateTokenParse): GallerySearchSegment[] => {
+ const invalidRaw = new Set(parse.invalidTokens.map((token) => `${token.key}:${token.raw}`.toLowerCase()));
+ const segments: GallerySearchSegment[] = [];
+ let lastIndex = 0;
+
+ for (const match of value.matchAll(TOKEN_PATTERN)) {
+ const matchIndex = match.index;
+ const raw = match[0];
+ // Keep the separating space out of the chip.
+ const leadingSpace = raw.startsWith(' ') ? ' ' : '';
+ const token = raw.slice(leadingSpace.length);
+
+ if (matchIndex > lastIndex) {
+ segments.push({ kind: 'text', text: value.slice(lastIndex, matchIndex) });
+ }
+
+ if (leadingSpace) {
+ segments.push({ kind: 'text', text: leadingSpace });
+ }
+
+ segments.push({ isInvalid: invalidRaw.has(token.toLowerCase()), kind: 'chip', text: token });
+ lastIndex = matchIndex + raw.length;
+ }
+
+ if (lastIndex < value.length) {
+ segments.push({ kind: 'text', text: value.slice(lastIndex) });
+ }
+
+ return segments;
+};
+
+const FIELD_CSS = {
+ ...formControlInteraction,
+ _focusWithin: { borderColor: 'accent.solid', outline: '1px solid {colors.accent.solid}' },
+} as const;
+
+const PLACEHOLDER_PROPS = { color: 'fg.subtle' } as const;
+
+const MIRROR_CHIP_CSS = {
+ borderRadius: 'sm',
+ marginInline: '-0.5',
+ paddingInline: '0.5',
+} as const;
+
+/**
+ * Search input that draws date tokens as chips. The mirror and the input share
+ * one zero-padded cell, so they align by construction rather than by matching
+ * padding; the input's own text is transparent and only its caret shows.
+ */
+export const GallerySearchField = ({
+ ariaLabel,
+ describedById,
+ endElement,
+ isInvalid,
+ placeholder,
+ value,
+ onChange,
+}: {
+ ariaLabel: string;
+ describedById?: string;
+ endElement?: ReactNode;
+ isInvalid?: boolean;
+ placeholder: string;
+ value: string;
+ onChange: (value: string) => void;
+}) => {
+ const mirrorRef = useRef<HTMLDivElement>(null);
+ const segments = useMemo(() => getGallerySearchSegments(value, parseDateTokens(value)), [value]);
+
+ const handleChange = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => onChange(event.currentTarget.value),
+ [onChange]
+ );
+
+ // The mirror has no scrollbar of its own; it follows the input's.
+ const handleScroll = useCallback((event: React.UIEvent<HTMLInputElement>) => {
+ const mirror = mirrorRef.current;
+
+ if (mirror) {
+ mirror.style.transform = `translateX(${String(-event.currentTarget.scrollLeft)}px)`;
+ }
+ }, []);
+
+ return (
+ <Box
+ alignItems="center"
+ aria-invalid={isInvalid || undefined}
+ bg="bg"
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ css={FIELD_CSS}
+ display="flex"
+ gap="1.5"
+ h="8"
+ minW="0"
+ position="relative"
+ px="2"
+ rounded="md"
+ w="full"
+ >
+ <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />
+ <Box flex="1" minW="0" position="relative">
+ {/* Flex-centred: Chakra reads a scale number in `lineHeight` as a
+ unitless multiplier, which drops the text out of the field. */}
+ <Box
+ ref={mirrorRef}
+ alignItems="center"
+ aria-hidden="true"
+ display="flex"
+ fontSize="xs"
+ inset="0"
+ pointerEvents="none"
+ position="absolute"
+ whiteSpace="pre"
+ >
+ {segments.map((segment, index) =>
+ segment.kind === 'chip' ? (
+ <Box
+ key={`${segment.text}-${String(index)}`}
+ as="span"
+ bg={segment.isInvalid ? 'bg.error' : 'accent.subtle'}
+ color={segment.isInvalid ? 'fg.error' : 'accent.fg'}
+ css={MIRROR_CHIP_CSS}
+ >
+ {segment.text}
+ </Box>
+ ) : (
+ <Box key={`text-${String(index)}`} as="span">
+ {segment.text}
+ </Box>
+ )
+ )}
+ </Box>
+ <Input
+ aria-describedby={describedById}
+ aria-invalid={isInvalid || undefined}
+ aria-label={ariaLabel}
+ bg="transparent"
+ border="0"
+ borderRadius="0"
+ caretColor="fg"
+ color="transparent"
+ fontSize="xs"
+ h="8"
+ minW="0"
+ px="0"
+ _placeholder={PLACEHOLDER_PROPS}
+ placeholder={placeholder}
+ position="relative"
+ w="full"
+ value={value}
+ onChange={handleChange}
+ onScroll={handleScroll}
+ />
+ </Box>
+ {endElement}
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
new file mode 100644
index 0000000000..678b43c3ce
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
@@ -0,0 +1,209 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryItem } from '@features/gallery/contracts';
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryStateView } from './galleryStateView';
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GallerySelectionBar } from './GallerySelectionBar';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en' },
+ t: (key: string, values?: Record<string, unknown>) => {
+ if (key === 'widgets.gallery.selectionCount') {
+ return `${String(values?.count)} selected`;
+ }
+ if (key === 'widgets.gallery.uncategorized') {
+ return 'Uncategorized';
+ }
+
+ return key;
+ },
+ }),
+}));
+
+const itemActions = {
+ deleteItems: vi.fn(async () => {}),
+ downloadItem: vi.fn(async () => {}),
+ downloadItems: vi.fn(async () => {}),
+ moveItemsToBoard: vi.fn(async () => {}),
+ openItemInNewTab: vi.fn(),
+ openItemInPreview: vi.fn(),
+ setItemsStarred: vi.fn(async () => {}),
+};
+
+const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
+ archived: false,
+ assetCount: 0,
+ imageCount: 0,
+ kind: 'board',
+ videoCount: 0,
+ ...overrides,
+});
+
+const createItem = (name: string, starred: boolean): GalleryItem => ({
+ boardId: 'dogs',
+ category: 'general',
+ createdAt: '2026-07-30T00:00:00.000Z',
+ fullUrl: `/full/${name}`,
+ height: 64,
+ isIntermediate: false,
+ kind: 'image',
+ name,
+ starred,
+ thumbnailUrl: `/thumb/${name}`,
+ width: 64,
+});
+
+const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateView =>
+ ({
+ boards: [
+ createBoard({ id: 'dogs', name: 'dogs' }),
+ createBoard({ id: 'cats', name: 'Cats' }),
+ createBoard({ id: 'none', kind: 'uncategorized', name: '' }),
+ createBoard({ archived: true, id: 'old', name: 'Old' }),
+ createBoard({ id: 'by_date:2026-07-30', kind: 'date', name: '30 July' }),
+ ],
+ compareImageKey: null,
+ currentItem: null,
+ galleryView: 'images',
+ isLoading: false,
+ items: [createItem('a.png', false), createItem('b.png', true)],
+ pendingPlaceholders: [],
+ projectBoardId: null,
+ searchTerm: '',
+ selectedBoardId: 'dogs',
+ selectedItemKey: 'image:a.png',
+ selectedItemKeys: ['image:a.png', 'image:b.png'],
+ settings: DEFAULT_GALLERY_SETTINGS,
+ ...overrides,
+ }) as GalleryStateView;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderBar = async (gallery: GalleryStateView) => {
+ const contextValue = { gallery, itemActions } as unknown as GalleryWidgetContextValue;
+
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GalleryWidgetContext value={contextValue}>
+ <GallerySelectionBar />
+ </GalleryWidgetContext>
+ </ChakraProvider>
+ )
+ );
+};
+
+const getButton = (label: string): HTMLButtonElement => {
+ const button = document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
+
+ if (!button) {
+ throw new Error(`no button labelled ${label}`);
+ }
+
+ return button;
+};
+
+const click = async (element: HTMLElement) => {
+ await act(async () => {
+ element.click();
+ await Promise.resolve();
+ });
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ Object.values(itemActions).forEach((mock) => mock.mockClear());
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GallerySelectionBar', () => {
+ it('stays out of the way until something is selected', async () => {
+ await renderBar(createGallery({ selectedItemKeys: [] }));
+
+ expect(document.querySelector('[role="toolbar"]')).toBeNull();
+ });
+
+ it('reports the selection size', async () => {
+ await renderBar(createGallery());
+
+ expect(host?.textContent).toContain('2 selected');
+ });
+
+ it('stars the whole selection when any member is unstarred', async () => {
+ await renderBar(createGallery());
+ await click(getButton('widgets.gallery.starSelection'));
+
+ expect(itemActions.setItemsStarred).toHaveBeenCalledExactlyOnceWith(
+ [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ ],
+ true
+ );
+ });
+
+ it('unstars only once every member is already starred', async () => {
+ await renderBar(createGallery({ items: [createItem('a.png', true), createItem('b.png', true)] }));
+ await click(getButton('widgets.gallery.unstarSelection'));
+
+ expect(itemActions.setItemsStarred).toHaveBeenCalledWith(expect.anything(), false);
+ });
+
+ it('downloads and deletes the selection', async () => {
+ const gallery = createGallery();
+
+ await renderBar(gallery);
+ await click(getButton('widgets.gallery.downloadSelection'));
+ await click(getButton('widgets.gallery.deleteSelection'));
+
+ expect(itemActions.downloadItems).toHaveBeenCalledWith(
+ [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ ],
+ gallery.items
+ );
+ expect(itemActions.deleteItems).toHaveBeenCalledWith([
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ ]);
+ });
+
+ it('offers only boards worth moving to — never a date board, an archived board, or where the items already are', async () => {
+ await renderBar(createGallery());
+ await click(getButton('widgets.gallery.moveSelectionToBoard'));
+
+ const labels = Array.from(document.querySelectorAll('[data-part="item-text"]')).map(
+ (element) => element.textContent
+ );
+
+ expect(labels).toEqual(['Cats', 'Uncategorized']);
+ });
+
+ it('disables the move control when there is nowhere to move to', async () => {
+ await renderBar(createGallery({ boards: [createBoard({ id: 'dogs', name: 'dogs' })] }));
+
+ expect(getButton('widgets.gallery.moveSelectionToBoard').disabled).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx
new file mode 100644
index 0000000000..f0713353de
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx
@@ -0,0 +1,154 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { parseGalleryItemKey, shouldStarSelection } from '@features/gallery/core/items';
+import { IconButton } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { DownloadIcon, FolderInputIcon, StarIcon, Trash2Icon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { BoardCover } from './GalleryBoardCover';
+import { useMenuTriggerIds } from './galleryMenuIds';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const MOVE_MENU_POSITIONING = { placement: 'top-end' } as const;
+
+/**
+ * Bulk actions for the current multi-selection. Until now these lived only in
+ * the right-click menu, which made them invisible to anyone who did not think
+ * to look for them.
+ */
+export const GallerySelectionBar = () => {
+ const { t } = useTranslation();
+ const { gallery, itemActions } = useGalleryWidget();
+ const moveTriggerIds = useMenuTriggerIds();
+ const selectedItemKeys = gallery.selectedItemKeys;
+ const selectionCount = selectedItemKeys.length;
+
+ const selectedItemRefs = useMemo(() => selectedItemKeys.map(parseGalleryItemKey), [selectedItemKeys]);
+
+ // Star acts on the whole selection: only "unstar all" when every selected
+ // item is already starred, matching the `.` hotkey.
+ const shouldStar = useMemo(
+ () => shouldStarSelection(gallery.items, selectedItemRefs),
+ [gallery.items, selectedItemRefs]
+ );
+
+ const moveTargets = useMemo(
+ () =>
+ gallery.boards.filter(
+ (board) => board.kind !== 'date' && !board.archived && board.id !== gallery.selectedBoardId
+ ),
+ [gallery.boards, gallery.selectedBoardId]
+ );
+
+ const handleToggleStarred = useCallback(
+ () => void itemActions.setItemsStarred(selectedItemRefs, shouldStar),
+ [itemActions, selectedItemRefs, shouldStar]
+ );
+
+ const handleDownload = useCallback(
+ () => void itemActions.downloadItems(selectedItemRefs, gallery.items),
+ [gallery.items, itemActions, selectedItemRefs]
+ );
+
+ const handleDelete = useCallback(
+ () => void itemActions.deleteItems(selectedItemRefs),
+ [itemActions, selectedItemRefs]
+ );
+
+ const handleMoveToBoard = useCallback(
+ (boardId: string) => void itemActions.moveItemsToBoard(selectedItemRefs, boardId),
+ [itemActions, selectedItemRefs]
+ );
+
+ if (selectionCount === 0) {
+ return null;
+ }
+
+ const starLabel = shouldStar ? t('widgets.gallery.starSelection') : t('widgets.gallery.unstarSelection');
+
+ return (
+ <HStack
+ bg="bg.subtle"
+ borderColor="border.subtle"
+ borderTopWidth="1px"
+ gap="1"
+ flexShrink={0}
+ minH="8"
+ px="2"
+ py="1"
+ role="toolbar"
+ aria-label={t('widgets.gallery.selectionActions')}
+ w="full"
+ >
+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums" me="auto">
+ {t('widgets.gallery.selectionCount', { count: selectionCount })}
+ </Text>
+ <Tooltip content={starLabel}>
+ <IconButton aria-label={starLabel} size="2xs" variant="ghost" onClick={handleToggleStarred}>
+ <Icon as={StarIcon} boxSize="3.5" fill={shouldStar ? 'none' : 'currentColor'} />
+ </IconButton>
+ </Tooltip>
+ <Menu.Root ids={moveTriggerIds} positioning={MOVE_MENU_POSITIONING}>
+ <Tooltip content={t('widgets.gallery.moveSelectionToBoard')} ids={moveTriggerIds}>
+ <Menu.Trigger asChild>
+ <IconButton
+ aria-label={t('widgets.gallery.moveSelectionToBoard')}
+ disabled={moveTargets.length === 0}
+ size="2xs"
+ variant="ghost"
+ >
+ <Icon as={FolderInputIcon} boxSize="3.5" />
+ </IconButton>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent maxH="18rem" minW="12rem" overflowY="auto">
+ {moveTargets.map((board) => (
+ <MoveTargetItem key={board.id} board={board} onSelect={handleMoveToBoard} />
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ <Tooltip content={t('widgets.gallery.downloadSelection')}>
+ <IconButton
+ aria-label={t('widgets.gallery.downloadSelection')}
+ size="2xs"
+ variant="ghost"
+ onClick={handleDownload}
+ >
+ <Icon as={DownloadIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content={t('widgets.gallery.deleteSelection')}>
+ <IconButton
+ aria-label={t('widgets.gallery.deleteSelection')}
+ colorPalette="red"
+ size="2xs"
+ variant="ghost"
+ onClick={handleDelete}
+ >
+ <Icon as={Trash2Icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ );
+};
+
+const MoveTargetItem = ({ board, onSelect }: { board: GalleryBoard; onSelect: (boardId: string) => void }) => {
+ const { t } = useTranslation();
+ const handleClick = useCallback(() => onSelect(board.id), [board.id, onSelect]);
+
+ return (
+ <Menu.Item value={board.id} onClick={handleClick}>
+ <BoardCover board={board} />
+ <Menu.ItemText>{getGalleryBoardLabel(board, t)}</Menu.ItemText>
+ </Menu.Item>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx
new file mode 100644
index 0000000000..7d5151531e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx
@@ -0,0 +1,78 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { GallerySettingsMenu } from './GallerySettingsMenu';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ 'widgets.gallery.imageSize': 'Image size',
+ 'widgets.gallery.settings': 'Settings',
+ 'widgets.gallery.settingsGridSize': 'Grid Size',
+ })[key] ?? key,
+ }),
+}));
+
+const settings = { ...DEFAULT_GALLERY_SETTINGS, imageDensityPercent: 25 };
+const onUpdateSettings = vi.fn();
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderMenu = async () => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GallerySettingsMenu settings={settings} onUpdateSettings={onUpdateSettings} />
+ </ChakraProvider>
+ )
+ );
+
+ const trigger = host?.querySelector<HTMLButtonElement>('button[aria-label="Settings"]');
+
+ await act(async () => {
+ trigger?.click();
+ await Promise.resolve();
+ });
+
+ return trigger;
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ onUpdateSettings.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GallerySettingsMenu grid size', () => {
+ it('presents the inverse of persisted density so higher values mean larger items', async () => {
+ const trigger = await renderMenu();
+ const menuContentId = trigger?.getAttribute('data-controls');
+ const menuContent = menuContentId ? document.getElementById(menuContentId) : null;
+
+ const slider = menuContent?.querySelector<HTMLElement>('[role="slider"][aria-label="Image size"]');
+
+ expect(menuContent?.textContent).toContain('Grid Size');
+ expect(menuContent?.textContent).toContain('75%');
+ expect(slider?.getAttribute('aria-valuenow')).toBe('75');
+
+ slider?.focus();
+ await act(() => userEvent.keyboard('{ArrowRight}'));
+
+ expect(onUpdateSettings).toHaveBeenLastCalledWith({ imageDensityPercent: 24 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx
new file mode 100644
index 0000000000..2ef7a13414
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx
@@ -0,0 +1,185 @@
+import type { GallerySettings } from '@features/gallery/core/settings';
+
+import { HStack, Icon, Menu, Portal, Slider, Stack, Switch, Text } from '@chakra-ui/react';
+import { Button, IconButton } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { SettingsIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useMenuTriggerIds } from './galleryMenuIds';
+
+const SETTINGS_POSITIONING = { placement: 'bottom-end' } as const;
+
+/**
+ * Presentation settings for the grid. Sort moved out to its own header control
+ * — it is a per-look decision, not something to go hunting in a popover for.
+ *
+ * Driven by props rather than the widget context: the widget frame renders
+ * header chrome outside the view, so in panel regions this menu mounts where
+ * `useGalleryWidget` does not reach.
+ */
+export const GallerySettingsMenu = ({
+ settings,
+ onUpdateSettings,
+}: {
+ settings: GallerySettings;
+ onUpdateSettings: (settings: Partial<GallerySettings>) => void;
+}) => {
+ const { t } = useTranslation();
+ const { imageDensityPercent, paginationMode, showImageDimensions, showPendingItems, thumbnailFit } = settings;
+ const imageSizePercent = 100 - imageDensityPercent;
+
+ const handleSizeKeyDown = useCallback((event: React.KeyboardEvent) => event.stopPropagation(), []);
+ const handleSizeChange = useCallback(
+ (event: { value: number[] }) =>
+ onUpdateSettings({ imageDensityPercent: 100 - (event.value[0] ?? imageSizePercent) }),
+ [imageSizePercent, onUpdateSettings]
+ );
+ const handleSquareFit = useCallback(() => onUpdateSettings({ thumbnailFit: 'square' }), [onUpdateSettings]);
+ const handleAspectFit = useCallback(() => onUpdateSettings({ thumbnailFit: 'aspect' }), [onUpdateSettings]);
+ const handleShowDimensionsChange = useCallback(
+ (showImageDimensions: boolean) => onUpdateSettings({ showImageDimensions }),
+ [onUpdateSettings]
+ );
+ const handleShowPendingItemsChange = useCallback(
+ (showPendingItems: boolean) => onUpdateSettings({ showPendingItems }),
+ [onUpdateSettings]
+ );
+ const handleInfinitePagination = useCallback(
+ () => onUpdateSettings({ paginationMode: 'infinite' }),
+ [onUpdateSettings]
+ );
+ const handlePaginatedPagination = useCallback(
+ () => onUpdateSettings({ paginationMode: 'paginated' }),
+ [onUpdateSettings]
+ );
+ const sizeAriaLabel = useMemo(() => [t('widgets.gallery.imageSize')], [t]);
+ const sizeValue = useMemo(() => [imageSizePercent], [imageSizePercent]);
+ const triggerIds = useMenuTriggerIds();
+
+ return (
+ <Menu.Root ids={triggerIds} positioning={SETTINGS_POSITIONING}>
+ <Tooltip content={t('widgets.gallery.settings')} ids={triggerIds}>
+ <Menu.Trigger asChild>
+ <IconButton aria-label={t('widgets.gallery.settings')} color="fg.muted" size="2xs" variant="ghost">
+ <Icon as={SettingsIcon} boxSize="3.5" />
+ </IconButton>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="14rem" p="3">
+ <Stack gap="3">
+ <Stack gap="2">
+ <HStack justify="space-between">
+ <SettingLabel>{t('widgets.gallery.settingsGridSize')}</SettingLabel>
+ <Text color="fg.subtle" fontSize="2xs">
+ {imageSizePercent}%
+ </Text>
+ </HStack>
+ <Slider.Root
+ aria-label={sizeAriaLabel}
+ max={100}
+ min={0}
+ step={1}
+ value={sizeValue}
+ onKeyDown={handleSizeKeyDown}
+ onValueChange={handleSizeChange}
+ >
+ <Slider.Control>
+ <Slider.Track>
+ <Slider.Range />
+ </Slider.Track>
+ <Slider.Thumbs />
+ </Slider.Control>
+ </Slider.Root>
+ </Stack>
+ <Stack gap="2">
+ <SettingLabel>{t('widgets.gallery.settingsThumbnails')}</SettingLabel>
+ <HStack gap="1">
+ <Button
+ flex="1"
+ size="2xs"
+ variant={thumbnailFit === 'square' ? 'solid' : 'outline'}
+ onClick={handleSquareFit}
+ >
+ {t('widgets.gallery.thumbnailFitSquare')}
+ </Button>
+ <Button
+ flex="1"
+ size="2xs"
+ variant={thumbnailFit === 'aspect' ? 'solid' : 'outline'}
+ onClick={handleAspectFit}
+ >
+ {t('widgets.gallery.thumbnailFitAspect')}
+ </Button>
+ </HStack>
+ <SettingSwitch
+ checked={showImageDimensions}
+ label={t('widgets.gallery.alwaysShowDimensions')}
+ onChange={handleShowDimensionsChange}
+ />
+ <SettingSwitch
+ checked={showPendingItems}
+ label={t('widgets.gallery.showPendingItems')}
+ onChange={handleShowPendingItemsChange}
+ />
+ </Stack>
+ <Stack gap="2">
+ <SettingLabel>{t('widgets.gallery.pagination')}</SettingLabel>
+ <HStack gap="1">
+ <Button
+ flex="1"
+ size="2xs"
+ variant={paginationMode === 'infinite' ? 'solid' : 'outline'}
+ onClick={handleInfinitePagination}
+ >
+ {t('widgets.gallery.infinite')}
+ </Button>
+ <Button
+ flex="1"
+ size="2xs"
+ variant={paginationMode === 'paginated' ? 'solid' : 'outline'}
+ onClick={handlePaginatedPagination}
+ >
+ {t('common.pages')}
+ </Button>
+ </HStack>
+ </Stack>
+ </Stack>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+const SettingSwitch = ({
+ checked,
+ label,
+ onChange,
+}: {
+ checked: boolean;
+ label: string;
+ onChange: (checked: boolean) => void;
+}) => {
+ const handleCheckedChange = useCallback((event: { checked: boolean }) => onChange(event.checked), [onChange]);
+
+ return (
+ <Switch.Root checked={checked} size="sm" onCheckedChange={handleCheckedChange}>
+ <Switch.HiddenInput />
+ <Switch.Control>
+ <Switch.Thumb />
+ </Switch.Control>
+ <Switch.Label fontSize="2xs">{label}</Switch.Label>
+ </Switch.Root>
+ );
+};
+
+const SettingLabel = ({ children }: { children: string }) => (
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ {children}
+ </Text>
+);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.browser.test.tsx
new file mode 100644
index 0000000000..a3872fcfe6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.browser.test.tsx
@@ -0,0 +1,165 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GallerySplitHandle } from './GallerySplitHandle';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const onCommit = vi.fn();
+const onPreview = vi.fn();
+
+const renderHandle = async (props: Partial<Parameters<typeof GallerySplitHandle>[0]> = {}) => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GallerySplitHandle
+ label="Resize board panel"
+ max={600}
+ min={120}
+ orientation="horizontal"
+ sizePx={280}
+ onCommit={onCommit}
+ onPreview={onPreview}
+ {...props}
+ />
+ </ChakraProvider>
+ )
+ );
+
+ const separator = document.querySelector('[role="separator"]');
+
+ if (!separator) {
+ throw new Error('split handle did not render');
+ }
+
+ return separator;
+};
+
+const interact = async (run: () => void) => {
+ await act(async () => {
+ run();
+ await Promise.resolve();
+ });
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ onCommit.mockClear();
+ onPreview.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GallerySplitHandle', () => {
+ it('exposes the resize range to assistive tech', async () => {
+ const separator = await renderHandle();
+
+ expect(separator.getAttribute('aria-label')).toBe('Resize board panel');
+ expect(separator.getAttribute('aria-orientation')).toBe('horizontal');
+ expect(separator.getAttribute('aria-valuenow')).toBe('280');
+ expect(separator.getAttribute('aria-valuemin')).toBe('120');
+ expect(separator.getAttribute('aria-valuemax')).toBe('600');
+ expect(separator.getAttribute('tabindex')).toBe('0');
+ });
+
+ it('previews during a drag and commits once on release', async () => {
+ const separator = await renderHandle();
+
+ await interact(() => {
+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0, clientY: 100 }));
+ });
+ await interact(() => {
+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 0, clientY: 140 }));
+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 0, clientY: 160 }));
+ });
+
+ expect(onPreview).toHaveBeenCalledWith(320);
+ expect(onPreview).toHaveBeenLastCalledWith(340);
+ expect(onCommit).not.toHaveBeenCalled();
+
+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientX: 0, clientY: 160 })));
+
+ expect(onPreview).toHaveBeenLastCalledWith(null);
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith(340);
+ });
+
+ it('stops previewing after release, so a stray move cannot resize', async () => {
+ const separator = await renderHandle();
+
+ await interact(() => {
+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0, clientY: 100 }));
+ });
+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientX: 0, clientY: 100 })));
+ onPreview.mockClear();
+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 0, clientY: 500 })));
+
+ expect(onPreview).not.toHaveBeenCalled();
+ });
+
+ it('clamps a drag to the bounds rather than reporting an impossible size', async () => {
+ const separator = await renderHandle();
+
+ await interact(() => {
+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0, clientY: 100 }));
+ });
+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 0, clientY: -9000 })));
+ expect(onPreview).toHaveBeenLastCalledWith(120);
+
+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 0, clientY: 9000 })));
+ expect(onPreview).toHaveBeenLastCalledWith(600);
+ });
+
+ it('resizes by keyboard along the axis it controls', async () => {
+ const separator = await renderHandle();
+
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));
+ expect(onCommit).toHaveBeenLastCalledWith(296);
+
+ await interact(() =>
+ separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowUp', shiftKey: true }))
+ );
+ expect(onCommit).toHaveBeenLastCalledWith(248);
+
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Home' })));
+ expect(onCommit).toHaveBeenLastCalledWith(120);
+
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'End' })));
+ expect(onCommit).toHaveBeenLastCalledWith(600);
+ });
+
+ it('drags and steps horizontally when it is the wide layout column edge', async () => {
+ const separator = await renderHandle({ max: 420, min: 180, orientation: 'vertical', sizePx: 240 });
+
+ expect(separator.getAttribute('aria-orientation')).toBe('vertical');
+
+ await interact(() => {
+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 100, clientY: 0 }));
+ });
+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 130, clientY: 0 })));
+ expect(onPreview).toHaveBeenLastCalledWith(270);
+
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' })));
+ expect(onCommit).toHaveBeenLastCalledWith(256);
+ });
+
+ it('ignores keys it does not own', async () => {
+ const separator = await renderHandle();
+
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' })));
+ await interact(() => separator.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowLeft' })));
+
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx
new file mode 100644
index 0000000000..893108dac1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx
@@ -0,0 +1,134 @@
+import { Box, Flex } from '@chakra-ui/react';
+import { useCallback, useMemo, type KeyboardEvent, type PointerEvent } from 'react';
+
+const SPLIT_SIZE_STEP_PX = 16;
+export const GALLERY_SPLIT_HANDLE_SIZE_PX = 8;
+
+const HANDLE_HOVER_PROPS = { '& > div': { color: 'accent.solid' } } as const;
+const HANDLE_FOCUS_PROPS = {
+ '& > div': { color: 'accent.solid' },
+ outline: '2px solid {colors.accent.solid}',
+ outlineOffset: '-1px',
+} as const;
+
+// An 8px target painting a 1px line: a divider as thick as its grab area reads
+// as a gap in the layout.
+const HORIZONTAL_PROPS = {
+ cursor: 'row-resize',
+ h: `${GALLERY_SPLIT_HANDLE_SIZE_PX}px`,
+ w: 'full',
+} as const;
+const VERTICAL_PROPS = {
+ cursor: 'col-resize',
+ h: 'full',
+ w: `${GALLERY_SPLIT_HANDLE_SIZE_PX}px`,
+} as const;
+
+const HORIZONTAL_LINE_PROPS = { h: '1px', w: 'full' } as const;
+const VERTICAL_LINE_PROPS = { h: 'full', w: '1px' } as const;
+
+export const clampSplitSize = (sizePx: number, { max, min }: { max: number; min: number }): number =>
+ Math.min(max, Math.max(min, Math.round(sizePx)));
+
+/**
+ * Resize handle for the board-panel split, serving both layouts. The parent
+ * holds `onPreview`'s live value so a drag renders without writing settings on
+ * every move; `onCommit` fires once, on release.
+ */
+export const GallerySplitHandle = ({
+ label,
+ max,
+ min,
+ orientation,
+ sizePx,
+ onCommit,
+ onPreview,
+}: {
+ label: string;
+ max: number;
+ min: number;
+ orientation: 'horizontal' | 'vertical';
+ /** The size currently rendered, including any in-flight drag preview. */
+ sizePx: number;
+ onCommit: (sizePx: number) => void;
+ onPreview: (sizePx: number | null) => void;
+}) => {
+ const isHorizontal = orientation === 'horizontal';
+
+ const handlePointerDown = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ event.preventDefault();
+
+ const startX = event.clientX;
+ const startY = event.clientY;
+ const startSizePx = sizePx;
+ let nextSizePx = startSizePx;
+ const pointerSession = new AbortController();
+
+ const handlePointerMove = (moveEvent: globalThis.PointerEvent) => {
+ const deltaPx = isHorizontal ? moveEvent.clientY - startY : moveEvent.clientX - startX;
+
+ nextSizePx = clampSplitSize(startSizePx + deltaPx, { max, min });
+ onPreview(nextSizePx);
+ };
+
+ const handlePointerUp = () => {
+ pointerSession.abort();
+ onPreview(null);
+ onCommit(nextSizePx);
+ };
+
+ window.addEventListener('pointermove', handlePointerMove, { signal: pointerSession.signal });
+ window.addEventListener('pointerup', handlePointerUp, { signal: pointerSession.signal });
+ window.addEventListener('pointercancel', handlePointerUp, { signal: pointerSession.signal });
+ },
+ [isHorizontal, max, min, sizePx, onCommit, onPreview]
+ );
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ const step = event.shiftKey ? SPLIT_SIZE_STEP_PX * 2 : SPLIT_SIZE_STEP_PX;
+ const sizeChanges: Partial<Record<string, number>> = isHorizontal
+ ? { ArrowDown: step, ArrowUp: -step, End: max - sizePx, Home: min - sizePx }
+ : { ArrowLeft: -step, ArrowRight: step, End: max - sizePx, Home: min - sizePx };
+ const sizeChange = sizeChanges[event.key];
+
+ if (sizeChange === undefined) {
+ return;
+ }
+
+ event.preventDefault();
+ onCommit(clampSplitSize(sizePx + sizeChange, { max, min }));
+ },
+ [isHorizontal, max, min, sizePx, onCommit]
+ );
+
+ const orientationProps = useMemo(() => (isHorizontal ? HORIZONTAL_PROPS : VERTICAL_PROPS), [isHorizontal]);
+
+ return (
+ <Flex
+ align="center"
+ aria-label={label}
+ aria-orientation={isHorizontal ? 'horizontal' : 'vertical'}
+ aria-valuemax={max}
+ aria-valuemin={min}
+ aria-valuenow={sizePx}
+ flexShrink={0}
+ justify="center"
+ role="separator"
+ tabIndex={0}
+ _focusVisible={HANDLE_FOCUS_PROPS}
+ _hover={HANDLE_HOVER_PROPS}
+ {...orientationProps}
+ onKeyDown={handleKeyDown}
+ onPointerDown={handlePointerDown}
+ >
+ <Box
+ bg="currentColor"
+ color="border.subtle"
+ transition="color var(--wb-motion-duration-fast) ease"
+ {...(isHorizontal ? HORIZONTAL_LINE_PROPS : VERTICAL_LINE_PROPS)}
+ />
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx
new file mode 100644
index 0000000000..c61aa06f76
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx
@@ -0,0 +1,136 @@
+import { Flex, HStack, Spacer, Stack } from '@chakra-ui/react';
+import {
+ GALLERY_BOARD_PANEL_MAX_HEIGHT_PX,
+ GALLERY_BOARD_PANEL_MIN_HEIGHT_PX,
+ GALLERY_MIN_GRID_HEIGHT_PX,
+} from '@features/gallery/core/settings';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GalleryBoardsPanel } from './GalleryBoardsPanel';
+import { GalleryImageGrid } from './GalleryImageGrid';
+import { GalleryItemSearch } from './GalleryItemSearch';
+import { GalleryItemSortMenu } from './GalleryItemSortMenu';
+import { GallerySelectionBar } from './GallerySelectionBar';
+import { GALLERY_SPLIT_HANDLE_SIZE_PX, GallerySplitHandle } from './GallerySplitHandle';
+import { GalleryViewTabs } from './GalleryViewTabs';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+/**
+ * Narrow arrangement: board panel above the items area. Pure arrangement —
+ * every child here is the same component the wide shell renders. The board
+ * panel's disclosure lives in the widget frame's header label, not here.
+ */
+export const GalleryStackedLayout = () => {
+ const { t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+ const { boardPanelCollapsed, boardPanelHeightPx } = gallery.settings;
+ const [dragHeightPx, setDragHeightPx] = useState<number | null>(null);
+ const [containerContentHeightPx, setContainerContentHeightPx] = useState<number | null>(null);
+ const [controlsHeightPx, setControlsHeightPx] = useState<number | null>(null);
+ const containerObserverRef = useRef<ResizeObserver | null>(null);
+ const controlsObserverRef = useRef<ResizeObserver | null>(null);
+
+ const containerRef = useCallback((element: HTMLDivElement | null) => {
+ containerObserverRef.current?.disconnect();
+ containerObserverRef.current = null;
+
+ if (!element) {
+ return;
+ }
+
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) {
+ setContainerContentHeightPx(entry.contentRect.height);
+ }
+ });
+
+ observer.observe(element);
+ containerObserverRef.current = observer;
+ }, []);
+
+ const controlsRef = useCallback((element: HTMLDivElement | null) => {
+ controlsObserverRef.current?.disconnect();
+ controlsObserverRef.current = null;
+
+ if (!element) {
+ return;
+ }
+
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) {
+ setControlsHeightPx(entry.contentRect.height);
+ }
+ });
+
+ observer.observe(element);
+ controlsObserverRef.current = observer;
+ }, []);
+
+ const measuredMaximumPx = useMemo(() => {
+ if (containerContentHeightPx === null || controlsHeightPx === null) {
+ return GALLERY_BOARD_PANEL_MIN_HEIGHT_PX;
+ }
+
+ const availableHeightPx =
+ containerContentHeightPx - controlsHeightPx - GALLERY_SPLIT_HANDLE_SIZE_PX - 3 * 8 - GALLERY_MIN_GRID_HEIGHT_PX;
+
+ return Math.min(
+ GALLERY_BOARD_PANEL_MAX_HEIGHT_PX,
+ Math.max(GALLERY_BOARD_PANEL_MIN_HEIGHT_PX, Math.floor(availableHeightPx))
+ );
+ }, [containerContentHeightPx, controlsHeightPx]);
+ const displayHeightPx = Math.min(dragHeightPx ?? boardPanelHeightPx, measuredMaximumPx);
+
+ const handleCommitHeight = useCallback(
+ (boardPanelHeightPx: number) => actions.updateSettings({ boardPanelHeightPx }),
+ [actions]
+ );
+
+ return (
+ <Stack gap="0" h="full" maxW="full" minH="0" minW="0" w="full">
+ <Stack
+ ref={containerRef}
+ flex="1"
+ gap="2"
+ minH="0"
+ minW="0"
+ pb="2"
+ pt="calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))"
+ px="2"
+ >
+ {boardPanelCollapsed ? null : (
+ <>
+ {/* A flex box with a definite height and hidden overflow: the panel
+ sizes its own scroll area from this, and without the containment
+ its board list spills over the grid below. */}
+ <Flex flexShrink={0} h={`${displayHeightPx}px`} minH="0" overflow="hidden" w="full">
+ <GalleryBoardsPanel />
+ </Flex>
+ <GallerySplitHandle
+ label={t('widgets.gallery.resizeBoardPanel')}
+ max={measuredMaximumPx}
+ min={GALLERY_BOARD_PANEL_MIN_HEIGHT_PX}
+ orientation="horizontal"
+ sizePx={displayHeightPx}
+ onCommit={handleCommitHeight}
+ onPreview={setDragHeightPx}
+ />
+ </>
+ )}
+ <Stack ref={controlsRef} flexShrink={0} gap="2" minW="0">
+ <HStack gap="1" minW="0">
+ <GalleryViewTabs />
+ <Spacer />
+ <GalleryItemSortMenu />
+ </HStack>
+ <GalleryItemSearch />
+ </Stack>
+ <Flex data-gallery-grid-wrapper flex="1" minH={`${GALLERY_MIN_GRID_HEIGHT_PX}px`} minW="0">
+ <GalleryImageGrid />
+ </Flex>
+ </Stack>
+ <GallerySelectionBar />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
new file mode 100644
index 0000000000..4c5cd46b4f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
@@ -0,0 +1,290 @@
+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';
+import type { GalleryThumbnailFit } from '@features/gallery/core/settings';
+
+import { Badge, Box } from '@chakra-ui/react';
+import { useDraggable } from '@dnd-kit/core';
+import { CSS } from '@dnd-kit/utilities';
+import { formatGalleryVideoDuration, toGalleryItemRef } from '@features/gallery/core/items';
+import { IconButton } from '@platform/ui/Button';
+import { PlayIcon, StarIcon } from 'lucide-react';
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';
+
+const THUMBNAIL_HOVER_CSS = {
+ '&:focus-within': { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' },
+ '&:hover .gallery-thumb-overlay, &:focus-within .gallery-thumb-overlay': { opacity: 1 },
+} as const;
+
+const PREVIEW_IMAGE_STYLE = {
+ borderRadius: '0.375rem',
+ boxShadow: '0 8px 24px rgb(0 0 0 / 45%)',
+ height: '100%',
+ objectFit: 'cover',
+ width: '100%',
+} as const;
+
+const THUMBNAIL_BUTTON_STYLE = {
+ background: 'transparent',
+ border: 0,
+ cursor: 'pointer',
+ display: 'block',
+ height: '100%',
+ inset: 0,
+ minWidth: 0,
+ outline: 'none',
+ padding: 0,
+ position: 'absolute',
+ width: '100%',
+} as const;
+
+const GalleryThumbnail = ({
+ alwaysShowDimensions,
+ compareRole,
+ dragItems,
+ dragScope,
+ fit,
+ isPrimary,
+ isSelected,
+ item,
+ onClick,
+ onContextMenu,
+ onToggleStarred,
+}: {
+ alwaysShowDimensions: boolean;
+ compareRole: string | null;
+ dragItems: GalleryItemRef[];
+ /** Separates this gallery's drags from another instance showing the same item. */
+ dragScope: string;
+ fit: GalleryThumbnailFit;
+ isPrimary: boolean;
+ isSelected: boolean;
+ item: GalleryItem;
+ onClick: (item: GalleryItem, event: MouseEvent) => void;
+ onContextMenu: (item: GalleryItem, x: number, y: number) => void;
+ onToggleStarred: (item: GalleryItem) => void;
+}) => {
+ const { t } = useTranslation();
+ const isCompared = compareRole !== null;
+ const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;
+
+ const { isDragging, listeners, setNodeRef, transform } = useDraggable({
+ data: getGalleryItemDragData(dragItems),
+ id: getGalleryItemDragId(toGalleryItemRef(item), 'gallery-grid', dragScope),
+ });
+
+ // The preview is portalled from where the tile started rather than moved in
+ // place: the grid scrolls inside `overflow: hidden` and its virtual rows carry
+ // their own transform, so a moved tile is clipped as soon as it leaves the
+ // grid — which is most of the way to any board.
+ const tileRef = useRef<HTMLDivElement | null>(null);
+ const [dragOrigin, setDragOrigin] = useState<DOMRect | null>(null);
+
+ useLayoutEffect(() => {
+ setDragOrigin(isDragging ? (tileRef.current?.getBoundingClientRect() ?? null) : null);
+ }, [isDragging]);
+
+ const setTileRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ tileRef.current = node;
+ setNodeRef(node);
+ },
+ [setNodeRef]
+ );
+
+ const previewStyle = useMemo(
+ () =>
+ dragOrigin
+ ? ({
+ height: `${String(dragOrigin.height)}px`,
+ left: `${String(dragOrigin.left)}px`,
+ pointerEvents: 'none',
+ position: 'fixed',
+ top: `${String(dragOrigin.top)}px`,
+ // Translate only: the full transform carries dnd-kit's scale factors,
+ // which squash the preview to whatever it is hovering over.
+ transform: CSS.Translate.toString(transform),
+ width: `${String(dragOrigin.width)}px`,
+ zIndex: 1500,
+ } as const)
+ : null,
+ [dragOrigin, transform]
+ );
+
+ const imageStyle = useMemo(
+ () =>
+ ({
+ display: 'block',
+ height: '100%',
+ inset: 0,
+ maxWidth: 'none',
+ objectFit: fit === 'aspect' ? 'contain' : 'cover',
+ position: 'absolute',
+ width: '100%',
+ }) as const,
+ [fit]
+ );
+
+ const handleContextMenu = useCallback(
+ (event: MouseEvent) => {
+ event.preventDefault();
+ onContextMenu(item, event.clientX, event.clientY);
+ },
+ [item, onContextMenu]
+ );
+
+ const handleClick = useCallback((event: MouseEvent) => onClick(item, event), [item, onClick]);
+
+ const handleActivationKeyDown = useCallback((event: KeyboardEvent<HTMLButtonElement>) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.stopPropagation();
+ }
+ }, []);
+
+ const handleToggleStarred = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ event.stopPropagation();
+
+ onToggleStarred(item);
+ },
+ [item, onToggleStarred]
+ );
+
+ return (
+ <Box
+ ref={setTileRef}
+ {...listeners}
+ aspectRatio={1}
+ bg="bg"
+ borderColor={isSelected || isCompared ? 'accent.solid' : 'border.subtle'}
+ borderWidth="2px"
+ boxShadow={isCompared ? 'inset 0 0 0 1px {colors.accent.solid}' : undefined}
+ css={THUMBNAIL_HOVER_CSS}
+ minW="0"
+ opacity={isDragging ? 0.4 : undefined}
+ overflow="hidden"
+ position="relative"
+ role="listitem"
+ rounded="md"
+ touchAction="none"
+ w="full"
+ onContextMenu={handleContextMenu}
+ >
+ <button
+ aria-current={isPrimary ? 'true' : undefined}
+ aria-label={
+ item.kind === 'video'
+ ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })
+ : t('widgets.gallery.selectImageForPreview', { name: item.name })
+ }
+ aria-pressed={isSelected}
+ style={THUMBNAIL_BUTTON_STYLE}
+ type="button"
+ onClick={handleClick}
+ onKeyDown={handleActivationKeyDown}
+ >
+ <img
+ alt={item.name}
+ decoding={item.kind === 'video' ? 'async' : undefined}
+ draggable={false}
+ src={item.thumbnailUrl || item.fullUrl}
+ style={imageStyle}
+ />
+ </button>
+ {compareRole && (
+ <Badge
+ insetInlineStart="1"
+ pointerEvents="none"
+ position="absolute"
+ size="xs"
+ top="1"
+ variant="solid"
+ zIndex="1"
+ >
+ {compareRole}
+ </Badge>
+ )}
+ <IconButton
+ aria-label={
+ item.starred
+ ? t('widgets.gallery.unstarImage', { name: item.name })
+ : t('widgets.gallery.starImage', { name: item.name })
+ }
+ className="gallery-thumb-overlay"
+ colorPalette={item.starred ? 'yellow' : 'gray'}
+ insetInlineEnd="1"
+ opacity={item.starred ? 1 : 0}
+ position="absolute"
+ size="2xs"
+ top="1"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="solid"
+ zIndex="1"
+ onClick={handleToggleStarred}
+ >
+ <StarIcon fill={item.starred ? 'currentColor' : 'none'} />
+ </IconButton>
+ {item.kind === 'image' && item.width > 0 && item.height > 0 && (
+ <Badge
+ bottom="1"
+ className="gallery-thumb-overlay"
+ insetInlineStart="1"
+ opacity={alwaysShowDimensions ? 1 : 0}
+ pointerEvents="none"
+ position="absolute"
+ size="xs"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="solid"
+ zIndex="1"
+ >
+ {item.width}x{item.height}
+ </Badge>
+ )}
+ {duration !== null && (
+ <Badge
+ bottom="1"
+ display="flex"
+ fontVariantNumeric="tabular-nums"
+ gap="1"
+ insetInlineStart="1"
+ opacity={1}
+ pointerEvents="none"
+ position="absolute"
+ size="xs"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="solid"
+ zIndex="1"
+ >
+ <PlayIcon aria-hidden="true" fill="currentColor" />
+ {duration}
+ </Badge>
+ )}
+ {previewStyle
+ ? createPortal(
+ <div aria-hidden="true" style={previewStyle}>
+ <img alt="" src={item.thumbnailUrl || item.fullUrl} style={PREVIEW_IMAGE_STYLE} />
+ </div>,
+ document.body
+ )
+ : null}
+ </Box>
+ );
+};
+
+/**
+ * Resolves the drag payload per item so the grid can hand down one stable
+ * callback rather than an array prop that changes identity every render.
+ */
+export const GalleryThumbnailCell = ({
+ getDragItems,
+ item,
+ ...props
+}: Omit<Parameters<typeof GalleryThumbnail>[0], 'dragItems'> & {
+ getDragItems: (item: GalleryItem) => GalleryItemRef[];
+}) => {
+ const dragItems = useMemo(() => getDragItems(item), [getDragItems, item]);
+
+ return <GalleryThumbnail {...props} dragItems={dragItems} item={item} />;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx
deleted file mode 100644
index 12d9b8208d..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx
+++ /dev/null
@@ -1,440 +0,0 @@
-import type { GalleryView } from '@features/gallery/core/types';
-
-import {
- Box,
- HStack,
- Icon,
- Input,
- InputGroup,
- Menu,
- Portal,
- SegmentGroup,
- Slider,
- Spacer,
- Stack,
- Switch,
- Text,
-} from '@chakra-ui/react';
-import { isDateBoardId } from '@features/gallery/data/backend';
-import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';
-import { Button, CloseButton, IconButton } from '@platform/ui';
-import { SearchIcon, SettingsIcon, UploadIcon } from 'lucide-react';
-import { useCallback, useMemo, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { GalleryBoardSelect } from './GalleryBoardSelect';
-import { useGalleryWidget } from './GalleryWidgetContext';
-
-const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp,video/mp4,.png,.jpg,.jpeg,.webp,.mp4';
-const galleryViewTabs = [
- { labelKey: 'common.media', value: 'images' },
- { labelKey: 'common.assets', value: 'assets' },
-] satisfies { labelKey: string; value: GalleryView }[];
-
-const UPLOAD_INPUT_STYLE = { display: 'none' } as const;
-const GALLERY_SETTINGS_POSITIONING = { placement: 'bottom-end' } as const;
-const SEARCH_START_ELEMENT = <Icon as={SearchIcon} size="sm" />;
-const SEARCH_DATE_HINT_ID = 'gallery-search-date-hint';
-
-export const GalleryToolbar = ({ layout }: { layout: 'stacked' | 'wide' }) => {
- const { i18n, t } = useTranslation();
- const { actions, gallery } = useGalleryWidget();
- const isWide = layout === 'wide';
-
- const handleViewChange = useCallback(
- (event: { value: string | null }) => {
- if (event.value) {
- actions.setView(event.value as GalleryView);
- }
- },
- [actions]
- );
-
- const handleClearSearch = useCallback(() => actions.setSearchTerm(''), [actions]);
-
- const handleSearchChange = useCallback(
- (event: React.ChangeEvent<HTMLInputElement>) => actions.setSearchTerm(event.currentTarget.value),
- [actions]
- );
-
- const searchClearButton = useMemo(
- () =>
- gallery.searchTerm ? (
- <CloseButton size="2xs" aria-label={t('common.clearSearch')} onClick={handleClearSearch} me="-2" />
- ) : null,
- [gallery.searchTerm, handleClearSearch, t]
- );
-
- const viewTabs = useMemo(
- () => (
- <SegmentGroup.Root
- aria-label={t('common.view')}
- size="sm"
- value={gallery.galleryView}
- onValueChange={handleViewChange}
- >
- <SegmentGroup.Indicator />
- {galleryViewTabs.map((item) => (
- <SegmentGroup.Item key={item.value} value={item.value}>
- <SegmentGroup.ItemHiddenInput />
- <SegmentGroup.ItemText fontSize="xs">{t(item.labelKey)}</SegmentGroup.ItemText>
- </SegmentGroup.Item>
- ))}
- </SegmentGroup.Root>
- ),
- [gallery.galleryView, handleViewChange, t]
- );
-
- const toolbarActions = useMemo(
- () => (
- <HStack gap="2">
- <GalleryUploadButton />
- <GallerySettingsMenu />
- </HStack>
- ),
- []
- );
-
- // Derived from the raw search term: an applied-range summary, or invalid-
- // token feedback.
- const dateHint = useMemo(() => {
- const parse = parseDateTokens(gallery.searchTerm);
- const invalid = findInvalidDateToken(gallery.searchTerm, parse);
-
- if (invalid) {
- return { isInvalid: true, label: t('widgets.gallery.dateFilterInvalid', { value: invalid.raw }) };
- }
-
- const shape = parse.range ? describeDateRange(parse.range) : null;
-
- if (!shape) {
- return null;
- }
-
- const locale = i18n.language;
-
- switch (shape.kind) {
- case 'day':
- return {
- isInvalid: false,
- label: t('widgets.gallery.dateFilterDay', { date: formatIsoDate(shape.date, locale) }),
- };
- case 'range':
- return {
- isInvalid: false,
- label: t('widgets.gallery.dateFilterRange', {
- from: formatIsoDate(shape.from, locale),
- to: formatIsoDate(shape.to, locale),
- }),
- };
- case 'from':
- return {
- isInvalid: false,
- label: t('widgets.gallery.dateFilterFrom', { date: formatIsoDate(shape.date, locale) }),
- };
- case 'through':
- return {
- isInvalid: false,
- label: t('widgets.gallery.dateFilterThrough', { date: formatIsoDate(shape.date, locale) }),
- };
- }
- }, [gallery.searchTerm, i18n.language, t]);
-
- const searchInput = useMemo(
- () => (
- <Stack gap="1">
- <InputGroup startElement={SEARCH_START_ELEMENT} endElement={searchClearButton}>
- <Input
- aria-describedby={dateHint?.isInvalid ? SEARCH_DATE_HINT_ID : undefined}
- aria-invalid={dateHint?.isInvalid || undefined}
- aria-label={t('widgets.gallery.searchImagesAriaLabel')}
- placeholder={t('widgets.gallery.searchImagesPlaceholder')}
- size="xs"
- value={gallery.searchTerm}
- onChange={handleSearchChange}
- />
- </InputGroup>
- {dateHint ? (
- <Text
- color={dateHint.isInvalid ? 'fg.error' : 'fg.muted'}
- fontSize="2xs"
- id={SEARCH_DATE_HINT_ID}
- role="status"
- >
- {dateHint.label}
- </Text>
- ) : null}
- </Stack>
- ),
- [dateHint, gallery.searchTerm, handleSearchChange, searchClearButton, t]
- );
-
- return (
- <Stack gap="2">
- {isWide ? (
- <HStack gap="2">
- <Box flex="1" maxW="16rem" minW="10rem">
- <GalleryBoardSelect />
- </Box>
- {viewTabs}
- <Spacer />
- <Box flex="1" maxW="20rem" minW="12rem">
- {searchInput}
- </Box>
- {toolbarActions}
- </HStack>
- ) : (
- <>
- <GalleryBoardSelect />
- <HStack justify="space-between">
- {viewTabs}
- {toolbarActions}
- </HStack>
- </>
- )}
- {!isWide && searchInput}
- </Stack>
- );
-};
-
-const GalleryUploadButton = () => {
- const { t } = useTranslation();
- const { actions, gallery } = useGalleryWidget();
- const fileInputRef = useRef<HTMLInputElement>(null);
- const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);
- const isVirtualTarget = isDateBoardId(gallery.selectedBoardId);
-
- const handleFileChange = useCallback(
- (event: React.ChangeEvent<HTMLInputElement>) => {
- const files = Array.from(event.currentTarget.files ?? []);
-
- event.currentTarget.value = '';
-
- if (files.length > 0) {
- void actions.uploadFiles(files);
- }
- },
- [actions]
- );
-
- const handleUploadClick = useCallback(() => fileInputRef.current?.click(), []);
-
- return (
- <>
- <input
- accept={ACCEPTED_UPLOAD_EXTENSIONS}
- multiple
- ref={fileInputRef}
- style={UPLOAD_INPUT_STYLE}
- type="file"
- onChange={handleFileChange}
- />
- <IconButton
- aria-label={
- isVirtualTarget
- ? t('widgets.gallery.uploadsUnavailableForDateBoards')
- : t('widgets.gallery.uploadMediaToBoard', {
- name: selectedBoard?.name ?? t('widgets.gallery.selectedBoardFallback'),
- })
- }
- disabled={isVirtualTarget}
- size="xs"
- variant="outline"
- onClick={handleUploadClick}
- >
- <UploadIcon />
- </IconButton>
- </>
- );
-};
-
-const GallerySettingsMenu = () => {
- const { t } = useTranslation();
- const { actions, gallery } = useGalleryWidget();
- const {
- imageDensityPercent,
- imageOrderDir,
- paginationMode,
- showImageDimensions,
- showPendingItems,
- starredFirst,
- thumbnailFit,
- } = gallery.settings;
- const handleDensityKeyDown = useCallback((event: React.KeyboardEvent) => event.stopPropagation(), []);
- const handleDensityChange = useCallback(
- (event: { value: number[] }) =>
- actions.updateSettings({ imageDensityPercent: event.value[0] ?? imageDensityPercent }),
- [actions, imageDensityPercent]
- );
- const handleSquareFit = useCallback(() => actions.updateSettings({ thumbnailFit: 'square' }), [actions]);
- const handleAspectFit = useCallback(() => actions.updateSettings({ thumbnailFit: 'aspect' }), [actions]);
- const handleShowDimensionsChange = useCallback(
- (showImageDimensions: boolean) => actions.updateSettings({ showImageDimensions }),
- [actions]
- );
- const handleShowPendingItemsChange = useCallback(
- (showPendingItems: boolean) => actions.updateSettings({ showPendingItems }),
- [actions]
- );
- const handleNewestFirst = useCallback(() => actions.updateSettings({ imageOrderDir: 'DESC' }), [actions]);
- const handleOldestFirst = useCallback(() => actions.updateSettings({ imageOrderDir: 'ASC' }), [actions]);
- const handleStarredFirstChange = useCallback(
- (starredFirst: boolean) => actions.updateSettings({ starredFirst }),
- [actions]
- );
- const handleInfinitePagination = useCallback(() => actions.updateSettings({ paginationMode: 'infinite' }), [actions]);
- const handlePaginatedPagination = useCallback(
- () => actions.updateSettings({ paginationMode: 'paginated' }),
- [actions]
- );
- const densityAriaLabel = useMemo(() => [t('widgets.gallery.imageDensity')], [t]);
- const densityValue = useMemo(() => [imageDensityPercent], [imageDensityPercent]);
-
- return (
- <Menu.Root positioning={GALLERY_SETTINGS_POSITIONING}>
- <Menu.Trigger asChild>
- <IconButton aria-label={t('widgets.gallery.settings')} size="xs" variant="outline">
- <SettingsIcon />
- </IconButton>
- </Menu.Trigger>
- <Portal>
- <Menu.Positioner>
- <Menu.Content minW="14rem" p="3">
- <Stack gap="3">
- <Stack gap="2">
- <HStack justify="space-between">
- <SettingLabel>{t('widgets.gallery.settingsGridDensity')}</SettingLabel>
- <Text color="fg.subtle" fontSize="2xs">
- {imageDensityPercent}%
- </Text>
- </HStack>
- <Slider.Root
- aria-label={densityAriaLabel}
- max={100}
- min={0}
- step={1}
- value={densityValue}
- onKeyDown={handleDensityKeyDown}
- onValueChange={handleDensityChange}
- >
- <Slider.Control>
- <Slider.Track>
- <Slider.Range />
- </Slider.Track>
- <Slider.Thumbs />
- </Slider.Control>
- </Slider.Root>
- </Stack>
- <Stack gap="2">
- <SettingLabel>{t('widgets.gallery.settingsThumbnails')}</SettingLabel>
- <HStack gap="1">
- <Button
- flex="1"
- size="2xs"
- variant={thumbnailFit === 'square' ? 'solid' : 'outline'}
- onClick={handleSquareFit}
- >
- {t('widgets.gallery.thumbnailFitSquare')}
- </Button>
- <Button
- flex="1"
- size="2xs"
- variant={thumbnailFit === 'aspect' ? 'solid' : 'outline'}
- onClick={handleAspectFit}
- >
- {t('widgets.gallery.thumbnailFitAspect')}
- </Button>
- </HStack>
- <SettingSwitch
- checked={showImageDimensions}
- label={t('widgets.gallery.alwaysShowDimensions')}
- onChange={handleShowDimensionsChange}
- />
- <SettingSwitch
- checked={showPendingItems}
- label={t('widgets.gallery.showPendingItems')}
- onChange={handleShowPendingItemsChange}
- />
- </Stack>
- <Stack gap="2">
- <SettingLabel>{t('widgets.gallery.imageSort')}</SettingLabel>
- <HStack gap="1">
- <Button
- flex="1"
- size="2xs"
- variant={imageOrderDir === 'DESC' ? 'solid' : 'outline'}
- onClick={handleNewestFirst}
- >
- {t('widgets.gallery.newest')}
- </Button>
- <Button
- flex="1"
- size="2xs"
- variant={imageOrderDir === 'ASC' ? 'solid' : 'outline'}
- onClick={handleOldestFirst}
- >
- {t('widgets.gallery.oldest')}
- </Button>
- </HStack>
- <SettingSwitch
- checked={starredFirst}
- label={t('widgets.gallery.showStarredImagesFirst')}
- onChange={handleStarredFirstChange}
- />
- </Stack>
- <Stack gap="2">
- <SettingLabel>{t('widgets.gallery.pagination')}</SettingLabel>
- <HStack gap="1">
- <Button
- flex="1"
- size="2xs"
- variant={paginationMode === 'infinite' ? 'solid' : 'outline'}
- onClick={handleInfinitePagination}
- >
- {t('widgets.gallery.infinite')}
- </Button>
- <Button
- flex="1"
- size="2xs"
- variant={paginationMode === 'paginated' ? 'solid' : 'outline'}
- onClick={handlePaginatedPagination}
- >
- {t('common.pages')}
- </Button>
- </HStack>
- </Stack>
- </Stack>
- </Menu.Content>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
- );
-};
-
-const SettingSwitch = ({
- checked,
- label,
- onChange,
-}: {
- checked: boolean;
- label: string;
- onChange: (checked: boolean) => void;
-}) => {
- const handleCheckedChange = useCallback((event: { checked: boolean }) => onChange(event.checked), [onChange]);
-
- return (
- <Switch.Root checked={checked} size="sm" onCheckedChange={handleCheckedChange}>
- <Switch.HiddenInput />
- <Switch.Control>
- <Switch.Thumb />
- </Switch.Control>
- <Switch.Label fontSize="2xs">{label}</Switch.Label>
- </Switch.Root>
- );
-};
-
-const SettingLabel = ({ children }: { children: string }) => (
- <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
- {children}
- </Text>
-);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx
new file mode 100644
index 0000000000..12c6bfdcef
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx
@@ -0,0 +1,65 @@
+import type { GalleryView } from '@features/gallery/core/types';
+
+import { SegmentGroup, Text } from '@chakra-ui/react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getGalleryCountForView } from './galleryBoardLabels';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const GALLERY_VIEW_TABS = [
+ { labelKey: 'common.media', value: 'images' },
+ { labelKey: 'common.assets', value: 'assets' },
+] 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.
+ *
+ * A segmented control rather than a tablist: this chooses which items the grid
+ * queries and owns no panel of its own. Real tabs publish `aria-controls`
+ * pointing at a tabpanel, and there is none to point at — the grid is a
+ * sibling slot each layout shell places independently.
+ */
+export const GalleryViewTabs = () => {
+ const { t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+ const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);
+
+ const handleViewChange = useCallback(
+ (event: { value: string | null }) => {
+ if (event.value) {
+ actions.setView(event.value as GalleryView);
+ }
+ },
+ [actions]
+ );
+
+ return (
+ <SegmentGroup.Root
+ aria-label={t('common.view')}
+ size="sm"
+ value={gallery.galleryView}
+ onValueChange={handleViewChange}
+ >
+ <SegmentGroup.Indicator />
+ {GALLERY_VIEW_TABS.map(({ labelKey, value }) => {
+ const count = selectedBoard ? getGalleryCountForView(selectedBoard, value) : null;
+
+ return (
+ <SegmentGroup.Item key={value} value={value}>
+ <SegmentGroup.ItemHiddenInput />
+ <SegmentGroup.ItemText display="flex" fontSize="xs" gap="1.5">
+ {t(labelKey)}
+ {count === null ? null : (
+ <Text as="span" color="fg.muted" fontVariantNumeric="tabular-nums">
+ {count}
+ </Text>
+ )}
+ </SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ );
+ })}
+ </SegmentGroup.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx
new file mode 100644
index 0000000000..0c139b2d01
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx
@@ -0,0 +1,80 @@
+import { Box, Flex, HStack, Spacer, Stack } from '@chakra-ui/react';
+import { GALLERY_BOARD_PANEL_MAX_WIDTH_PX, GALLERY_BOARD_PANEL_MIN_WIDTH_PX } from '@features/gallery/core/settings';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GalleryBoardsPanel } from './GalleryBoardsPanel';
+import { GalleryImageGrid } from './GalleryImageGrid';
+import { GalleryItemSearch } from './GalleryItemSearch';
+import { GalleryItemSortMenu } from './GalleryItemSortMenu';
+import { GallerySelectionBar } from './GallerySelectionBar';
+import { GallerySplitHandle } from './GallerySplitHandle';
+import { GalleryViewTabs } from './GalleryViewTabs';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const CHROME_INSET_PADDING_TOP = 'calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))';
+
+/**
+ * Roomy arrangement: board panel beside the items area, always open, with the
+ * header controls on one row. Pure arrangement — every child here is the same
+ * component the stacked shell renders.
+ */
+export const GalleryWideLayout = () => {
+ const { t } = useTranslation();
+ const { actions, gallery } = useGalleryWidget();
+ const { boardPanelCollapsed, boardPanelWidthPx } = gallery.settings;
+ const [dragWidthPx, setDragWidthPx] = useState<number | null>(null);
+ const displayWidthPx = dragWidthPx ?? boardPanelWidthPx;
+
+ const handleCommitWidth = useCallback(
+ (boardPanelWidthPx: number) => actions.updateSettings({ boardPanelWidthPx }),
+ [actions]
+ );
+
+ return (
+ <Flex h="full" maxW="full" minH="0" minW="0" w="full">
+ {boardPanelCollapsed ? null : (
+ <>
+ <Flex
+ flexShrink={0}
+ minH="0"
+ overflow="hidden"
+ pb="2"
+ pe="1"
+ ps="2"
+ pt={CHROME_INSET_PADDING_TOP}
+ w={`${displayWidthPx}px`}
+ >
+ <GalleryBoardsPanel />
+ </Flex>
+ <GallerySplitHandle
+ label={t('widgets.gallery.resizeBoardPanel')}
+ max={GALLERY_BOARD_PANEL_MAX_WIDTH_PX}
+ min={GALLERY_BOARD_PANEL_MIN_WIDTH_PX}
+ orientation="vertical"
+ sizePx={displayWidthPx}
+ onCommit={handleCommitWidth}
+ onPreview={setDragWidthPx}
+ />
+ </>
+ )}
+ <Stack flex="1" gap="0" minH="0" minW="0">
+ {/* Tabs anchor the start of the row; everything you reach for while
+ looking at the grid — find, order, add, configure — collects at the
+ end, so the eye has one place to go. */}
+ <HStack gap="1" minW="0" pb="2" pe="3" ps="3" pt={CHROME_INSET_PADDING_TOP}>
+ <GalleryViewTabs />
+ <Spacer />
+ <Box flex="1" maxW="22rem" minW="9rem">
+ <GalleryItemSearch />
+ </Box>
+ <GalleryItemSortMenu />
+ </HStack>
+ <Box flex="1" minH="0" minW="0" pb="2" pe="3" ps="3">
+ <GalleryImageGrid />
+ </Box>
+ <GallerySelectionBar />
+ </Stack>
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx
new file mode 100644
index 0000000000..40ec76ebc1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx
@@ -0,0 +1,173 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryUiAdapter } from '@features/gallery/react';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { GalleryUiProvider } from '@features/gallery/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GalleryWidgetHeaderActions, GalleryWidgetLabel } from './GalleryWidgetChrome';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en' },
+ t: (key: string, values?: Record<string, unknown>) =>
+ values?.name === undefined ? key : `${key}:${String(values.name)}`,
+ }),
+}));
+
+const board = {
+ archived: false,
+ assetCount: 0,
+ id: 'dogs',
+ imageCount: 3,
+ kind: 'board',
+ name: 'dogs',
+ videoCount: 0,
+};
+
+const uncategorized = { ...board, id: 'none', kind: 'uncategorized', name: '' };
+const dateBoard = { ...board, id: 'by_date:2026-07-30', kind: 'date', name: '30 July' };
+
+vi.mock('@features/gallery/data/queries', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ galleryBoardsOptions: () => ({
+ queryFn: () => Promise.resolve([board, uncategorized, dateBoard]),
+ queryKey: ['test-gallery-boards'],
+ staleTime: Infinity,
+ }),
+}));
+
+const updateSettings = vi.fn();
+
+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 createAdapter = (values: Record<string, unknown>) =>
+ ({
+ gallery: { updateSettings },
+ galleryValues: values,
+ projectName: 'Project',
+ }) as unknown as GalleryUiAdapter;
+
+const renderChrome = async (
+ Component: typeof GalleryWidgetLabel | typeof GalleryWidgetHeaderActions,
+ values: Record<string, unknown> = {},
+ region: 'center' | 'right' = 'right'
+) => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient!}>
+ <GalleryUiProvider adapter={createAdapter(values)}>
+ <Component region={region} />
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+ // Let the boards query resolve so the label can name the board.
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
+const getToggle = (): HTMLButtonElement => {
+ const button = host?.querySelector<HTMLButtonElement>('button[aria-expanded]');
+
+ if (!button) {
+ throw new Error('board toggle did not render');
+ }
+
+ return button;
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ host.style.cssText = 'left:0;position:fixed;top:0;width:400px;';
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ updateSettings.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ queryClient = null;
+});
+
+describe('GalleryWidgetLabel', () => {
+ it('names the widget and the board in panel regions', async () => {
+ await renderChrome(GalleryWidgetLabel, { selectedBoardId: 'dogs' });
+
+ expect(host?.textContent).toContain('widgets.labels.gallery');
+ expect(host?.textContent).toContain('dogs');
+ });
+
+ it('drops the widget name in the center, where the view selector already says it', async () => {
+ await renderChrome(GalleryWidgetLabel, { selectedBoardId: 'dogs' }, 'center');
+
+ expect(host?.textContent).not.toContain('widgets.labels.gallery');
+ expect(host?.textContent).toContain('dogs');
+ });
+
+ it('translates the uncategorized board rather than showing the transported name', async () => {
+ await renderChrome(GalleryWidgetLabel, { selectedBoardId: 'none' });
+
+ expect(host?.textContent).toContain('widgets.gallery.uncategorized');
+ });
+
+ it('collapses the boards when expanded', async () => {
+ await renderChrome(GalleryWidgetLabel, { selectedBoardId: 'dogs' });
+
+ expect(getToggle().getAttribute('aria-expanded')).toBe('true');
+
+ await act(async () => {
+ getToggle().click();
+ await Promise.resolve();
+ });
+
+ expect(updateSettings).toHaveBeenCalledWith({ boardPanelCollapsed: true });
+ });
+
+ it('expands the boards again when collapsed', async () => {
+ await renderChrome(GalleryWidgetLabel, { boardPanelCollapsed: true, selectedBoardId: 'dogs' });
+
+ expect(getToggle().getAttribute('aria-expanded')).toBe('false');
+
+ await act(async () => {
+ getToggle().click();
+ await Promise.resolve();
+ });
+
+ expect(updateSettings).toHaveBeenCalledWith({ boardPanelCollapsed: false });
+ });
+});
+
+describe('GalleryWidgetHeaderActions', () => {
+ it('offers upload and settings in every region, since the body renders neither', async () => {
+ for (const region of ['center', 'right'] as const) {
+ await renderChrome(GalleryWidgetHeaderActions, { selectedBoardId: 'dogs' }, region);
+
+ expect(host?.querySelector('button[aria-label^="widgets.gallery.upload"]'), region).not.toBeNull();
+ expect(host?.querySelector('button[aria-label="widgets.gallery.settings"]'), region).not.toBeNull();
+ }
+ });
+
+ it('disables upload for a date board, which cannot receive one', async () => {
+ await renderChrome(GalleryWidgetHeaderActions, { selectedBoardId: 'by_date:2026-07-30' });
+
+ const upload = host?.querySelector<HTMLButtonElement>('button[aria-label^="widgets.gallery.upload"]');
+
+ expect(upload?.disabled).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx
new file mode 100644
index 0000000000..0bbcb7df73
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx
@@ -0,0 +1,193 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { HStack, Icon, Text } from '@chakra-ui/react';
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { getGallerySettings } from '@features/gallery/core/settings';
+import { isDateBoardId } from '@features/gallery/data/backend';
+import { galleryBoardsOptions } from '@features/gallery/data/queries';
+import { Button, IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { useQuery } from '@tanstack/react-query';
+import { ChevronsDownUpIcon, ChevronsUpDownIcon, UploadIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GalleryWidgetProps } from './GalleryUiContext';
+
+import { GallerySettingsMenu } from './GallerySettingsMenu';
+import { getGallerySelectedBoardId, getGalleryView } from './galleryStateView';
+import { useGalleryUi } from './GalleryUiContext';
+import { useGalleryUploadAction } from './useGalleryUploadAction';
+
+type GalleryChromeProps = { region: GalleryWidgetProps['region'] };
+
+const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp,video/mp4,.png,.jpg,.jpeg,.webp,.mp4';
+const UPLOAD_INPUT_STYLE = { display: 'none' } as const;
+// Ghost buttons fill when expanded, and the boards start expanded — which left
+// the label looking pressed at rest. The chevron carries the state instead.
+const LABEL_EXPANDED_PROPS = { bg: 'transparent' } as const;
+
+/**
+ * Frame chrome mounts outside `GalleryWidgetView` and so outside its context;
+ * it reads the App-owned UI port directly. The boards query is the one the view
+ * already caches.
+ */
+const useGalleryChromeBoards = () => {
+ const { gallery, galleryValues } = useGalleryUi();
+ const settings = getGallerySettings(galleryValues);
+ const { data: boards } = useQuery(
+ galleryBoardsOptions({
+ includeArchived: settings.showArchivedBoards,
+ includeDateBoards: settings.showDateBoards,
+ orderBy: settings.boardOrderBy,
+ orderDir: settings.boardOrderDir,
+ })
+ );
+ const resolvedBoards = useMemo(() => boards ?? [], [boards]);
+
+ return {
+ boards: resolvedBoards,
+ gallery,
+ galleryValues,
+ selectedBoardId: getGallerySelectedBoardId(galleryValues, resolvedBoards),
+ settings,
+ };
+};
+
+/** Separate from the read-only hook so the label skips assembling upload actions. */
+const useGalleryChromeActions = () => {
+ const { boards, galleryValues, selectedBoardId, ...rest } = useGalleryChromeBoards();
+ const galleryView = getGalleryView(galleryValues);
+ const currentGalleryLocationRef = useRef({ galleryView, selectedBoardId });
+
+ // eslint-disable-next-line react/react-compiler
+ currentGalleryLocationRef.current = { galleryView, selectedBoardId };
+ const getCurrentGalleryLocation = useCallback(() => currentGalleryLocationRef.current, []);
+ const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });
+
+ return { ...rest, boards, galleryValues, selectedBoardId, uploadFiles };
+};
+
+/**
+ * `Gallery / [Board]`, where the board name expands and collapses the panel —
+ * the shape the workflow widget uses for its library trigger.
+ */
+export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {
+ const { t } = useTranslation();
+ const { boards, gallery, selectedBoardId, settings } = useGalleryChromeBoards();
+ const selectedBoard = boards.find((board) => board.id === selectedBoardId);
+ const boardName = selectedBoard ? getGalleryBoardLabel(selectedBoard, t) : t('widgets.gallery.selectedBoardFallback');
+ const isCollapsed = settings.boardPanelCollapsed;
+
+ const toggleBoards = useCallback(
+ () => gallery.updateSettings({ boardPanelCollapsed: !isCollapsed }),
+ [gallery, isCollapsed]
+ );
+
+ return (
+ // End padding keeps the name off the frame's actions; the center floats
+ // this in its own island and is exempt.
+ <HStack flex="1" gap="1" minW="0" pe={region === 'center' ? undefined : '2'}>
+ {/* The center's view selector already names the widget. */}
+ {region === 'center' ? null : (
+ <Text flexShrink={0} fontSize="xs" fontWeight="700">
+ {t('widgets.labels.gallery')}
+ </Text>
+ )}
+ <Text color="fg.subtle" flexShrink={0} fontSize="xs">
+ /
+ </Text>
+ {/* No tooltip: it renders over the button and steals its hover. */}
+ <Button
+ _expanded={LABEL_EXPANDED_PROPS}
+ aria-expanded={!isCollapsed}
+ aria-label={t('widgets.gallery.toggleBoardsNamed', { name: boardName })}
+ maxW="14rem"
+ minW="0"
+ size="2xs"
+ variant="ghost"
+ onClick={toggleBoards}
+ >
+ <Text fontWeight="600" minW="0" truncate>
+ {boardName}
+ </Text>
+ <Icon as={isCollapsed ? ChevronsUpDownIcon : ChevronsDownUpIcon} boxSize="3" color="fg.subtle" flexShrink={0} />
+ </Button>
+ </HStack>
+ );
+};
+
+/**
+ * Upload and grid settings, in every region. The frame owns these because the
+ * center hoists header chrome into an island that would otherwise sit empty.
+ */
+export const GalleryWidgetHeaderActions = (_props: GalleryChromeProps) => {
+ const { boards, gallery, selectedBoardId, settings, uploadFiles } = useGalleryChromeActions();
+
+ return (
+ <HStack gap="0.5">
+ <GalleryUploadButton boards={boards} selectedBoardId={selectedBoardId} onUploadFiles={uploadFiles} />
+ <GallerySettingsMenu settings={settings} onUpdateSettings={gallery.updateSettings} />
+ </HStack>
+ );
+};
+
+const GalleryUploadButton = ({
+ boards,
+ selectedBoardId,
+ onUploadFiles,
+}: {
+ boards: GalleryBoard[];
+ selectedBoardId: string;
+ onUploadFiles: (files: File[]) => Promise<void>;
+}) => {
+ const { t } = useTranslation();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ 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 handleFileChange = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(event.currentTarget.files ?? []);
+
+ event.currentTarget.value = '';
+
+ if (files.length > 0) {
+ void onUploadFiles(files);
+ }
+ },
+ [onUploadFiles]
+ );
+
+ const handleUploadClick = useCallback(() => fileInputRef.current?.click(), []);
+
+ return (
+ <>
+ <input
+ accept={ACCEPTED_UPLOAD_EXTENSIONS}
+ multiple
+ ref={fileInputRef}
+ style={UPLOAD_INPUT_STYLE}
+ type="file"
+ onChange={handleFileChange}
+ />
+ <Tooltip content={label}>
+ <IconButton
+ aria-label={label}
+ color="fg.muted"
+ disabled={isVirtualTarget}
+ size="2xs"
+ variant="ghost"
+ onClick={handleUploadClick}
+ >
+ <Icon as={UploadIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
index 1d9e8de574..a620bc517b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
@@ -1,11 +1,12 @@
import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/contracts';
import type { GallerySettings } from '@features/gallery/core/settings';
import type { GalleryView } from '@features/gallery/core/types';
+import type { GalleryItemsFilter } from '@features/gallery/data/queries';
import { createContext, use } from 'react';
import type { GalleryStateView } from './galleryStateView';
-import type { GalleryItemActions, GalleryWidgetRuntime } from './GalleryUiContext';
+import type { GalleryItemActions, GalleryWidgetProps, GalleryWidgetRuntime } from './GalleryUiContext';
/**
* Gallery-widget intents. The provider (GalleryWidgetView) is the only place
@@ -36,10 +37,18 @@ export interface GalleryActions {
export interface GalleryWidgetContextValue {
gallery: GalleryStateView;
actions: GalleryActions;
+ /**
+ * The query filter the visible items came from. Shared rather than re-derived
+ * so range selection and the item list can never disagree about which query
+ * they are operating on.
+ */
+ filter: GalleryItemsFilter;
itemActions: GalleryItemActions;
/** The infinite window is full and the board holds images it cannot reach. */
isWindowTruncated: boolean;
projectName: string;
+ /** Placement, used only to scope cached viewport measurements. */
+ region: GalleryWidgetProps['region'];
runtime: GalleryWidgetRuntime;
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
index 3e83209deb..73a7c0fd9a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.ts
@@ -38,12 +38,6 @@ describe('mixed-media gallery translations', () => {
});
expect(instance.t('widgets.gallery.statusChip', { count: 12 })).toBe('Gallery: 12 items');
- expect(
- instance.t('widgets.gallery.boardMediaCountBreakdown', {
- images: instance.t('widgets.gallery.imageCount', { count: 2 }),
- videos: instance.t('widgets.gallery.videoCount', { count: 3 }),
- })
- ).toBe('2 images · 3 videos');
expect(
instance.t('widgets.gallery.boardItemCounts', {
assets: instance.t('widgets.gallery.assetCount', { count: 4 }),
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
index 4b0210cafd..f0e6fc954a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
@@ -1,3 +1,5 @@
+import type { GalleryItemsFilter } from '@features/gallery/data/queries';
+
import { getBoundedRecentImages } from '@features/gallery/core/recentImages';
import { getGallerySettings } from '@features/gallery/core/settings';
import { GALLERY_PAGE_SIZE, galleryItemNamesOptions } from '@features/gallery/data/queries';
@@ -9,7 +11,8 @@ import { useTranslation } from 'react-i18next';
import type { GalleryStateView } from './galleryStateView';
-import { GalleryPanelContent } from './GalleryPanelContent';
+import { GalleryBoardDragMonitor } from './GalleryBoardDragMonitor';
+import { GalleryLayout } from './GalleryLayout';
import {
getGalleryPage,
getGalleryProjectBoardId,
@@ -135,8 +138,6 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
selectedBoardId,
});
- const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');
-
// Publish the backend total into widget values so the manifest footer can
// render page navigation without its own fetch, and clamp the page when the
// query shrinks (e.g. after deletions).
@@ -190,10 +191,11 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
>
<GalleryWidgetContent
actions={actions}
+ filter={data.filter}
gallery={gallery}
isWindowTruncated={data.isWindowTruncated}
- layout={isWidePlacement ? 'wide' : 'stacked'}
projectName={projectName}
+ region={region}
runtime={runtime}
/>
</ItemActionsProvider>
@@ -202,28 +204,31 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
const GalleryWidgetContent = ({
actions,
+ filter,
gallery,
isWindowTruncated,
- layout,
projectName,
+ region,
runtime,
}: {
actions: GalleryActions;
+ filter: GalleryItemsFilter;
gallery: GalleryStateView;
isWindowTruncated: boolean;
- layout: 'stacked' | 'wide';
projectName: string;
+ region: GalleryWidgetProps['region'];
runtime: GalleryWidgetRuntime;
}) => {
const itemActions = useGalleryItemActions();
const contextValue = useMemo<GalleryWidgetContextValue>(
- () => ({ actions, gallery, isWindowTruncated, itemActions, projectName, runtime }),
- [actions, gallery, isWindowTruncated, itemActions, projectName, runtime]
+ () => ({ actions, filter, gallery, isWindowTruncated, itemActions, projectName, region, runtime }),
+ [actions, filter, gallery, isWindowTruncated, itemActions, projectName, region, runtime]
);
return (
<GalleryWidgetContext value={contextValue}>
- <GalleryPanelContent layout={layout} />
+ <GalleryBoardDragMonitor />
+ <GalleryLayout region={region} />
</GalleryWidgetContext>
);
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
new file mode 100644
index 0000000000..8c0b3ad730
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
@@ -0,0 +1,99 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { describe, expect, it } from 'vitest';
+
+import { getGalleryBoardGroups } from './galleryBoardGroups';
+
+const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
+ archived: false,
+ assetCount: 0,
+ imageCount: 0,
+ kind: 'board',
+ videoCount: 0,
+ ...overrides,
+});
+
+const uncategorized = createBoard({ id: 'none', kind: 'uncategorized', name: '' });
+const dogs = createBoard({ id: 'dogs', name: 'dogs' });
+const cats = createBoard({ id: 'cats', name: 'Cats' });
+const archived = createBoard({ archived: true, id: 'gorl', name: 'GORL' });
+const dateBoard = createBoard({ id: 'by_date:2026-07-28', kind: 'date', name: '28 July' });
+const t = (key: string) => (key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key);
+
+const groupsOf = (overrides: Partial<Parameters<typeof getGalleryBoardGroups>[0]> = {}) =>
+ getGalleryBoardGroups({
+ boards: [uncategorized, dogs, cats, archived, dateBoard],
+ projectBoardId: null,
+ projectName: 'Project',
+ searchTerm: '',
+ showArchived: true,
+ showDates: true,
+ t,
+ ...overrides,
+ });
+
+describe('getGalleryBoardGroups', () => {
+ it('splits archived boards into their own section instead of the main list', () => {
+ const groups = groupsOf();
+
+ expect(groups.yourBoards.map((board) => board.id)).toEqual(['dogs', 'cats', 'none']);
+ expect(groups.archivedBoards.map((board) => board.id)).toEqual(['gorl']);
+ });
+
+ it('puts Uncategorized last and hoists the project board first', () => {
+ const groups = groupsOf({ projectBoardId: 'cats' });
+
+ expect(groups.yourBoards.map((board) => board.id)).toEqual(['cats', 'dogs', 'none']);
+ });
+
+ it('hides the date and archived sections when their toggles are off', () => {
+ const groups = groupsOf({ showArchived: false, showDates: false });
+
+ expect(groups.archivedBoards).toEqual([]);
+ expect(groups.dateBoards).toEqual([]);
+ expect(groups.yourBoards.map((board) => board.id)).toEqual(['dogs', 'cats', 'none']);
+ });
+
+ it('filters every section by a case-insensitive substring match', () => {
+ const groups = groupsOf({ searchTerm: 'DOG' });
+
+ expect(groups.yourBoards.map((board) => board.id)).toEqual(['dogs']);
+ expect(groups.archivedBoards).toEqual([]);
+ expect(groups.dateBoards).toEqual([]);
+ expect(groups.hasAnyMatch).toBe(true);
+ });
+
+ it('matches anywhere in the name, so Uncategorized answers to "cat"', () => {
+ expect(groupsOf({ searchTerm: 'cat' }).yourBoards.map((board) => board.id)).toEqual(['cats', 'none']);
+ });
+
+ it('offers to create only when the search names no existing board', () => {
+ expect(groupsOf({ searchTerm: 'birds' }).canCreateFromSearch).toBe(true);
+ expect(groupsOf({ searchTerm: 'cats' }).canCreateFromSearch).toBe(false);
+ expect(groupsOf({ searchTerm: ' CATS ' }).canCreateFromSearch).toBe(false);
+ expect(groupsOf({ searchTerm: '' }).canCreateFromSearch).toBe(false);
+ });
+
+ it('treats the localized Uncategorized label as an exact match', () => {
+ expect(groupsOf({ searchTerm: 'Uncategorized' }).canCreateFromSearch).toBe(false);
+ });
+
+ it('treats the yet-to-exist project board as an exact match so it is never duplicated', () => {
+ const groups = groupsOf({ searchTerm: 'Project' });
+
+ expect(groups.hasProjectBoardPlaceholder).toBe(true);
+ expect(groups.canCreateFromSearch).toBe(false);
+ expect(groups.hasAnyMatch).toBe(true);
+ });
+
+ it('drops the project placeholder once the project board exists', () => {
+ expect(groupsOf({ projectBoardId: 'cats' }).hasProjectBoardPlaceholder).toBe(false);
+ });
+
+ it('reports no match when the search excludes every row', () => {
+ const groups = groupsOf({ searchTerm: 'nothing-here' });
+
+ expect(groups.hasAnyMatch).toBe(false);
+ expect(groups.canCreateFromSearch).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts
new file mode 100644
index 0000000000..3258d9112f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts
@@ -0,0 +1,81 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { getGalleryBoardLabel, type GalleryBoardTranslate } from '@features/gallery/core/boardLabels';
+
+export interface GalleryBoardGroups {
+ /** Archived boards, split out of the main list into their own section. */
+ archivedBoards: GalleryBoard[];
+ /** The search term names no existing board, so it can create one. */
+ canCreateFromSearch: boolean;
+ dateBoards: GalleryBoard[];
+ /** Any row at all survived the search — drives the "no matches" copy. */
+ hasAnyMatch: boolean;
+ /**
+ * True when the project has no board yet and the search does not hide the
+ * row, so the panel can offer to create one on demand.
+ */
+ hasProjectBoardPlaceholder: boolean;
+ /** Project board (if any), then other boards, then Uncategorized last. */
+ yourBoards: GalleryBoard[];
+}
+
+/**
+ * Splits the flat board list into the panel's three sections.
+ *
+ * Pure and total: it filters on `showArchived`/`showDates` itself rather than
+ * trusting the query to have excluded them, so grouping can be reasoned about
+ * (and tested) without a fetch in the picture.
+ */
+export const getGalleryBoardGroups = ({
+ boards,
+ projectBoardId,
+ projectName,
+ searchTerm,
+ showArchived,
+ showDates,
+ t,
+}: {
+ boards: readonly GalleryBoard[];
+ projectBoardId: string | null;
+ projectName: string;
+ searchTerm: string;
+ showArchived: boolean;
+ showDates: boolean;
+ t: GalleryBoardTranslate;
+}): GalleryBoardGroups => {
+ const normalizedSearchTerm = searchTerm.trim().toLowerCase();
+ const matchesSearch = (name: string) => !normalizedSearchTerm || name.toLowerCase().includes(normalizedSearchTerm);
+
+ const uncategorizedBoard = boards.find((board) => board.kind === 'uncategorized') ?? null;
+ const projectBoard = projectBoardId ? (boards.find((board) => board.id === projectBoardId) ?? null) : null;
+ const projectRowName = projectBoard?.name ?? projectName;
+
+ const matchesBoardSearch = (board: GalleryBoard) => matchesSearch(getGalleryBoardLabel(board, t));
+ const regularBoards = boards.filter(
+ (board) => board.kind === 'board' && board.id !== projectBoard?.id && matchesBoardSearch(board)
+ );
+ const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];
+ const archivedBoards = showArchived ? regularBoards.filter((board) => board.archived) : [];
+
+ const yourBoards = [
+ ...(projectBoard && matchesBoardSearch(projectBoard) ? [projectBoard] : []),
+ ...regularBoards.filter((board) => !board.archived),
+ ...(uncategorizedBoard && matchesBoardSearch(uncategorizedBoard) ? [uncategorizedBoard] : []),
+ ];
+
+ const hasProjectBoardPlaceholder = projectBoard === null && matchesSearch(projectRowName);
+ const hasAnyMatch =
+ yourBoards.length > 0 || dateBoards.length > 0 || archivedBoards.length > 0 || hasProjectBoardPlaceholder;
+ const hasExactMatch =
+ boards.some((board) => getGalleryBoardLabel(board, t).toLowerCase() === normalizedSearchTerm) ||
+ projectRowName.toLowerCase() === normalizedSearchTerm;
+
+ return {
+ archivedBoards,
+ canCreateFromSearch: normalizedSearchTerm.length > 0 && !hasExactMatch,
+ dateBoards,
+ hasAnyMatch,
+ hasProjectBoardPlaceholder,
+ yourBoards,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
new file mode 100644
index 0000000000..cfa414335a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
@@ -0,0 +1,26 @@
+import type { GalleryBoard } from '@features/gallery/core/types';
+
+import { describe, expect, it } from 'vitest';
+
+import { getGalleryCountForView } from './galleryBoardLabels';
+
+const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
+ archived: false,
+ assetCount: 3,
+ id: 'dogs',
+ imageCount: 50,
+ kind: 'board',
+ name: 'dogs',
+ videoCount: 4,
+ ...overrides,
+});
+
+describe('getGalleryCountForView', () => {
+ it('counts images and videos together for the media view', () => {
+ expect(getGalleryCountForView(createBoard(), 'images')).toBe(54);
+ });
+
+ it('counts assets alone for the assets view', () => {
+ expect(getGalleryCountForView(createBoard(), 'assets')).toBe(3);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
new file mode 100644
index 0000000000..42ab71ffe5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
@@ -0,0 +1,13 @@
+import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';
+
+import { getBoardCounts } from './galleryStateView';
+
+/**
+ * How many items the active tab would show for a board, so a count always
+ * answers "how many of what I'm looking at".
+ */
+export const getGalleryCountForView = (board: GalleryBoard, galleryView: GalleryView): number => {
+ const counts = getBoardCounts(board);
+
+ return galleryView === 'assets' ? counts.assetCount : counts.imageCount + counts.videoCount;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.test.ts
new file mode 100644
index 0000000000..958cb13c1b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { GALLERY_WIDE_MIN_WIDTH_PX, getGalleryLayout } from './galleryDensity';
+
+describe('getGalleryLayout', () => {
+ it('keeps side panels stacked however wide they are measured', () => {
+ expect(getGalleryLayout({ region: 'left', widthPx: 2000 })).toBe('stacked');
+ expect(getGalleryLayout({ region: 'right', widthPx: 2000 })).toBe('stacked');
+ });
+
+ it('switches to wide at the threshold and back below it', () => {
+ expect(getGalleryLayout({ region: 'center', widthPx: GALLERY_WIDE_MIN_WIDTH_PX })).toBe('wide');
+ expect(getGalleryLayout({ region: 'center', widthPx: GALLERY_WIDE_MIN_WIDTH_PX - 1 })).toBe('stacked');
+ expect(getGalleryLayout({ region: 'bottom', widthPx: GALLERY_WIDE_MIN_WIDTH_PX })).toBe('wide');
+ expect(getGalleryLayout({ region: 'bottom', widthPx: 320 })).toBe('stacked');
+ });
+
+ it('stays stacked before the first measurement reports a width', () => {
+ expect(getGalleryLayout({ region: 'center', widthPx: 0 })).toBe('stacked');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts
new file mode 100644
index 0000000000..97851c154f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts
@@ -0,0 +1,68 @@
+import { useCallback, useLayoutEffect, useRef, useState, type Ref } from 'react';
+
+import type { GalleryWidgetProps } from './GalleryUiContext';
+
+type GalleryRegion = GalleryWidgetProps['region'];
+
+/**
+ * The gallery's two arrangements of one component set. Only the two shell
+ * components read it: every slot renders one way, so a size-dependent
+ * difference must be expressible as "which shell puts this where".
+ */
+export type GalleryLayoutMode = 'stacked' | 'wide';
+
+/** Below this the board column's ~240px leaves too little grid to scan. */
+export const GALLERY_WIDE_MIN_WIDTH_PX = 560;
+
+/** Side panels are capped well under the threshold, so they skip measuring. */
+export const getGalleryLayout = ({
+ region,
+ widthPx,
+}: {
+ region: GalleryRegion;
+ widthPx: number;
+}): GalleryLayoutMode => {
+ if (region === 'left' || region === 'right') {
+ return 'stacked';
+ }
+
+ return widthPx >= GALLERY_WIDE_MIN_WIDTH_PX ? 'wide' : 'stacked';
+};
+
+/** State only changes when the layout flips, not on every measured pixel. */
+export const useGalleryLayout = (
+ region: GalleryRegion
+): { layout: GalleryLayoutMode; rootRef: Ref<HTMLDivElement> } => {
+ const [layout, setLayout] = useState<GalleryLayoutMode>(() =>
+ region === 'left' || region === 'right' ? 'stacked' : 'wide'
+ );
+ const regionRef = useRef(region);
+
+ useLayoutEffect(() => {
+ regionRef.current = region;
+ }, [region]);
+
+ const applyMeasuredWidth = useCallback((widthPx: number) => {
+ setLayout(getGalleryLayout({ region: regionRef.current, widthPx }));
+ }, []);
+
+ const [rootRef] = useState(() => (node: HTMLDivElement | null) => {
+ if (!node) {
+ return;
+ }
+
+ const observer = new ResizeObserver((entries) => {
+ const widthPx = entries[0]?.contentRect.width;
+
+ if (typeof widthPx === 'number' && widthPx > 0) {
+ applyMeasuredWidth(widthPx);
+ }
+ });
+
+ observer.observe(node);
+
+ return () => observer.disconnect();
+ });
+
+ return { layout, rootRef };
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts
index 62b85448bf..d21c06b8c7 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts
@@ -1,8 +1,9 @@
import type { GalleryItem } from '@features/gallery/contracts';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
+ forwardGalleryBoardDrop,
getGalleryBoardDropData,
getGalleryItemDragData,
getGalleryItemDragId,
@@ -46,6 +47,17 @@ describe('galleryDnd', () => {
expect(getGalleryItemDragId(refs[1], 'gallery-grid')).toBe('gallery-grid:video:shared');
});
+ it("separates the same item in two surfaces, so one gallery's drag is not the other's", () => {
+ const ref = { kind: 'image', name: 'shared' } as const;
+
+ expect(getGalleryItemDragId(ref, 'gallery-grid', 'center')).toBe('gallery-grid#center:image:shared');
+ expect(getGalleryItemDragId(ref, 'gallery-grid', 'right')).not.toBe(
+ getGalleryItemDragId(ref, 'gallery-grid', 'center')
+ );
+ // Unscoped callers (the preview surfaces) keep their original ids.
+ expect(getGalleryItemDragId(ref, 'preview-frame')).toBe('preview-frame:image:shared');
+ });
+
it('recognizes only non-empty, well-formed gallery item payloads', () => {
expect(isGalleryItemDragData(getGalleryItemDragData([{ kind: 'video', name: 'clip.mp4' }]))).toBe(true);
expect(isGalleryItemDragData({ items: [], kind: 'gallery-item' })).toBe(false);
@@ -134,3 +146,51 @@ describe('galleryDnd', () => {
expect(isGalleryBoardDropData({ boardId: 'board-a', boardKind: 'generated', kind: 'gallery-board' })).toBe(false);
});
});
+
+describe('forwardGalleryBoardDrop', () => {
+ it('forwards the full ordered mixed resolution without stripping video refs', () => {
+ const moveItemsToBoard = vi.fn();
+ const dragData = getGalleryItemDragData([
+ { kind: 'video', name: 'shared' },
+ { kind: 'image', name: 'image.png' },
+ { kind: 'image', name: 'shared' },
+ ]);
+ const loadedItems = [
+ createItem('image', 'shared', 'board-b'),
+ createItem('video', 'shared', 'board-a'),
+ createItem('image', 'image.png', 'none'),
+ ];
+
+ expect(
+ forwardGalleryBoardDrop({
+ activeData: dragData,
+ loadedItems,
+ moveItemsToBoard,
+ overData: getGalleryBoardDropData('board-b', 'board'),
+ })
+ ).toBe(true);
+ expect(moveItemsToBoard).toHaveBeenCalledOnce();
+ expect(moveItemsToBoard).toHaveBeenCalledWith(
+ [
+ { kind: 'video', name: 'shared' },
+ { kind: 'image', name: 'image.png' },
+ ],
+ 'board-b'
+ );
+ });
+
+ it('reports an unresolved drop without moving anything', () => {
+ const moveItemsToBoard = vi.fn();
+ const image = createItem('image', 'image.png', 'board-a');
+
+ expect(
+ forwardGalleryBoardDrop({
+ activeData: getGalleryItemDragData([{ kind: 'image', name: image.name }]),
+ loadedItems: [image],
+ moveItemsToBoard,
+ overData: getGalleryBoardDropData('by_date:2026-07-30', 'date'),
+ })
+ ).toBe(false);
+ expect(moveItemsToBoard).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
index fb868da594..f2167ee8a2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts
@@ -29,10 +29,17 @@ export interface GalleryBoardDropResolution {
}
export type GalleryItemDragSource = 'gallery-grid' | 'preview-filmstrip' | 'preview-frame';
-export type GalleryItemDragId = `${GalleryItemDragSource}:${GalleryItemKey}`;
-
-export const getGalleryItemDragId = (item: GalleryItemRef, source: GalleryItemDragSource): GalleryItemDragId =>
- `${source}:${toGalleryItemKey(item)}`;
+export type GalleryItemDragId = `${GalleryItemDragSource}${string}:${GalleryItemKey}`;
+
+/**
+ * `scope` separates surfaces showing the same item: dnd-kit keys drag state by
+ * id, so two galleries sharing one both report as dragging.
+ */
+export const getGalleryItemDragId = (
+ item: GalleryItemRef,
+ source: GalleryItemDragSource,
+ scope?: string
+): GalleryItemDragId => `${source}${scope ? `#${scope}` : ''}:${toGalleryItemKey(item)}`;
export const getGalleryBoardDropId = (boardId: string): string => `gallery-board:${boardId}`;
@@ -95,6 +102,28 @@ export const resolveGalleryBoardDrop = (
return items.length > 0 ? { boardId: overData.boardId, items } : null;
};
+/** Applies a board drop if the drag resolves to one, reporting whether it did. */
+export const forwardGalleryBoardDrop = ({
+ activeData,
+ loadedItems,
+ moveItemsToBoard,
+ overData,
+}: {
+ activeData: unknown;
+ loadedItems: readonly GalleryItem[];
+ moveItemsToBoard: (items: GalleryItemRef[], boardId: string) => void;
+ overData: unknown;
+}): boolean => {
+ const resolution = resolveGalleryBoardDrop(activeData, overData, loadedItems);
+
+ if (!resolution) {
+ return false;
+ }
+
+ moveItemsToBoard(resolution.items, resolution.boardId);
+ return true;
+};
+
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;
const isGalleryItemRef = (value: unknown): value is GalleryItemRef =>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts
new file mode 100644
index 0000000000..b628f1eb86
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { GALLERY_GRID_GAP_PX, getGalleryCellSizePx, getGalleryColumnCount } from './galleryGridLayout';
+
+describe('getGalleryColumnCount', () => {
+ it('gives the same answer at the same width regardless of placement', () => {
+ // The whole point of measuring rather than branching on layout: a 600px
+ // gallery is a 600px gallery whether it sits in a panel or the center.
+ const stacked = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 600 });
+ const wide = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 600 });
+
+ expect(stacked).toBe(wide);
+ });
+
+ it('fits more columns as the viewport grows', () => {
+ const narrow = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 360 });
+ const roomy = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 1200 });
+
+ expect(roomy).toBeGreaterThan(narrow);
+ });
+
+ it('fits more columns as density rises', () => {
+ const sparse = getGalleryColumnCount({ imageDensityPercent: 0, widthPx: 800 });
+ const dense = getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 800 });
+
+ expect(dense).toBeGreaterThan(sparse);
+ });
+
+ it('clamps to a usable range at both extremes', () => {
+ expect(getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 40 })).toBe(2);
+ expect(getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 8000 })).toBe(12);
+ expect(getGalleryColumnCount({ imageDensityPercent: 0, widthPx: 8000 })).toBe(12);
+ });
+
+ it('ignores out-of-range density instead of producing a nonsense count', () => {
+ expect(getGalleryColumnCount({ imageDensityPercent: -50, widthPx: 800 })).toBe(
+ getGalleryColumnCount({ imageDensityPercent: 0, widthPx: 800 })
+ );
+ expect(getGalleryColumnCount({ imageDensityPercent: 500, widthPx: 800 })).toBe(
+ getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 800 })
+ );
+ });
+
+ it('falls back to the minimum before the viewport has been measured', () => {
+ expect(getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 0 })).toBe(2);
+ });
+});
+
+describe('getGalleryCellSizePx', () => {
+ it('divides the width evenly after removing the inter-column gaps', () => {
+ expect(getGalleryCellSizePx({ columnCount: 4, widthPx: 400 + GALLERY_GRID_GAP_PX * 3 })).toBe(100);
+ });
+
+ it('uses a plausible square before measurement so the first paint is not zero-height', () => {
+ expect(getGalleryCellSizePx({ columnCount: 4, widthPx: 0 })).toBe(96);
+ });
+
+ it('never returns a non-positive size when the width is smaller than the gaps', () => {
+ expect(getGalleryCellSizePx({ columnCount: 12, widthPx: 4 })).toBeGreaterThan(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts
new file mode 100644
index 0000000000..24a3444206
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts
@@ -0,0 +1,44 @@
+export const GALLERY_GRID_GAP_PX = 4;
+
+const GALLERY_MIN_COLUMN_COUNT = 2;
+const GALLERY_MAX_COLUMN_COUNT = 12;
+
+/** Cell size the density slider interpolates between: 0% is largest, 100% smallest. */
+const GALLERY_MAX_CELL_PX = 192;
+const GALLERY_MIN_CELL_PX = 48;
+
+/**
+ * Density picks a target thumbnail size, and the available width decides how
+ * many of those fit.
+ *
+ * Keying off width rather than placement is what lets the two layouts share
+ * one grid: at equal pixel width the same density produces the same columns
+ * whether the gallery sits in a side panel or the center. The old
+ * layout-keyed maximum meant 50% density meant ~90px cells stacked and ~200px
+ * cells wide.
+ */
+export const getGalleryTargetCellPx = (imageDensityPercent: number): number => {
+ const percent = Math.min(100, Math.max(0, imageDensityPercent));
+
+ return GALLERY_MAX_CELL_PX - ((GALLERY_MAX_CELL_PX - GALLERY_MIN_CELL_PX) * percent) / 100;
+};
+
+export const getGalleryColumnCount = ({
+ imageDensityPercent,
+ widthPx,
+}: {
+ imageDensityPercent: number;
+ widthPx: number;
+}): number => {
+ if (widthPx <= 0) {
+ return GALLERY_MIN_COLUMN_COUNT;
+ }
+
+ const columnCount = Math.round(widthPx / getGalleryTargetCellPx(imageDensityPercent));
+
+ return Math.min(GALLERY_MAX_COLUMN_COUNT, Math.max(GALLERY_MIN_COLUMN_COUNT, columnCount));
+};
+
+/** Falls back to a plausible square before the viewport has been measured. */
+export const getGalleryCellSizePx = ({ columnCount, widthPx }: { columnCount: number; widthPx: number }): number =>
+ widthPx > 0 ? Math.max(1, (widthPx - GALLERY_GRID_GAP_PX * (columnCount - 1)) / columnCount) : 96;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts
new file mode 100644
index 0000000000..68a1aed7df
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts
@@ -0,0 +1,14 @@
+import { useId, useMemo } from 'react';
+
+/**
+ * Shared trigger id for a menu whose trigger a `Tooltip` wraps. Both machines
+ * render onto one element and each wants to own its id; without this the menu
+ * has no anchor and opens at the viewport origin.
+ *
+ * @see workbench/shell/topbar/RoutingControl.tsx
+ */
+export const useMenuTriggerIds = (): { trigger: string } => {
+ const triggerId = useId();
+
+ return useMemo(() => ({ trigger: triggerId }), [triggerId]);
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index 6586683fa6..995df40b3d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -21,7 +21,7 @@ const boards: GalleryBoard[] = [
id: 'none',
imageCount: 1,
kind: 'uncategorized',
- name: 'Uncategorized',
+ name: '',
videoCount: 0,
},
{ archived: false, assetCount: 0, id: 'board-1', imageCount: 2, kind: 'board', name: 'Board 1', videoCount: 0 },
@@ -138,6 +138,10 @@ describe('gallery state view', () => {
expect(gallery.settings).toEqual({
boardOrderBy: 'board_name',
boardOrderDir: 'DESC',
+ boardPanelCollapsed: false,
+ boardPanelHeightPx: 280,
+ boardPanelWidthPx: 240,
+ collapsedBoardSections: [],
imageDensityPercent: 50,
imageOrderDir: 'DESC',
paginationMode: 'infinite',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index ef992d5b69..3cdd27ab92 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -16,13 +16,18 @@ import {
import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';
import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';
+/**
+ * Stand-in shown before any board has loaded. `name` is intentionally empty:
+ * the UI labels uncategorized boards from `kind` through `getGalleryBoardLabel`,
+ * so there is no English string to invent here.
+ */
const UNCATEGORIZED_BOARD: GalleryBoard = {
archived: false,
assetCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
- name: 'Uncategorized',
+ name: '',
videoCount: 0,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
index 6f30c26f7f..8e9c2b5a74 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
@@ -71,6 +71,7 @@ vi.mock('react-i18next', () => ({
)}. ${String(values?.failed)} failed.`,
'widgets.gallery.uploadSuccessTitle': `Uploaded ${String(values?.count)} files`,
'widgets.gallery.uploadUnsupported': 'No supported media files to upload (PNG, JPEG, WebP, or MP4).',
+ 'widgets.gallery.uncategorized': 'Uncategorized',
'widgets.gallery.videoCount': `${String(values?.count)} videos`,
};
@@ -121,6 +122,15 @@ const Probe = ({
name: 'Board 1',
videoCount: 1,
},
+ {
+ archived: false,
+ assetCount: 0,
+ id: 'none',
+ imageCount: 0,
+ kind: 'uncategorized',
+ name: '',
+ videoCount: 0,
+ },
],
loadMore: vi.fn(),
projectBoardId: null,
@@ -254,6 +264,22 @@ describe('deleteBoard', () => {
});
});
+describe('localized board labels', () => {
+ it('uses the localized Uncategorized label in board notifications', async () => {
+ mocks.downloadGalleryArchive.mockResolvedValue({ blob: new Blob(['archive']), fileName: 'gallery.zip' });
+
+ await act(async () => {
+ await actionsRef.current?.downloadBoard('none');
+ });
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'info',
+ message: 'Preparing an image archive of "Uncategorized". 0 video will be omitted.',
+ title: 'Preparing download',
+ });
+ });
+});
+
describe('mixed item selection', () => {
it('forwards an ordered same-name mixed range as qualified item keys', () => {
const primaryItem = {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 231286be47..95d721369e 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -1,16 +1,12 @@
-import type { GalleryItem } from '@features/gallery/core/items';
import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';
-import { compareGalleryItems, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery/core/items';
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { toGalleryItemKey } from '@features/gallery/core/items';
import {
- classifyGalleryUpload,
createGalleryBoard,
deleteGalleryBoard,
downloadGalleryArchive,
- isDateBoardId,
updateGalleryBoard,
- uploadGalleryImage,
- uploadGalleryVideo,
} from '@features/gallery/data/backend';
import { invalidateGallery } from '@features/gallery/data/queryCache';
import { downloadBlob } from '@platform/browser/downloadBlob';
@@ -26,6 +22,7 @@ import { useTranslation } from 'react-i18next';
import type { GalleryActions } from './GalleryWidgetContext';
import { useGalleryUi } from './GalleryUiContext';
+import { useGalleryUploadAction } from './useGalleryUploadAction';
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
@@ -47,6 +44,7 @@ export const useGalleryActions = ({
const { gallery, notifications } = useGalleryUi();
const queryClient = useQueryClient();
const { t } = useTranslation();
+ const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });
return useMemo<GalleryActions>(() => {
const recordError = (error: unknown) =>
@@ -54,7 +52,11 @@ export const useGalleryActions = ({
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
const refresh = () => void invalidateGallery(queryClient);
const getBoard = (boardId: string) => boards.find((board) => board.id === boardId);
- const getBoardName = (boardId: string) => getBoard(boardId)?.name ?? t('widgets.gallery.uncategorized');
+ const getBoardName = (boardId: string) => {
+ const board = getBoard(boardId);
+
+ return board ? getGalleryBoardLabel(board, t) : t('widgets.gallery.uncategorized');
+ };
const formatImageCount = (count: number) => t('widgets.gallery.imageCount', { count });
const formatVideoCount = (count: number) => t('widgets.gallery.videoCount', { count });
@@ -224,134 +226,11 @@ export const useGalleryActions = ({
setView: gallery.setView,
toggleItemInSelection: gallery.toggleItemSelection,
updateSettings: gallery.updateSettings,
- uploadFiles: async (files) => {
- const owner = captureAccountScope();
-
- if (isDateBoardId(selectedBoardId)) {
- notifications.reportError({
- area: 'gallery-upload',
- message: t('widgets.gallery.uploadDateBoardUnavailable'),
- namespace: 'gallery',
- });
- return;
- }
-
- const accepted = files.flatMap((file) => {
- const classification = classifyGalleryUpload(file);
-
- return classification ? [{ file, kind: classification.kind }] : [];
- });
-
- if (accepted.length === 0) {
- notifications.reportError({
- area: 'gallery-upload',
- message: t('widgets.gallery.uploadUnsupported'),
- namespace: 'gallery',
- });
- return;
- }
-
- try {
- const targetBoardId = getBoard(selectedBoardId)?.kind === 'board' ? selectedBoardId : 'none';
- const targetBoardName = getBoardName(selectedBoardId);
- const imageUploads = accepted.filter((upload) => upload.kind === 'image');
- const videoUploads = accepted.filter((upload) => upload.kind === 'video');
- const imageResultsPromise = Promise.allSettled(
- imageUploads.map(({ file }) => uploadGalleryImage(file, targetBoardId, { signal: owner.signal }))
- );
- const videoResultsPromise = (async () => {
- const results: PromiseSettledResult<GalleryItem>[] = [];
-
- for (const { file } of videoUploads) {
- owner.signal.throwIfAborted();
-
- try {
- results.push({
- status: 'fulfilled',
- value: await uploadGalleryVideo(file, targetBoardId, { signal: owner.signal }),
- });
- } catch (reason: unknown) {
- if (owner.signal.aborted) {
- throw reason;
- }
-
- results.push({ reason, status: 'rejected' });
- }
- }
-
- return results;
- })();
- const [imageResults, videoResults] = await Promise.all([imageResultsPromise, videoResultsPromise]);
-
- assertAccountScopeCurrent(owner);
- const uploadedImages = imageResults.flatMap((result) =>
- result.status === 'fulfilled' ? [legacyGeneratedImageToGalleryItem(result.value)] : []
- );
- const uploadedVideos = videoResults.flatMap((result) =>
- result.status === 'fulfilled' ? [result.value] : []
- );
- const uploadedItems = [...uploadedImages, ...uploadedVideos];
- const failedCount = files.length - uploadedItems.length;
-
- if (uploadedItems.length === 0) {
- notifications.reportError({
- area: 'gallery-upload',
- message: t('widgets.gallery.uploadFailed', { failed: failedCount }),
- namespace: 'gallery',
- });
- 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 newestVisibleUpload = visibleUploads.reduce<GalleryItem | undefined>(
- (newest, item) =>
- newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,
- undefined
- );
-
- if (newestVisibleUpload) {
- gallery.selectItem(newestVisibleUpload);
- }
-
- refresh();
-
- const summary = t('widgets.gallery.uploadSummary', {
- board: targetBoardName,
- failed: failedCount,
- images: formatImageCount(uploadedImages.length),
- videos: formatVideoCount(uploadedVideos.length),
- });
- const split =
- imageUploads.length > 0 && videoUploads.length > 0 ? ` ${t('widgets.gallery.uploadSplit')}` : '';
- recordSuccess(
- t(
- failedCount > 0 ? 'widgets.gallery.uploadPartialTitle' : 'widgets.gallery.uploadSuccessTitle',
- failedCount > 0
- ? { succeeded: uploadedItems.length, total: files.length }
- : { count: uploadedItems.length }
- ),
- `${summary}${split}`
- );
- } catch (error: unknown) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- recordError(error);
- }
- },
+ uploadFiles,
};
}, [
boards,
gallery,
- getCurrentGalleryLocation,
loadMore,
notifications,
projectBoardId,
@@ -359,5 +238,6 @@ export const useGalleryActions = ({
queryClient,
selectedBoardId,
t,
+ uploadFiles,
]);
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts
new file mode 100644
index 0000000000..fa9d67450a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts
@@ -0,0 +1,115 @@
+import type { GalleryItemRef } from '@features/gallery/core/items';
+
+import { shouldStarSelection, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/core/items';
+import { useEffect, useEffectEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGalleryUi } from './GalleryUiContext';
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+type GalleryNavDirection = 'down' | 'left' | 'right' | 'up';
+
+const GALLERY_HOTKEYS = [
+ ['gallery.selectAllOnPage', 'widgets.gallery.commands.selectAllOnPage', null, ['mod+a']],
+ ['gallery.clearSelection', 'widgets.gallery.commands.clearSelection', null, ['esc']],
+ ['gallery.galleryNavUp', 'widgets.gallery.commands.navigationUp', 'up', ['arrowup']],
+ ['gallery.galleryNavRight', 'widgets.gallery.commands.navigationRight', 'right', ['arrowright']],
+ ['gallery.galleryNavDown', 'widgets.gallery.commands.navigationDown', 'down', ['arrowdown']],
+ ['gallery.galleryNavLeft', 'widgets.gallery.commands.navigationLeft', 'left', ['arrowleft']],
+ ['gallery.galleryNavUpAlt', 'widgets.gallery.commands.navigationUp', 'up', ['alt+arrowup']],
+ ['gallery.galleryNavRightAlt', 'widgets.gallery.commands.navigationRight', 'right', ['alt+arrowright']],
+ ['gallery.galleryNavDownAlt', 'widgets.gallery.commands.navigationDown', 'down', ['alt+arrowdown']],
+ ['gallery.galleryNavLeftAlt', 'widgets.gallery.commands.navigationLeft', 'left', ['alt+arrowleft']],
+ ['gallery.deleteSelection', 'widgets.gallery.commands.deleteSelection', null, ['delete', 'backspace']],
+ ['gallery.starImage', 'widgets.gallery.commands.toggleStarImage', null, ['.']],
+] as const satisfies readonly (readonly [string, string, GalleryNavDirection | null, readonly string[]])[];
+
+/**
+ * Registers the grid's commands and their default keys.
+ *
+ * Handlers run through `useEffectEvent` so registration depends only on the
+ * runtime and the translator: re-registering every command on each selection
+ * change would churn the palette and the hotkey map on every click.
+ */
+export const useGalleryGridHotkeys = ({
+ actionSelectionRefs,
+ columnCount,
+ scrollToItemIndex,
+}: {
+ actionSelectionRefs: GalleryItemRef[];
+ columnCount: number;
+ scrollToItemIndex: (itemIndex: number) => void;
+}) => {
+ const { t } = useTranslation();
+ const { actions, gallery, itemActions, runtime } = useGalleryWidget();
+ const { widgets } = useGalleryUi();
+
+ const navigate = useEffectEvent((direction: GalleryNavDirection) => {
+ const itemCount = gallery.items.length;
+
+ if (itemCount === 0) {
+ return;
+ }
+
+ const selectedIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === gallery.selectedItemKey);
+ const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;
+ const delta =
+ direction === 'right' ? 1 : direction === 'left' ? -1 : direction === 'down' ? columnCount : -columnCount;
+ const nextIndex = Math.min(itemCount - 1, Math.max(0, fallbackIndex + delta));
+ const nextItem = gallery.items[nextIndex];
+
+ if (nextItem && (nextIndex !== selectedIndex || selectedIndex === -1)) {
+ actions.selectItem(nextItem);
+ scrollToItemIndex(nextIndex);
+ }
+ });
+
+ const executeGalleryHotkey = useEffectEvent((commandId: string) => {
+ if (commandId === 'gallery.selectAllOnPage') {
+ const primaryItem = gallery.items[0];
+
+ if (primaryItem) {
+ actions.selectItemRange(gallery.items.map(toGalleryItemRef), primaryItem);
+ }
+ return;
+ }
+
+ if (commandId === 'gallery.clearSelection') {
+ widgets.patchGalleryValues({
+ selectedImage: null,
+ selectedImageName: null,
+ selectedImageNames: [],
+ });
+ return;
+ }
+
+ if (commandId === 'gallery.deleteSelection' && actionSelectionRefs.length > 0) {
+ void itemActions.deleteItems(actionSelectionRefs);
+ return;
+ }
+
+ if (commandId === 'gallery.starImage' && actionSelectionRefs.length > 0) {
+ void itemActions.setItemsStarred(actionSelectionRefs, shouldStarSelection(gallery.items, actionSelectionRefs));
+ }
+ });
+
+ useEffect(() => {
+ const disposers = GALLERY_HOTKEYS.flatMap(([id, titleKey, direction, defaultKeys]) => [
+ runtime.commands.register({
+ handler: () => (direction ? navigate(direction) : executeGalleryHotkey(id)),
+ id,
+ title: t(titleKey),
+ }),
+ runtime.hotkeys.register({
+ commandId: id,
+ defaultKeys: [...defaultKeys],
+ id,
+ title: t(titleKey),
+ }),
+ ]);
+
+ return () => {
+ disposers.forEach((dispose) => dispose());
+ };
+ }, [runtime.commands, runtime.hotkeys, t]);
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts
new file mode 100644
index 0000000000..de8f61c2fe
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts
@@ -0,0 +1,220 @@
+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';
+
+import {
+ isGalleryImageItem,
+ parseGalleryItemKey,
+ toGalleryItemKey,
+ toGalleryItemRef,
+} from '@features/gallery/core/items';
+import { isDateBoardId, type GalleryItemNames } from '@features/gallery/data/backend';
+import { galleryItemNamesOptions } from '@features/gallery/data/queries';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
+import { useCallback, useMemo, useRef, useState, type MouseEvent } from 'react';
+
+import type { GalleryItemContextMenuTarget } from './GalleryUiContext';
+
+import { useGalleryWidget } from './GalleryWidgetContext';
+
+const getGalleryItemRange = (
+ orderedRefs: readonly GalleryItemRef[],
+ anchorItemKey: string,
+ targetItemKey: string
+): GalleryItemRef[] | null => {
+ const anchorIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === anchorItemKey);
+ const targetIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === targetItemKey);
+
+ if (anchorIndex === -1 || targetIndex === -1) {
+ return null;
+ }
+
+ const start = Math.min(anchorIndex, targetIndex);
+ const end = Math.max(anchorIndex, targetIndex);
+
+ return orderedRefs.slice(start, end + 1);
+};
+
+/**
+ * Click semantics for grid tiles — plain select, shift-range, ctrl/cmd-toggle,
+ * alt-compare — plus the context-menu target.
+ *
+ * Range selection can span beyond the loaded window, so it fetches the full
+ * ordered name list. That is asynchronous, and the user can keep interacting
+ * while it is in flight, hence the captured-context guard: a range only applies
+ * if the account, the query filter, and the anchor are all still what they were
+ * when the click happened.
+ */
+export const useGalleryGridSelection = () => {
+ const { actions, filter, gallery } = useGalleryWidget();
+ const queryClient = useQueryClient();
+ const [contextMenuTarget, setContextMenuTarget] = useState<GalleryItemContextMenuTarget | null>(null);
+
+ const selectedItemKeys = useMemo(() => new Set(gallery.selectedItemKeys), [gallery.selectedItemKeys]);
+ const selectedItemRefs = useMemo(() => gallery.selectedItemKeys.map(parseGalleryItemKey), [gallery.selectedItemKeys]);
+
+ const filterIdentity = useMemo(() => JSON.stringify(filter), [filter]);
+ const rangeInteractionContextRef = useRef({ filterIdentity, selectedItemKey: gallery.selectedItemKey });
+
+ const syncRangeInteractionContext = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (node) {
+ rangeInteractionContextRef.current = { filterIdentity, selectedItemKey: gallery.selectedItemKey };
+ }
+ },
+ [filterIdentity, gallery.selectedItemKey]
+ );
+
+ const activeContextMenuTarget = useMemo(() => {
+ const primaryTargetItem = contextMenuTarget?.items[0];
+
+ if (!primaryTargetItem) {
+ return contextMenuTarget;
+ }
+
+ const primaryTargetItemKey = toGalleryItemKey(primaryTargetItem);
+
+ return gallery.items.some((item) => toGalleryItemKey(item) === primaryTargetItemKey) ? contextMenuTarget : null;
+ }, [contextMenuTarget, gallery.items]);
+
+ const selectItemRange = useCallback(
+ async (item: GalleryItem) => {
+ const owner = captureAccountScope();
+ const capturedContext = rangeInteractionContextRef.current;
+ const anchorItemKey = capturedContext.selectedItemKey;
+ const targetItemKey = toGalleryItemKey(item);
+
+ if (!anchorItemKey) {
+ actions.selectItem(item);
+ return;
+ }
+
+ const isInteractionCurrent = () =>
+ isAccountScopeCurrent(owner) &&
+ rangeInteractionContextRef.current.filterIdentity === capturedContext.filterIdentity &&
+ rangeInteractionContextRef.current.selectedItemKey === capturedContext.selectedItemKey;
+ const selectFromRefs = (refs: readonly GalleryItemRef[]): boolean => {
+ const range = getGalleryItemRange(refs, anchorItemKey, targetItemKey);
+
+ if (!range) {
+ return false;
+ }
+
+ actions.selectItemRange(range, item);
+ return true;
+ };
+ const materializedRefs = gallery.items.map(toGalleryItemRef);
+ const namesOptions = galleryItemNamesOptions(filter);
+
+ try {
+ const orderedRefs = isDateBoardId(filter.boardId)
+ ? queryClient.getQueryData<GalleryItemNames>(namesOptions.queryKey)?.items
+ : (await queryClient.fetchQuery(namesOptions)).items;
+
+ if (!isInteractionCurrent()) {
+ return;
+ }
+
+ if (orderedRefs && selectFromRefs(orderedRefs)) {
+ return;
+ }
+ } catch {
+ if (!isInteractionCurrent()) {
+ return;
+ }
+ }
+
+ if (!selectFromRefs(materializedRefs)) {
+ actions.selectItem(item);
+ }
+ },
+ [actions, filter, gallery.items, queryClient]
+ );
+
+ const handleThumbnailClick = useCallback(
+ (item: GalleryItem, event: MouseEvent) => {
+ if (event.shiftKey) {
+ void selectItemRange(item);
+ return;
+ }
+
+ if (event.altKey && isGalleryImageItem(item)) {
+ actions.setCompareItem(item);
+ return;
+ }
+
+ if (event.ctrlKey || event.metaKey) {
+ const itemKey = toGalleryItemKey(item);
+ const remainingItemKeys = gallery.selectedItemKeys.filter((key) => key !== itemKey);
+ const nextPrimaryItem =
+ gallery.selectedItemKey === itemKey
+ ? (gallery.items.find(
+ (candidate) => toGalleryItemKey(candidate) === remainingItemKeys[remainingItemKeys.length - 1]
+ ) ?? null)
+ : null;
+
+ actions.toggleItemInSelection(item, nextPrimaryItem);
+ } else {
+ actions.selectItem(item);
+ }
+ },
+ [actions, gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys, selectItemRange]
+ );
+
+ const handleThumbnailContextMenu = useCallback(
+ (item: GalleryItem, x: number, y: number) => {
+ const itemKey = toGalleryItemKey(item);
+
+ if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {
+ const selectionItems = [
+ item,
+ ...gallery.items.filter(
+ (candidate) => toGalleryItemKey(candidate) !== itemKey && selectedItemKeys.has(toGalleryItemKey(candidate))
+ ),
+ ];
+
+ setContextMenuTarget({ itemRefs: selectedItemRefs, items: selectionItems, x, y });
+ return;
+ }
+
+ setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y });
+ },
+ [gallery.items, selectedItemKeys, selectedItemRefs]
+ );
+
+ const getDragItems = useCallback(
+ (item: GalleryItem): GalleryItemRef[] => {
+ const itemKey = toGalleryItemKey(item);
+
+ if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {
+ return selectedItemRefs;
+ }
+
+ return [toGalleryItemRef(item)];
+ },
+ [selectedItemKeys, selectedItemRefs]
+ );
+
+ const handleCloseContextMenu = useCallback(() => setContextMenuTarget(null), []);
+
+ /** Falls back to the primary selection so hotkeys work before a multi-select. */
+ const actionSelectionRefs = useMemo(
+ () =>
+ selectedItemRefs.length > 0
+ ? selectedItemRefs
+ : gallery.selectedItemKey
+ ? [parseGalleryItemKey(gallery.selectedItemKey)]
+ : [],
+ [gallery.selectedItemKey, selectedItemRefs]
+ );
+
+ return {
+ actionSelectionRefs,
+ activeContextMenuTarget,
+ getDragItems,
+ handleCloseContextMenu,
+ handleThumbnailClick,
+ handleThumbnailContextMenu,
+ selectedItemKeys,
+ syncRangeInteractionContext,
+ };
+};
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.tsx
new file mode 100644
index 0000000000..2e1d6a0ba1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
@@ -0,0 +1,421 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
+
+import { GalleryUiProvider } from '@features/gallery/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, createRef, type Ref, type ReactNode, useCallback, useImperativeHandle, useRef } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GalleryActions } from './GalleryWidgetContext';
+
+import { useGalleryUploadAction } from './useGalleryUploadAction';
+
+const mocks = vi.hoisted(() => ({
+ invalidateGallery: vi.fn(),
+ notificationsAdd: vi.fn(),
+ notificationsReportError: vi.fn(),
+ uploadGalleryImage: vi.fn(),
+ uploadGalleryVideo: vi.fn(),
+}));
+
+vi.mock('@features/gallery/data/backend', () => ({
+ classifyGalleryUpload: (file: File) => {
+ const type = file.type.toLowerCase();
+ const name = file.name.toLowerCase();
+
+ if (['image/jpeg', 'image/jpg', 'image/png', 'image/webp'].includes(type) || /\.(jpe?g|png|webp)$/.test(name)) {
+ return { kind: 'image' as const };
+ }
+ if (type === 'video/mp4' || name.endsWith('.mp4')) {
+ return { kind: 'video' as const };
+ }
+ return null;
+ },
+ isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),
+ uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),
+ uploadGalleryVideo: (...args: unknown[]) => mocks.uploadGalleryVideo(...args),
+}));
+
+vi.mock('@features/gallery/data/queryCache', () => ({
+ invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const messages: Record<string, string> = {
+ 'widgets.gallery.imageCount': `${String(values?.count)} images`,
+ 'widgets.gallery.uploadDateBoardUnavailable': 'Uploads are unavailable for date boards.',
+ 'widgets.gallery.uploadFailed': `No files uploaded. ${String(values?.failed)} failed.`,
+ 'widgets.gallery.uploadPartialTitle': `Uploaded ${String(values?.succeeded)} of ${String(values?.total)} files`,
+ 'widgets.gallery.uploadSplit': 'Images appear in Assets; videos appear in Media.',
+ 'widgets.gallery.uploadSummary': `${String(values?.images)} and ${String(values?.videos)} uploaded to ${String(
+ values?.board
+ )}. ${String(values?.failed)} failed.`,
+ 'widgets.gallery.uploadSuccessTitle': `Uploaded ${String(values?.count)} files`,
+ 'widgets.gallery.uploadUnsupported': 'No supported media files to upload (PNG, JPEG, WebP, or MP4).',
+ 'widgets.gallery.uncategorized': 'Uncategorized',
+ 'widgets.gallery.videoCount': `${String(values?.count)} videos`,
+ };
+
+ return messages[key] ?? key;
+ },
+ }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+const uploadFilesRef = createRef<GalleryActions['uploadFiles']>();
+const selectItem = vi.fn();
+const noop = vi.fn();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const NoopProvider = ({ children }: { children: ReactNode }) => children;
+const adapter: GalleryUiAdapter = {
+ ItemActionsProvider: NoopProvider,
+ ImageContextMenu: () => null,
+ account: { enableLiveFollow: noop },
+ antialiasProgressImages: false,
+ gallery: {
+ reconcileDeletedBoardOutcome: noop,
+ selectBoard: noop,
+ selectImage: noop,
+ selectItem,
+ setCompareImage: noop,
+ setCompareItem: noop,
+ setItemMultiSelection: noop,
+ setPage: noop,
+ setPageInfo: noop,
+ setProjectBoard: noop,
+ setSearchTerm: noop,
+ setView: noop,
+ toggleItemSelection: noop,
+ updateSettings: noop,
+ },
+ galleryValues: {},
+ generateValues: {},
+ liveFollowEnabled: false,
+ liveProgressTarget: null,
+ notifications: {
+ add: (...args: unknown[]) => mocks.notificationsAdd(...args),
+ reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),
+ },
+ projectId: 'project-1',
+ projectName: 'Project',
+ queueItems: [],
+ widgets: { patchGalleryValues: noop },
+};
+
+const Probe = ({
+ galleryView,
+ ref,
+ selectedBoardId,
+}: {
+ galleryView: 'images' | 'assets';
+ ref: Ref<GalleryActions['uploadFiles']>;
+ selectedBoardId: string;
+}) => {
+ const currentGalleryLocationRef = useRef({ galleryView, selectedBoardId });
+
+ // eslint-disable-next-line react/react-compiler
+ currentGalleryLocationRef.current = { galleryView, selectedBoardId };
+ const getCurrentGalleryLocation = useCallback(() => currentGalleryLocationRef.current, []);
+ const uploadFiles = useGalleryUploadAction({
+ boards: [
+ {
+ archived: false,
+ assetCount: 0,
+ id: 'board-1',
+ imageCount: 2,
+ kind: 'board',
+ name: 'Board 1',
+ videoCount: 1,
+ },
+ {
+ archived: false,
+ assetCount: 0,
+ id: 'none',
+ imageCount: 0,
+ kind: 'uncategorized',
+ name: '',
+ videoCount: 0,
+ },
+ ],
+ getCurrentGalleryLocation,
+ selectedBoardId,
+ });
+
+ useImperativeHandle(ref, () => uploadFiles, [uploadFiles]);
+ return null;
+};
+
+let selectedBoardId = 'board-1';
+let galleryView: 'images' | 'assets' = 'images';
+
+const renderProbe = async () => {
+ await act(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <GalleryUiProvider adapter={adapter}>
+ <Probe galleryView={galleryView} ref={uploadFilesRef} selectedBoardId={selectedBoardId} />
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ );
+ });
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ accountLifecycle.activate('user-a');
+ selectedBoardId = 'board-1';
+ galleryView = 'images';
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await renderProbe();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+const imageUpload = (name: string, queuedAt: string, boardId = 'board-1') => ({
+ boardId,
+ height: 64,
+ imageCategory: 'user' as const,
+ imageName: name,
+ imageUrl: `/images/${name}`,
+ queuedAt,
+ sourceQueueItemId: 'upload',
+ starred: false,
+ thumbnailUrl: `/thumbnails/${name}`,
+ width: 64,
+});
+
+const videoUpload = (name: string, createdAt: string) => ({
+ boardId: 'board-1',
+ category: 'general' as const,
+ createdAt,
+ durationSeconds: 4,
+ fullUrl: `/videos/${name}`,
+ height: 64,
+ isIntermediate: false,
+ kind: 'video' as const,
+ name,
+ starred: false,
+ thumbnailUrl: `/video-thumbnails/${name}`,
+ width: 64,
+});
+
+describe('focused gallery upload action', () => {
+ it('rejects a date-board upload before starting any request', async () => {
+ selectedBoardId = 'by_date:2026-07-30';
+ await renderProbe();
+
+ await act(async () => {
+ await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
+ });
+
+ expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
+ expect(mocks.uploadGalleryVideo).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).toHaveBeenCalledWith({
+ area: 'gallery-upload',
+ message: 'Uploads are unavailable for date boards.',
+ namespace: 'gallery',
+ });
+ });
+
+ it('uploads images concurrently while running videos sequentially and continuing after a file failure', async () => {
+ let resolveFirstImage: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ let resolveSecondImage: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ let resolveFirstVideo: ((value: ReturnType<typeof videoUpload>) => void) | undefined;
+ const firstImage = new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveFirstImage = resolve;
+ });
+ const secondImage = new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveSecondImage = resolve;
+ });
+ const firstVideo = new Promise<ReturnType<typeof videoUpload>>((resolve) => {
+ resolveFirstVideo = resolve;
+ });
+ mocks.uploadGalleryImage.mockReturnValueOnce(firstImage).mockReturnValueOnce(secondImage);
+ mocks.uploadGalleryVideo
+ .mockReturnValueOnce(firstVideo)
+ .mockRejectedValueOnce(new Error('bad second video'))
+ .mockResolvedValueOnce(videoUpload('third.mp4', '2026-07-30T12:00:05.000Z'));
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = uploadFilesRef.current?.([
+ new File(['image'], 'one.png', { type: 'image/png' }),
+ new File(['image'], 'two.webp', { type: 'image/webp' }),
+ new File(['video'], 'one.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'two.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'three.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+
+ await vi.waitFor(() => {
+ expect(mocks.uploadGalleryImage).toHaveBeenCalledTimes(2);
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledTimes(1);
+ });
+
+ resolveFirstImage?.(imageUpload('one.png', '2026-07-30T12:00:01.000Z'));
+ resolveSecondImage?.(imageUpload('two.webp', '2026-07-30T12:00:02.000Z'));
+ resolveFirstVideo?.(videoUpload('one.mp4', '2026-07-30T12:00:03.000Z'));
+
+ await act(async () => {
+ await upload;
+ });
+
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledTimes(3);
+ expect(mocks.uploadGalleryVideo.mock.invocationCallOrder[1]).toBeLessThan(
+ mocks.uploadGalleryVideo.mock.invocationCallOrder[2] ?? Number.POSITIVE_INFINITY
+ );
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ message: '2 images and 2 videos uploaded to Board 1. 1 failed. Images appear in Assets; videos appear in Media.',
+ title: 'Uploaded 4 of 5 files',
+ });
+ });
+
+ it('selects the newest successful upload visible in the active view', async () => {
+ galleryView = 'assets';
+ await renderProbe();
+ mocks.uploadGalleryImage
+ .mockResolvedValueOnce(imageUpload('older.png', '2026-07-30T12:00:01.000Z'))
+ .mockResolvedValueOnce(imageUpload('newer.png', '2026-07-30T12:00:04.000Z'));
+ mocks.uploadGalleryVideo.mockResolvedValue(videoUpload('newest.mp4', '2026-07-30T12:00:05.000Z'));
+
+ await act(async () => {
+ await uploadFilesRef.current?.([
+ new File(['image'], 'older.png', { type: 'image/png' }),
+ new File(['video'], 'newest.mp4', { type: 'video/mp4' }),
+ new File(['image'], 'newer.png', { type: 'image/png' }),
+ ]);
+ });
+
+ expect(selectItem).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ category: 'user', kind: 'image', name: 'newer.png' })
+ );
+ });
+
+ it('does not select an upload from the launch board after the active board changes in flight', async () => {
+ let resolveUpload: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ mocks.uploadGalleryImage.mockReturnValueOnce(
+ new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveUpload = resolve;
+ })
+ );
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
+ });
+ await vi.waitFor(() => expect(mocks.uploadGalleryImage).toHaveBeenCalledOnce());
+
+ selectedBoardId = 'none';
+ await renderProbe();
+ resolveUpload?.(imageUpload('photo.png', '2026-07-30T12:00:04.000Z'));
+
+ await act(async () => {
+ await upload;
+ });
+
+ expect(selectItem).not.toHaveBeenCalled();
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ });
+
+ it('does not select an upload hidden by a view change while the upload is in flight', async () => {
+ galleryView = 'assets';
+ await renderProbe();
+ let resolveUpload: ((value: ReturnType<typeof imageUpload>) => void) | undefined;
+ mocks.uploadGalleryImage.mockReturnValueOnce(
+ new Promise<ReturnType<typeof imageUpload>>((resolve) => {
+ resolveUpload = resolve;
+ })
+ );
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
+ });
+ await vi.waitFor(() => expect(mocks.uploadGalleryImage).toHaveBeenCalledOnce());
+
+ galleryView = 'images';
+ await renderProbe();
+ resolveUpload?.(imageUpload('photo.png', '2026-07-30T12:00:04.000Z'));
+
+ await act(async () => {
+ await upload;
+ });
+
+ expect(selectItem).not.toHaveBeenCalled();
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ });
+
+ it('reports unsupported and rejected files once without aborting supported uploads', async () => {
+ mocks.uploadGalleryVideo.mockRejectedValue(new Error('corrupt video'));
+
+ await act(async () => {
+ await uploadFilesRef.current?.([
+ new File(['text'], 'notes.txt', { type: 'text/plain' }),
+ new File(['video'], 'corrupt.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+
+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).toHaveBeenCalledExactlyOnceWith({
+ area: 'gallery-upload',
+ message: 'No files uploaded. 2 failed.',
+ namespace: 'gallery',
+ });
+ });
+
+ it('does not schedule another expensive video after the account lifetime aborts', async () => {
+ let rejectFirstVideo: ((reason: unknown) => void) | undefined;
+ mocks.uploadGalleryVideo.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ rejectFirstVideo = reject;
+ })
+ );
+
+ let upload: Promise<void> | undefined;
+ act(() => {
+ upload = uploadFilesRef.current?.([
+ new File(['video'], 'one.mp4', { type: 'video/mp4' }),
+ new File(['video'], 'two.mp4', { type: 'video/mp4' }),
+ ]);
+ });
+ await vi.waitFor(() => expect(mocks.uploadGalleryVideo).toHaveBeenCalledOnce());
+
+ accountLifecycle.invalidate();
+ rejectFirstVideo?.(new DOMException('The operation was aborted.', 'AbortError'));
+ await act(async () => {
+ await upload;
+ });
+
+ expect(mocks.uploadGalleryVideo).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();
+ expect(mocks.notificationsReportError).not.toHaveBeenCalled();
+ });
+
+ it('uses the localized Uncategorized label in a successful upload notification', async () => {
+ selectedBoardId = 'none';
+ await renderProbe();
+ mocks.uploadGalleryImage.mockResolvedValue(imageUpload('photo.png', '2026-07-30T12:00:04.000Z', 'none'));
+
+ await act(async () => {
+ await uploadFilesRef.current?.([new File(['image'], 'photo.png', { type: 'image/png' })]);
+ });
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith(
+ expect.objectContaining({ message: '1 images and 0 videos uploaded to Uncategorized. 0 failed.' })
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts
new file mode 100644
index 0000000000..43b869cfd1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts
@@ -0,0 +1,172 @@
+import type { GalleryItem } from '@features/gallery/core/items';
+import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';
+
+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
+import { compareGalleryItems, legacyGeneratedImageToGalleryItem } from '@features/gallery/core/items';
+import {
+ classifyGalleryUpload,
+ isDateBoardId,
+ uploadGalleryImage,
+ uploadGalleryVideo,
+} from '@features/gallery/data/backend';
+import { invalidateGallery } from '@features/gallery/data/queryCache';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GalleryActions } from './GalleryWidgetContext';
+
+import { useGalleryUi } from './GalleryUiContext';
+
+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+export const useGalleryUploadAction = ({
+ boards,
+ getCurrentGalleryLocation,
+ selectedBoardId,
+}: {
+ boards: GalleryBoard[];
+ getCurrentGalleryLocation: () => { galleryView: GalleryView; selectedBoardId: string };
+ selectedBoardId: string;
+}): GalleryActions['uploadFiles'] => {
+ const { gallery, notifications } = useGalleryUi();
+ const queryClient = useQueryClient();
+ const { t } = useTranslation();
+
+ return useCallback(
+ async (files) => {
+ const owner = captureAccountScope();
+
+ if (isDateBoardId(selectedBoardId)) {
+ notifications.reportError({
+ area: 'gallery-upload',
+ message: t('widgets.gallery.uploadDateBoardUnavailable'),
+ namespace: 'gallery',
+ });
+ return;
+ }
+
+ const accepted = files.flatMap((file) => {
+ const classification = classifyGalleryUpload(file);
+
+ return classification ? [{ file, kind: classification.kind }] : [];
+ });
+
+ if (accepted.length === 0) {
+ notifications.reportError({
+ area: 'gallery-upload',
+ message: t('widgets.gallery.uploadUnsupported'),
+ namespace: 'gallery',
+ });
+ return;
+ }
+
+ const getBoard = (boardId: string) => boards.find((board) => board.id === boardId);
+ const selectedBoard = getBoard(selectedBoardId);
+ const targetBoardName = selectedBoard
+ ? getGalleryBoardLabel(selectedBoard, t)
+ : t('widgets.gallery.uncategorized');
+ const formatImageCount = (count: number) => t('widgets.gallery.imageCount', { count });
+ const formatVideoCount = (count: number) => t('widgets.gallery.videoCount', { count });
+ const recordError = (error: unknown) =>
+ notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });
+
+ try {
+ const targetBoardId = selectedBoard?.kind === 'board' ? selectedBoardId : 'none';
+ const imageUploads = accepted.filter((upload) => upload.kind === 'image');
+ const videoUploads = accepted.filter((upload) => upload.kind === 'video');
+ const imageResultsPromise = Promise.allSettled(
+ imageUploads.map(({ file }) => uploadGalleryImage(file, targetBoardId, { signal: owner.signal }))
+ );
+ const videoResultsPromise = (async () => {
+ const results: PromiseSettledResult<GalleryItem>[] = [];
+
+ for (const { file } of videoUploads) {
+ owner.signal.throwIfAborted();
+
+ try {
+ results.push({
+ status: 'fulfilled',
+ value: await uploadGalleryVideo(file, targetBoardId, { signal: owner.signal }),
+ });
+ } catch (reason: unknown) {
+ if (owner.signal.aborted) {
+ throw reason;
+ }
+
+ results.push({ reason, status: 'rejected' });
+ }
+ }
+
+ return results;
+ })();
+ const [imageResults, videoResults] = await Promise.all([imageResultsPromise, videoResultsPromise]);
+
+ assertAccountScopeCurrent(owner);
+ const uploadedImages = imageResults.flatMap((result) =>
+ result.status === 'fulfilled' ? [legacyGeneratedImageToGalleryItem(result.value)] : []
+ );
+ const uploadedVideos = videoResults.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []));
+ const uploadedItems = [...uploadedImages, ...uploadedVideos];
+ const failedCount = files.length - uploadedItems.length;
+
+ if (uploadedItems.length === 0) {
+ notifications.reportError({
+ area: 'gallery-upload',
+ message: t('widgets.gallery.uploadFailed', { failed: failedCount }),
+ namespace: 'gallery',
+ });
+ 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 newestVisibleUpload = visibleUploads.reduce<GalleryItem | undefined>(
+ (newest, item) =>
+ newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,
+ undefined
+ );
+
+ if (newestVisibleUpload) {
+ gallery.selectItem(newestVisibleUpload);
+ }
+
+ void invalidateGallery(queryClient);
+
+ const summary = t('widgets.gallery.uploadSummary', {
+ board: targetBoardName,
+ failed: failedCount,
+ images: formatImageCount(uploadedImages.length),
+ videos: formatVideoCount(uploadedVideos.length),
+ });
+ const split = imageUploads.length > 0 && videoUploads.length > 0 ? ` ${t('widgets.gallery.uploadSplit')}` : '';
+ notifications.add({
+ kind: 'success',
+ message: `${summary}${split}`,
+ title: t(
+ failedCount > 0 ? 'widgets.gallery.uploadPartialTitle' : 'widgets.gallery.uploadSuccessTitle',
+ failedCount > 0 ? { succeeded: uploadedItems.length, total: files.length } : { count: uploadedItems.length }
+ ),
+ });
+ } catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ recordError(error);
+ }
+ },
+ [boards, gallery, getCurrentGalleryLocation, notifications, queryClient, selectedBoardId, t]
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/widget.ts b/invokeai/frontend/webv2/src/features/gallery/widget.ts
index e30742fa4e..08480b6b20 100644
--- a/invokeai/frontend/webv2/src/features/gallery/widget.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/widget.ts
@@ -1,2 +1,3 @@
export { GalleryWidgetFooter } from './ui/GalleryWidgetFooter';
+export { GalleryWidgetHeaderActions, GalleryWidgetLabel } from './ui/GalleryWidgetChrome';
export { GalleryWidgetView } from './ui/GalleryWidgetView';
diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
index d9c5aba0ba..a934bda0ba 100644
--- a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts
@@ -23,6 +23,14 @@ describe('parseDateTokens', () => {
});
});
+ it('treats a bare relative value as ordinary text', () => {
+ expect(parseDateTokens('7d', NOW)).toEqual({
+ invalidTokens: [],
+ range: undefined,
+ text: '7d',
+ });
+ });
+
it('parses ISO from/to and strips the tokens from text', () => {
const parse = parseDateTokens('sunset from:2026-07-01 to:2026-07-15 boulevard', NOW);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
index c4039f3f33..a740d5861c 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
@@ -1,12 +1,15 @@
+import type { GalleryBoard, GalleryImage } from '@features/gallery/contracts';
import type { GenerationModelCatalogItem } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
import type { TFunction } from 'i18next';
import { describe, expect, it, vi } from 'vitest';
-const { ensureModelsLoaded, getModelsSnapshot } = vi.hoisted(() => ({
+const { ensureModelsLoaded, fetchQuery, getModelsSnapshot, listPaletteImages } = vi.hoisted(() => ({
ensureModelsLoaded: vi.fn(() => Promise.resolve()),
+ fetchQuery: vi.fn(),
getModelsSnapshot: vi.fn(),
+ listPaletteImages: vi.fn(),
}));
vi.mock('@features/models', () => ({
@@ -16,14 +19,80 @@ vi.mock('@features/models', () => ({
}));
vi.mock('@features/generation/react', () => ({ focusPositivePrompt: vi.fn() }));
+vi.mock('@features/gallery/paletteSearch', () => ({
+ ALL_READABLE_BOARDS_ID: 'all',
+ listPaletteImages: (...args: unknown[]) => listPaletteImages(...args),
+}));
+vi.mock('@platform/query/client', () => ({ queryClient: { fetchQuery: (...args: unknown[]) => fetchQuery(...args) } }));
-import { createModelsProvider, createPromptHistoryProvider } from './paletteProviders';
+import {
+ createBoardsProvider,
+ createImagesProvider,
+ createModelsProvider,
+ createPromptHistoryProvider,
+} from './paletteProviders';
const model = (key: string, base: string, type = 'main'): ModelConfig =>
({ base, key, name: key, type }) as unknown as ModelConfig;
const t = ((key: string) => key) as TFunction;
const searchContext = () => ({ signal: new AbortController().signal });
+const uncategorized: GalleryBoard = {
+ archived: false,
+ assetCount: 0,
+ id: 'none',
+ imageCount: 1,
+ kind: 'uncategorized',
+ name: '',
+ videoCount: 0,
+};
+const galleryT = ((key: string) => {
+ if (key === 'widgets.gallery.uncategorized' || key === 'commandPalette.providers.uncategorized') {
+ return 'Uncategorized';
+ }
+
+ return key;
+}) as TFunction;
+
+describe('localized gallery board labels', () => {
+ it('searches and displays the localized Uncategorized board name', async () => {
+ fetchQuery.mockResolvedValue([uncategorized]);
+ const provider = createBoardsProvider({ openGalleryWidget: vi.fn(), selectBoard: vi.fn(), t: galleryT });
+
+ const entries = await provider.search({ text: 'cat' }, searchContext());
+
+ expect(entries.map((entry) => entry.title)).toEqual(['Uncategorized']);
+ });
+
+ it('uses the localized board name in image-result subtitles', async () => {
+ const image = {
+ boardId: 'none',
+ height: 512,
+ imageCategory: 'general',
+ imageName: 'image.png',
+ imageUrl: '/full/image.png',
+ queuedAt: '2026-07-30T00:00:00.000Z',
+ starred: false,
+ thumbnailUrl: '/thumb/image.png',
+ width: 512,
+ } as GalleryImage;
+ fetchQuery.mockResolvedValue([uncategorized]);
+ listPaletteImages.mockResolvedValue({ images: [image], total: 1 });
+ const provider = createImagesProvider({
+ locale: 'en',
+ openGalleryWidget: vi.fn(),
+ openPreviewWidget: vi.fn(),
+ selectBoard: vi.fn(),
+ selectImage: vi.fn(),
+ t: galleryT,
+ });
+
+ const entries = await provider.search({ text: '' }, searchContext());
+
+ expect(entries[0]?.subtitle).toBe('Uncategorized · 512×512');
+ });
+});
+
describe('createModelsProvider', () => {
it('lists only supported Generate models and applies one before opening the widget', async () => {
const supported = model('supported-sdxl', 'sdxl');
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
index d9f8fd2444..177e192c4f 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
@@ -1,10 +1,10 @@
-import type { GalleryBoard, GalleryImage } from '@features/gallery/contracts';
import type { GenerateModelConfig } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
import type { QueueReadModel } from '@features/queue/contracts';
import type { PromptHistoryItem } from '@workbench/projectContracts';
import type { TFunction } from 'i18next';
+import { getGalleryBoardLabel, type GalleryBoard, type GalleryImage } from '@features/gallery/contracts';
import { ALL_READABLE_BOARDS_ID, listPaletteImages } from '@features/gallery/paletteSearch';
import { galleryBoardsOptions } from '@features/gallery/queries';
import { focusPositivePrompt } from '@features/generation/react';
@@ -106,7 +106,7 @@ export const createBoardsProvider = ({
return boards
.filter(
(board: GalleryBoard) =>
- matchesQuery(board.name) &&
+ matchesQuery(getGalleryBoardLabel(board, t)) &&
// Boards without a creation date (uncategorized, date virtual
// boards) are excluded only while a date range is active.
(query.range === undefined || isTimestampInRange(board.createdAt ?? '', query.range))
@@ -121,7 +121,7 @@ export const createBoardsProvider = ({
selectBoard(board.id);
},
subtitle: t('commandPalette.providers.boardSubtitle', { count: board.imageCount }),
- title: board.name,
+ title: getGalleryBoardLabel(board, t),
}));
},
});
@@ -319,7 +319,9 @@ export const createImagesProvider = ({
}),
loadActiveBoards(),
]);
- const boardNames = new Map(boards.map((board: GalleryBoard) => [board.id, board.name]));
+ const boardNames = new Map(
+ boards.map((board: GalleryBoard) => [board.id, getGalleryBoardLabel(board, t)] as const)
+ );
// Images carry no prompt, so the creation date+time is the title; the time
// keeps same-day results (the common case for 20 recents) distinguishable.
return page.images.map<PaletteEntry>((image) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
index 900d3135e8..3c6b49f0b7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
@@ -6,7 +6,6 @@ export const galleryWidgetManifest: WidgetManifest = {
allowMultiple: false,
allowedRegions: ['left', 'right', 'center', 'bottom'],
bottomPanel: 'expandable',
- chrome: { header: 'hidden' },
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
icon: ImageIcon,
id: 'gallery',
@@ -14,6 +13,8 @@ export const galleryWidgetManifest: WidgetManifest = {
load: () =>
import('@features/gallery/widget').then((module) => ({
footer: module.GalleryWidgetFooter,
+ headerActions: module.GalleryWidgetHeaderActions,
+ headerLabel: module.GalleryWidgetLabel,
view: module.GalleryWidgetView,
})),
version: 1,