Skip to content

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

fix(webv2): keep gallery virtualizer offsets in sync with the row model

joshistoast68a8fd532fab
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index b557e06fb7..36f02326fe 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
@@ -901,6 +901,32 @@ describe('GalleryImageGrid virtualization', () => {
expect(secondOptions?.getScrollElement).toBe(firstOptions?.getScrollElement);
});
+ it('re-measures when the row model changes without a resize, and only then', async () => {
+ const gallery = createGallery({
+ items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],
+ });
+
+ await renderGallery(gallery);
+
+ // Collapsing starred keeps the visible range identical, so without an
+ // explicit measure() the virtualizer would keep serving the expanded
+ // offsets — the new rows would paint below a stale starred-sized hole.
+ mocks.measure.mockClear();
+ await click(getButton('Collapse starred items'));
+ expect(mocks.measure).toHaveBeenCalled();
+
+ // Swapping the item list (e.g. the media/assets view switch) is the same
+ // structural change arriving through props.
+ mocks.measure.mockClear();
+ await renderGallery(createGallery({ items: [createItem('image', 'other.png')] }));
+ expect(mocks.measure).toHaveBeenCalled();
+
+ // An equivalent render leaves the row model alone and must not thrash.
+ mocks.measure.mockClear();
+ await renderGallery({ ...currentGallery });
+ expect(mocks.measure).not.toHaveBeenCalled();
+ });
+
it('retains constant row estimates, overscan, and the near-end infinite-load trigger', async () => {
const items = Array.from({ length: 14 }, (_, index) => createItem('image', `image-${index}.png`));
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 5bd33af969..e519b12dd4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -16,11 +16,16 @@ import {
import { useVirtualizer } from 'react-hook-tanstack-virtual';
import { useTranslation } from 'react-i18next';
-import type { GalleryQueuePlaceholder } from './galleryStateView';
-
-import { GALLERY_GRID_GAP_PX, getGalleryCellSizePx, getGalleryColumnCount } from './galleryGridLayout';
+import {
+ buildGalleryGridRows,
+ GALLERY_GRID_GAP_PX,
+ GALLERY_STARRED_HEADER_HEIGHT_PX,
+ getGalleryCellSizePx,
+ getGalleryColumnCount,
+ getGalleryGridRowHeightPx,
+ getGalleryGridRowIndexForItem,
+} from './galleryGridLayout';
import { GalleryQueuePlaceholderCell } from './GalleryQueuePlaceholderCell';
-import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';
import { GalleryThumbnailCell } from './GalleryThumbnail';
import { useGalleryUi } from './GalleryUiContext';
import { useGalleryWidget } from './GalleryWidgetContext';
@@ -33,31 +38,76 @@ import { useGalleryGridSelection } from './useGalleryGridSelection';
* tiles before the ResizeObserver reports.
*/
const viewportWidthCache = new Map<string, number>();
-const STARRED_HEADER_HEIGHT_PX = 24;
-const STARRED_SECTION_GAP_PX = GALLERY_GRID_GAP_PX;
const STARRED_TRIGGER_HOVER_STYLES = { color: 'fg' } as const;
const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');
-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-gap' }
- | { 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 });
- }
+/** The disclosure row above the starred items, styled to match board rows. */
+const GalleryStarredSectionHeader = ({
+ isOpen,
+ itemCount,
+ offsetPx,
+ onToggle,
+}: {
+ isOpen: boolean;
+ itemCount: number;
+ offsetPx: number;
+ onToggle: () => void;
+}) => {
+ const { t } = useTranslation();
- return rows;
+ return (
+ <Flex
+ align="center"
+ h={`${GALLERY_STARRED_HEADER_HEIGHT_PX}px`}
+ left="0"
+ position="absolute"
+ px="1"
+ top="0"
+ transform={`translateY(${offsetPx}px)`}
+ w="full"
+ >
+ <chakra.button
+ aria-expanded={isOpen}
+ aria-label={t(isOpen ? 'widgets.gallery.collapseStarredItems' : 'widgets.gallery.expandStarredItems')}
+ alignItems="center"
+ color="fg.muted"
+ cursor="pointer"
+ display="flex"
+ flex="1"
+ gap="1"
+ minW="0"
+ transition="color var(--wb-motion-duration-fast) ease"
+ type="button"
+ _hover={STARRED_TRIGGER_HOVER_STYLES}
+ onClick={onToggle}
+ >
+ <Icon
+ as={ChevronRightIcon}
+ boxSize="3"
+ transform={isOpen ? '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"
+ lineHeight="1"
+ textTransform="uppercase"
+ truncate
+ >
+ {t('widgets.gallery.starredItems')}
+ </Text>
+ <Text as="span" color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums" lineHeight="1">
+ {itemCount}
+ </Text>
+ </HStack>
+ </chakra.button>
+ </Flex>
+ );
};
/**
@@ -100,50 +150,17 @@ export const GalleryImageGrid = () => {
: t('widgets.gallery.selectedBoardFallback');
const isEmpty = gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0;
- 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 placeholderCells: GridCell[] = gallery.pendingPlaceholders.map((placeholder) => ({
- kind: 'placeholder',
- placeholder,
- }));
- const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(regularItems, imageOrderDir, false);
- const regularCells = [
- ...regularItemCells.slice(0, placeholderInsertionIndex),
- ...placeholderCells,
- ...regularItemCells.slice(placeholderInsertionIndex),
- ];
- const nextRows: GridRow[] = [];
-
- if (starredItemCells.length > 0) {
- nextRows.push({ itemCount: starredItemCells.length, kind: 'starred-header' });
-
- if (isStarredOpen) {
- nextRows.push(...chunkCellsIntoRows(starredItemCells, columnCount, 'starred'));
- }
-
- if (regularCells.length > 0) {
- nextRows.push({ kind: 'starred-gap' });
- }
- }
-
- nextRows.push(...chunkCellsIntoRows(regularCells, columnCount, 'regular'));
-
- return nextRows;
- }, [columnCount, gallery.items, gallery.pendingPlaceholders, imageOrderDir, isStarredOpen]);
+ const rows = useMemo(
+ () =>
+ buildGalleryGridRows({
+ columnCount,
+ imageOrderDir,
+ isStarredOpen,
+ items: gallery.items,
+ pendingPlaceholders: gallery.pendingPlaceholders,
+ }),
+ [columnCount, gallery.items, gallery.pendingPlaceholders, imageOrderDir, isStarredOpen]
+ );
const rowCount = rows.length;
const cellSizePx = getGalleryCellSizePx({ columnCount, widthPx: viewportWidth });
@@ -152,23 +169,17 @@ export const GalleryImageGrid = () => {
(index: number) => {
const row = rows[index];
- if (row?.kind === 'starred-header') {
- return STARRED_HEADER_HEIGHT_PX;
- }
-
- if (row?.kind === 'starred-gap') {
- return STARRED_SECTION_GAP_PX;
- }
-
- return rowHeightPx;
+ return row ? getGalleryGridRowHeightPx(row, rowHeightPx) : rowHeightPx;
},
[rowHeightPx, rows]
);
+ const getRowKey = useCallback((index: number) => rows[index]?.key ?? index, [rows]);
const getScrollElement = useCallback(() => viewportRef.current, []);
const virtualizer = useVirtualizer({
count: rowCount,
estimateSize: estimateRowSize,
+ getItemKey: getRowKey,
getScrollElement,
overscan: 4,
});
@@ -182,9 +193,7 @@ 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 rowIndex = rows.findIndex(
- (row) => row.kind === 'cells' && row.cells.some((cell) => cell.kind === 'item' && cell.itemIndex === itemIndex)
- );
+ const rowIndex = getGalleryGridRowIndexForItem(rows, itemIndex);
if (rowIndex >= 0) {
virtualizer.scrollToIndex(rowIndex);
@@ -223,9 +232,16 @@ export const GalleryImageGrid = () => {
return () => observer.disconnect();
}, [isEmpty, region]);
- useEffect(() => {
+ // The virtualizer only recomputes offsets lazily and only notifies
+ // subscribers when the visible index range changes, so a row-model change
+ // that keeps the range identical — collapsing the starred section, items
+ // moving between sections, a view switch swapping the item list — would
+ // paint the new rows at the previous rows' offsets. measure() recomputes
+ // from the current estimates and notifies unconditionally; running it as a
+ // layout effect keeps the stale frame from ever reaching the screen.
+ useLayoutEffect(() => {
measureVirtualizer();
- }, [rowHeightPx]);
+ }, [rowHeightPx, rows]);
const virtualRows = virtualizer.virtualItems;
const lastVisibleRowIndex = virtualRows[virtualRows.length - 1]?.index ?? 0;
@@ -321,80 +337,22 @@ export const GalleryImageGrid = () => {
{virtualRows.map((virtualRow) => {
const row = rows[virtualRow.index];
- if (!row) {
+ if (!row || row.kind === 'starred-gap') {
return null;
}
if (row.kind === 'starred-header') {
return (
- <Flex
+ <GalleryStarredSectionHeader
key={virtualRow.key}
- align="center"
- h={`${STARRED_HEADER_HEIGHT_PX}px`}
- left="0"
- position="absolute"
- px="1"
- top="0"
- transform={`translateY(${virtualRow.start}px)`}
- w="full"
- >
- <chakra.button
- aria-expanded={isStarredOpen}
- aria-label={t(
- isStarredOpen
- ? 'widgets.gallery.collapseStarredItems'
- : 'widgets.gallery.expandStarredItems'
- )}
- alignItems="center"
- color="fg.muted"
- cursor="pointer"
- display="flex"
- flex="1"
- gap="1"
- minW="0"
- transition="color var(--wb-motion-duration-fast) ease"
- type="button"
- _hover={STARRED_TRIGGER_HOVER_STYLES}
- 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"
- lineHeight="1"
- textTransform="uppercase"
- truncate
- >
- {t('widgets.gallery.starredItems')}
- </Text>
- <Text
- as="span"
- color="fg.subtle"
- fontSize="2xs"
- fontVariantNumeric="tabular-nums"
- lineHeight="1"
- >
- {row.itemCount}
- </Text>
- </HStack>
- </chakra.button>
- </Flex>
+ isOpen={isStarredOpen}
+ itemCount={row.itemCount}
+ offsetPx={virtualRow.start}
+ onToggle={handleToggleStarredSection}
+ />
);
}
- if (row.kind === 'starred-gap') {
- return null;
- }
-
return (
<Box
key={virtualRow.key}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts
index b628f1eb86..12d548591c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts
@@ -1,6 +1,52 @@
+import type { GalleryImageItem } from '@features/gallery/core/items';
+
import { describe, expect, it } from 'vitest';
-import { GALLERY_GRID_GAP_PX, getGalleryCellSizePx, getGalleryColumnCount } from './galleryGridLayout';
+import type { GalleryQueuePlaceholder } from './galleryStateView';
+
+import {
+ buildGalleryGridRows,
+ GALLERY_GRID_GAP_PX,
+ GALLERY_STARRED_HEADER_HEIGHT_PX,
+ getGalleryCellSizePx,
+ getGalleryColumnCount,
+ getGalleryGridRowHeightPx,
+ getGalleryGridRowIndexForItem,
+} from './galleryGridLayout';
+
+const createImageItem = (name: string, starred = false): GalleryImageItem => ({
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-06-09T00:00:00.000Z',
+ fullUrl: `/api/v1/images/i/${name}/full`,
+ height: 768,
+ isIntermediate: false,
+ kind: 'image',
+ name,
+ starred,
+ thumbnailUrl: `/api/v1/images/i/${name}/thumbnail`,
+ width: 512,
+});
+
+const createPlaceholder = (id: string): GalleryQueuePlaceholder => ({
+ backendItemId: null,
+ boardId: 'none',
+ height: 1024,
+ id,
+ itemIndex: 0,
+ queueItemId: `queue-${id}`,
+ width: 1024,
+});
+
+const buildRows = (overrides: Partial<Parameters<typeof buildGalleryGridRows>[0]> = {}) =>
+ buildGalleryGridRows({
+ columnCount: 2,
+ imageOrderDir: 'DESC',
+ isStarredOpen: true,
+ items: [],
+ pendingPlaceholders: [],
+ ...overrides,
+ });
describe('getGalleryColumnCount', () => {
it('gives the same answer at the same width regardless of placement', () => {
@@ -59,3 +105,104 @@ describe('getGalleryCellSizePx', () => {
expect(getGalleryCellSizePx({ columnCount: 12, widthPx: 4 })).toBeGreaterThan(0);
});
});
+
+describe('buildGalleryGridRows', () => {
+ it('chunks plain items into rows of the column count with no section chrome', () => {
+ const rows = buildRows({ items: ['a', 'b', 'c'].map((name) => createImageItem(name)) });
+
+ expect(rows.map((row) => row.kind)).toEqual(['cells', 'cells']);
+ expect(rows[0]?.kind === 'cells' && rows[0].cells.length).toBe(2);
+ expect(rows[1]?.kind === 'cells' && rows[1].cells.length).toBe(1);
+ });
+
+ it('lifts starred items into a header-led section above the regular items', () => {
+ const rows = buildRows({
+ items: [createImageItem('regular-1'), createImageItem('starred-1', true), createImageItem('regular-2')],
+ });
+
+ expect(rows.map((row) => row.kind)).toEqual(['starred-header', 'cells', 'starred-gap', 'cells']);
+ expect(rows[0]?.kind === 'starred-header' && rows[0].itemCount).toBe(1);
+ expect(rows[1]?.kind === 'cells' && rows[1].section).toBe('starred');
+ expect(rows[3]?.kind === 'cells' && rows[3].section).toBe('regular');
+ });
+
+ it('keeps the header but drops the starred rows while collapsed', () => {
+ const items = [createImageItem('starred-1', true), createImageItem('regular-1')];
+ const rows = buildRows({ isStarredOpen: false, items });
+
+ expect(rows.map((row) => row.kind)).toEqual(['starred-header', 'starred-gap', 'cells']);
+ });
+
+ it('keeps regular row keys stable across a starred collapse so their cells are not recreated', () => {
+ const items = [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')];
+ const openKeys = buildRows({ items })
+ .filter((row) => row.kind === 'cells' && row.section === 'regular')
+ .map((row) => row.key);
+ const collapsedKeys = buildRows({ isStarredOpen: false, items })
+ .filter((row) => row.kind === 'cells' && row.section === 'regular')
+ .map((row) => row.key);
+
+ expect(collapsedKeys).toEqual(openKeys);
+ });
+
+ it('gives every row a unique key', () => {
+ const rows = buildRows({
+ items: [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')],
+ pendingPlaceholders: [createPlaceholder('slot-1')],
+ });
+ const keys = rows.map((row) => row.key);
+
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+
+ it('slots placeholders ahead of regular items for newest-first ordering and after them otherwise', () => {
+ const items = [createImageItem('regular-1')];
+ const pendingPlaceholders = [createPlaceholder('slot-1')];
+
+ const newestFirst = buildRows({ items, pendingPlaceholders });
+ expect(newestFirst[0]?.kind === 'cells' && newestFirst[0].cells[0]?.kind).toBe('placeholder');
+
+ const oldestFirst = buildRows({ imageOrderDir: 'ASC', items, pendingPlaceholders });
+ expect(oldestFirst[0]?.kind === 'cells' && oldestFirst[0].cells[0]?.kind).toBe('item');
+ });
+
+ it('never mixes starred and regular cells in one row', () => {
+ const rows = buildRows({
+ columnCount: 3,
+ items: [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')],
+ });
+
+ for (const row of rows) {
+ if (row.kind === 'cells') {
+ expect(row.cells.length).toBeLessThanOrEqual(3);
+ }
+ }
+ expect(rows.filter((row) => row.kind === 'cells')).toHaveLength(2);
+ });
+});
+
+describe('getGalleryGridRowHeightPx', () => {
+ it('sizes chrome rows by their own constants and cell rows by the shared row height', () => {
+ const rows = buildRows({ items: [createImageItem('starred-1', true), createImageItem('regular-1')] });
+
+ expect(rows.map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([
+ GALLERY_STARRED_HEADER_HEIGHT_PX,
+ 100,
+ GALLERY_GRID_GAP_PX,
+ 100,
+ ]);
+ });
+});
+
+describe('getGalleryGridRowIndexForItem', () => {
+ it('finds the row holding an item by its index in the source list, across sections', () => {
+ const rows = buildRows({
+ items: [createImageItem('regular-1'), createImageItem('starred-1', true), createImageItem('regular-2')],
+ });
+
+ // Item 1 is starred, so it lives in the starred row despite its list position.
+ expect(getGalleryGridRowIndexForItem(rows, 1)).toBe(1);
+ expect(getGalleryGridRowIndexForItem(rows, 2)).toBe(3);
+ expect(getGalleryGridRowIndexForItem(rows, 99)).toBe(-1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts
index 24a3444206..59b941ff75 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts
@@ -1,4 +1,14 @@
+import type { GalleryItem } from '@features/gallery/core/items';
+import type { GalleryOrderDir } from '@features/gallery/core/types';
+
+import { toGalleryItemKey } from '@features/gallery/core/items';
+
+import type { GalleryQueuePlaceholder } from './galleryStateView';
+
+import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';
+
export const GALLERY_GRID_GAP_PX = 4;
+export const GALLERY_STARRED_HEADER_HEIGHT_PX = 24;
const GALLERY_MIN_COLUMN_COUNT = 2;
const GALLERY_MAX_COLUMN_COUNT = 12;
@@ -42,3 +52,124 @@ export const getGalleryColumnCount = ({
/** Falls back to a plausible square before the viewport has been measured. */
export const getGalleryCellSizePx = ({ columnCount, widthPx }: { columnCount: number; widthPx: number }): number =>
widthPx > 0 ? Math.max(1, (widthPx - GALLERY_GRID_GAP_PX * (columnCount - 1)) / columnCount) : 96;
+
+export type GalleryGridCell =
+ | { kind: 'item'; item: GalleryItem; itemIndex: number }
+ | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };
+
+export type GalleryGridSection = 'regular' | 'starred';
+
+export type GalleryGridRow =
+ | { cells: GalleryGridCell[]; key: string; kind: 'cells'; section: GalleryGridSection }
+ | { key: string; kind: 'starred-gap' }
+ | { itemCount: number; key: string; kind: 'starred-header' };
+
+const getGalleryGridCellKey = (cell: GalleryGridCell): string =>
+ cell.kind === 'placeholder' ? `placeholder:${cell.placeholder.id}` : toGalleryItemKey(cell.item);
+
+/**
+ * Rows are keyed by their leading cell rather than their index so that
+ * structural changes above a row (collapsing the starred section, a
+ * placeholder resolving) move the row without recreating it: the virtualizer
+ * and React both track the row by key, so its thumbnails keep their DOM.
+ */
+const chunkGalleryCellsIntoRows = (
+ cells: GalleryGridCell[],
+ columnCount: number,
+ section: GalleryGridSection
+): GalleryGridRow[] => {
+ const rows: GalleryGridRow[] = [];
+
+ for (let index = 0; index < cells.length; index += columnCount) {
+ const rowCells = cells.slice(index, index + columnCount);
+
+ rows.push({
+ cells: rowCells,
+ key: `${section}:${getGalleryGridCellKey(rowCells[0]!)}`,
+ kind: 'cells',
+ section,
+ });
+ }
+
+ return rows;
+};
+
+/**
+ * The grid's whole row model in one pure pass: starred items become a
+ * disclosure section above the regular items, and pending queue placeholders
+ * slot into the regular section at the position their images will land.
+ */
+export const buildGalleryGridRows = ({
+ columnCount,
+ imageOrderDir,
+ isStarredOpen,
+ items,
+ pendingPlaceholders,
+}: {
+ columnCount: number;
+ imageOrderDir: GalleryOrderDir;
+ isStarredOpen: boolean;
+ items: GalleryItem[];
+ pendingPlaceholders: GalleryQueuePlaceholder[];
+}): GalleryGridRow[] => {
+ const regularItemCells: GalleryGridCell[] = [];
+ const regularItems: GalleryItem[] = [];
+ const starredItemCells: GalleryGridCell[] = [];
+
+ items.forEach((item, itemIndex) => {
+ const cell: GalleryGridCell = { item, itemIndex, kind: 'item' };
+
+ if (item.starred) {
+ starredItemCells.push(cell);
+ } else {
+ regularItemCells.push(cell);
+ regularItems.push(item);
+ }
+ });
+
+ const placeholderCells: GalleryGridCell[] = pendingPlaceholders.map((placeholder) => ({
+ kind: 'placeholder',
+ placeholder,
+ }));
+ const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(regularItems, imageOrderDir, false);
+ const regularCells = [
+ ...regularItemCells.slice(0, placeholderInsertionIndex),
+ ...placeholderCells,
+ ...regularItemCells.slice(placeholderInsertionIndex),
+ ];
+ const rows: GalleryGridRow[] = [];
+
+ if (starredItemCells.length > 0) {
+ rows.push({ itemCount: starredItemCells.length, key: 'starred-header', kind: 'starred-header' });
+
+ if (isStarredOpen) {
+ rows.push(...chunkGalleryCellsIntoRows(starredItemCells, columnCount, 'starred'));
+ }
+
+ if (regularCells.length > 0) {
+ rows.push({ key: 'starred-gap', kind: 'starred-gap' });
+ }
+ }
+
+ rows.push(...chunkGalleryCellsIntoRows(regularCells, columnCount, 'regular'));
+
+ return rows;
+};
+
+/** `cellRowHeightPx` is the thumbnail row height including its trailing gap. */
+export const getGalleryGridRowHeightPx = (row: GalleryGridRow, cellRowHeightPx: number): number => {
+ if (row.kind === 'starred-header') {
+ return GALLERY_STARRED_HEADER_HEIGHT_PX;
+ }
+
+ if (row.kind === 'starred-gap') {
+ return GALLERY_GRID_GAP_PX;
+ }
+
+ return cellRowHeightPx;
+};
+
+export const getGalleryGridRowIndexForItem = (rows: GalleryGridRow[], itemIndex: number): number =>
+ rows.findIndex(
+ (row) => row.kind === 'cells' && row.cells.some((cell) => cell.kind === 'item' && cell.itemIndex === itemIndex)
+ );