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
fix(webv2): separate starred gallery items
joshistoast8b4539a906c8
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 2204c65c98..3487ed95b4 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2719,6 +2719,7 @@},"createBoard": "Create board","createBoardNamed": "Create board \"{{name}}\"",+ "collapseStarredItems": "Collapse starred items","dateFilterDay": "{{date}}","dateFilterFrom": "From {{date}}","dateFilterInvalid": "Unrecognized date “{{value}}” — use YYYY-MM-DD, today, yesterday, 7d, 2w, 1m",@@ -2750,6 +2751,7 @@"downloadSelection": "Download selection","dropMediaToUploadToBoard": "Drop images or videos to upload to {{name}}","exportProjectFromBoard": "Export project (.invk)",+ "expandStarredItems": "Expand starred items","generationProgress": "Generation progress","generationProgressPercent": "Generation {{percentage}}%","hideArchivedBoards": "Hide archived boards",@@ -2832,6 +2834,7 @@"sortBoardsBy": "Sort by","sortBoardsDescending": "Sort boards descending","starImage": "Star {{name}}",+ "starredItems": "Starred","starSelection": "Star selection","statusChip_one": "Gallery: {{count}} item","statusChip_other": "Gallery: {{count}} items",diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 05f807579d..f8e312abb3 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -115,6 +115,8 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySett: DEFAULT_GALLERY_SETTINGS.showImageDimensions,showPendingItems:typeof values.showPendingItems === 'boolean' ? values.showPendingItems : DEFAULT_GALLERY_SETTINGS.showPendingItems,- starredFirst: typeof values.starredFirst === 'boolean' ? values.starredFirst : DEFAULT_GALLERY_SETTINGS.starredFirst,+ // Starred items have a dedicated section, so the backing window must always+ // fetch them first to keep that section complete under infinite pagination.+ starredFirst: true,thumbnailFit: values.thumbnailFit === 'aspect' ? 'aspect' : DEFAULT_GALLERY_SETTINGS.thumbnailFit,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex c37e90e9a2..f04ffd9d58 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -42,7 +42,7 @@ const mocks = vi.hoisted(() => ({scrollToIndex: vi.fn(),virtualizerOptions: [] as Array<{count: number;- estimateSize: () => number;+ estimateSize: (index: number) => number;getScrollElement: () => Element | null;overscan: number;}>,@@ -62,23 +62,24 @@ vi.mock('@features/gallery/data/queries', async (importOriginal) => ({vi.mock('react-hook-tanstack-virtual', () => ({useVirtualizer: (options: {count: number;- estimateSize: () => number;+ estimateSize: (index: number) => number;getScrollElement: () => Element | null;overscan: number;}) => {mocks.virtualizerOptions.push(options);- const size = options.estimateSize();+ const sizes = Array.from({ length: options.count }, (_, index) => options.estimateSize(index));+ const starts = sizes.map((_, index) => sizes.slice(0, index).reduce((total, size) => total + size, 0));return {measure: mocks.measure,scrollToIndex: mocks.scrollToIndex,- totalSize: options.count * size,+ totalSize: sizes.reduce((total, size) => total + size, 0),virtualItems: Array.from({ length: options.count }, (_, index) => ({- end: (index + 1) * size,+ end: (starts[index] ?? 0) + (sizes[index] ?? 0),index,key: index,- size,- start: index * size,+ size: sizes[index] ?? 0,+ start: starts[index] ?? 0,})),};},@@ -115,11 +116,14 @@ void i18n.use(initReactI18next).init({itemsAriaLabel: 'Gallery items',loadingBackendGallery: 'Loading gallery',noImagesMatch: 'No items',+ collapseStarredItems: 'Collapse starred items',dropMediaToUploadToBoard: 'Drop media to {{name}}',+ expandStarredItems: 'Expand starred items',selectImageForPreview: 'Select {{name}} for preview',selectVideoForPreview: 'Select video {{name}}, duration {{duration}}, for preview',selectedBoardFallback: 'selected board',starImage: 'Star {{name}}',+ starredItems: 'Starred',unstarImage: 'Unstar {{name}}',uncategorized: 'Uncategorized',windowLimit: 'Limited to {{count}}',@@ -455,6 +459,47 @@ afterEach(async () => {});describe('GalleryImageGrid mixed item cells', () => {+ it('separates starred items into an expanded disclosure above regular items', async () => {+ await renderGallery(+ createGallery({+ items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],+ })+ );++ const trigger = getButton('Collapse starred items');+ const starredSection = host?.querySelector('[data-gallery-section="starred"]');+ const regularSection = host?.querySelector('[data-gallery-section="regular"]');++ expect(trigger.getAttribute('aria-expanded')).toBe('true');+ expect(trigger.textContent).toContain('Starred');+ expect(starredSection?.querySelector('button[aria-label="Select starred.png for preview"]')).not.toBeNull();+ expect(regularSection?.querySelector('button[aria-label="Select regular.png for preview"]')).not.toBeNull();+ expect(+ Array.from(host?.querySelectorAll('[data-gallery-section]') ?? []).map((row) =>+ row.getAttribute('data-gallery-section')+ )+ ).toEqual(['starred', 'regular']);+ });++ it('collapses only the starred items and omits the disclosure when no stars are loaded', async () => {+ await renderGallery(+ createGallery({+ items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],+ })+ );++ await click(getButton('Collapse starred items'));++ expect(getButton('Expand starred items').getAttribute('aria-expanded')).toBe('false');+ expect(host?.querySelector('button[aria-label="Select starred.png for preview"]')).toBeNull();+ expect(host?.querySelector('button[aria-label="Select regular.png for preview"]')).not.toBeNull();++ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')] }));++ expect(host?.querySelector('button[aria-label="Expand starred items"]')).toBeNull();+ expect(host?.querySelector('button[aria-label="Collapse starred items"]')).toBeNull();+ });+it('renders same-name media independently and gives a video a static accessible poster', async () => {const gallery = createGallery({items: [createItem('image', 'shared'), createItem('video', 'shared')],@@ -831,7 +876,7 @@ describe('GalleryImageGrid virtualization', () => {expect(options?.count).toBe(renderedRows);expect(renderedCells).toBe(items.length);expect(options?.overscan).toBe(4);- expect(options?.estimateSize()).toBe(options?.estimateSize());+ expect(options?.estimateSize(0)).toBe(options?.estimateSize(0));expect(host?.querySelector('[role="listitem"]')).toHaveStyle({ aspectRatio: '1 / 1' });});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex cab03efd28..11366ba395 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -1,8 +1,8 @@-import { Box, Flex, ScrollArea, Spinner, Text } from '@chakra-ui/react';+import { Box, Flex, HStack, Icon, ScrollArea, Spinner, Text } from '@chakra-ui/react';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { toGalleryItemKey, type GalleryItem } from '@features/gallery/core/items';-import { DropZone } from '@platform/ui';-import { UploadIcon } from 'lucide-react';+import { Button, DropZone } from '@platform/ui';+import { ChevronRightIcon, StarIcon, UploadIcon } from 'lucide-react';import {useCallback,useEffect,@@ -33,6 +33,7 @@ import { useGalleryGridSelection } from './useGalleryGridSelection';* tiles before the ResizeObserver reports.*/const viewportWidthCache = new Map<string, number>();+const STARRED_HEADER_HEIGHT_PX = 28;const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');@@ -40,6 +41,22 @@ type GridCell =| { kind: 'item'; item: GalleryItem; itemIndex: number }| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };+type GridSection = 'regular' | 'starred';++type GridRow =+ | { kind: 'cells'; cells: GridCell[]; section: GridSection }+ | { kind: 'starred-header'; itemCount: number };++const chunkCellsIntoRows = (cells: GridCell[], columnCount: number, section: GridSection): GridRow[] => {+ const rows: GridRow[] = [];++ for (let index = 0; index < cells.length; index += columnCount) {+ rows.push({ cells: cells.slice(index, index + columnCount), kind: 'cells', section });+ }++ return rows;+};+/*** The virtualized thumbnail grid. Column count comes from the measured* viewport width, so the grid is layout-blind: both shells render it the same@@ -50,11 +67,11 @@ export const GalleryImageGrid = () => {const { actions, gallery, isWindowTruncated, itemActions, region } = useGalleryWidget();const { account, antialiasProgressImages, ImageContextMenu } = useGalleryUi();const [isDropActive, setIsDropActive] = useState(false);+ const [isStarredOpen, setIsStarredOpen] = useState(true);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(region) ?? 0);const dragDepthRef = useRef(0);const viewportRef = useRef<HTMLDivElement | null>(null);- const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =- gallery.settings;+ const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, thumbnailFit } = gallery.settings;const {actionSelectionRefs,@@ -80,30 +97,54 @@ export const GalleryImageGrid = () => {: t('widgets.gallery.selectedBoardFallback');const isEmpty = gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0;- const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(gallery.items, imageOrderDir, starredFirst);+ const rows = useMemo<GridRow[]>(() => {+ const regularItemCells: GridCell[] = [];+ const regularItems: GalleryItem[] = [];+ const starredItemCells: GridCell[] = [];++ gallery.items.forEach((item, itemIndex) => {+ const cell: GridCell = { item, itemIndex, kind: 'item' };++ if (item.starred) {+ starredItemCells.push(cell);+ } else {+ regularItemCells.push(cell);+ regularItems.push(item);+ }+ });- const cells = useMemo<GridCell[]>(() => {- const itemCells: GridCell[] = gallery.items.map((item, itemIndex) => ({- item,- itemIndex,- kind: 'item',- }));const placeholderCells: GridCell[] = gallery.pendingPlaceholders.map((placeholder) => ({kind: 'placeholder',placeholder,}));-- return [- ...itemCells.slice(0, placeholderInsertionIndex),+ const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(regularItems, imageOrderDir, false);+ const regularCells = [+ ...regularItemCells.slice(0, placeholderInsertionIndex),...placeholderCells,- ...itemCells.slice(placeholderInsertionIndex),+ ...regularItemCells.slice(placeholderInsertionIndex),];- }, [gallery.items, gallery.pendingPlaceholders, placeholderInsertionIndex]);+ const nextRows: GridRow[] = [];- const rowCount = Math.ceil(cells.length / columnCount);+ if (starredItemCells.length > 0) {+ nextRows.push({ itemCount: starredItemCells.length, kind: 'starred-header' });++ if (isStarredOpen) {+ nextRows.push(...chunkCellsIntoRows(starredItemCells, columnCount, 'starred'));+ }+ }++ nextRows.push(...chunkCellsIntoRows(regularCells, columnCount, 'regular'));++ return nextRows;+ }, [columnCount, gallery.items, gallery.pendingPlaceholders, imageOrderDir, isStarredOpen]);++ const rowCount = rows.length;const cellSizePx = getGalleryCellSizePx({ columnCount, widthPx: viewportWidth });const rowHeightPx = cellSizePx + GALLERY_GRID_GAP_PX;- const estimateRowSize = useCallback(() => rowHeightPx, [rowHeightPx]);+ const estimateRowSize = useCallback(+ (index: number) => (rows[index]?.kind === 'starred-header' ? STARRED_HEADER_HEIGHT_PX : rowHeightPx),+ [rowHeightPx, rows]+ );const getScrollElement = useCallback(() => viewportRef.current, []);const virtualizer = useVirtualizer({@@ -122,10 +163,13 @@ export const GalleryImageGrid = () => {// identity would buy nothing and pinning the mutable virtualizer into a// dependency array defeats the compiler's own memoization.const scrollToItemIndex = (itemIndex: number) => {- const cellIndex =- itemIndex >= placeholderInsertionIndex ? itemIndex + gallery.pendingPlaceholders.length : itemIndex;+ const rowIndex = rows.findIndex(+ (row) => row.kind === 'cells' && row.cells.some((cell) => cell.kind === 'item' && cell.itemIndex === itemIndex)+ );- virtualizer.scrollToIndex(Math.floor(cellIndex / columnCount));+ if (rowIndex >= 0) {+ virtualizer.scrollToIndex(rowIndex);+ }};useGalleryGridHotkeys({ actionSelectionRefs, columnCount, scrollToItemIndex });@@ -220,6 +264,10 @@ export const GalleryImageGrid = () => {account.enableLiveFollow();}, [account]);+ const handleToggleStarredSection = useCallback(() => {+ setIsStarredOpen((isOpen) => !isOpen);+ }, []);+const handleToggleStarred = useCallback((item: GalleryItem) => void itemActions.setItemsStarred([{ kind: item.kind, name: item.name }], !item.starred),[itemActions]@@ -250,22 +298,82 @@ export const GalleryImageGrid = () => {<ScrollArea.Viewport ref={viewportRef} h="full" outline="none" w="full"><ScrollArea.Content aria-label={t('widgets.gallery.itemsAriaLabel')} role="list"><Box h={`${virtualizer.totalSize}px`} position="relative" w="full">- {virtualRows.map((virtualRow) => (- <Box- key={virtualRow.key}- display="grid"- gap={`${GALLERY_GRID_GAP_PX}px`}- gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}- left="0"- position="absolute"- role="presentation"- top="0"- transform={`translateY(${virtualRow.start}px)`}- w="full"- >- {cells- .slice(virtualRow.index * columnCount, (virtualRow.index + 1) * columnCount)- .map((cell) =>+ {virtualRows.map((virtualRow) => {+ const row = rows[virtualRow.index];++ if (!row) {+ return null;+ }++ if (row.kind === 'starred-header') {+ return (+ <Flex+ key={virtualRow.key}+ align="center"+ h={`${STARRED_HEADER_HEIGHT_PX}px`}+ left="0"+ position="absolute"+ top="0"+ transform={`translateY(${virtualRow.start}px)`}+ w="full"+ >+ <Button+ aria-expanded={isStarredOpen}+ aria-label={t(+ isStarredOpen+ ? 'widgets.gallery.collapseStarredItems'+ : 'widgets.gallery.expandStarredItems'+ )}+ color="fg.muted"+ h="6"+ justifyContent="flex-start"+ px="1"+ size="xs"+ variant="ghost"+ w="full"+ onClick={handleToggleStarredSection}+ >+ <Icon+ as={ChevronRightIcon}+ boxSize="3"+ transform={isStarredOpen ? 'rotate(90deg)' : undefined}+ transition="transform var(--wb-motion-duration-medium) ease"+ />+ <Icon as={StarIcon} boxSize="3" fill="currentColor" />+ <HStack gap="1">+ <Text+ as="span"+ fontSize="2xs"+ fontWeight="600"+ letterSpacing="wide"+ textTransform="uppercase"+ >+ {t('widgets.gallery.starredItems')}+ </Text>+ <Text as="span" color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">+ {row.itemCount}+ </Text>+ </HStack>+ </Button>+ </Flex>+ );+ }++ return (+ <Box+ key={virtualRow.key}+ data-gallery-section={row.section}+ display="grid"+ gap={`${GALLERY_GRID_GAP_PX}px`}+ gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}+ left="0"+ position="absolute"+ role="presentation"+ top="0"+ transform={`translateY(${virtualRow.start}px)`}+ w="full"+ >+ {row.cells.map((cell) =>cell.kind === 'placeholder' ? (<GalleryQueuePlaceholderCellkey={cell.placeholder.id}@@ -301,8 +409,9 @@ export const GalleryImageGrid = () => {/>))}- </Box>- ))}+ </Box>+ );+ })}</Box>{paginationMode === 'infinite' && gallery.isLoading && gallery.items.length > 0 && (<Flex align="center" justify="center" py="2">diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsxindex edcbefadbc..ee3318c12f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx@@ -18,18 +18,13 @@ const SORT_POSITIONING = { placement: 'bottom-end' } as const;export const GalleryItemSortMenu = () => {const { t } = useTranslation();const { actions, gallery } = useGalleryWidget();- const { imageOrderDir, starredFirst } = gallery.settings;+ const { imageOrderDir } = gallery.settings;const handleOrderDirChange = useCallback((event: { value: string }) => actions.updateSettings({ imageOrderDir: event.value as GalleryOrderDir }),[actions]);- const handleStarredFirstChange = useCallback(- (starredFirst: boolean) => actions.updateSettings({ starredFirst }),- [actions]- );-return (<Menu.Root positioning={SORT_POSITIONING}><Menu.Trigger asChild>@@ -59,18 +54,6 @@ export const GalleryItemSortMenu = () => {<Menu.ItemText>{t('widgets.gallery.oldest')}</Menu.ItemText></Menu.RadioItem></Menu.RadioItemGroup>- <Menu.Separator />- {/* A real checkbox item rather than a Switch smuggled into a menu- item, which needed closeOnSelect + a click-swallower to behave. */}- <Menu.CheckboxItem- checked={starredFirst}- closeOnSelect={false}- value="starred-first"- onCheckedChange={handleStarredFirstChange}- >- <Menu.ItemIndicator />- <Menu.ItemText>{t('widgets.gallery.showStarredImagesFirst')}</Menu.ItemText>- </Menu.CheckboxItem></MenuContent></Menu.Positioner></Portal>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 738a6bef6f..b418d3d906 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -179,7 +179,7 @@ describe('gallery state view', () => {});});- it('parses persisted gallery settings with safe defaults', () => {+ it('parses persisted gallery settings with safe defaults and keeps the starred section complete', () => {const gallery = getGalleryStateView({ boardOrderBy: 'board_name', starredFirst: false }, boards, [], false);expect(gallery.settings).toEqual({@@ -196,7 +196,7 @@ describe('gallery state view', () => {showDateBoards: false,showImageDimensions: false,showPendingItems: true,- starredFirst: false,+ starredFirst: true,thumbnailFit: 'square',});});