Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): rebuild gallery widget with virtualized grid and board management
joshistoast4122f7d1f6e7
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 5000e48d61..45b4dd7901 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -20,6 +20,7 @@"dependencies": {"@chakra-ui/react": "^3.28.0","@emotion/react": "^11.14.0",+ "@tanstack/react-virtual": "^3.14.2","lucide-react": "^1.17.0","react": "^19.1.0","react-dom": "^19.1.0",diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex 77cd316882..63238bf647 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -14,6 +14,9 @@ importers:'@emotion/react':specifier: ^11.14.0version: 11.14.0(@types/[email protected])([email protected])+ '@tanstack/react-virtual':+ specifier: ^3.14.2lucide-react:specifier: ^1.17.0version: 1.17.0([email protected])@@ -796,6 +799,15 @@ packages:'@swc/[email protected]':resolution: {integrity: sha512-lyMwd7WGgG79RS7EERZV3T8wMdmPq3xwyg+1nmAM64kIhx5yl+juO2PYIHb7vTiPgPCj8LYjsNV2T5wiQHUEaw==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-IpWnmCLvuymRfeeLNVXIzNEYBFLpd3drVIS91sqV78VTZFyldlChkOocZRCPp1B+Wnk09bcLNme8WaMU/9/9bQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-gOxY/hFkPh/XQYhnThBHzkbkX3Ed+z/iushyz+R+JAr213aXxUDgQoTgTdrDpBSRsjFM73P/KfUyWmaF9WHMkQ==}+'@types/[email protected]':resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}@@ -2050,6 +2062,14 @@ snapshots:dependencies:'@swc/counter': 0.1.3+ dependencies:+ '@tanstack/virtual-core': 3.17.0+ react: 19.2.7+ react-dom: 19.2.7([email protected])++ '@tanstack/[email protected]': {}+'@types/[email protected]':dependencies:'@types/deep-eql': 4.0.2diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsxnew file mode 100644index 0000000000..a9f33dd02c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsx@@ -0,0 +1,261 @@+import { Dialog, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { useEffect, useRef, useState, type ComponentType } from 'react';+import { PiArchiveBold, PiDownloadSimpleBold, PiPencilSimpleBold, PiTrashSimpleBold } from 'react-icons/pi';++import type { GalleryBoard } from '../../gallery/api';+import { Button } from '../../components/ui/Button';+import { useGalleryWidget } from './GalleryWidgetContext';++export interface GalleryBoardMenuTarget {+ board: GalleryBoard;+ x: number;+ y: number;+}++/**+ * Cursor-anchored actions menu for a single board row (download, rename,+ * archive, delete) so boards can be managed without selecting them first.+ * Opened from the board dropdown via right-click or the row's hover actions+ * button; the dropdown stays open underneath (see onActiveChange).+ */+export const GalleryBoardMenu = ({+ target,+ onActiveChange,+ onClose,+}: {+ target: GalleryBoardMenuTarget | null;+ /** Reports whether the menu or one of its dialogs is showing, so the host dropdown can stay open. */+ onActiveChange?: (isActive: boolean) => void;+ onClose: () => void;+}) => {+ const { actions, gallery } = useGalleryWidget();+ const [renameTarget, setRenameTarget] = useState<GalleryBoard | null>(null);+ const [deleteTarget, setDeleteTarget] = useState<GalleryBoard | null>(null);+ const [renameValue, setRenameValue] = useState('');+ const targetRef = useRef(target);++ targetRef.current = target;++ const board = target?.board ?? null;+ // Project boards can be downloaded but never renamed, archived, or deleted.+ const isManagedBoard = board !== null && board.kind === 'board' && board.id !== gallery.projectBoardId;+ const isActive = target !== null || renameTarget !== null || deleteTarget !== null;++ useEffect(() => {+ onActiveChange?.(isActive);+ }, [isActive, onActiveChange]);++ const submitRename = () => {+ const trimmedName = renameValue.trim();++ if (renameTarget && trimmedName && trimmedName !== renameTarget.name) {+ void actions.renameBoard(renameTarget.id, trimmedName);+ }++ setRenameTarget(null);+ };++ return (+ <>+ <Menu.Root+ key={board ? board.id : 'closed'}+ lazyMount+ open={target !== null}+ positioning={{+ getAnchorRect: () => {+ const currentTarget = targetRef.current;++ return currentTarget ? { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y } : null;+ },+ placement: 'bottom-start',+ }}+ unmountOnExit+ onOpenChange={(event) => {+ if (!event.open) {+ onClose();+ }+ }}+ >+ <Portal>+ <Menu.Positioner>+ {board && (+ <Menu.Content+ bg="bg.surfaceRaised"+ borderColor="border.emphasis"+ borderWidth="1px"+ color="fg.default"+ minW="12rem"+ py="1"+ rounded="lg"+ shadow="lg"+ >+ <BoardMenuItem+ icon={PiDownloadSimpleBold}+ label="Download Board"+ value="download-board"+ onClick={() => void actions.downloadBoard(board.id)}+ />+ {isManagedBoard && (+ <>+ <BoardMenuItem+ icon={PiPencilSimpleBold}+ label="Rename Board"+ value="rename-board"+ onClick={() => {+ setRenameValue(board.name);+ setRenameTarget(board);+ }}+ />+ <BoardMenuItem+ icon={PiArchiveBold}+ label={board.archived ? 'Unarchive Board' : 'Archive Board'}+ value="toggle-archived"+ onClick={() => void actions.archiveBoard(board.id, !board.archived)}+ />+ <Menu.Separator borderColor="border.subtle" />+ <BoardMenuItem+ color="fg.error"+ icon={PiTrashSimpleBold}+ label="Delete Board"+ value="delete-board"+ onClick={() => setDeleteTarget(board)}+ />+ </>+ )}+ </Menu.Content>+ )}+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ <Dialog.Root+ initialFocusEl={undefined}+ open={renameTarget !== null}+ onOpenChange={(event) => {+ if (!event.open) {+ setRenameTarget(null);+ }+ }}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content bg="bg.surfaceRaised" borderColor="border.emphasis" borderWidth="1px" color="fg.default">+ <Dialog.Header>+ <Dialog.Title fontSize="sm">Rename board</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Input+ aria-label="Board name"+ autoFocus+ size="sm"+ value={renameValue}+ onChange={(event) => setRenameValue(event.currentTarget.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ submitRename();+ }+ }}+ />+ </Dialog.Body>+ <Dialog.Footer gap="2">+ <Button size="xs" variant="outline" onClick={() => setRenameTarget(null)}>+ Cancel+ </Button>+ <Button disabled={renameValue.trim().length === 0} size="xs" onClick={submitRename}>+ Rename+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ <Dialog.Root+ open={deleteTarget !== null}+ role="alertdialog"+ onOpenChange={(event) => {+ if (!event.open) {+ setDeleteTarget(null);+ }+ }}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content bg="bg.surfaceRaised" borderColor="border.emphasis" borderWidth="1px" color="fg.default">+ <Dialog.Header>+ <Dialog.Title fontSize="sm">Delete board “{deleteTarget?.name}”?</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="2">+ <Text color="fg.subtle" fontSize="xs">+ Deleted boards cannot be restored. Choose whether the board’s images move to Uncategorized or+ are permanently deleted with it.+ </Text>+ <Text color="fg.subtle" fontSize="2xs">+ {deleteTarget?.imageCount ?? 0} images | {deleteTarget?.assetCount ?? 0} assets+ </Text>+ </Stack>+ </Dialog.Body>+ <Dialog.Footer gap="2">+ <Button size="xs" variant="outline" onClick={() => setDeleteTarget(null)}>+ Cancel+ </Button>+ <Button+ colorPalette="red"+ size="xs"+ variant="outline"+ onClick={() => {+ if (deleteTarget) {+ void actions.deleteBoard(deleteTarget.id, false);+ }++ setDeleteTarget(null);+ }}+ >+ Delete Board Only+ </Button>+ <Button+ colorPalette="red"+ size="xs"+ onClick={() => {+ if (deleteTarget) {+ void actions.deleteBoard(deleteTarget.id, true);+ }++ setDeleteTarget(null);+ }}+ >+ Delete Board and Images+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ </>+ );+};++const BoardMenuItem = ({+ color,+ icon,+ label,+ value,+ onClick,+}: {+ color?: string;+ icon: ComponentType;+ label: string;+ value: string;+ onClick: () => void;+}) => (+ <Menu.Item color={color} value={value} onClick={onClick}>+ <HStack gap="2" minW="0" w="full">+ <Icon as={icon} boxSize="3.5" color={color ?? 'fg.subtle'} flexShrink={0} />+ <Text flex="1" fontSize="xs">+ {label}+ </Text>+ </HStack>+ </Menu.Item>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsxnew file mode 100644index 0000000000..1aa49647ed--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx@@ -0,0 +1,425 @@+import { Badge, Flex, HStack, Icon, Image, Input, Menu, Portal, ScrollArea, Stack, Text } from '@chakra-ui/react';+import { useRef, useState, type MouseEvent } from 'react';+import {+ PiArchiveBold,+ PiCalendarBlankBold,+ PiCaretDownBold,+ PiDotsThreeVerticalBold,+ PiImageBold,+ PiPlusBold,+ PiPushPinBold,+ PiSortAscendingBold,+ PiSortDescendingBold,+} from 'react-icons/pi';++import { Button, IconButton } from '../../components/ui/Button';+import type { GalleryBoard } from '../../gallery/api';+import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenu';+import { getBoardCounts } from './galleryStateView';+import { useGalleryWidget } from './GalleryWidgetContext';++export const GalleryBoardSelect = () => {+ const { actions, gallery, projectName } = useGalleryWidget();+ const [isOpen, setIsOpen] = useState(false);+ const [boardSearchTerm, setBoardSearchTerm] = useState('');+ const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);+ const boardMenuActiveRef = useRef(false);+ const trimmedSearchTerm = boardSearchTerm.trim();+ const normalizedSearchTerm = trimmedSearchTerm.toLowerCase();+ const matchesSearch = (name: string) => !normalizedSearchTerm || name.toLowerCase().includes(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 = () => {+ setIsOpen(false);+ setBoardSearchTerm('');+ };++ const createBoardFromSearch = () => {+ if (!canCreateFromSearch) {+ return;+ }++ closeAndReset();+ void actions.createBoard(trimmedSearchTerm);+ };++ const openBoardMenu = (board: GalleryBoard, x: number, y: number) => {+ setBoardMenuTarget({ board, x, y });+ };++ return (+ <>+ <Menu.Root+ open={isOpen}+ positioning={{ placement: 'bottom-start' }}+ onOpenChange={(event) => {+ if (event.open) {+ setIsOpen(true);+ return;+ }++ // Interactions with the board actions menu (or its dialogs) land+ // outside this dropdown; swallow the resulting close request so the+ // user returns to the still-open board list.+ if (boardMenuActiveRef.current) {+ return;+ }++ closeAndReset();+ }}+ >+ <Menu.Trigger asChild>+ <Button justifyContent="space-between" minW="0" size="sm" variant="outline" w="full" px="1">+ {selectedBoard ? (+ <BoardOptionContent+ badge={selectedBoard.id === gallery.projectBoardId ? 'Project' : undefined}+ board={selectedBoard}+ isSelected={false}+ />+ ) : (+ <Text fontSize="xs">Loading board...</Text>+ )}+ <Icon as={PiCaretDownBold} boxSize="3" flexShrink={0} />+ </Button>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <Menu.Content+ bg="bg.surfaceRaised"+ borderWidth="1px"+ borderColor="border.emphasis"+ color="fg.default"+ maxH="min(30rem, calc(100vh - 6rem))"+ minW="min(22rem, calc(100vw - 2rem))"+ overflow="hidden"+ rounded="lg"+ shadow="lg"+ >+ <Stack gap="2" p="2">+ <Input+ aria-label="Search or create boards"+ placeholder="Search or create boards"+ size="sm"+ value={boardSearchTerm}+ onChange={(event) => setBoardSearchTerm(event.currentTarget.value)}+ onKeyDown={(event) => {+ event.stopPropagation();++ if (event.key === 'Enter' && !hasAnyMatch) {+ event.preventDefault();+ createBoardFromSearch();+ }+ }}+ />+ <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="Project"+ board={projectBoard}+ isSelected={projectBoard.id === gallery.selectedBoardId}+ onOpenMenu={(x, y) => openBoardMenu(projectBoard, x, y)}+ onSelect={() => {+ closeAndReset();+ actions.selectBoard(projectBoard.id);+ }}+ />+ ) : (+ <Menu.Item+ value="__project-board__"+ onClick={() => {+ closeAndReset();+ void actions.selectProjectBoard();+ }}+ >+ <HStack gap="2" minW="0" w="full">+ <BoardCoverIcon icon={PiPushPinBold} />+ <Text flex="1" fontSize="xs" fontWeight="500" minW="0" truncate>+ {projectRowName}+ </Text>+ <Badge colorPalette="blue" flexShrink={0} size="xs" variant="subtle">+ Project+ </Badge>+ </HStack>+ </Menu.Item>+ ))}+ {showUncategorizedRow && uncategorizedBoard && (+ <BoardRow+ board={uncategorizedBoard}+ isSelected={uncategorizedBoard.id === gallery.selectedBoardId}+ onOpenMenu={(x, y) => openBoardMenu(uncategorizedBoard, x, y)}+ onSelect={() => {+ closeAndReset();+ actions.selectBoard(uncategorizedBoard.id);+ }}+ />+ )}+ {dateBoards.length > 0 && (+ <>+ <BoardGroupLabel>By Date</BoardGroupLabel>+ {dateBoards.map((board) => (+ <BoardRow+ key={board.id}+ board={board}+ isSelected={board.id === gallery.selectedBoardId}+ onSelect={() => {+ closeAndReset();+ actions.selectBoard(board.id);+ }}+ />+ ))}+ </>+ )}+ {(regularBoards.length > 0 || canCreateFromSearch) && <BoardGroupLabel>Boards</BoardGroupLabel>}+ {regularBoards.map((board) => (+ <BoardRow+ key={board.id}+ badge={board.archived ? 'Archived' : undefined}+ board={board}+ isSelected={board.id === gallery.selectedBoardId}+ onOpenMenu={(x, y) => openBoardMenu(board, x, y)}+ onSelect={() => {+ closeAndReset();+ actions.selectBoard(board.id);+ }}+ />+ ))}+ {!hasAnyMatch && !canCreateFromSearch && (+ <Text color="fg.subtle" fontSize="2xs" px="3" py="2">+ No boards match this search.+ </Text>+ )}+ {canCreateFromSearch && (+ <Menu.Item value="__create-board__" onClick={createBoardFromSearch}>+ <HStack gap="2" minW="0" w="full">+ <BoardCoverIcon icon={PiPlusBold} />+ <Text flex="1" fontSize="xs" fontWeight="600" minW="0" truncate>+ Create board “{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={(isActive) => {+ boardMenuActiveRef.current = isActive;+ }}+ onClose={() => setBoardMenuTarget(null)}+ />+ </>+ );+};++const BoardListControls = () => {+ const { actions, gallery } = useGalleryWidget();+ const { boardOrderBy, boardOrderDir, showArchivedBoards, showDateBoards } = gallery.settings;+ const isAscending = boardOrderDir === 'ASC';++ return (+ <HStack gap="1" justify="space-between">+ <HStack gap="1">+ <Button+ size="2xs"+ variant={boardOrderBy === 'board_name' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ boardOrderBy: 'board_name' })}+ >+ Name+ </Button>+ <Button+ size="2xs"+ variant={boardOrderBy === 'created_at' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ boardOrderBy: 'created_at' })}+ >+ Created+ </Button>+ <IconButton+ aria-label={isAscending ? 'Sort boards descending' : 'Sort boards ascending'}+ size="2xs"+ variant="outline"+ onClick={() => actions.updateSettings({ boardOrderDir: isAscending ? 'DESC' : 'ASC' })}+ >+ {isAscending ? <PiSortAscendingBold /> : <PiSortDescendingBold />}+ </IconButton>+ </HStack>+ <HStack gap="1">+ <IconButton+ aria-label={showDateBoards ? 'Hide date boards' : 'Show date boards'}+ aria-pressed={showDateBoards}+ size="2xs"+ title={showDateBoards ? 'Hide date boards' : 'Show date boards'}+ variant={showDateBoards ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ showDateBoards: !showDateBoards })}+ >+ <PiCalendarBlankBold />+ </IconButton>+ <IconButton+ aria-label={showArchivedBoards ? 'Hide archived boards' : 'Show archived boards'}+ aria-pressed={showArchivedBoards}+ size="2xs"+ title={showArchivedBoards ? 'Hide archived boards' : 'Show archived boards'}+ variant={showArchivedBoards ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ showArchivedBoards: !showArchivedBoards })}+ >+ <PiArchiveBold />+ </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,+ board,+ isSelected,+ onOpenMenu,+ onSelect,+}: {+ badge?: 'Project' | 'Archived';+ board: GalleryBoard;+ isSelected: boolean;+ onOpenMenu?: (x: number, y: number) => void;+ onSelect: () => void;+}) => (+ <Menu.Item+ css={onOpenMenu ? { '&:hover .board-row-actions': { opacity: 1 } } : undefined}+ value={board.id}+ onClick={onSelect}+ onContextMenu={+ onOpenMenu+ ? (event: MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ onOpenMenu(event.clientX, event.clientY);+ }+ : undefined+ }+ >+ <BoardOptionContent badge={badge} board={board} isSelected={isSelected} />+ {onOpenMenu && (+ <IconButton+ aria-label={`Board actions for ${board.name}`}+ className="board-row-actions"+ flexShrink={0}+ opacity={0}+ size="2xs"+ transition="opacity 0.15s ease"+ variant="ghost"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();++ const rect = event.currentTarget.getBoundingClientRect();++ onOpenMenu(rect.left, rect.bottom);+ }}+ onPointerDown={(event) => event.stopPropagation()}+ onPointerUp={(event) => event.stopPropagation()}+ >+ <PiDotsThreeVerticalBold />+ </IconButton>+ )}+ </Menu.Item>+);++const BoardOptionContent = ({+ badge,+ board,+ isSelected,+}: {+ badge?: 'Project' | 'Archived';+ board: GalleryBoard;+ isSelected: boolean;+}) => {+ const counts = getBoardCounts(board);++ return (+ <HStack gap="2" minW="0" w="full">+ <BoardCover board={board} />+ <Text flex="1" fontSize="xs" fontWeight={isSelected ? '700' : '500'} minW="0" truncate>+ {board.name}+ </Text>+ {badge && (+ <Badge colorPalette={badge === 'Project' ? 'blue' : 'gray'} flexShrink={0} size="xs" variant="subtle">+ {badge}+ </Badge>+ )}+ <Badge flexShrink={0} size="xs" variant={isSelected ? 'solid' : 'subtle'}>+ {counts.imageCount} | {counts.assetCount}+ </Badge>+ </HStack>+ );+};++const BoardCoverIcon = ({ icon }: { icon: typeof PiImageBold }) => (+ <Flex+ align="center"+ bg="bg.panel"+ borderWidth="1px"+ borderColor="border.subtle"+ boxSize="7"+ color="fg.subtle"+ flexShrink={0}+ justify="center"+ rounded="md"+ >+ <Icon as={icon} boxSize="4" />+ </Flex>+);++const BoardCover = ({ board }: { board: GalleryBoard }) => {+ if (board.coverThumbnailUrl) {+ return (+ <Image+ alt=""+ bg="bg.panel"+ borderWidth="1px"+ borderColor="border.subtle"+ boxSize="7"+ flexShrink={0}+ objectFit="cover"+ rounded="md"+ src={board.coverThumbnailUrl}+ />+ );+ }++ return <BoardCoverIcon icon={board.kind === 'date' ? PiCalendarBlankBold : PiImageBold} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsxnew file mode 100644index 0000000000..a22900e57b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx@@ -0,0 +1,491 @@+import { Badge, Box, Flex, ScrollArea, Skeleton, Spinner, Text } from '@chakra-ui/react';+import { useVirtualizer } from '@tanstack/react-virtual';+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type DragEvent, type MouseEvent } from 'react';+import { PiStarBold, PiStarFill, PiUploadSimpleBold } from 'react-icons/pi';++import { ImageContextMenu, type ImageContextMenuTarget } from '../../components/ImageContextMenu';+import { IconButton } from '../../components/ui/Button';+import type { GalleryImage } from '../../gallery/api';+import type { GalleryThumbnailFit } from '../../gallery/settings';+import type { GalleryQueuePlaceholder } from './galleryStateView';+import { useGalleryWidget } from './GalleryWidgetContext';++const GRID_GAP_PX = 8;++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);+};++const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');++type GridCell =+ | { kind: 'image'; image: GalleryImage; imageIndex: number }+ | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };++export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {+ const { actions, gallery, imageActions } = useGalleryWidget();+ const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);+ const [isDropActive, setIsDropActive] = useState(false);+ const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(layout) ?? 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 selectedNames = useMemo(() => new Set(gallery.selectedImageNames), [gallery.selectedImageNames]);+ const isComparisonActive =+ gallery.compareImageName !== null &&+ gallery.selectedImageName !== null &&+ gallery.compareImageName !== gallery.selectedImageName;+ const selectedBoardName = gallery.boards.find((board) => board.id === gallery.selectedBoardId)?.name ?? 'this board';+ const isEmpty = gallery.images.length === 0 && gallery.pendingPlaceholders.length === 0;++ // Fresh generations are unstarred, so with newest-first ordering they land+ // right after the starred block — pending placeholders go there too.+ const leadingStarredCount = useMemo(() => {+ if (imageOrderDir !== 'DESC' || !starredFirst) {+ return 0;+ }++ let count = 0;++ while (count < gallery.images.length && gallery.images[count].starred) {+ count += 1;+ }++ return count;+ }, [gallery.images, imageOrderDir, starredFirst]);+ const cells = useMemo<GridCell[]>(() => {+ const imageCells: GridCell[] = gallery.images.map((image, imageIndex) => ({ image, imageIndex, kind: 'image' }));+ const placeholderCells: GridCell[] = gallery.pendingPlaceholders.map((placeholder) => ({+ kind: 'placeholder',+ placeholder,+ }));++ if (imageOrderDir !== 'DESC') {+ return [...imageCells, ...placeholderCells];+ }++ return [...imageCells.slice(0, leadingStarredCount), ...placeholderCells, ...imageCells.slice(leadingStarredCount)];+ }, [gallery.images, gallery.pendingPlaceholders, imageOrderDir, leadingStarredCount]);+ const getCellIndexForImage = (imageIndex: number): number =>+ imageOrderDir === 'DESC' && imageIndex >= leadingStarredCount+ ? imageIndex + gallery.pendingPlaceholders.length+ : imageIndex;+ 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 rowHeightRef = useRef(rowHeightPx);++ rowHeightRef.current = rowHeightPx;++ const virtualizer = useVirtualizer({+ count: rowCount,+ estimateSize: () => rowHeightRef.current,+ getScrollElement: () => viewportRef.current,+ overscan: 4,+ });++ useLayoutEffect(() => {+ const viewport = viewportRef.current;++ if (!viewport) {+ return;+ }++ const setMeasuredWidth = (width: number) => {+ if (width <= 0) {+ return;+ }++ viewportWidthCache.set(layout, width);+ setViewportWidth((currentWidth) => (currentWidth === width ? currentWidth : width));+ };++ const observer = new ResizeObserver((entries) => {+ const width = entries[0]?.contentRect.width;++ if (typeof width === 'number') {+ setMeasuredWidth(width);+ }+ });++ setMeasuredWidth(viewport.clientWidth);+ observer.observe(viewport);++ return () => observer.disconnect();+ }, [isEmpty, layout]);++ useEffect(() => {+ virtualizer.measure();+ }, [rowHeightPx, virtualizer]);++ const virtualRows = virtualizer.getVirtualItems();+ const lastVisibleRowIndex = virtualRows[virtualRows.length - 1]?.index ?? 0;++ useEffect(() => {+ if (paginationMode === 'infinite' && rowCount > 0 && lastVisibleRowIndex >= rowCount - 2) {+ actions.loadMore();+ }+ }, [actions, lastVisibleRowIndex, paginationMode, rowCount]);++ const handleThumbnailClick = (image: GalleryImage, event: MouseEvent) => {+ if (event.shiftKey) {+ const targetIndex = gallery.images.findIndex((candidate) => candidate.imageName === image.imageName);+ const anchorIndex = gallery.images.findIndex((candidate) => candidate.imageName === gallery.selectedImageName);++ if (targetIndex !== -1 && anchorIndex !== -1 && targetIndex !== anchorIndex) {+ const start = Math.min(anchorIndex, targetIndex);+ const end = Math.max(anchorIndex, targetIndex);++ actions.selectImageRange(+ gallery.images.slice(start, end + 1).map((candidate) => candidate.imageName),+ image+ );+ return;+ }+ }++ if (event.ctrlKey || event.metaKey) {+ actions.toggleImageInSelection(image);+ } else {+ actions.selectImage(image);+ }+ };++ const handleThumbnailContextMenu = (image: GalleryImage, x: number, y: number) => {+ if (selectedNames.has(image.imageName) && selectedNames.size > 1) {+ const selectionImages = [+ image,+ ...gallery.images.filter(+ (candidate) => candidate.imageName !== image.imageName && selectedNames.has(candidate.imageName)+ ),+ ];++ setContextMenuTarget({ images: selectionImages, x, y });+ return;+ }++ setContextMenuTarget({ images: [image], x, y });+ };++ const navigate = (direction: 'down' | 'left' | 'right' | 'up') => {+ const imageCount = gallery.images.length;++ if (imageCount === 0) {+ return;+ }++ const selectedIndex = gallery.images.findIndex((image) => image.imageName === gallery.selectedImageName);+ const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;+ const delta =+ direction === 'right' ? 1 : direction === 'left' ? -1 : direction === 'down' ? columnCount : -columnCount;+ const nextIndex = Math.min(imageCount - 1, Math.max(0, fallbackIndex + delta));+ const nextImage = gallery.images[nextIndex];++ if (nextImage && (nextIndex !== selectedIndex || selectedIndex === -1)) {+ actions.selectImage(nextImage);+ virtualizer.scrollToIndex(Math.floor(getCellIndexForImage(nextIndex) / columnCount));+ }+ };++ return (+ <Box+ flex="1"+ maxW="full"+ minH="0"+ minW="0"+ position="relative"+ w="full"+ onDragEnter={(event) => {+ if (!dragEventContainsFiles(event)) {+ return;+ }++ event.preventDefault();+ dragDepthRef.current += 1;+ setIsDropActive(true);+ }}+ onDragLeave={(event) => {+ if (!dragEventContainsFiles(event)) {+ return;+ }++ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);++ if (dragDepthRef.current === 0) {+ setIsDropActive(false);+ }+ }}+ onDragOver={(event) => {+ if (dragEventContainsFiles(event)) {+ event.preventDefault();+ }+ }}+ onDrop={(event) => {+ event.preventDefault();+ dragDepthRef.current = 0;+ setIsDropActive(false);++ const files = Array.from(event.dataTransfer.files);++ if (files.length > 0) {+ void actions.uploadFiles(files);+ }+ }}+ >+ {isEmpty ? (+ <Flex align="center" color="fg.subtle" h="full" justify="center" minH="8rem">+ <Text fontSize="2xs">+ {gallery.isLoading ? 'Loading backend gallery...' : 'No images match this board, tab, or search.'}+ </Text>+ </Flex>+ ) : (+ <ScrollArea.Root h="full" minH="0" size="xs" variant="hover" w="full">+ <ScrollArea.Viewport+ ref={viewportRef}+ aria-label="Gallery images"+ h="full"+ role="listbox"+ tabIndex={0}+ w="full"+ onKeyDown={(event) => {+ const direction =+ event.key === 'ArrowRight'+ ? ('right' as const)+ : event.key === 'ArrowLeft'+ ? ('left' as const)+ : event.key === 'ArrowDown'+ ? ('down' as const)+ : event.key === 'ArrowUp'+ ? ('up' as const)+ : null;++ if (direction) {+ event.preventDefault();+ navigate(direction);+ }+ }}+ >+ <ScrollArea.Content>+ <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">+ {virtualRows.map((virtualRow) => (+ <Box+ key={virtualRow.key}+ display="grid"+ gap={`${GRID_GAP_PX}px`}+ gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}+ left="0"+ position="absolute"+ top="0"+ transform={`translateY(${virtualRow.start}px)`}+ w="full"+ >+ {cells+ .slice(virtualRow.index * columnCount, (virtualRow.index + 1) * columnCount)+ .map((cell) =>+ cell.kind === 'placeholder' ? (+ <Skeleton key={cell.placeholder.id} aspectRatio={1} minW="0" rounded="md" w="full" />+ ) : (+ <GalleryThumbnail+ key={cell.image.imageName}+ alwaysShowDimensions={showImageDimensions}+ compareRole={+ isComparisonActive && cell.image.imageName === gallery.selectedImageName+ ? 'Viewing'+ : isComparisonActive && cell.image.imageName === gallery.compareImageName+ ? 'Compare'+ : null+ }+ fit={thumbnailFit}+ image={cell.image}+ isPrimary={cell.image.imageName === gallery.selectedImageName}+ isSelected={selectedNames.has(cell.image.imageName)}+ onClick={handleThumbnailClick}+ onContextMenu={handleThumbnailContextMenu}+ onToggleStarred={(image) =>+ void imageActions.setImagesStarred([image.imageName], !image.starred)+ }+ />+ )+ )}+ </Box>+ ))}+ </Box>+ {paginationMode === 'infinite' && gallery.isLoading && gallery.images.length > 0 && (+ <Flex align="center" justify="center" py="2">+ <Spinner color="fg.subtle" size="xs" />+ </Flex>+ )}+ </ScrollArea.Content>+ </ScrollArea.Viewport>+ <ScrollArea.Scrollbar>+ <ScrollArea.Thumb />+ </ScrollArea.Scrollbar>+ </ScrollArea.Root>+ )}+ {isDropActive && (+ <Flex+ align="center"+ bg="bg.surfaceRaised/80"+ borderColor="accent.active"+ borderStyle="dashed"+ borderWidth="2px"+ direction="column"+ gap="2"+ inset="0"+ justify="center"+ pointerEvents="none"+ position="absolute"+ rounded="md"+ zIndex="1"+ >+ <PiUploadSimpleBold size="20" />+ <Text fontSize="xs" fontWeight="600">+ Drop images to upload to {selectedBoardName}+ </Text>+ </Flex>+ )}+ <ImageContextMenu+ actions={imageActions}+ boards={gallery.boards}+ target={contextMenuTarget}+ onClose={() => setContextMenuTarget(null)}+ />+ </Box>+ );+};++const GalleryThumbnail = ({+ alwaysShowDimensions,+ compareRole,+ fit,+ image,+ isPrimary,+ isSelected,+ onClick,+ onContextMenu,+ onToggleStarred,+}: {+ alwaysShowDimensions: boolean;+ compareRole: 'Compare' | 'Viewing' | null;+ fit: GalleryThumbnailFit;+ image: GalleryImage;+ isPrimary: boolean;+ isSelected: boolean;+ onClick: (image: GalleryImage, event: MouseEvent) => void;+ onContextMenu: (image: GalleryImage, x: number, y: number) => void;+ onToggleStarred: (image: GalleryImage) => void;+}) => {+ const isCompared = compareRole !== null;++ return (+ <Box+ aspectRatio={1}+ bg="bg.panel"+ borderWidth="2px"+ borderColor={isSelected || isCompared ? 'accent.active' : 'border.subtle'}+ boxShadow={isCompared ? 'inset 0 0 0 1px var(--chakra-colors-accent-active)' : undefined}+ css={{ '&:hover .gallery-thumb-overlay': { opacity: 1 } }}+ minW="0"+ overflow="hidden"+ role="option"+ aria-selected={isSelected}+ position="relative"+ rounded="md"+ w="full"+ onContextMenu={(event) => {+ event.preventDefault();+ onContextMenu(image, event.clientX, event.clientY);+ }}+ >+ <button+ aria-label={`Select ${image.imageName} for preview`}+ style={{+ background: 'transparent',+ border: 0,+ cursor: 'pointer',+ display: 'block',+ height: '100%',+ inset: 0,+ minWidth: 0,+ padding: 0,+ position: 'absolute',+ width: '100%',+ }}+ tabIndex={isPrimary ? 0 : -1}+ type="button"+ onClick={(event) => onClick(image, event)}+ >+ <img+ alt={image.imageName}+ src={image.thumbnailUrl || image.imageUrl}+ style={{+ display: 'block',+ height: '100%',+ inset: 0,+ maxWidth: 'none',+ objectFit: fit === 'aspect' ? 'contain' : 'cover',+ position: 'absolute',+ width: '100%',+ }}+ />+ </button>+ {compareRole && (+ <Badge+ insetInlineStart="1"+ pointerEvents="none"+ position="absolute"+ size="xs"+ top="1"+ variant="solid"+ zIndex="1"+ >+ {compareRole}+ </Badge>+ )}+ <IconButton+ aria-label={image.starred ? `Unstar ${image.imageName}` : `Star ${image.imageName}`}+ className="gallery-thumb-overlay"+ colorPalette={image.starred ? 'yellow' : 'gray'}+ insetInlineEnd="1"+ opacity={image.starred ? 1 : 0}+ position="absolute"+ size="2xs"+ top="1"+ transition="opacity 0.15s ease"+ variant="solid"+ zIndex="1"+ onClick={(event) => {+ event.stopPropagation();+ onToggleStarred(image);+ }}+ >+ {image.starred ? <PiStarFill /> : <PiStarBold />}+ </IconButton>+ {image.width > 0 && image.height > 0 && (+ <Badge+ bottom="1"+ className="gallery-thumb-overlay"+ insetInlineStart="1"+ opacity={alwaysShowDimensions ? 1 : 0}+ pointerEvents="none"+ position="absolute"+ size="xs"+ transition="opacity 0.15s ease"+ variant="solid"+ zIndex="1"+ >+ {image.width}x{image.height}+ </Badge>+ )}+ </Box>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsxindex 5bc6a10194..8df020e3a2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsx@@ -1,493 +1,11 @@-import {- Badge,- Box,- Button,- Flex,- HStack,- Icon,- IconButton,- Image,- Input,- Menu,- Portal,- Slider,- Stack,- Text,-} from '@chakra-ui/react';-import { useState } from 'react';-import { PiCaretDownBold, PiGearSixBold, PiImageBold, PiPlusBold } from 'react-icons/pi';+import { Stack } from '@chakra-ui/react';-import type { GalleryBoard, GalleryView } from '../../gallery/api';-import type { GeneratedImageContract, WorkbenchRegion } from '../../types';-import { getBoardCounts, type GalleryStateView } from './galleryStateView';+import { GalleryImageGrid } from './GalleryImageGrid';+import { GalleryToolbar } from './GalleryToolbar';-export const GalleryPanelContent = ({- gallery,- layout,- region,- onCreateBoard,- onSearch,- onSetImageDensityPercent,- onSelectBoard,- onSelectImage,- onSetView,-}: {- gallery: GalleryStateView;- layout: 'stacked' | 'wide';- region: WorkbenchRegion;- onCreateBoard: () => void;- onSearch: (searchTerm: string) => void;- onSetImageDensityPercent: (imageDensityPercent: number) => void;- onSelectBoard: (boardId: string) => void;- onSelectImage: (image: GeneratedImageContract) => void;- onSetView: (galleryView: GalleryView) => void;-}) => {- const isWide = layout === 'wide';-- return (- <Flex direction={isWide ? 'row' : 'column'} gap="3" h="full" maxW="full" minH="0" minW="0" w="full">- <GalleryBoardSelect- gallery={gallery}- layout={layout}- onCreateBoard={onCreateBoard}- onSelectBoard={onSelectBoard}- />- <Stack flex="1" gap="3" maxW="full" minH="0" minW="0" w="full">- <GalleryToolbar- gallery={gallery}- onSearch={onSearch}- onSetImageDensityPercent={onSetImageDensityPercent}- onSetView={onSetView}- />- <GalleryImages- columnCount={getGalleryColumnCount(gallery.imageDensityPercent, layout)}- imageDensityPercent={gallery.imageDensityPercent}- images={gallery.images}- isLoading={gallery.isLoading}- region={region}- selectedImageName={gallery.selectedImageName}- onNavigate={(direction) => {- const selectedIndex = gallery.images.findIndex((image) => image.imageName === gallery.selectedImageName);- const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;- const nextIndex =- direction === 'next'- ? Math.min(gallery.images.length - 1, fallbackIndex + 1)- : Math.max(0, fallbackIndex - 1);- const nextImage = gallery.images[nextIndex];-- if (nextImage) {- onSelectImage(nextImage);- }- }}- onSelect={onSelectImage}- />- </Stack>- </Flex>- );-};--const GalleryBoardSelect = ({- gallery,- layout,- onCreateBoard,- onSelectBoard,-}: {- gallery: GalleryStateView;- layout: 'stacked' | 'wide';- onCreateBoard: () => void;- onSelectBoard: (boardId: string) => void;-}) => {- const isWide = layout === 'wide';- const [boardSearchTerm, setBoardSearchTerm] = useState('');- const normalizedSearchTerm = boardSearchTerm.trim().toLowerCase();- const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId) ?? null;- const filteredBoards = normalizedSearchTerm- ? gallery.boards.filter((board) => board.name.toLowerCase().includes(normalizedSearchTerm))- : gallery.boards;-- return (- <Stack flex={isWide ? '0 0 16rem' : '0 0 auto'} gap="2" maxW="full" minW="0" w={isWide ? undefined : 'full'}>- <HStack justify="space-between">- <Text fontSize="xs" fontWeight="700">- Boards- </Text>- <Button size="2xs" variant="outline" onClick={onCreateBoard}>- <PiPlusBold />- Board- </Button>- </HStack>- <Menu.Root positioning={{ placement: isWide ? 'bottom-start' : 'bottom' }}>- <Menu.Trigger asChild>- <Button justifyContent="space-between" size="sm" variant="outline" w="full" px="1">- {selectedBoard ? (- <BoardOptionContent board={selectedBoard} isSelected={false} />- ) : (- <Text>Loading board...</Text>- )}- <Icon as={PiCaretDownBold} boxSize="3" flexShrink={0} />- </Button>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <Menu.Content- bg="bg.surfaceRaised"- borderWidth="1px"- borderColor="border.emphasis"- color="fg.default"- maxH="min(28rem, calc(100vh - 6rem))"- minW={isWide ? '16rem' : 'min(22rem, calc(100vw - 2rem))'}- overflow="hidden"- rounded="lg"- shadow="lg"- >- <Box p="2">- <Input- aria-label="Search boards"- placeholder="Search boards"- size="sm"- value={boardSearchTerm}- onChange={(event) => setBoardSearchTerm(event.currentTarget.value)}- onKeyDown={(event) => event.stopPropagation()}- />- </Box>- <Menu.Separator borderColor="border.subtle" />- <Box maxH="18rem" overflowY="auto" py="1">- {filteredBoards.length ? (- filteredBoards.map((board) => {- const isSelected = board.id === gallery.selectedBoardId;-- return (- <Menu.Item key={board.id} value={board.id} onClick={() => onSelectBoard(board.id)}>- <BoardOptionContent board={board} isSelected={isSelected} />- </Menu.Item>- );- })- ) : (- <Text color="fg.subtle" fontSize="2xs" px="3" py="2">- No boards match this search.- </Text>- )}- </Box>- </Menu.Content>- </Menu.Positioner>- </Portal>- </Menu.Root>- </Stack>- );-};--const BoardOptionContent = ({ board, isSelected }: { board: GalleryBoard; isSelected: boolean }) => {- const counts = getBoardCounts(board);-- return (- <HStack gap="2" minW="0" w="full">- <BoardCover board={board} />- <Text flex="1" fontSize="xs" fontWeight={isSelected ? '700' : '500'} minW="0" truncate>- {board.name}- </Text>- <Badge flexShrink={0} size="xs" variant={isSelected ? 'solid' : 'subtle'}>- {counts.imageCount} | {counts.assetCount}- </Badge>- </HStack>- );-};--const BoardCover = ({ board }: { board: GalleryBoard }) => {- if (board.coverThumbnailUrl) {- return (- <Image- alt=""- bg="bg.panel"- borderWidth="1px"- borderColor="border.subtle"- boxSize="7"- flexShrink={0}- objectFit="cover"- rounded="md"- src={board.coverThumbnailUrl}- />- );- }-- return (- <Flex- align="center"- bg="bg.panel"- borderWidth="1px"- borderColor="border.subtle"- boxSize="7"- color="fg.subtle"- flexShrink={0}- justify="center"- rounded="md"- >- <Icon as={PiImageBold} boxSize="4" />- </Flex>- );-};--const GalleryToolbar = ({- gallery,- onSearch,- onSetImageDensityPercent,- onSetView,-}: {- gallery: GalleryStateView;- onSearch: (searchTerm: string) => void;- onSetImageDensityPercent: (imageDensityPercent: number) => void;- onSetView: (galleryView: GalleryView) => void;-}) => (- <Stack gap="2">- <HStack justify="space-between">- <HStack gap="1">- <Button- size="xs"- variant={gallery.galleryView === 'images' ? 'solid' : 'outline'}- onClick={() => onSetView('images')}- >- Images- </Button>- <Button- size="xs"- variant={gallery.galleryView === 'assets' ? 'solid' : 'outline'}- onClick={() => onSetView('assets')}- >- Assets- </Button>- </HStack>- <HStack gap="2">- <Text color="fg.subtle" fontSize="2xs">- {gallery.images.length} total- </Text>- <GallerySettingsMenu gallery={gallery} onSetImageDensityPercent={onSetImageDensityPercent} />- </HStack>- </HStack>- <Input- aria-label="Search gallery images"- placeholder="Search images"- size="sm"- value={gallery.searchTerm}- onChange={(event) => onSearch(event.currentTarget.value)}- />+export const GalleryPanelContent = ({ layout }: { layout: 'stacked' | 'wide' }) => (+ <Stack gap="3" h="full" maxW="full" minH="0" minW="0" w="full">+ <GalleryToolbar layout={layout} />+ <GalleryImageGrid layout={layout} /></Stack>);--const GallerySettingsMenu = ({- gallery,- onSetImageDensityPercent,-}: {- gallery: GalleryStateView;- onSetImageDensityPercent: (imageDensityPercent: number) => void;-}) => (- <Menu.Root positioning={{ placement: 'bottom-end' }}>- <Menu.Trigger asChild>- <IconButton aria-label="Gallery settings" size="xs" variant="outline">- <PiGearSixBold />- </IconButton>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <Menu.Content- bg="bg.surfaceRaised"- borderWidth="1px"- borderColor="border.emphasis"- color="fg.default"- minW="14rem"- p="3"- rounded="lg"- shadow="lg"- >- <Stack gap="2">- <HStack justify="space-between">- <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">- Grid Density- </Text>- <Text color="fg.subtle" fontSize="2xs">- {gallery.imageDensityPercent}%- </Text>- </HStack>- <Slider.Root- aria-label={['Gallery image density']}- max={100}- min={0}- step={1}- value={[gallery.imageDensityPercent]}- onKeyDown={(event) => event.stopPropagation()}- onValueChange={(event) => onSetImageDensityPercent(event.value[0] ?? gallery.imageDensityPercent)}- >- <Slider.Control>- <Slider.Track>- <Slider.Range />- </Slider.Track>- <Slider.Thumbs />- </Slider.Control>- </Slider.Root>- </Stack>- </Menu.Content>- </Menu.Positioner>- </Portal>- </Menu.Root>-);--const getGalleryColumnCount = (imageDensityPercent: number, layout: 'stacked' | 'wide'): number => {- const min = 2;- const max = layout === 'wide' ? 10 : 5;- const percent = Math.min(100, Math.max(0, imageDensityPercent));-- return Math.round(min + ((max - min) * percent) / 100);-};--const getCompactThumbnailSizeRem = (imageDensityPercent: number): number => {- const percent = Math.min(100, Math.max(0, imageDensityPercent));-- return 7 - (3 * percent) / 100;-};--const GalleryImages = ({- columnCount,- imageDensityPercent,- images,- isLoading,- region,- selectedImageName,- onNavigate,- onSelect,-}: {- columnCount: number;- imageDensityPercent: number;- images: GeneratedImageContract[];- isLoading: boolean;- region: WorkbenchRegion;- selectedImageName: string | null;- onNavigate: (direction: 'next' | 'previous') => void;- onSelect: (image: GeneratedImageContract) => void;-}) => {- const isLargePlacement = region === 'center' || region === 'bottom';- const thumbnailAspectRatio = isLargePlacement ? 1 : 4 / 3;- const selectedIndex = images.findIndex((image) => image.imageName === selectedImageName);- const compactThumbnailSizeRem = getCompactThumbnailSizeRem(imageDensityPercent);- const gridTemplateColumns = isLargePlacement- ? `repeat(${columnCount}, minmax(0, 1fr))`- : `repeat(auto-fill, minmax(min(100%, ${compactThumbnailSizeRem}rem), ${compactThumbnailSizeRem}rem))`;-- if (images.length === 0) {- return (- <Flex align="center" color="fg.subtle" flex="1" justify="center" minH="8rem">- <Text fontSize="2xs">- {isLoading ? 'Loading backend gallery...' : 'No images match this board, tab, or search.'}- </Text>- </Flex>- );- }-- return (- <Box- aria-label="Gallery images"- flex="1"- maxW="full"- minH="0"- minW="0"- overflowX="hidden"- overflowY="auto"- role="listbox"- tabIndex={0}- w="full"- onKeyDown={(event) => {- if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {- event.preventDefault();- onNavigate('next');- }-- if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {- event.preventDefault();- onNavigate('previous');- }- }}- >- <Box- display="grid"- gap="2"- gridTemplateColumns={gridTemplateColumns}- justifyContent={isLargePlacement ? undefined : 'start'}- maxW="full"- minW="0"- w="full"- >- {images.map((image, index) => (- <GalleryThumbnail- key={image.imageName}- image={image}- index={index}- isSelected={image.imageName === selectedImageName}- selectedIndex={selectedIndex}- thumbnailAspectRatio={thumbnailAspectRatio}- onSelect={onSelect}- />- ))}- </Box>- </Box>- );-};--const GalleryThumbnail = ({- image,- index,- isSelected,- selectedIndex,- thumbnailAspectRatio,- onSelect,-}: {- image: GeneratedImageContract;- index: number;- isSelected: boolean;- selectedIndex: number;- thumbnailAspectRatio: number;- onSelect: (image: GeneratedImageContract) => void;-}) => (- <Box- aspectRatio={thumbnailAspectRatio}- bg="bg.panel"- borderWidth="2px"- borderColor={isSelected ? 'accent.active' : 'border.subtle'}- minW="0"- overflow="hidden"- role="option"- aria-selected={isSelected}- position="relative"- rounded="md"- w="full"- >- <button- aria-label={`Select ${image.imageName} for preview`}- style={{- background: 'transparent',- border: 0,- cursor: 'pointer',- display: 'block',- height: '100%',- inset: 0,- minWidth: 0,- padding: 0,- position: 'absolute',- width: '100%',- }}- tabIndex={selectedIndex === -1 ? (index === 0 ? 0 : -1) : isSelected ? 0 : -1}- type="button"- onClick={() => onSelect(image)}- >- <img- alt={image.imageName}- src={image.thumbnailUrl || image.imageUrl}- style={{- display: 'block',- height: '100%',- inset: 0,- maxWidth: 'none',- objectFit: 'cover',- position: 'absolute',- width: '100%',- }}- />- </button>- </Box>-);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsxnew file mode 100644index 0000000000..bb018b5399--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsx@@ -0,0 +1,269 @@+import { Box, HStack, Input, Menu, Portal, Slider, Spacer, Stack, Switch, Text } from '@chakra-ui/react';+import { useRef } from 'react';+import { PiGearSixBold, PiUploadSimpleBold } from 'react-icons/pi';++import { Button, IconButton } from '../../components/ui/Button';+import { isDateBoardId } from '../../gallery/api';+import { GalleryBoardSelect } from './GalleryBoardSelect';+import { useGalleryWidget } from './GalleryWidgetContext';++const ACCEPTED_UPLOAD_EXTENSIONS = 'image/png,image/jpeg,image/webp';++export const GalleryToolbar = ({ layout }: { layout: 'stacked' | 'wide' }) => {+ const { actions, gallery } = useGalleryWidget();+ const isWide = layout === 'wide';+ const viewTabs = (+ <HStack gap="1">+ <Button+ size="xs"+ variant={gallery.galleryView === 'images' ? 'solid' : 'outline'}+ onClick={() => actions.setView('images')}+ >+ Images+ </Button>+ <Button+ size="xs"+ variant={gallery.galleryView === 'assets' ? 'solid' : 'outline'}+ onClick={() => actions.setView('assets')}+ >+ Assets+ </Button>+ </HStack>+ );+ const toolbarActions = (+ <HStack gap="2">+ <Text color="fg.subtle" fontSize="2xs">+ {gallery.images.length} loaded+ </Text>+ <GalleryUploadButton />+ <GallerySettingsMenu />+ </HStack>+ );++ return (+ <Stack gap="2">+ {isWide ? (+ <HStack gap="2">+ <Box flex="1" maxW="24rem" minW="10rem">+ <GalleryBoardSelect />+ </Box>+ {viewTabs}+ <Spacer />+ {toolbarActions}+ </HStack>+ ) : (+ <>+ <GalleryBoardSelect />+ <HStack justify="space-between">+ {viewTabs}+ {toolbarActions}+ </HStack>+ </>+ )}+ <Input+ aria-label="Search gallery images"+ placeholder="Search images"+ size="sm"+ value={gallery.searchTerm}+ onChange={(event) => actions.setSearchTerm(event.currentTarget.value)}+ />+ </Stack>+ );+};++const GalleryUploadButton = () => {+ const { actions, gallery } = useGalleryWidget();+ const fileInputRef = useRef<HTMLInputElement>(null);+ const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);+ const isVirtualTarget = isDateBoardId(gallery.selectedBoardId);++ return (+ <>+ <input+ accept={ACCEPTED_UPLOAD_EXTENSIONS}+ multiple+ ref={fileInputRef}+ style={{ display: 'none' }}+ type="file"+ onChange={(event) => {+ const files = Array.from(event.currentTarget.files ?? []);++ event.currentTarget.value = '';++ if (files.length > 0) {+ void actions.uploadFiles(files);+ }+ }}+ />+ <IconButton+ aria-label={+ isVirtualTarget+ ? 'Uploads are unavailable for date boards'+ : `Upload images to ${selectedBoard?.name ?? 'the selected board'}`+ }+ disabled={isVirtualTarget}+ size="xs"+ variant="outline"+ onClick={() => fileInputRef.current?.click()}+ >+ <PiUploadSimpleBold />+ </IconButton>+ </>+ );+};++const GallerySettingsMenu = () => {+ const { actions, gallery } = useGalleryWidget();+ const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =+ gallery.settings;++ return (+ <Menu.Root positioning={{ placement: 'bottom-end' }}>+ <Menu.Trigger asChild>+ <IconButton aria-label="Gallery settings" size="xs" variant="outline">+ <PiGearSixBold />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <Menu.Content+ bg="bg.surfaceRaised"+ borderWidth="1px"+ borderColor="border.emphasis"+ color="fg.default"+ minW="14rem"+ p="3"+ rounded="lg"+ shadow="lg"+ >+ <Stack gap="3">+ <Stack gap="2">+ <HStack justify="space-between">+ <SettingLabel>Grid Density</SettingLabel>+ <Text color="fg.subtle" fontSize="2xs">+ {imageDensityPercent}%+ </Text>+ </HStack>+ <Slider.Root+ aria-label={['Gallery image density']}+ max={100}+ min={0}+ step={1}+ value={[imageDensityPercent]}+ onKeyDown={(event) => event.stopPropagation()}+ onValueChange={(event) =>+ actions.updateSettings({ imageDensityPercent: event.value[0] ?? imageDensityPercent })+ }+ >+ <Slider.Control>+ <Slider.Track>+ <Slider.Range />+ </Slider.Track>+ <Slider.Thumbs />+ </Slider.Control>+ </Slider.Root>+ </Stack>+ <Stack gap="2">+ <SettingLabel>Thumbnails</SettingLabel>+ <HStack gap="1">+ <Button+ flex="1"+ size="2xs"+ variant={thumbnailFit === 'square' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ thumbnailFit: 'square' })}+ >+ Square+ </Button>+ <Button+ flex="1"+ size="2xs"+ variant={thumbnailFit === 'aspect' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ thumbnailFit: 'aspect' })}+ >+ Aspect+ </Button>+ </HStack>+ <SettingSwitch+ checked={showImageDimensions}+ label="Always show dimensions"+ onChange={(checked) => actions.updateSettings({ showImageDimensions: checked })}+ />+ </Stack>+ <Stack gap="2">+ <SettingLabel>Image Sort</SettingLabel>+ <HStack gap="1">+ <Button+ flex="1"+ size="2xs"+ variant={imageOrderDir === 'DESC' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ imageOrderDir: 'DESC' })}+ >+ Newest+ </Button>+ <Button+ flex="1"+ size="2xs"+ variant={imageOrderDir === 'ASC' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ imageOrderDir: 'ASC' })}+ >+ Oldest+ </Button>+ </HStack>+ <SettingSwitch+ checked={starredFirst}+ label="Show starred images first"+ onChange={(checked) => actions.updateSettings({ starredFirst: checked })}+ />+ </Stack>+ <Stack gap="2">+ <SettingLabel>Pagination</SettingLabel>+ <HStack gap="1">+ <Button+ flex="1"+ size="2xs"+ variant={paginationMode === 'infinite' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ paginationMode: 'infinite' })}+ >+ Infinite+ </Button>+ <Button+ flex="1"+ size="2xs"+ variant={paginationMode === 'paginated' ? 'solid' : 'outline'}+ onClick={() => actions.updateSettings({ paginationMode: 'paginated' })}+ >+ 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;+}) => (+ <Switch.Root checked={checked} size="sm" onCheckedChange={(event) => onChange(event.checked)}>+ <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/workbench/widgets/gallery/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsxnew file mode 100644index 0000000000..fea6fa1d47--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx@@ -0,0 +1,50 @@+import { createContext, use } from 'react';++import type { ImageActions } from '../../components/useImageActions';+import type { GalleryImage, GalleryView } from '../../gallery/api';+import type { GallerySettings } from '../../gallery/settings';+import type { GalleryStateView } from './galleryStateView';++/**+ * Gallery-widget intents. The provider (GalleryWidgetView) is the only place+ * that knows whether an intent maps to a workbench dispatch, a backend call,+ * or both. Image-level operations (star, delete, move, ...) live in the shared+ * ImageActions contract instead so other widgets reuse them.+ */+export interface GalleryActions {+ archiveBoard: (boardId: string, archived: boolean) => Promise<void>;+ createBoard: (boardName: string) => Promise<void>;+ deleteBoard: (boardId: string, includeImages: boolean) => Promise<void>;+ downloadBoard: (boardId: string) => Promise<void>;+ loadMore: () => void;+ refresh: () => void;+ renameBoard: (boardId: string, boardName: string) => Promise<void>;+ selectBoard: (boardId: string) => void;+ selectImage: (image: GalleryImage) => void;+ selectImageRange: (imageNames: string[], primaryImage: GalleryImage) => void;+ selectProjectBoard: () => Promise<void>;+ setSearchTerm: (searchTerm: string) => void;+ setView: (galleryView: GalleryView) => void;+ toggleImageInSelection: (image: GalleryImage) => void;+ updateSettings: (settings: Partial<GallerySettings>) => void;+ uploadFiles: (files: File[]) => Promise<void>;+}++export interface GalleryWidgetContextValue {+ gallery: GalleryStateView;+ actions: GalleryActions;+ imageActions: ImageActions;+ projectName: string;+}++export const GalleryWidgetContext = createContext<GalleryWidgetContextValue | null>(null);++export const useGalleryWidget = (): GalleryWidgetContextValue => {+ const value = use(GalleryWidgetContext);++ if (!value) {+ throw new Error('useGalleryWidget must be used within the gallery widget.');+ }++ return value;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsxnew file mode 100644index 0000000000..3b4b98d934--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx@@ -0,0 +1,58 @@+import { ButtonGroup, HStack, Pagination } from '@chakra-ui/react';+import { PiCaretLeftBold, PiCaretRightBold } from 'react-icons/pi';++import { IconButton } from '../../components/ui/Button';+import { getGallerySettings } from '../../gallery/settings';+import type { WidgetViewProps } from '../../types';+import { useWorkbench } from '../../WorkbenchContext';+import { getGalleryPage, getGalleryTotalImages } from './galleryStateView';+import { GALLERY_PAGE_SIZE } from './useGalleryData';++/**+ * Widget-chrome footer: page navigation for the gallery's paginated mode.+ * Reads everything from the gallery widget's persisted values so it stays+ * decoupled from the view's data fetching.+ */+export const GalleryWidgetFooter = (_props: WidgetViewProps) => {+ const { activeProject, dispatch } = useWorkbench();+ const galleryValues = activeProject.widgetStates.gallery.values;+ const settings = getGallerySettings(galleryValues);+ const page = getGalleryPage(galleryValues);+ const totalImages = getGalleryTotalImages(galleryValues);++ if (settings.paginationMode !== 'paginated' || totalImages === null || totalImages <= GALLERY_PAGE_SIZE) {+ return null;+ }++ return (+ <HStack justify="center" py="1" w="full">+ <Pagination.Root+ count={totalImages}+ page={page + 1}+ pageSize={GALLERY_PAGE_SIZE}+ siblingCount={1}+ onPageChange={(event) => dispatch({ page: event.page - 1, type: 'setGalleryPage' })}+ >+ <ButtonGroup gap="1" size="2xs" variant="ghost">+ <Pagination.PrevTrigger asChild>+ <IconButton aria-label="Previous page">+ <PiCaretLeftBold />+ </IconButton>+ </Pagination.PrevTrigger>+ <Pagination.Items+ render={(paginationPage) => (+ <IconButton aria-label={`Page ${paginationPage.value}`} variant={{ _selected: 'outline', base: 'ghost' }}>+ {paginationPage.value}+ </IconButton>+ )}+ />+ <Pagination.NextTrigger asChild>+ <IconButton aria-label="Next page">+ <PiCaretRightBold />+ </IconButton>+ </Pagination.NextTrigger>+ </ButtonGroup>+ </Pagination.Root>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsxindex 29e3433b80..77b7ffa691 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx@@ -1,139 +1,144 @@-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';import { PiImageBold } from 'react-icons/pi';import { StatusWidgetChip } from '../../components/WidgetFrames';-import {- createGalleryBoard,- listGalleryBoards,- listGalleryImages,- type GalleryBoard,- type GalleryImage,-} from '../../gallery/api';+import { useImageActions } from '../../components/useImageActions';+import { getGallerySettings } from '../../gallery/settings';import type { WidgetViewProps } from '../../types';import { useWorkbench } from '../../WorkbenchContext';import { GalleryPanelContent } from './GalleryPanelContent';import {+ getGalleryPage,+ getGalleryProjectBoardId,getGalleryRecentImagesKey,+ getGalleryRefreshToken,getGallerySearchTerm,getGallerySelectedBoardId,getGalleryStateView,+ getGalleryTotalImages,getGalleryView,} from './galleryStateView';--interface BackendImagesResult {- images: GalleryImage[];- queryKey: string;-}--const EMPTY_BACKEND_IMAGES: GalleryImage[] = [];--const getGalleryQueryKey = ({- boardId,- galleryView,- searchTerm,-}: {- boardId: string;- galleryView: string;- searchTerm: string;-}): string => `${galleryView}\0${boardId}\0${searchTerm.trim()}`;+import { GalleryWidgetContext, type GalleryWidgetContextValue } from './GalleryWidgetContext';+import { useGalleryActions } from './useGalleryActions';+import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) => {const { activeProject, dispatch } = useWorkbench();- const [backendBoards, setBackendBoards] = useState<GalleryBoard[]>([]);- const [backendImagesResult, setBackendImagesResult] = useState<BackendImagesResult | null>(null);- const [loadingImageQueryKey, setLoadingImageQueryKey] = useState<string | null>(null);const galleryValues = activeProject.widgetStates.gallery.values;- const selectedBoardId = getGallerySelectedBoardId(galleryValues, backendBoards);const galleryView = getGalleryView(galleryValues);const searchTerm = getGallerySearchTerm(galleryValues);const recentImagesKey = getGalleryRecentImagesKey(galleryValues);- const imageQueryKey = getGalleryQueryKey({ boardId: selectedBoardId, galleryView, searchTerm });- const isAwaitingCurrentImages = backendImagesResult !== null && backendImagesResult.queryKey !== imageQueryKey;- const backendImages =- backendImagesResult === null- ? null- : backendImagesResult.queryKey === imageQueryKey- ? backendImagesResult.images- : EMPTY_BACKEND_IMAGES;- const isLoadingImages = loadingImageQueryKey === imageQueryKey || isAwaitingCurrentImages;- const gallery = getGalleryStateView(galleryValues, backendBoards, backendImages, isLoadingImages);- const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');+ const refreshToken = getGalleryRefreshToken(galleryValues);+ const page = getGalleryPage(galleryValues);+ const knownTotalImages = getGalleryTotalImages(galleryValues);+ const settings = getGallerySettings(galleryValues);+ const onError = useCallback((message: string) => dispatch({ message, type: 'recordError' }), [dispatch]);+ const data = useGalleryData({+ galleryView,+ onError,+ page,+ recentImagesKey,+ refreshToken,+ searchTerm,+ selectedBoardId: getGallerySelectedBoardId(galleryValues, []),+ settings,+ });+ const { loadMore, patchImages, total } = data;+ const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);+ const gallery = getGalleryStateView(+ galleryValues,+ data.boards,+ data.images,+ data.isLoadingImages,+ activeProject.queue.items+ );+ const onStarredChange = useCallback(+ (imageNames: string[], starred: boolean) => {+ patchImages((images) =>+ images.map((image) => (imageNames.includes(image.imageName) ? { ...image, starred } : image))+ );+ },+ [patchImages]+ );+ const galleryImagesRef = useRef(gallery.images);+ const selectedImageNameRef = useRef(gallery.selectedImageName);- useEffect(() => {- let isStale = false;+ galleryImagesRef.current = gallery.images;+ selectedImageNameRef.current = gallery.selectedImageName;- listGalleryBoards()- .then((boards) => {- if (!isStale) {- setBackendBoards(boards);- }- })- .catch((error: unknown) => {- dispatch({ message: error instanceof Error ? error.message : String(error), type: 'recordError' });- });+ // After a deletion that takes out the previewed image, move the selection to+ // the image that now occupies the old index, else the one before it.+ const onImagesDeleted = useCallback(+ (imageNames: string[]) => {+ const deletedNames = new Set(imageNames);+ const images = galleryImagesRef.current;+ const anchorName = selectedImageNameRef.current;- return () => {- isStale = true;- };- }, [dispatch, recentImagesKey]);+ if (!anchorName || !deletedNames.has(anchorName)) {+ return;+ }+ const anchorIndex = images.findIndex((image) => image.imageName === anchorName);++ if (anchorIndex === -1) {+ return;+ }++ const remaining = images.filter((image) => !deletedNames.has(image.imageName));+ const remainingBeforeAnchor = images+ .slice(0, anchorIndex)+ .filter((image) => !deletedNames.has(image.imageName)).length;+ const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;++ if (nextImage) {+ dispatch({ image: nextImage, type: 'selectGalleryImage' });+ }+ },+ [dispatch]+ );+ const imageActions = useImageActions({ boards: data.boards, dispatch, onImagesDeleted, onStarredChange });+ const actions = useGalleryActions({+ boards: data.boards,+ dispatch,+ loadMore,+ projectBoardId: getGalleryProjectBoardId(galleryValues),+ projectName: activeProject.name,+ selectedBoardId,+ });+ const contextValue = useMemo<GalleryWidgetContextValue>(+ () => ({ actions, gallery, imageActions, projectName: activeProject.name }),+ [actions, activeProject.name, gallery, imageActions]+ );+ 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).useEffect(() => {- let isStale = false;+ if (total !== null && total !== knownTotalImages) {+ dispatch({ totalImages: total, type: 'setGalleryPageInfo' });+ }+ }, [dispatch, knownTotalImages, total]);- setLoadingImageQueryKey(imageQueryKey);- listGalleryImages({- boardId: selectedBoardId,- galleryView,- searchTerm,- })- .then((images) => {- if (!isStale) {- setBackendImagesResult({ images, queryKey: imageQueryKey });- }- })- .catch((error: unknown) => {- if (!isStale) {- setBackendImagesResult({ images: [], queryKey: imageQueryKey });- dispatch({ message: error instanceof Error ? error.message : String(error), type: 'recordError' });- }- })- .finally(() => {- if (!isStale) {- setLoadingImageQueryKey((currentQueryKey) => (currentQueryKey === imageQueryKey ? null : currentQueryKey));- }- });+ useEffect(() => {+ if (settings.paginationMode !== 'paginated' || total === null) {+ return;+ }- return () => {- isStale = true;- };- }, [dispatch, galleryView, imageQueryKey, recentImagesKey, searchTerm, selectedBoardId]);+ const maxPage = Math.max(0, Math.ceil(total / GALLERY_PAGE_SIZE) - 1);++ if (page > maxPage) {+ dispatch({ page: maxPage, type: 'setGalleryPage' });+ }+ }, [dispatch, page, settings.paginationMode, total]);if (region === 'bottom' && presentation !== 'expanded') {- return <StatusWidgetChip icon={PiImageBold}>Gallery: {gallery.images.length}</StatusWidgetChip>;+ return <StatusWidgetChip icon={PiImageBold}>Gallery: {total ?? gallery.images.length}</StatusWidgetChip>;}return (- <GalleryPanelContent- gallery={gallery}- layout={isWidePlacement ? 'wide' : 'stacked'}- region={region}- onCreateBoard={() => {- createGalleryBoard(`Board ${backendBoards.length}`)- .then((board) => {- setBackendBoards((boards) => [...boards, board]);- dispatch({ boardId: board.id, type: 'selectGalleryBoard' });- })- .catch((error: unknown) => {- dispatch({ message: error instanceof Error ? error.message : String(error), type: 'recordError' });- });- }}- onSearch={(searchTerm) => dispatch({ searchTerm, type: 'setGallerySearchTerm' })}- onSetImageDensityPercent={(imageDensityPercent) =>- dispatch({ imageDensityPercent, type: 'setGalleryImageDensityPercent' })- }- onSelectBoard={(boardId) => dispatch({ boardId, type: 'selectGalleryBoard' })}- onSelectImage={(image) => dispatch({ image, type: 'selectGalleryImage' })}- onSetView={(galleryView) => dispatch({ galleryView, type: 'setGalleryView' })}- />+ <GalleryWidgetContext value={contextValue}>+ <GalleryPanelContent layout={isWidePlacement ? 'wide' : 'stacked'} />+ </GalleryWidgetContext>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.tsindex db8a94ad6e..e7dc0f1216 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts@@ -1,10 +1,12 @@import type { WidgetManifest } from '../../types';+import { GalleryWidgetFooter } from './GalleryWidgetFooter';import { GalleryWidgetView } from './GalleryWidgetView';export const galleryWidgetManifest: WidgetManifest = {bottomPanel: 'expandable',chrome: { header: 'hidden' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ footer: GalleryWidgetFooter,icon: 'lucide-react:image',id: 'gallery',label: 'Gallery',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.tsnew file mode 100644index 0000000000..f2753d48cd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.ts@@ -0,0 +1,164 @@+import { useMemo, type Dispatch } from 'react';++import { saveBlobToDisk } from '../../components/useImageActions';+import {+ createGalleryBoard,+ deleteGalleryBoard,+ downloadGalleryArchive,+ updateGalleryBoard,+ uploadGalleryImage,+ type GalleryBoard,+} from '../../gallery/api';+import type { WorkbenchAction } from '../../workbenchState';+import type { GalleryActions } from './GalleryWidgetContext';++const ACCEPTED_UPLOAD_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);++const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));++export const useGalleryActions = ({+ boards,+ dispatch,+ loadMore,+ projectBoardId,+ projectName,+ selectedBoardId,+}: {+ boards: GalleryBoard[];+ dispatch: Dispatch<WorkbenchAction>;+ loadMore: () => void;+ projectBoardId: string | null;+ projectName: string;+ selectedBoardId: string;+}): GalleryActions => {+ return useMemo<GalleryActions>(() => {+ const recordError = (error: unknown) => dispatch({ message: toErrorMessage(error), type: 'recordError' });+ const recordSuccess = (title: string, message?: string) =>+ dispatch({ kind: 'success', message, title, type: 'recordNotice' });+ const refresh = () => dispatch({ type: 'touchGalleryRefresh' });+ const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';++ return {+ archiveBoard: async (boardId, archived) => {+ try {+ await updateGalleryBoard(boardId, { archived });+ recordSuccess(`${archived ? 'Archived' : 'Unarchived'} board "${getBoardName(boardId)}"`);++ if (archived && boardId === selectedBoardId) {+ dispatch({ boardId: 'none', type: 'selectGalleryBoard' });+ }++ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ createBoard: async (boardName) => {+ try {+ const board = await createGalleryBoard(boardName);++ dispatch({ boardId: board.id, type: 'selectGalleryBoard' });+ recordSuccess(`Created board "${board.name}"`);+ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ deleteBoard: async (boardId, includeImages) => {+ try {+ const boardName = getBoardName(boardId);++ await deleteGalleryBoard(boardId, includeImages);+ recordSuccess(+ `Deleted board "${boardName}"`,+ includeImages ? 'Its images were permanently deleted.' : 'Its images were moved to Uncategorized.'+ );++ if (boardId === selectedBoardId) {+ dispatch({ boardId: 'none', type: 'selectGalleryBoard' });+ }++ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ downloadBoard: async (boardId) => {+ try {+ dispatch({+ kind: 'info',+ message: `Preparing an archive of "${getBoardName(boardId)}".`,+ title: 'Preparing download',+ type: 'recordNotice',+ });++ const { blob, fileName } = await downloadGalleryArchive({ boardId });++ saveBlobToDisk(blob, fileName);+ recordSuccess('Download ready');+ } catch (error: unknown) {+ recordError(error);+ }+ },+ loadMore,+ refresh,+ renameBoard: async (boardId, boardName) => {+ try {+ await updateGalleryBoard(boardId, { name: boardName });+ recordSuccess(`Renamed board to "${boardName}"`);+ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ selectBoard: (boardId) => dispatch({ boardId, type: 'selectGalleryBoard' }),+ selectImage: (image) => dispatch({ image, type: 'selectGalleryImage' }),+ selectImageRange: (imageNames, primaryImage) =>+ dispatch({ imageNames, primaryImage, type: 'setGalleryMultiSelection' }),+ selectProjectBoard: async () => {+ if (projectBoardId && boards.some((board) => board.id === projectBoardId)) {+ dispatch({ boardId: projectBoardId, type: 'selectGalleryBoard' });+ return;+ }++ if (boards.length === 0) {+ return;+ }++ try {+ const board = await createGalleryBoard(projectName);++ dispatch({ boardId: board.id, type: 'setGalleryProjectBoardId' });+ dispatch({ boardId: board.id, type: 'selectGalleryBoard' });+ recordSuccess(`Created project board "${board.name}"`);+ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ setSearchTerm: (searchTerm) => dispatch({ searchTerm, type: 'setGallerySearchTerm' }),+ setView: (galleryView) => dispatch({ galleryView, type: 'setGalleryView' }),+ toggleImageInSelection: (image) => dispatch({ image, type: 'toggleGalleryImageInSelection' }),+ updateSettings: (settings) => dispatch({ settings, type: 'updateGallerySettings' }),+ uploadFiles: async (files) => {+ const accepted = files.filter((file) => ACCEPTED_UPLOAD_TYPES.has(file.type));++ if (accepted.length === 0) {+ dispatch({ message: 'No supported image files to upload (PNG, JPEG, or WebP).', type: 'recordError' });+ return;+ }++ try {+ await Promise.all(accepted.map((file) => uploadGalleryImage(file, selectedBoardId)));+ recordSuccess(+ `Uploaded ${accepted.length} ${accepted.length === 1 ? 'image' : 'images'}`,+ `Added to ${getBoardName(selectedBoardId)} as assets.`+ );+ refresh();+ } catch (error: unknown) {+ recordError(error);+ }+ },+ };+ }, [boards, dispatch, loadMore, projectBoardId, projectName, selectedBoardId]);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.tsnew file mode 100644index 0000000000..7177aa6d53--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.ts@@ -0,0 +1,281 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import {+ listGalleryBoards,+ listGalleryDateBoards,+ listGalleryImages,+ type GalleryBoard,+ type GalleryImage,+ type GalleryView,+} from '../../gallery/api';+import type { GallerySettings } from '../../gallery/settings';++export const GALLERY_PAGE_SIZE = 60;++const GALLERY_CACHE_TTL_MS = 60_000;+const GALLERY_BOARDS_CACHE_LIMIT = 8;+const GALLERY_IMAGES_CACHE_LIMIT = 24;+const GALLERY_INFINITE_WINDOW_CACHE_LIMIT = 24;++interface CacheEntry<T> {+ cachedAt: number;+ value: T;+}++interface BoardsResult {+ boards: GalleryBoard[];+ key: string;+}++interface BackendImagesResult {+ /** Query identity without the pagination window — results stay visible while the window changes. */+ baseKey: string;+ /** Full identity including the pagination window and refresh token. */+ fetchKey: string;+ images: GalleryImage[];+ total: number;+}++const boardsCache = new Map<string, CacheEntry<GalleryBoard[]>>();+const imageResultByFetchKeyCache = new Map<string, CacheEntry<BackendImagesResult>>();+const imageResultByBaseKeyCache = new Map<string, CacheEntry<BackendImagesResult>>();+const infiniteWindowCache = new Map<string, number>();++const isCacheEntryFresh = <T>(entry: CacheEntry<T> | undefined): boolean =>+ entry !== undefined && Date.now() - entry.cachedAt < GALLERY_CACHE_TTL_MS;++const setLimitedMapEntry = <T>(cache: Map<string, T>, key: string, value: T, limit: number): void => {+ cache.delete(key);+ cache.set(key, value);++ while (cache.size > limit) {+ const oldestKey = cache.keys().next().value;++ if (oldestKey === undefined) {+ return;+ }++ cache.delete(oldestKey);+ }+};++const cacheBoards = (key: string, boards: GalleryBoard[]): void => {+ setLimitedMapEntry(boardsCache, key, { cachedAt: Date.now(), value: boards }, GALLERY_BOARDS_CACHE_LIMIT);+};++const cacheImageResult = (result: BackendImagesResult): void => {+ const entry = { cachedAt: Date.now(), value: result };++ setLimitedMapEntry(imageResultByFetchKeyCache, result.fetchKey, entry, GALLERY_IMAGES_CACHE_LIMIT);+ setLimitedMapEntry(imageResultByBaseKeyCache, result.baseKey, entry, GALLERY_IMAGES_CACHE_LIMIT);+};++const getCachedPageCount = (baseKey: string): number => Math.max(1, infiniteWindowCache.get(baseKey) ?? 1);++const cachePageCount = (baseKey: string, pageCount: number): void => {+ setLimitedMapEntry(infiniteWindowCache, baseKey, Math.max(1, pageCount), GALLERY_INFINITE_WINDOW_CACHE_LIMIT);+};++export interface GalleryData {+ boards: GalleryBoard[];+ /** True while more items exist beyond the loaded infinite-scroll window. */+ hasMore: boolean;+ images: GalleryImage[] | null;+ isLoadingImages: boolean;+ /** Grow the infinite-scroll window by one page. No-op while fetching, when exhausted, or in paginated mode. */+ loadMore: () => void;+ /** Optimistically patch the currently loaded image list (e.g. star toggles). */+ patchImages: (getImages: (images: GalleryImage[]) => GalleryImage[]) => void;+ /** Backend total for the current query, or null while unknown. */+ total: number | null;+}++export const useGalleryData = ({+ galleryView,+ onError,+ page,+ recentImagesKey,+ refreshToken,+ searchTerm,+ selectedBoardId,+ settings,+}: {+ galleryView: GalleryView;+ onError: (message: string) => void;+ page: number;+ recentImagesKey: string;+ refreshToken: string;+ searchTerm: string;+ selectedBoardId: string;+ settings: GallerySettings;+}): GalleryData => {+ const {+ boardOrderBy,+ boardOrderDir,+ imageOrderDir,+ paginationMode,+ showArchivedBoards,+ showDateBoards,+ starredFirst,+ } = settings;+ const boardsKey = [+ String(showArchivedBoards),+ boardOrderBy,+ boardOrderDir,+ String(showDateBoards),+ refreshToken,+ recentImagesKey,+ ].join('\0');+ const cachedBoardsEntry = boardsCache.get(boardsKey);+ const isBoardsCacheFresh = isCacheEntryFresh(cachedBoardsEntry);+ const [boardsResult, setBoardsResult] = useState<BoardsResult | null>(() =>+ cachedBoardsEntry ? { boards: cachedBoardsEntry.value, key: boardsKey } : null+ );+ const boards = boardsResult?.key === boardsKey ? boardsResult.boards : (cachedBoardsEntry?.value ?? []);+ const boardId =+ boards.length === 0 || boards.some((board) => board.id === selectedBoardId) ? selectedBoardId : 'none';+ const baseKey = [galleryView, boardId, searchTerm.trim(), imageOrderDir, String(starredFirst)].join('\0');+ const cachedPageCount = getCachedPageCount(baseKey);+ const [infiniteWindow, setInfiniteWindow] = useState<{ baseKey: string; pageCount: number }>(() => ({+ baseKey,+ pageCount: cachedPageCount,+ }));+ const isPaginated = paginationMode === 'paginated';+ const pageCount = infiniteWindow.baseKey === baseKey ? infiniteWindow.pageCount : cachedPageCount;+ const offset = isPaginated ? page * GALLERY_PAGE_SIZE : 0;+ const limit = isPaginated ? GALLERY_PAGE_SIZE : pageCount * GALLERY_PAGE_SIZE;+ const fetchKey = [baseKey, String(offset), String(limit), refreshToken, recentImagesKey].join('\0');+ const exactCachedImageResultEntry = imageResultByFetchKeyCache.get(fetchKey);+ const baseCachedImageResultEntry = imageResultByBaseKeyCache.get(baseKey);+ const cachedImageResultEntry = exactCachedImageResultEntry ?? baseCachedImageResultEntry;+ const isExactImageCacheFresh = isCacheEntryFresh(exactCachedImageResultEntry);+ const [result, setResult] = useState<BackendImagesResult | null>(() => cachedImageResultEntry?.value ?? null);+ const [loadingFetchKey, setLoadingFetchKey] = useState<string | null>(null);+ const stateResult = result !== null && result.baseKey === baseKey ? result : null;+ const visibleResult = exactCachedImageResultEntry?.value ?? stateResult ?? baseCachedImageResultEntry?.value ?? null;+ const images = visibleResult !== null && visibleResult.baseKey === baseKey ? visibleResult.images : null;+ const total = visibleResult !== null && visibleResult.baseKey === baseKey ? visibleResult.total : null;+ const isLoadingImages = loadingFetchKey === fetchKey || (!isExactImageCacheFresh && result?.fetchKey !== fetchKey);+ const hasMore = !isPaginated && total !== null && images !== null && images.length < total;+ const hasMoreRef = useRef(hasMore);+ const isLoadingRef = useRef(isLoadingImages);+ const visibleResultRef = useRef(visibleResult);++ hasMoreRef.current = hasMore;+ isLoadingRef.current = isLoadingImages;+ visibleResultRef.current = visibleResult;++ useEffect(() => {+ if (isBoardsCacheFresh) {+ return;+ }++ let isStale = false;++ Promise.all([+ listGalleryBoards({ includeArchived: showArchivedBoards, orderBy: boardOrderBy, orderDir: boardOrderDir }),+ showDateBoards ? listGalleryDateBoards() : Promise.resolve([]),+ ])+ .then(([backendBoards, dateBoards]) => {+ if (!isStale) {+ const nextBoards = [...backendBoards, ...dateBoards];++ cacheBoards(boardsKey, nextBoards);+ setBoardsResult({ boards: nextBoards, key: boardsKey });+ }+ })+ .catch((error: unknown) => {+ onError(error instanceof Error ? error.message : String(error));+ });++ return () => {+ isStale = true;+ };+ }, [boardOrderBy, boardOrderDir, boardsKey, isBoardsCacheFresh, onError, showArchivedBoards, showDateBoards]);++ useEffect(() => {+ if (isExactImageCacheFresh) {+ return;+ }++ let isStale = false;++ setLoadingFetchKey(fetchKey);+ listGalleryImages({+ boardId,+ galleryView,+ limit,+ offset,+ orderDir: imageOrderDir,+ searchTerm,+ starredFirst,+ })+ .then((backendPage) => {+ if (!isStale) {+ const nextResult = { baseKey, fetchKey, images: backendPage.images, total: backendPage.total };++ cacheImageResult(nextResult);+ setResult(nextResult);+ }+ })+ .catch((error: unknown) => {+ if (!isStale) {+ const fallbackResult = visibleResultRef.current?.baseKey === baseKey ? visibleResultRef.current : null;++ setResult(fallbackResult ? { ...fallbackResult, fetchKey } : { baseKey, fetchKey, images: [], total: 0 });+ onError(error instanceof Error ? error.message : String(error));+ }+ })+ .finally(() => {+ if (!isStale) {+ setLoadingFetchKey((currentFetchKey) => (currentFetchKey === fetchKey ? null : currentFetchKey));+ }+ });++ return () => {+ isStale = true;+ };+ }, [+ baseKey,+ boardId,+ fetchKey,+ galleryView,+ imageOrderDir,+ isExactImageCacheFresh,+ limit,+ offset,+ onError,+ searchTerm,+ starredFirst,+ ]);++ const patchImages = useCallback((getImages: (images: GalleryImage[]) => GalleryImage[]) => {+ const currentResult = visibleResultRef.current;++ if (currentResult === null) {+ return;+ }++ const nextResult = { ...currentResult, images: getImages(currentResult.images) };++ cacheImageResult(nextResult);+ setResult(nextResult);+ }, []);++ const loadMore = useCallback(() => {+ if (!hasMoreRef.current || isLoadingRef.current) {+ return;+ }++ setInfiniteWindow((currentWindow) => {+ const nextPageCount =+ currentWindow.baseKey === baseKey ? currentWindow.pageCount + 1 : getCachedPageCount(baseKey) + 1;++ cachePageCount(baseKey, nextPageCount);++ return { baseKey, pageCount: nextPageCount };+ });+ }, [baseKey]);++ return { boards, hasMore, images, isLoadingImages, loadMore, patchImages, total };+};