Skip to content

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

feat(webv2): expand gallery data model and settings

joshistoast25355424888b
diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
index a68a0d1e83..c1ec3a7815 100644
--- a/invokeai/frontend/webv2/src/workbench/gallery/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
@@ -4,6 +4,10 @@ const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';
export type GalleryView = 'images' | 'assets';
+export type GalleryOrderDir = 'ASC' | 'DESC';
+
+export type GalleryBoardOrderBy = 'created_at' | 'board_name';
+
export interface BackendBoardDTO {
board_id: string;
board_name: string;
@@ -13,16 +17,30 @@ export interface BackendBoardDTO {
cover_image_name?: string | null;
}
+/**
+ * 'board' is a real backend board; 'uncategorized' is the pseudo-board for
+ * unassigned images (board_id 'none'); 'date' is a read-only virtual board
+ * grouping images by creation date (id 'by_date:YYYY-MM-DD').
+ */
+export type GalleryBoardKind = 'board' | 'uncategorized' | 'date';
+
export interface GalleryBoard {
id: string;
name: string;
+ kind: GalleryBoardKind;
imageCount: number;
assetCount: number;
+ archived: boolean;
coverImageName?: string | null;
coverThumbnailUrl?: string;
- isVirtual?: boolean;
}
+const DATE_BOARD_ID_PREFIX = 'by_date:';
+
+export const isDateBoardId = (boardId: string): boolean => boardId.startsWith(DATE_BOARD_ID_PREFIX);
+
+const getDateFromBoardId = (boardId: string): string => boardId.slice(DATE_BOARD_ID_PREFIX.length);
+
export interface BackendImageDTO {
image_name: string;
image_url: string;
@@ -32,12 +50,14 @@ export interface BackendImageDTO {
created_at: string;
image_category: 'general' | 'control' | 'mask' | 'user' | 'other';
is_intermediate: boolean;
+ starred?: boolean;
board_id?: string | null;
}
export interface GalleryImage extends GeneratedImageContract {
boardId: string;
imageCategory: BackendImageDTO['image_category'];
+ starred: boolean;
}
interface ListImagesResponse {
@@ -94,11 +114,13 @@ const toSearchParams = (entries: Record<string, boolean | number | string | stri
};
const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({
+ archived: board.archived,
assetCount: board.asset_count,
coverImageName: board.cover_image_name,
coverThumbnailUrl: board.cover_image_name ? getImageThumbnailUrl(board.cover_image_name) : undefined,
id: board.board_id,
imageCount: board.image_count,
+ kind: 'board',
name: board.board_name,
});
@@ -124,12 +146,27 @@ const mapImage = (image: BackendImageDTO): GalleryImage => ({
imageUrl: absolutizeImageUrl(image.image_url),
queuedAt: image.created_at,
sourceQueueItemId: 'backend-gallery',
+ starred: image.starred ?? false,
thumbnailUrl: absolutizeImageUrl(image.thumbnail_url),
width: image.width,
});
-export const listGalleryBoards = async (): Promise<GalleryBoard[]> => {
- const boardsResponsePromise = fetch(buildUrl('/api/v1/boards/?all=true&include_archived=false')).then(assertOk);
+export const listGalleryBoards = async ({
+ includeArchived = false,
+ orderBy = 'created_at',
+ orderDir = 'DESC',
+}: {
+ includeArchived?: boolean;
+ orderBy?: GalleryBoardOrderBy;
+ orderDir?: GalleryOrderDir;
+} = {}): Promise<GalleryBoard[]> => {
+ const boardsQuery = toSearchParams({
+ all: true,
+ direction: orderDir,
+ include_archived: includeArchived,
+ order_by: orderBy,
+ });
+ const boardsResponsePromise = fetch(buildUrl(`/api/v1/boards/?${boardsQuery}`)).then(assertOk);
const [response, uncategorizedImageCount, uncategorizedAssetCount] = await Promise.all([
boardsResponsePromise,
@@ -141,38 +178,136 @@ export const listGalleryBoards = async (): Promise<GalleryBoard[]> => {
return [
{
+ archived: false,
assetCount: uncategorizedAssetCount,
id: 'none',
imageCount: uncategorizedImageCount,
- isVirtual: true,
+ kind: 'uncategorized',
name: 'Uncategorized',
},
- ...boards.filter((board) => !board.archived).map(mapBoard),
+ ...boards.filter((board) => includeArchived || !board.archived).map(mapBoard),
];
};
+interface VirtualDateBoardDTO {
+ virtual_board_id: string;
+ board_name: string;
+ date: string;
+ image_count: number;
+ asset_count: number;
+ cover_image_name?: string | null;
+}
+
+export const listGalleryDateBoards = async (): Promise<GalleryBoard[]> => {
+ const response = await assertOk(await fetch(buildUrl('/api/v1/virtual_boards/by_date')));
+ const body = (await response.json()) as VirtualDateBoardDTO[];
+
+ return body.map((board) => ({
+ archived: false,
+ assetCount: board.asset_count,
+ coverImageName: board.cover_image_name,
+ coverThumbnailUrl: board.cover_image_name ? getImageThumbnailUrl(board.cover_image_name) : undefined,
+ id: board.virtual_board_id,
+ imageCount: board.image_count,
+ kind: 'date',
+ name: board.board_name,
+ }));
+};
+
+export interface GalleryImagesPage {
+ images: GalleryImage[];
+ total: number;
+}
+
+const getGalleryImagesByNames = async (imageNames: string[]): Promise<GalleryImage[]> => {
+ if (imageNames.length === 0) {
+ return [];
+ }
+
+ const response = await assertOk(
+ await fetch(buildUrl('/api/v1/images/images_by_names'), {
+ body: JSON.stringify({ image_names: imageNames }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ })
+ );
+
+ return ((await response.json()) as BackendImageDTO[]).map(mapImage);
+};
+
+/**
+ * Date virtual boards have no offset-paginated DTO endpoint; list the ordered
+ * names for the date, slice the requested window, then bulk-hydrate DTOs.
+ */
+const listGalleryDateBoardImages = async ({
+ boardId,
+ galleryView,
+ limit,
+ offset,
+ orderDir,
+ searchTerm,
+ starredFirst,
+}: {
+ boardId: string;
+ galleryView: GalleryView;
+ limit: number;
+ offset: number;
+ orderDir: GalleryOrderDir;
+ searchTerm: string;
+ starredFirst: boolean;
+}): Promise<GalleryImagesPage> => {
+ const query = toSearchParams({
+ categories: galleryView === 'assets' ? assetCategories : imageCategories,
+ order_dir: orderDir,
+ search_term: searchTerm.trim() || undefined,
+ starred_first: starredFirst,
+ });
+ const response = await assertOk(
+ await fetch(
+ buildUrl(`/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`)
+ )
+ );
+ const body = (await response.json()) as { image_names: string[]; total_count: number };
+ const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit));
+
+ return { images, total: body.total_count };
+};
+
export const listGalleryImages = async ({
boardId,
galleryView,
+ limit = 100,
+ offset = 0,
+ orderDir = 'DESC',
searchTerm,
+ starredFirst = false,
}: {
boardId: string;
galleryView: GalleryView;
+ limit?: number;
+ offset?: number;
+ orderDir?: GalleryOrderDir;
searchTerm: string;
-}): Promise<GalleryImage[]> => {
+ starredFirst?: boolean;
+}): Promise<GalleryImagesPage> => {
+ if (isDateBoardId(boardId)) {
+ return listGalleryDateBoardImages({ boardId, galleryView, limit, offset, orderDir, searchTerm, starredFirst });
+ }
+
const query = toSearchParams({
board_id: boardId,
categories: galleryView === 'assets' ? assetCategories : imageCategories,
is_intermediate: false,
- limit: 100,
- offset: 0,
- order_dir: 'DESC',
+ limit,
+ offset,
+ order_dir: orderDir,
search_term: searchTerm.trim() || undefined,
+ starred_first: starredFirst,
});
const response = await assertOk(await fetch(buildUrl(`/api/v1/images/?${query}`)));
const body = (await response.json()) as ListImagesResponse;
- return body.items.map(mapImage);
+ return { images: body.items.map(mapImage), total: body.total };
};
export const createGalleryBoard = async (boardName: string): Promise<GalleryBoard> => {
@@ -186,8 +321,39 @@ export const createGalleryBoard = async (boardName: string): Promise<GalleryBoar
return mapBoard((await response.json()) as BackendBoardDTO);
};
+export const updateGalleryBoard = async (
+ boardId: string,
+ changes: { name?: string; archived?: boolean }
+): Promise<GalleryBoard> => {
+ const response = await assertOk(
+ await fetch(buildUrl(`/api/v1/boards/${encodeURIComponent(boardId)}`), {
+ body: JSON.stringify({ archived: changes.archived, board_name: changes.name }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PATCH',
+ })
+ );
+
+ return mapBoard((await response.json()) as BackendBoardDTO);
+};
+
+export const deleteGalleryBoard = async (boardId: string, includeImages: boolean): Promise<void> => {
+ const query = toSearchParams({ include_images: includeImages });
+
+ await assertOk(
+ await fetch(buildUrl(`/api/v1/boards/${encodeURIComponent(boardId)}?${query}`), {
+ method: 'DELETE',
+ })
+ );
+};
+
export const addImagesToGalleryBoard = async (boardId: string, imageNames: string[]): Promise<void> => {
- if (boardId === 'none' || boardId === 'generated' || boardId === 'assets' || imageNames.length === 0) {
+ if (
+ boardId === 'none' ||
+ boardId === 'generated' ||
+ boardId === 'assets' ||
+ isDateBoardId(boardId) ||
+ imageNames.length === 0
+ ) {
return;
}
@@ -199,3 +365,122 @@ export const addImagesToGalleryBoard = async (boardId: string, imageNames: strin
})
);
};
+
+export const removeImagesFromGalleryBoard = async (imageNames: string[]): Promise<void> => {
+ if (imageNames.length === 0) {
+ return;
+ }
+
+ await assertOk(
+ await fetch(buildUrl('/api/v1/board_images/batch/delete'), {
+ body: JSON.stringify({ image_names: imageNames }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ })
+ );
+};
+
+const setGalleryImagesStarred = async (imageNames: string[], starred: boolean): Promise<void> => {
+ if (imageNames.length === 0) {
+ return;
+ }
+
+ await assertOk(
+ await fetch(buildUrl(`/api/v1/images/${starred ? 'star' : 'unstar'}`), {
+ body: JSON.stringify({ image_names: imageNames }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ })
+ );
+};
+
+export const starGalleryImages = (imageNames: string[]): Promise<void> => setGalleryImagesStarred(imageNames, true);
+
+export const unstarGalleryImages = (imageNames: string[]): Promise<void> => setGalleryImagesStarred(imageNames, false);
+
+export const deleteGalleryImages = async (imageNames: string[]): Promise<void> => {
+ if (imageNames.length === 0) {
+ return;
+ }
+
+ await assertOk(
+ await fetch(buildUrl('/api/v1/images/delete'), {
+ body: JSON.stringify({ image_names: imageNames }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ })
+ );
+};
+
+const BULK_DOWNLOAD_POLL_INTERVAL_MS = 2000;
+const BULK_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
+
+const sleep = (ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ window.setTimeout(resolve, ms);
+ });
+
+/**
+ * Starts a bulk download (a zip prepared in a backend background task) and
+ * polls the artifact endpoint until it exists. Returns the archive blob and
+ * its file name.
+ */
+export const downloadGalleryArchive = async ({
+ boardId,
+ imageNames,
+}: {
+ boardId?: string;
+ imageNames?: string[];
+}): Promise<{ blob: Blob; fileName: string }> => {
+ const startResponse = await assertOk(
+ await fetch(buildUrl('/api/v1/images/download'), {
+ body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ })
+ );
+ const { bulk_download_item_name: fileName } = (await startResponse.json()) as {
+ bulk_download_item_name?: string | null;
+ };
+
+ if (!fileName) {
+ throw new Error('The bulk download failed to start.');
+ }
+
+ const startedAt = Date.now();
+
+ while (Date.now() - startedAt < BULK_DOWNLOAD_TIMEOUT_MS) {
+ const response = await fetch(buildUrl(`/api/v1/images/download/${encodeURIComponent(fileName)}`));
+
+ if (response.ok) {
+ return { blob: await response.blob(), fileName };
+ }
+
+ if (response.status !== 404) {
+ throw new Error(`${response.status} ${response.statusText}`);
+ }
+
+ await sleep(BULK_DOWNLOAD_POLL_INTERVAL_MS);
+ }
+
+ throw new Error('Timed out preparing the download archive.');
+};
+
+export const uploadGalleryImage = async (file: File, boardId: string): Promise<GalleryImage> => {
+ const query = toSearchParams({
+ board_id: boardId === 'none' || isDateBoardId(boardId) ? undefined : boardId,
+ image_category: 'user',
+ is_intermediate: false,
+ });
+ const body = new FormData();
+ body.append('file', file);
+
+ const response = await assertOk(
+ await fetch(buildUrl(`/api/v1/images/upload?${query}`), {
+ body,
+ method: 'POST',
+ })
+ );
+
+ return mapImage((await response.json()) as BackendImageDTO);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/gallery/settings.ts b/invokeai/frontend/webv2/src/workbench/gallery/settings.ts
new file mode 100644
index 0000000000..c09613df29
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/gallery/settings.ts
@@ -0,0 +1,63 @@
+import type { GalleryBoardOrderBy, GalleryOrderDir } from './api';
+
+export type GalleryThumbnailFit = 'square' | 'aspect';
+
+export type GalleryPaginationMode = 'infinite' | 'paginated';
+
+/**
+ * User-tunable gallery settings. Persisted as plain entries in the gallery
+ * widget's `values` record so they survive workbench autosave/hydration.
+ */
+export interface GallerySettings {
+ boardOrderBy: GalleryBoardOrderBy;
+ boardOrderDir: GalleryOrderDir;
+ imageDensityPercent: number;
+ imageOrderDir: GalleryOrderDir;
+ paginationMode: GalleryPaginationMode;
+ showArchivedBoards: boolean;
+ showDateBoards: boolean;
+ showImageDimensions: boolean;
+ starredFirst: boolean;
+ thumbnailFit: GalleryThumbnailFit;
+}
+
+export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {
+ boardOrderBy: 'created_at',
+ boardOrderDir: 'DESC',
+ imageDensityPercent: 50,
+ imageOrderDir: 'DESC',
+ paginationMode: 'infinite',
+ showArchivedBoards: false,
+ showDateBoards: false,
+ showImageDimensions: false,
+ starredFirst: true,
+ thumbnailFit: 'square',
+};
+
+const isOrderDir = (value: unknown): value is GalleryOrderDir => value === 'ASC' || value === 'DESC';
+
+const isBoardOrderBy = (value: unknown): value is GalleryBoardOrderBy =>
+ value === 'created_at' || value === 'board_name';
+
+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,
+ imageDensityPercent:
+ typeof values.imageDensityPercent === 'number' && Number.isFinite(values.imageDensityPercent)
+ ? Math.min(100, Math.max(0, values.imageDensityPercent))
+ : DEFAULT_GALLERY_SETTINGS.imageDensityPercent,
+ imageOrderDir: isOrderDir(values.imageOrderDir) ? values.imageOrderDir : DEFAULT_GALLERY_SETTINGS.imageOrderDir,
+ paginationMode: values.paginationMode === 'paginated' ? 'paginated' : DEFAULT_GALLERY_SETTINGS.paginationMode,
+ showArchivedBoards:
+ typeof values.showArchivedBoards === 'boolean'
+ ? values.showArchivedBoards
+ : DEFAULT_GALLERY_SETTINGS.showArchivedBoards,
+ showDateBoards:
+ typeof values.showDateBoards === 'boolean' ? values.showDateBoards : DEFAULT_GALLERY_SETTINGS.showDateBoards,
+ showImageDimensions:
+ typeof values.showImageDimensions === 'boolean'
+ ? values.showImageDimensions
+ : DEFAULT_GALLERY_SETTINGS.showImageDimensions,
+ starredFirst: typeof values.starredFirst === 'boolean' ? values.starredFirst : DEFAULT_GALLERY_SETTINGS.starredFirst,
+ thumbnailFit: values.thumbnailFit === 'aspect' ? 'aspect' : DEFAULT_GALLERY_SETTINGS.thumbnailFit,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index 52e2b15781..0d84f65304 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -397,6 +397,7 @@ export interface WorkbenchPreferences {
themeId: WorkbenchThemeId;
reduceMotion: boolean;
showFocusRegionHighlight: boolean;
+ confirmImageDeletion: boolean;
}
export interface AccountState {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts
index edfd06482e..25c1c2e5d0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts
@@ -1,12 +1,17 @@
import { describe, expect, it } from 'vitest';
import type { GalleryBoard } from '../../gallery/api';
-import type { GeneratedImageContract } from '../../types';
-import { getBoardCounts, getGallerySelectedBoardId, getGalleryStateView } from './galleryStateView';
+import type { GeneratedImageContract, QueueItem, QueueItemStatus } from '../../types';
+import {
+ getBoardCounts,
+ getGalleryQueuePlaceholders,
+ getGallerySelectedBoardId,
+ getGalleryStateView,
+} from './galleryStateView';
const boards: GalleryBoard[] = [
- { assetCount: 0, id: 'none', imageCount: 1, isVirtual: true, name: 'Uncategorized' },
- { assetCount: 0, id: 'board-1', imageCount: 2, name: 'Board 1' },
+ { archived: false, assetCount: 0, id: 'none', imageCount: 1, kind: 'uncategorized', name: 'Uncategorized' },
+ { archived: false, assetCount: 0, id: 'board-1', imageCount: 2, kind: 'board', name: 'Board 1' },
];
const createImage = (imageName: string): GeneratedImageContract => ({
@@ -19,6 +24,33 @@ const createImage = (imageName: string): GeneratedImageContract => ({
width: 512,
});
+const createQueueItem = ({
+ backendItemIds,
+ batchCount = 1,
+ boardId = 'none',
+ destination = 'gallery',
+ status = 'pending',
+}: {
+ backendItemIds?: number[];
+ batchCount?: number;
+ boardId?: string;
+ destination?: 'gallery' | 'canvas';
+ status?: QueueItemStatus;
+}): QueueItem =>
+ ({
+ backendItemIds,
+ cancellable: true,
+ id: `queue-item-${status}-${boardId}`,
+ snapshot: {
+ destination,
+ widgetStates: {
+ gallery: { id: 'gallery', label: 'Gallery', values: { selectedBoardId: boardId }, version: 1 },
+ generate: { id: 'generate', label: 'Generate', values: { batchCount, height: 768, width: 512 }, version: 1 },
+ },
+ },
+ status,
+ }) as unknown as QueueItem;
+
describe('gallery state view', () => {
it('preserves a selected backend board id while boards are still loading', () => {
const values = { selectedBoardId: 'board-1' };
@@ -45,4 +77,71 @@ describe('gallery state view', () => {
it('exposes both image and asset counts for board labels', () => {
expect(getBoardCounts(boards[1])).toEqual({ assetCount: 0, imageCount: 2 });
});
+
+ it('parses persisted gallery settings with safe defaults', () => {
+ const gallery = getGalleryStateView({ boardOrderBy: 'board_name', starredFirst: false }, boards, [], false);
+
+ expect(gallery.settings).toEqual({
+ boardOrderBy: 'board_name',
+ boardOrderDir: 'DESC',
+ imageDensityPercent: 50,
+ imageOrderDir: 'DESC',
+ paginationMode: 'infinite',
+ showArchivedBoards: false,
+ showDateBoards: false,
+ showImageDimensions: false,
+ starredFirst: false,
+ thumbnailFit: 'square',
+ });
+ });
+
+ it('derives the multi-selection from persisted values with a single-selection fallback', () => {
+ expect(
+ getGalleryStateView({ selectedImageNames: ['a.png', 'b.png', 7] }, boards, [], false).selectedImageNames
+ ).toEqual(['a.png', 'b.png']);
+ expect(getGalleryStateView({ selectedImageName: 'a.png' }, boards, [], false).selectedImageNames).toEqual([
+ 'a.png',
+ ]);
+ });
+
+ it('creates placeholders for in-flight gallery queue items on the viewed board', () => {
+ const queueItems = [
+ createQueueItem({ batchCount: 2, boardId: 'board-1', status: 'pending' }),
+ createQueueItem({ backendItemIds: [11, 12, 13], boardId: 'board-1', status: 'running' }),
+ ];
+ const placeholders = getGalleryQueuePlaceholders(queueItems, {
+ galleryView: 'images',
+ searchTerm: '',
+ selectedBoardId: 'board-1',
+ });
+
+ expect(placeholders).toHaveLength(5);
+ expect(placeholders[0]).toMatchObject({ height: 768, width: 512 });
+ });
+
+ it('does not create placeholders for other boards, finished items, or canvas runs', () => {
+ const queueItems = [
+ createQueueItem({ boardId: 'board-2', status: 'pending' }),
+ createQueueItem({ boardId: 'board-1', status: 'completed' }),
+ createQueueItem({ boardId: 'board-1', destination: 'canvas', status: 'pending' }),
+ ];
+
+ expect(
+ getGalleryQueuePlaceholders(queueItems, { galleryView: 'images', searchTerm: '', selectedBoardId: 'board-1' })
+ ).toEqual([]);
+ });
+
+ it('hides placeholders while searching or browsing assets', () => {
+ const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];
+
+ expect(
+ getGalleryQueuePlaceholders(queueItems, { galleryView: 'images', searchTerm: 'cat', selectedBoardId: 'none' })
+ ).toEqual([]);
+ expect(
+ getGalleryQueuePlaceholders(queueItems, { galleryView: 'assets', searchTerm: '', selectedBoardId: 'none' })
+ ).toEqual([]);
+ expect(
+ getGalleryStateView({ selectedBoardId: 'none' }, boards, [], false, queueItems).pendingPlaceholders
+ ).toHaveLength(1);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts
index 31d7b00f83..8028a7dee9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts
@@ -1,23 +1,39 @@
import type { GalleryBoard, GalleryImage, GalleryView } from '../../gallery/api';
-import type { GeneratedImageContract } from '../../types';
+import { getGallerySettings, type GallerySettings } from '../../gallery/settings';
+import type { GeneratedImageContract, QueueItem } from '../../types';
const UNCATEGORIZED_BOARD: GalleryBoard = {
+ archived: false,
assetCount: 0,
id: 'none',
imageCount: 0,
- isVirtual: true,
+ kind: 'uncategorized',
name: 'Uncategorized',
};
+/**
+ * A grid cell standing in for an image that an in-flight queue item will
+ * deliver to the currently viewed board once generation completes.
+ */
+export interface GalleryQueuePlaceholder {
+ id: string;
+ width: number;
+ height: number;
+}
+
export interface GalleryStateView {
boards: GalleryBoard[];
+ compareImageName: string | null;
galleryView: GalleryView;
- imageDensityPercent: number;
images: GalleryImage[];
isLoading: boolean;
+ pendingPlaceholders: GalleryQueuePlaceholder[];
+ projectBoardId: string | null;
searchTerm: string;
selectedBoardId: string;
selectedImageName: string | null;
+ selectedImageNames: string[];
+ settings: GallerySettings;
}
export const getGalleryView = (values: Record<string, unknown>): GalleryView =>
@@ -36,6 +52,44 @@ export const getGallerySelectedBoardId = (values: Record<string, unknown>, backe
return 'none';
};
+export const getGallerySelectedImageNames = (values: Record<string, unknown>): string[] => {
+ if (Array.isArray(values.selectedImageNames)) {
+ return (values.selectedImageNames as unknown[]).filter((name): name is string => typeof name === 'string');
+ }
+
+ return typeof values.selectedImageName === 'string' ? [values.selectedImageName] : [];
+};
+
+export const getGalleryPage = (values: Record<string, unknown>): number =>
+ typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)
+ ? Math.max(0, Math.floor(values.galleryPage))
+ : 0;
+
+export const getGalleryTotalImages = (values: Record<string, unknown>): number | null =>
+ typeof values.galleryTotalImages === 'number' && Number.isFinite(values.galleryTotalImages)
+ ? Math.max(0, values.galleryTotalImages)
+ : null;
+
+export const getGalleryRefreshToken = (values: Record<string, unknown>): string =>
+ typeof values.galleryRefreshToken === 'string' ? values.galleryRefreshToken : '';
+
+export const getGalleryProjectBoardId = (values: Record<string, unknown>): string | null =>
+ typeof values.projectBoardId === 'string' ? values.projectBoardId : null;
+
+export const getGalleryCompareImage = (values: Record<string, unknown>): GeneratedImageContract | null => {
+ const compareImage = values.compareImage;
+
+ if (
+ compareImage &&
+ typeof compareImage === 'object' &&
+ typeof (compareImage as GeneratedImageContract).imageName === 'string'
+ ) {
+ return compareImage as GeneratedImageContract;
+ }
+
+ return null;
+};
+
export const getGalleryRecentImagesKey = (values: Record<string, unknown>): string => {
if (!Array.isArray(values.recentImages)) {
return '';
@@ -44,39 +98,91 @@ export const getGalleryRecentImagesKey = (values: Record<string, unknown>): stri
return (values.recentImages as GeneratedImageContract[]).map((image) => image.imageName).join('\0');
};
+const getFiniteNumber = (value: unknown, fallback: number): number =>
+ typeof value === 'number' && Number.isFinite(value) ? value : fallback;
+
+export const getGalleryQueuePlaceholders = (
+ queueItems: QueueItem[],
+ {
+ galleryView,
+ searchTerm,
+ selectedBoardId,
+ }: { galleryView: GalleryView; searchTerm: string; selectedBoardId: string }
+): GalleryQueuePlaceholder[] => {
+ if (galleryView !== 'images' || searchTerm.trim() !== '') {
+ return [];
+ }
+
+ const placeholders: GalleryQueuePlaceholder[] = [];
+
+ for (const item of queueItems) {
+ if (item.status !== 'pending' && item.status !== 'running') {
+ continue;
+ }
+
+ if (item.snapshot.destination !== 'gallery') {
+ continue;
+ }
+
+ const galleryValues = item.snapshot.widgetStates.gallery?.values ?? {};
+ const targetBoardId = typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none';
+
+ if (targetBoardId !== selectedBoardId) {
+ continue;
+ }
+
+ const generateValues = item.snapshot.widgetStates.generate?.values ?? {};
+ const expectedImageCount = item.backendItemIds?.length
+ ? item.backendItemIds.length
+ : Math.max(1, Math.round(getFiniteNumber(generateValues.batchCount, 1)));
+ const width = getFiniteNumber(generateValues.width, 1024);
+ const height = getFiniteNumber(generateValues.height, 1024);
+
+ for (let index = 0; index < expectedImageCount; index++) {
+ placeholders.push({ height, id: `${item.id}:${index}`, width });
+ }
+ }
+
+ return placeholders;
+};
+
export const getGalleryStateView = (
values: Record<string, unknown>,
backendBoards: GalleryBoard[],
backendImages: GalleryImage[] | null,
- isLoading: boolean
+ isLoading: boolean,
+ queueItems: QueueItem[] = []
): GalleryStateView => {
const localImages = Array.isArray(values.recentImages)
? (values.recentImages as GeneratedImageContract[]).map((image) => ({
...image,
boardId: 'none',
imageCategory: 'general' as const,
+ starred: false,
}))
: [];
const images = backendImages ?? (isLoading ? [] : localImages);
const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
const galleryView = getGalleryView(values);
- const imageDensityPercent =
- typeof values.imageDensityPercent === 'number' && Number.isFinite(values.imageDensityPercent)
- ? Math.min(100, Math.max(0, values.imageDensityPercent))
- : 50;
+ const settings = getGallerySettings(values);
const searchTerm = getGallerySearchTerm(values);
const boards = backendBoards.length ? backendBoards : [{ ...UNCATEGORIZED_BOARD, imageCount: images.length }];
const selectedBoardId = getGallerySelectedBoardId(values, backendBoards);
+ const compareImage = getGalleryCompareImage(values);
return {
boards,
+ compareImageName: compareImage?.imageName ?? null,
galleryView,
- imageDensityPercent,
images,
isLoading,
+ pendingPlaceholders: getGalleryQueuePlaceholders(queueItems, { galleryView, searchTerm, selectedBoardId }),
+ projectBoardId: getGalleryProjectBoardId(values),
searchTerm,
selectedBoardId,
selectedImageName: images.some((image) => image.imageName === selectedImageName) ? selectedImageName : null,
+ selectedImageNames: getGallerySelectedImageNames(values),
+ settings,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 8874e66730..98f38df13a 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -543,7 +543,12 @@ describe('workbench preferences', () => {
it('defaults to the dark theme with motion enabled', () => {
const state = createInitialWorkbenchState();
- expect(state.account.preferences).toEqual({ reduceMotion: false, showFocusRegionHighlight: true, themeId: 'dark' });
+ expect(state.account.preferences).toEqual({
+ confirmImageDeletion: true,
+ reduceMotion: false,
+ showFocusRegionHighlight: true,
+ themeId: 'dark',
+ });
});
it('updates the theme without dropping other preferences', () => {
@@ -554,6 +559,7 @@ describe('workbench preferences', () => {
state = workbenchReducer(state, { preferences: { themeId: 'forest' }, type: 'setPreferences' });
expect(state.account.preferences).toEqual({
+ confirmImageDeletion: true,
reduceMotion: true,
showFocusRegionHighlight: false,
themeId: 'forest',
@@ -579,7 +585,12 @@ describe('workbench preferences', () => {
const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });
- expect(state.account.preferences).toEqual({ reduceMotion: false, showFocusRegionHighlight: true, themeId: 'dark' });
+ expect(state.account.preferences).toEqual({
+ confirmImageDeletion: true,
+ reduceMotion: false,
+ showFocusRegionHighlight: true,
+ themeId: 'dark',
+ });
});
it('heals hydrated state with an unsupported theme id', () => {
@@ -595,6 +606,7 @@ describe('workbench preferences', () => {
const state = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });
expect(state.account.preferences).toEqual({
+ confirmImageDeletion: true,
reduceMotion: true,
showFocusRegionHighlight: false,
themeId: 'dark',
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 1adc7fbc41..2666a6ea28 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -6,6 +6,7 @@ import {
} from './invocation';
import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '../theme/themes';
import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';
+import type { GallerySettings } from './gallery/settings';
import type { GenerateWidgetValues, MainModelConfig } from './generation/types';
import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';
import type {
@@ -68,10 +69,18 @@ type WorkbenchAction =
| { type: 'toggleCanvasStagingVisibility' }
| { type: 'toggleCanvasStagingThumbnailsVisibility' }
| { type: 'selectGalleryImage'; image: GeneratedImageContract }
+ | { type: 'toggleGalleryImageInSelection'; image: GeneratedImageContract }
+ | { type: 'setGalleryMultiSelection'; imageNames: string[]; primaryImage: GeneratedImageContract }
+ | { type: 'setGalleryCompareImage'; image: GeneratedImageContract | null }
| { type: 'selectGalleryBoard'; boardId: string }
| { type: 'setGalleryView'; galleryView: 'images' | 'assets' }
| { type: 'setGallerySearchTerm'; searchTerm: string }
- | { type: 'setGalleryImageDensityPercent'; imageDensityPercent: number }
+ | { type: 'updateGallerySettings'; settings: Partial<GallerySettings> }
+ | { type: 'setGalleryPage'; page: number }
+ | { type: 'setGalleryPageInfo'; totalImages: number }
+ | { type: 'touchGalleryRefresh' }
+ | { type: 'removeGalleryImages'; imageNames: string[] }
+ | { type: 'setGalleryProjectBoardId'; boardId: string }
| { type: 'acceptStagedImage' }
| { type: 'clearCanvasStaging' }
| { type: 'cancelQueueItem'; queueItemId: string }
@@ -86,7 +95,8 @@ type WorkbenchAction =
| { type: 'clearErrorLog' }
| { type: 'recordWidgetFailure'; failure: WidgetFailure }
| { type: 'setPreferences'; preferences: Partial<WorkbenchPreferences> }
- | { type: 'recordError'; message: string };
+ | { type: 'recordError'; message: string }
+ | { type: 'recordNotice'; kind: WorkbenchNotificationKind; title: string; message?: string };
const HISTORY_LIMIT = 40;
const INITIAL_PROJECT_COUNT = 3;
@@ -248,6 +258,14 @@ const cycleStagedImageIndex = (imageIndex: number, pendingImageCount: number, di
const getGalleryImages = (values: Record<string, unknown>): GeneratedImageContract[] =>
Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];
+const getGallerySelectedImageNames = (values: Record<string, unknown>): string[] => {
+ if (Array.isArray(values.selectedImageNames)) {
+ return (values.selectedImageNames as unknown[]).filter((name): name is string => typeof name === 'string');
+ }
+
+ return typeof values.selectedImageName === 'string' ? [values.selectedImageName] : [];
+};
+
const cloneCanvas = (canvas: CanvasStateContract): CanvasStateContract => ({
version: 1,
document: normalizeCanvasDocument(canvas),
@@ -582,8 +600,12 @@ const normalizePreferences = (preferences?: Partial<WorkbenchPreferences>): Work
typeof preferences?.showFocusRegionHighlight === 'boolean'
? preferences.showFocusRegionHighlight
: DEFAULT_PREFERENCES.showFocusRegionHighlight;
+ const confirmImageDeletion =
+ typeof preferences?.confirmImageDeletion === 'boolean'
+ ? preferences.confirmImageDeletion
+ : DEFAULT_PREFERENCES.confirmImageDeletion;
- return { reduceMotion, showFocusRegionHighlight, themeId };
+ return { confirmImageDeletion, reduceMotion, showFocusRegionHighlight, themeId };
};
const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({
@@ -725,6 +747,21 @@ const updateProjectById = (
),
});
+const updateGalleryValues = (
+ state: WorkbenchState,
+ getValues: (values: Record<string, unknown>) => Record<string, unknown>
+): WorkbenchState =>
+ updateActiveProject(state, (project) => ({
+ ...project,
+ widgetStates: {
+ ...project.widgetStates,
+ gallery: {
+ ...project.widgetStates.gallery,
+ values: getValues(project.widgetStates.gallery.values),
+ },
+ },
+ }));
+
const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => ({
...project,
queue: {
@@ -758,6 +795,7 @@ const routeQueueItemResults = (project: Project, queueItemId: string, images: Ge
recentImages: [...images, ...existingImages],
selectedImage: images[0] ?? galleryValues.selectedImage,
selectedImageName: images[0]?.imageName ?? nextProject.widgetStates.gallery.values.selectedImageName,
+ selectedImageNames: images[0] ? [images[0].imageName] : getGallerySelectedImageNames(galleryValues),
},
},
},
@@ -848,6 +886,7 @@ const submitInvocationSnapshot = (
};
export const DEFAULT_PREFERENCES: WorkbenchPreferences = {
+ confirmImageDeletion: true,
reduceMotion: false,
showFocusRegionHighlight: true,
themeId: DEFAULT_THEME_ID,
@@ -1216,69 +1255,116 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
}));
}
case 'selectGalleryImage': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: {
- ...project.widgetStates.gallery.values,
- selectedImage: action.image,
- selectedImageName: action.image.imageName,
- },
- },
- },
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ selectedImage: action.image,
+ selectedImageName: action.image.imageName,
+ selectedImageNames: [action.image.imageName],
+ }));
+ }
+ case 'toggleGalleryImageInSelection': {
+ return updateGalleryValues(state, (values) => {
+ const imageName = action.image.imageName;
+ const selectedImageNames = getGallerySelectedImageNames(values);
+
+ if (!selectedImageNames.includes(imageName)) {
+ return {
+ ...values,
+ selectedImage: action.image,
+ selectedImageName: imageName,
+ selectedImageNames: [...selectedImageNames, imageName],
+ };
+ }
+
+ const remainingImageNames = selectedImageNames.filter((name) => name !== imageName);
+ const wasPrimary = values.selectedImageName === imageName;
+
+ return {
+ ...values,
+ selectedImage: wasPrimary ? null : values.selectedImage,
+ selectedImageName: wasPrimary
+ ? (remainingImageNames[remainingImageNames.length - 1] ?? null)
+ : values.selectedImageName,
+ selectedImageNames: remainingImageNames,
+ };
+ });
+ }
+ case 'setGalleryMultiSelection': {
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ selectedImage: action.primaryImage,
+ selectedImageName: action.primaryImage.imageName,
+ selectedImageNames: action.imageNames,
}));
}
+ case 'setGalleryCompareImage': {
+ return updateGalleryValues(state, (values) => ({ ...values, compareImage: action.image }));
+ }
case 'selectGalleryBoard': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: { ...project.widgetStates.gallery.values, selectedBoardId: action.boardId },
- },
- },
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ galleryPage: 0,
+ selectedBoardId: action.boardId,
+ selectedImageNames: [],
}));
}
case 'setGalleryView': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: { ...project.widgetStates.gallery.values, galleryView: action.galleryView },
- },
- },
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ galleryPage: 0,
+ galleryView: action.galleryView,
+ selectedImageNames: [],
}));
}
case 'setGallerySearchTerm': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: { ...project.widgetStates.gallery.values, searchTerm: action.searchTerm },
- },
- },
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ galleryPage: 0,
+ searchTerm: action.searchTerm,
}));
}
- case 'setGalleryImageDensityPercent': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: { ...project.widgetStates.gallery.values, imageDensityPercent: action.imageDensityPercent },
- },
- },
+ case 'updateGallerySettings': {
+ const resetsQuery =
+ action.settings.imageOrderDir !== undefined ||
+ action.settings.starredFirst !== undefined ||
+ action.settings.paginationMode !== undefined;
+
+ return updateGalleryValues(state, (values) => ({
+ ...values,
+ ...action.settings,
+ ...(resetsQuery ? { galleryPage: 0 } : {}),
}));
}
+ case 'setGalleryPage': {
+ return updateGalleryValues(state, (values) => ({ ...values, galleryPage: Math.max(0, action.page) }));
+ }
+ case 'setGalleryPageInfo': {
+ return updateGalleryValues(state, (values) => ({ ...values, galleryTotalImages: action.totalImages }));
+ }
+ case 'touchGalleryRefresh': {
+ return updateGalleryValues(state, (values) => ({ ...values, galleryRefreshToken: createId('gallery-refresh') }));
+ }
+ case 'removeGalleryImages': {
+ const removedImageNames = new Set(action.imageNames);
+
+ return updateGalleryValues(state, (values) => {
+ const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;
+ const compareImage = values.compareImage as GeneratedImageContract | null | undefined;
+ const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
+
+ return {
+ ...values,
+ compareImage: compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage,
+ recentImages: getGalleryImages(values).filter((image) => !removedImageNames.has(image.imageName)),
+ selectedImage: selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage,
+ selectedImageName: selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName,
+ selectedImageNames: getGallerySelectedImageNames(values).filter((name) => !removedImageNames.has(name)),
+ };
+ });
+ }
+ case 'setGalleryProjectBoardId': {
+ return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }));
+ }
case 'toggleCanvasStagingVisibility': {
return updateActiveProject(state, (project) => {
if (project.canvas.stagingArea.pendingImages.length === 0) {
@@ -1524,6 +1610,12 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
createNotification({ kind: 'error', message: action.message, title: 'Error' })
);
}
+ case 'recordNotice': {
+ return addNotification(
+ state,
+ createNotification({ kind: action.kind, message: action.message, title: action.title })
+ );
+ }
case 'setPreferences': {
const preferences = normalizePreferences({ ...state.account.preferences, ...action.preferences });