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): add a shared list family to platform/ui
Josh Corbett03f3da7fdddc
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b32399a47f..34e4402594 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -195,6 +195,9 @@"scrubber": {"editValue": "Edit {{label}}"},+ "list": {+ "selectItem": "Select {{name}}"+ },"configure": "Configure","copy": "Copy","crop": "Crop",diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxindex 43d0fa54e3..777f72e8bd 100644--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx@@ -7,6 +7,7 @@ import { Button, CloseButton } from './Button';export const ConfirmDialog = ({body,confirmLabel,+ finalFocusEl,isDestructive = true,isOpen,onClose,@@ -15,6 +16,8 @@ export const ConfirmDialog = ({}: {body: ReactNode;confirmLabel: string;+ /** Where focus returns on close when the opener may no longer exist, e.g. a row the confirmed action deleted. */+ finalFocusEl?: () => HTMLElement | null;isDestructive?: boolean;isOpen: boolean;onClose: () => void;@@ -64,6 +67,7 @@ export const ConfirmDialog = ({<Dialog.RootcloseOnEscape={!isPending}closeOnInteractOutside={!isPending}+ finalFocusEl={finalFocusEl}open={isOpen}role="alertdialog"size="sm"diff --git a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsxindex 87d35c158b..21e12fae23 100644--- a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx@@ -38,15 +38,16 @@ export interface MiddleTruncateProps extends Omit<TextProps, 'children'> {}/**- * For identifiers whose suffix matters. Keep white-space: pre so flex boundaries retain spaces; preserve full DOM- * text for copy and accessibility.+ * For identifiers whose suffix matters. Keep white-space: pre across the head/tail boundary so the space there+ * survives; a head with no tail collapses newlines like any single-line label. Preserve full DOM text for copy and+ * accessibility.*/export const MiddleTruncate = ({ tailGraphemes = DEFAULT_TAIL_GRAPHEMES, text, ...textProps }: MiddleTruncateProps) => {const { head, tail } = useMemo(() => splitTextForMiddleTruncation(text, tailGraphemes), [tailGraphemes, text]);return (<Text display="flex" minW="0" overflow="hidden" title={text} whiteSpace="nowrap" {...textProps}>- <chakra.span flex="0 1 auto" overflow="hidden" textOverflow="ellipsis" whiteSpace="pre">+ <chakra.span flex="0 1 auto" overflow="hidden" textOverflow="ellipsis" whiteSpace={tail ? 'pre' : 'nowrap'}>{head}</chakra.span>{tail ? (diff --git a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx b/invokeai/frontend/webv2/src/platform/ui/Picker.tsxindex a013489168..e79a9a48cd 100644--- a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Picker.tsx@@ -192,8 +192,7 @@ export const Picker = <T,>({))}</ScrollArea.Content></ScrollArea.Viewport>- {/* Keep the scrollbar above opaque sticky headers at z-index 1. */}- <ScrollArea.Scrollbar zIndex="2">+ <ScrollArea.Scrollbar><ScrollArea.Thumb /></ScrollArea.Scrollbar></ScrollArea.Root>diff --git a/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsxnew file mode 100644index 0000000000..2249aa596f--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsx@@ -0,0 +1,537 @@+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import type { ListContextMenuAnchor } from './ListItem';+import type { ListRow } from './listRows';++import { List, type ListRowProps } from './List';+import { ListItem } from './ListItem';+import { listRowsFromSections } from './listRows';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => (options?.name ? `${key}:${String(options.name)}` : key),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++interface Item {+ id: string;+ name: string;+}++const HEADER_PX = 32;+const ROW_PX = 56;++const section = (key: string, label: string, count: number): { items: Item[]; key: string; label: string } => ({+ items: Array.from({ length: count }, (_, index) => ({ id: `${key}-${index}`, name: `${label} ${index}` })),+ key,+ label,+});++const rowsOf = (...sections: { items: Item[]; key: string; label: string }[]): ListRow<Item>[] =>+ listRowsFromSections(sections, (item) => item.id);++const settleFrame = async () => {+ await act(async () => {+ await Promise.resolve();+ });+ await act(async () => {+ await new Promise((resolve) => {+ requestAnimationFrame(() => resolve(undefined));+ });+ });+};++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'display:flex;flex-direction:column;height:400px;width:360px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++const Harness = ({+ activeKey = null,+ rows,+ onCheckedChange,+ onContextMenu,+ onPress,+}: {+ activeKey?: string | null;+ rows: ListRow<Item>[];+ onCheckedChange?: (item: Item, checked: boolean) => void;+ onContextMenu?: (item: Item, anchor: ListContextMenuAnchor) => void;+ onPress?: (item: Item) => void;+}) => (+ <ChakraProvider value={system}>+ <List+ activeKey={activeKey}+ density="comfortable"+ emptyState={<span>nothing</span>}+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => (+ <ListItem+ {...rowProps}+ title={item.name}+ onCheckedChange={onCheckedChange ? (checked) => onCheckedChange(item, checked) : undefined}+ onContextMenu={onContextMenu ? (anchor) => onContextMenu(item, anchor) : undefined}+ onPress={onPress ? () => onPress(item) : undefined}+ />+ )}+ rows={rows}+ />+ </ChakraProvider>+);++const render = async (element: React.ReactElement) => {+ await act(() => root.render(element));+ await settleFrame();+};++const viewport = () => host.querySelector<HTMLElement>('[data-list-viewport]')!;+const pinnedHeader = () => host.querySelector<HTMLElement>('[data-list-pinned-header]');+const primaryButtons = () => [...host.querySelectorAll<HTMLButtonElement>('[data-list-primary]')];++const scrollTo = async (top: number) => {+ await act(async () => {+ viewport().scrollTop = top;+ viewport().dispatchEvent(new Event('scroll'));+ await new Promise((resolve) => {+ requestAnimationFrame(() => resolve(undefined));+ });+ });+};++describe('List virtualization and pinned headers', () => {+ it('mounts only the rows near the viewport and exposes the full set size', async () => {+ await render(<Harness rows={rowsOf(section('main', 'Main', 40), section('lora', 'LoRAs', 40))} />);++ const mounted = primaryButtons();++ expect(mounted.length).toBeGreaterThan(0);+ expect(mounted.length).toBeLessThan(40);+ expect(host.querySelector('[role="list"][aria-label="subjects"]')).not.toBeNull();+ expect(host.querySelector('[role="listitem"]')?.getAttribute('aria-setsize')).toBe('80');+ expect(host.querySelector('[role="listitem"]')?.getAttribute('aria-posinset')).toBe('1');+ });++ it('pins the header of the section at the top of the visible range and pushes it out with the next one', async () => {+ await render(<Harness rows={rowsOf(section('main', 'Main', 20), section('lora', 'LoRAs', 20))} />);++ expect(pinnedHeader()?.textContent).toContain('Main');+ expect(pinnedHeader()?.getBoundingClientRect().top).toBe(viewport().getBoundingClientRect().top);++ // The LoRAs header starts after the Main header and its 20 rows. One row past it, LoRAs is pinned.+ const loraHeaderTop = HEADER_PX + 20 * ROW_PX;++ await scrollTo(loraHeaderTop + ROW_PX);+ expect(pinnedHeader()?.textContent).toContain('LoRAs');+ expect(pinnedHeader()?.getBoundingClientRect().top).toBe(viewport().getBoundingClientRect().top);++ // Half a header before the LoRAs header arrives, the Main header is pushed half-way out.+ await scrollTo(loraHeaderTop - HEADER_PX / 2);+ expect(pinnedHeader()?.textContent).toContain('Main');+ expect(pinnedHeader()!.getBoundingClientRect().top).toBeCloseTo(+ viewport().getBoundingClientRect().top - HEADER_PX / 2,+ 0+ );++ await scrollTo(0);+ expect(pinnedHeader()?.textContent).toContain('Main');+ });++ it('paints the pinned header opaquely so rows scrolling beneath it stay hidden', async () => {+ await render(<Harness rows={rowsOf(section('main', 'Main', 40))} />);+ await scrollTo(200);++ const background = getComputedStyle(pinnedHeader()!).backgroundColor;++ expect(background).not.toBe('rgba(0, 0, 0, 0)');+ expect(background).not.toBe('transparent');+ });+});++describe('List active row', () => {+ it('opens scrolled to an active row far down the list so the selection is visible', async () => {+ await render(+ <ChakraProvider value={system}>+ <List+ activeKey="main-45"+ density="comfortable"+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => <ListItem {...rowProps} title={item.name} />}+ revealActiveOnMount+ rows={rowsOf(section('main', 'Main', 60))}+ />+ </ChakraProvider>+ );++ const active = host.querySelector<HTMLElement>('[data-list-primary][aria-current="true"]')!;+ const viewportRect = viewport().getBoundingClientRect();+ const rowRect = active.getBoundingClientRect();++ expect(viewport().scrollTop).toBeGreaterThan(0);+ expect(rowRect.top).toBeGreaterThanOrEqual(viewportRect.top + HEADER_PX - 1);+ expect(rowRect.bottom).toBeLessThanOrEqual(viewportRect.bottom + 1);+ });+ it('keeps opening at the top unless asked to reveal the active row', async () => {+ await render(<Harness activeKey="main-45" rows={rowsOf(section('main', 'Main', 60))} />);++ expect(viewport().scrollTop).toBe(0);+ });+});++describe('List keyboard behavior', () => {+ it('rovers focus with the arrow keys, keeping one tab stop and following pointer focus', async () => {+ const onPress = vi.fn();++ await render(+ <Harness+ activeKey="main-2"+ rows={rowsOf(section('main', 'Main', 3), section('lora', 'LoRAs', 3))}+ onPress={onPress}+ />+ );++ const tabStops = primaryButtons().filter((button) => button.tabIndex === 0);++ expect(tabStops).toHaveLength(1);+ expect(tabStops[0]!.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('main-2');++ await act(() => tabStops[0]!.focus());+ await userEvent.keyboard('{ArrowDown}');+ await settleFrame();+ expect(document.activeElement?.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('lora-0');+ expect(primaryButtons().filter((button) => button.tabIndex === 0)).toHaveLength(1);++ await userEvent.keyboard('{End}');+ await settleFrame();+ expect(document.activeElement?.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('lora-2');++ await userEvent.keyboard('{Home}');+ await settleFrame();+ expect(document.activeElement?.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('main-0');++ await userEvent.keyboard('{Enter}');+ expect(onPress).toHaveBeenCalledWith({ id: 'main-0', name: 'Main 0' });++ const third = primaryButtons().find((button) => button.closest('[data-list-row="main-1"]'))!;++ await act(() => third.focus());+ expect(third.tabIndex).toBe(0);+ expect(primaryButtons().filter((button) => button.tabIndex === 0)).toHaveLength(1);+ });++ it('keeps the focused row mounted and scrolls it into view when arrowing far past the viewport', async () => {+ await render(<Harness rows={rowsOf(section('main', 'Main', 60))} />);++ await act(() => primaryButtons()[0]!.focus());+ await userEvent.keyboard('{End}');+ await settleFrame();+ await settleFrame();++ const focused = document.activeElement?.closest<HTMLElement>('[data-list-row]');++ expect(focused?.getAttribute('data-list-row')).toBe('main-59');+ expect(viewport().scrollTop).toBeGreaterThan(0);+ expect(focused!.getBoundingClientRect().bottom).toBeLessThanOrEqual(viewport().getBoundingClientRect().bottom + 1);+ });++ it('opens the context menu at the pointer, or under the row for keyboard requests, and can restore focus', async () => {+ const onContextMenu = vi.fn<(item: Item, anchor: ListContextMenuAnchor) => void>();++ await render(<Harness rows={rowsOf(section('main', 'Main', 3))} onContextMenu={onContextMenu} />);++ const row = host.querySelector<HTMLElement>('[data-list-row="main-1"]')!;++ await act(() => {+ row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 90 }));+ });+ expect(onContextMenu).toHaveBeenLastCalledWith(+ { id: 'main-1', name: 'Main 1' },+ expect.objectContaining({ x: 120, y: 90 })+ );++ await act(() => {+ row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 0, clientY: 0 }));+ });+ const rect = row.getBoundingClientRect();+ const anchor = onContextMenu.mock.lastCall![1];++ expect(anchor.x).toBeGreaterThanOrEqual(rect.left);+ expect(anchor.x).toBeLessThan(rect.right);+ expect(anchor.y).toBeCloseTo(rect.bottom, 0);++ (document.activeElement as HTMLElement | null)?.blur();+ await act(() => anchor.restoreFocus());+ expect(document.activeElement).toBe(row.querySelector('[data-list-primary]'));+ });+});++describe('List focus repair', () => {+ it('moves focus to the fallback row when the focused row disappears while the list owns focus', async () => {+ await render(<Harness activeKey="main-0" rows={rowsOf(section('main', 'Main', 4))} />);++ const second = primaryButtons().find((button) => button.closest('[data-list-row="main-1"]'))!;++ await act(() => second.focus());+ expect(document.activeElement).toBe(second);++ // A filter drops the focused row; focus must not be stranded on the body.+ await render(+ <Harness+ activeKey="main-0"+ rows={rowsOf({+ items: [+ { id: 'main-0', name: 'Main 0' },+ { id: 'main-3', name: 'Main 3' },+ ],+ key: 'main',+ label: 'Main',+ })}+ />+ );++ expect(document.activeElement?.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('main-0');+ expect(primaryButtons().filter((button) => button.tabIndex === 0)).toHaveLength(1);+ });++ it('leaves focus alone when the user had already moved it outside the list', async () => {+ await render(+ <ChakraProvider value={system}>+ <input aria-label="outside" />+ <Harness rows={rowsOf(section('main', 'Main', 4))} />+ </ChakraProvider>+ );++ const second = primaryButtons().find((button) => button.closest('[data-list-row="main-1"]'))!;+ const outside = host.querySelector<HTMLInputElement>('input[aria-label="outside"]')!;++ await act(() => second.focus());+ await act(() => outside.focus());+ await render(+ <ChakraProvider value={system}>+ <input aria-label="outside" />+ <Harness rows={rowsOf(section('main', 'Main', 1))} />+ </ChakraProvider>+ );++ expect(document.activeElement).toBe(host.querySelector('input[aria-label="outside"]'));+ });++ it('forgets focus ownership when the viewport unmounts, so a refill cannot steal focus later', async () => {+ const outsideInput = document.createElement('input');++ outsideInput.setAttribute('aria-label', 'elsewhere');+ document.body.append(outsideInput);++ try {+ await render(<Harness rows={rowsOf(section('main', 'Main', 3))} />);+ await act(() => primaryButtons()[1]!.focus());++ // An external change empties the list while a row is focused; focus falls to the body without a blur.+ await render(<Harness rows={[]} />);+ expect(host.querySelector('[data-list-viewport]')).toBeNull();++ await act(() => outsideInput.focus());+ await render(<Harness rows={rowsOf(section('main', 'Main', 3))} />);++ expect(document.activeElement).toBe(outsideInput);+ } finally {+ outsideInput.remove();+ }+ });++ it('resolves a context-menu focus target to the tab stop once its row is gone', async () => {+ const onContextMenu = vi.fn<(item: Item, anchor: ListContextMenuAnchor) => void>();++ await render(<Harness rows={rowsOf(section('main', 'Main', 3))} onContextMenu={onContextMenu} />);+ const row = host.querySelector<HTMLElement>('[data-list-row="main-2"]')!;++ await act(() => {+ row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 0, clientY: 0 }));+ });+ const anchor = onContextMenu.mock.lastCall![1];++ expect(anchor.focusTarget()).toBe(row.querySelector('[data-list-primary]'));++ await render(<Harness rows={rowsOf(section('main', 'Main', 2))} onContextMenu={onContextMenu} />);+ const target = anchor.focusTarget();++ expect(target).not.toBeNull();+ expect(target!.tabIndex).toBe(0);+ expect(target!.closest('[data-list-row]')?.getAttribute('data-list-row')).toBe('main-0');+ });+});++describe('List scroll offset persistence', () => {+ it('starts at the given offset and reports the last offset when it unmounts', async () => {+ const onScrollOffsetPersist = vi.fn();+ const rows = rowsOf(section('main', 'Main', 60));+ const element = (+ <ChakraProvider value={system}>+ <List+ density="comfortable"+ initialScrollOffset={500}+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => <ListItem {...rowProps} title={item.name} />}+ rows={rows}+ onScrollOffsetPersist={onScrollOffsetPersist}+ />+ </ChakraProvider>+ );++ await render(element);+ expect(viewport().scrollTop).toBe(500);+ expect(host.querySelector('[data-index="0"]')).toBeNull();++ await scrollTo(1234);+ await act(() => root.unmount());+ root = createRoot(host);++ expect(onScrollOffsetPersist).toHaveBeenCalledTimes(1);+ expect(onScrollOffsetPersist).toHaveBeenCalledWith(1234);+ });+});++describe('ListItem checkbox', () => {+ it('names the checkbox after the row and reports toggles without pressing the row', async () => {+ const onCheckedChange = vi.fn();+ const onPress = vi.fn();++ await render(+ <Harness rows={rowsOf(section('main', 'Main', 2))} onCheckedChange={onCheckedChange} onPress={onPress} />+ );++ const labelled = host.querySelector<HTMLElement>('[aria-label="common.list.selectItem:Main 0"]');++ expect(labelled).not.toBeNull();+ expect(labelled!.closest('[data-list-primary]')).toBeNull();++ const checkbox = labelled!.matches('input') ? labelled! : labelled!.querySelector<HTMLInputElement>('input')!;++ await act(() => checkbox.click());+ expect(onCheckedChange).toHaveBeenCalledWith({ id: 'main-0', name: 'Main 0' }, true);+ expect(onPress).not.toHaveBeenCalled();+ });+});++describe('List measured rows', () => {+ it('sizes each row by its content and still pushes the pinned header out with the next one', async () => {+ const tall = new Set(['main-1']);+ const rows = rowsOf(section('main', 'Main', 12), section('lora', 'LoRAs', 12));++ await render(+ <ChakraProvider value={system}>+ <List+ density="comfortable"+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => (+ <div+ aria-posinset={rowProps.positionInSet}+ aria-setsize={rowProps.setSize}+ data-testid={item.id}+ role="listitem"+ style={{ height: tall.has(item.id) ? 120 : 30 }}+ >+ {item.name}+ </div>+ )}+ rowHeight="measured"+ rows={rows}+ />+ </ChakraProvider>+ );+ await settleFrame();++ const top = (id: string) => host.querySelector<HTMLElement>(`[data-testid="${id}"]`)!.getBoundingClientRect().top;+ // Each slot is its content plus the 4px gap: the tall row's successor sits 124px below it, a short one 34px.+ expect(top('main-2') - top('main-1')).toBeCloseTo(124, 0);+ expect(top('main-3') - top('main-2')).toBeCloseTo(34, 0);++ // A row that grows after mount (an editor adding a line) pushes the rows after it down.+ const before = top('main-3') - top('main-2');+ tall.add('main-2');+ await render(+ <ChakraProvider value={system}>+ <List+ density="comfortable"+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => (+ <div+ aria-posinset={rowProps.positionInSet}+ aria-setsize={rowProps.setSize}+ data-testid={item.id}+ role="listitem"+ style={{ height: tall.has(item.id) ? 120 : 30 }}+ >+ {item.name}+ </div>+ )}+ rowHeight="measured"+ rows={rows}+ />+ </ChakraProvider>+ );+ await settleFrame();+ await settleFrame();+ expect(top('main-3') - top('main-2') - before).toBeCloseTo(90, 0);+ tall.delete('main-2');+ await render(+ <ChakraProvider value={system}>+ <List+ density="comfortable"+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => (+ <div+ aria-posinset={rowProps.positionInSet}+ aria-setsize={rowProps.setSize}+ data-testid={item.id}+ role="listitem"+ style={{ height: tall.has(item.id) ? 120 : 30 }}+ >+ {item.name}+ </div>+ )}+ rowHeight="measured"+ rows={rows}+ />+ </ChakraProvider>+ );+ await settleFrame();+ await settleFrame();+ expect(top('main-3') - top('main-2')).toBeCloseTo(34, 0);++ const loraHeaderTop = HEADER_PX + 120 + 4 + 11 * 34;++ await scrollTo(loraHeaderTop - HEADER_PX / 2);+ expect(pinnedHeader()?.textContent).toContain('Main');+ expect(pinnedHeader()!.getBoundingClientRect().top).toBeCloseTo(+ viewport().getBoundingClientRect().top - HEADER_PX / 2,+ 0+ );+ });+});++describe('List states', () => {+ it('renders the caller-owned empty state when no item rows remain', async () => {+ await render(<Harness rows={[]} />);++ expect(host.textContent).toContain('nothing');+ expect(host.querySelector('[role="list"]')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/List.tsx b/invokeai/frontend/webv2/src/platform/ui/list/List.tsxnew file mode 100644index 0000000000..64db229bfd--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/List.tsx@@ -0,0 +1,495 @@+import type { CSSProperties, FocusEvent, KeyboardEvent, ReactNode, UIEvent } from 'react';++import { Box, Flex, Spinner } from '@chakra-ui/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Scrollable } from '@platform/ui/Scrollable';+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { defaultRangeExtractor, useVirtualizer, type Range } from 'react-hook-tanstack-virtual';+import { useTranslation } from 'react-i18next';++import type { ListDensity } from './ListItem';+import type { ListRow } from './listRows';++import { ListDivider } from './ListDivider';+import { LIST_ROW_GAP_PX as ROW_GAP_PX, LIST_ROW_INSET as INSET } from './listLayout';+import { LIST_SECTION_HEADER_HEIGHT_PX, ListSectionHeader } from './ListSectionHeader';++const ITEM_HEIGHT_PX: Record<ListDensity, number> = { comfortable: 52, compact: 28, regular: 40 };+const OVERSCAN_ROWS = 8;+const PRIMARY_SELECTOR = '[data-list-primary]';++// Rows are fixed-height slots: content that outgrows its density clips instead of overlapping the next row.+const ITEM_WRAPPER_STYLE: CSSProperties = {+ display: 'grid',+ left: 0,+ overflow: 'hidden',+ paddingBottom: ROW_GAP_PX,+ paddingInline: INSET,+ position: 'absolute',+ top: 0,+ width: '100%',+};+const MEASURED_ITEM_WRAPPER_STYLE: CSSProperties = {+ left: 0,+ paddingBottom: ROW_GAP_PX,+ paddingInline: INSET,+ position: 'absolute',+ top: 0,+ width: '100%',+};+const HEADER_WRAPPER_STYLE: CSSProperties = {+ height: LIST_SECTION_HEADER_HEIGHT_PX,+ left: 0,+ paddingInline: INSET,+ position: 'absolute',+ top: 0,+ width: '100%',+};+const PINNED_HEADER_WRAPPER_STYLE: CSSProperties = {+ background: 'var(--list-surface)',+ height: LIST_SECTION_HEADER_HEIGHT_PX,+ paddingInline: INSET,+ position: 'sticky',+ top: 0,+ zIndex: 1,+};++export type ListSurface = 'bg' | 'bg.subtle' | 'bg.panel';++/**+ * Spread onto the ListItem a renderItem returns; the List owns density, focus order and set semantics. A row that+ * is not a ListItem (an inline editor, say) renders `role="listitem"` with the set position itself and keeps its+ * own tab order; the List does not track its focus, so scrolling can still unmount it while it is being edited.+ */+export interface ListRowProps {+ density: ListDensity;+ isActive: boolean;+ isBusy: boolean;+ itemKey: string;+ positionInSet: number;+ setSize: number;+ tabIndex: number;+}++export interface ListProps<T> {+ rows: readonly ListRow<T>[];+ /** Accessible name of the list. */+ label: string;+ renderItem: (item: T, rowProps: ListRowProps) => ReactNode;+ /** Key of the row whose detail is open; it is the initial keyboard target. */+ activeKey?: string | null;+ /** Row pitch; fixed for the list's lifetime, so change it with a keyed remount. */+ density?: ListDensity;+ /**+ * `measured` sizes each row by its content, for rows that grow (inline editors, wrapped errors); density is then+ * only the estimate. Fixed rows clip to the density's pitch and never measure.+ */+ rowHeight?: 'fixed' | 'measured';+ /** Typical measured row height; a close estimate keeps the scrollbar steady before rows are measured. */+ estimatedRowHeight?: number;+ status?: 'loading' | 'error' | 'ready';+ /** Shown instead of rows while status is error. */+ errorState?: ReactNode;+ /** Shown instead of rows when there are none; the caller decides between empty and no-match copy. */+ emptyState?: ReactNode;+ /** Rows belong to a request being replaced: announced with aria-busy and rendered inert. */+ isBusy?: boolean;+ /** The background pinned headers paint over rows with; match the surface the list sits on. */+ surface?: ListSurface;+ /** Hairlines between rows of a section, inset from the edges. */+ dividers?: boolean;+ initialScrollOffset?: number;+ /**+ * Without an initial offset, open with the active row at the top: for lists reopened after a selection was made+ * elsewhere. Needs its rows on first render, so it suits lists whose data is already in hand.+ */+ revealActiveOnMount?: boolean;+ /** Receives the final scroll offset on unmount; must be referentially stable. */+ onScrollOffsetPersist?: (offset: number) => void;+}++const lastHeaderAtOrBefore = (headerIndexes: readonly number[], index: number): number | null => {+ let low = 0;+ let high = headerIndexes.length - 1;+ let found: number | null = null;++ while (low <= high) {+ const middle = (low + high) >> 1;++ if (headerIndexes[middle]! <= index) {+ found = headerIndexes[middle]!;+ low = middle + 1;+ } else {+ high = middle - 1;+ }+ }++ return found;+};++const findItemIndex = <T,>(rows: readonly ListRow<T>[], from: number, step: 1 | -1): number => {+ for (let index = from; index >= 0 && index < rows.length; index += step) {+ if (rows[index]?.kind === 'item') {+ return index;+ }+ }++ return -1;+};++const primaryOf = (viewport: HTMLElement, key: string): HTMLElement | null =>+ viewport.querySelector<HTMLElement>(`[data-list-row="${CSS.escape(key)}"] ${PRIMARY_SELECTOR}`);++/**+ * Virtualized list with pinned section headers and a roving tabindex. Headers and items share one flat index+ * space; the header at the top of the visible range renders in flow as a sticky element, pushed out by the next.+ */+export const List = <T,>({+ activeKey = null,+ density = 'regular',+ dividers = false,+ emptyState,+ errorState,+ estimatedRowHeight,+ initialScrollOffset,+ isBusy = false,+ label,+ renderItem,+ revealActiveOnMount = false,+ rowHeight = 'fixed',+ rows,+ status = 'ready',+ surface = 'bg',+ onScrollOffsetPersist,+}: ListProps<T>) => {+ const { t } = useTranslation();+ const viewportRef = useRef<HTMLDivElement | null>(null);+ const pendingFocus = useRef<string | null>(null);+ // Focus inside the list at the last focus event; a focused row that unmounts fires no blur, so this stays true.+ const listOwnsFocus = useRef(false);+ const lastScrollOffset = useRef(initialScrollOffset ?? 0);+ const [focusKey, setFocusKey] = useState<string | null>(null);+ const itemPitch =+ (rowHeight === 'measured' && estimatedRowHeight !== undefined ? estimatedRowHeight : ITEM_HEIGHT_PX[density]) ++ ROW_GAP_PX;++ const layout = useMemo(() => {+ const headerIndexes: number[] = [];+ const indexByKey = new Map<string, number>();+ /** 1-based position among items for aria-posinset; 0 for headers. */+ const ordinals: number[] = [];+ let firstItemKey: string | null = null;+ let itemCount = 0;++ rows.forEach((row, index) => {+ indexByKey.set(row.key, index);++ if (row.kind === 'header') {+ headerIndexes.push(index);+ ordinals.push(0);+ } else {+ firstItemKey ??= row.key;+ itemCount += 1;+ ordinals.push(itemCount);+ }+ });++ return { firstItemKey, headerIndexes, indexByKey, itemCount, ordinals };+ }, [rows]);+ const { firstItemKey, headerIndexes, indexByKey, itemCount, ordinals } = layout;+ const isMeasured = rowHeight === 'measured';+ const hasHeaders = headerIndexes.length > 0;++ // The roving target survives filtering: fall back to the active row, then the first item.+ const focusKeyIsStale = focusKey !== null && !indexByKey.has(focusKey);+ const resolvedFocusKey =+ !focusKeyIsStale && focusKey !== null+ ? focusKey+ : activeKey !== null && indexByKey.has(activeKey)+ ? activeKey+ : firstItemKey;+ const focusIndex = resolvedFocusKey === null ? -1 : (indexByKey.get(resolvedFocusKey) ?? -1);++ // Keep the pinned header and the focused row mounted whatever the scroll position: focus must never fall off+ // the list, and the sticky header is the one that scrolled past the top of the visible range.+ const rangeExtractor = useCallback(+ (range: Range) => {+ const indexes = defaultRangeExtractor(range);+ const pinned = lastHeaderAtOrBefore(headerIndexes, range.startIndex);+ let changed = false;++ if (pinned !== null && !indexes.includes(pinned)) {+ indexes.push(pinned);+ changed = true;+ }++ if (focusIndex >= 0 && !indexes.includes(focusIndex)) {+ indexes.push(focusIndex);+ changed = true;+ }++ if (changed) {+ indexes.sort((a, b) => a - b);+ }++ return indexes;+ },+ [focusIndex, headerIndexes]+ );+ const estimateSize = useCallback(+ (index: number) => (rows[index]?.kind === 'header' ? LIST_SECTION_HEADER_HEIGHT_PX : itemPitch),+ [itemPitch, rows]+ );+ const getItemKey = useCallback((index: number) => rows[index]?.key ?? index, [rows]);+ const activeIndex = revealActiveOnMount && activeKey !== null ? (indexByKey.get(activeKey) ?? -1) : -1;+ const getActiveRowOffset = useCallback(() => {+ let offset = 0;++ for (let index = 0; index < activeIndex; index += 1) {+ offset += estimateSize(index);+ }++ return Math.max(0, offset - (hasHeaders ? LIST_SECTION_HEADER_HEIGHT_PX : 0));+ }, [activeIndex, estimateSize, hasHeaders]);+ const getScrollElement = useCallback(() => viewportRef.current, []);+ // A viewport that unmounts (empty or loading state) takes no blur with it; forget ownership so a later remount+ // cannot pull focus away from wherever the user went meanwhile.+ const attachViewport = useCallback((element: HTMLDivElement | null) => {+ viewportRef.current = element;++ if (element === null) {+ listOwnsFocus.current = false;+ }+ }, []);+ const virtualizer = useVirtualizer({+ count: rows.length,+ estimateSize,+ getItemKey,+ getScrollElement,+ initialOffset: initialScrollOffset ?? getActiveRowOffset,+ overscan: OVERSCAN_ROWS,+ rangeExtractor,+ scrollPaddingStart: hasHeaders ? LIST_SECTION_HEADER_HEIGHT_PX : 0,+ // Scrollable's phantom-scrollbar heal dispatches a scroll event from a mount effect, where flushSync is a+ // React error; useSyncExternalStore already commits scroll snapshots synchronously.+ useFlushSync: false,+ });+ const { scrollToIndex, virtualItems } = virtualizer;+ const scrollOffset = virtualizer.scrollOffset ?? 0;++ const pinnedIndex = hasHeaders ? lastHeaderAtOrBefore(headerIndexes, virtualizer.range?.startIndex ?? 0) : null;+ // The next header can only push the pinned one while it is near the top, which keeps it mounted; its live start+ // holds for measured rows as well as fixed ones.+ const nextHeaderIndex = pinnedIndex === null ? undefined : headerIndexes[headerIndexes.indexOf(pinnedIndex) + 1];+ const nextHeaderStart = virtualItems.find((virtualRow) => virtualRow.index === nextHeaderIndex)?.start;+ const pinnedStyle = useMemo(() => {+ const nextTop = nextHeaderStart === undefined ? Number.POSITIVE_INFINITY : nextHeaderStart - scrollOffset;+ const shift = Math.min(0, nextTop - LIST_SECTION_HEADER_HEIGHT_PX);++ return shift === 0+ ? PINNED_HEADER_WRAPPER_STYLE+ : { ...PINNED_HEADER_WRAPPER_STYLE, transform: `translateY(${shift}px)` };+ }, [nextHeaderStart, scrollOffset]);++ // Focus lands before paint so the ring never lags the scroll that revealed the row. The same pass repairs focus+ // a vanished row left on the body: keyboard users keep their place when a filter or a delete removes it.+ useLayoutEffect(() => {+ const viewport = viewportRef.current;++ if (!viewport) {+ return;+ }++ const pending = pendingFocus.current;++ if (pending !== null) {+ if (!indexByKey.has(pending)) {+ pendingFocus.current = null;+ } else {+ const target = primaryOf(viewport, pending);++ if (target) {+ target.focus();+ pendingFocus.current = null;+ }++ return;+ }+ }++ if (+ focusKeyIsStale &&+ resolvedFocusKey !== null &&+ listOwnsFocus.current &&+ !viewport.contains(document.activeElement)+ ) {+ primaryOf(viewport, resolvedFocusKey)?.focus();+ }+ }, [focusKeyIsStale, indexByKey, resolvedFocusKey, virtualItems]);++ const moveFocus = useCallback(+ (index: number) => {+ const row = rows[index];++ if (!row) {+ return;+ }++ setFocusKey(row.key);+ pendingFocus.current = row.key;+ scrollToIndex(index, { align: 'auto' });+ },+ [rows, scrollToIndex]+ );+ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.defaultPrevented || !(event.target as HTMLElement).closest('[data-list-row]')) {+ return;+ }++ let next: number;++ switch (event.key) {+ case 'ArrowDown':+ next = findItemIndex(rows, focusIndex + 1, 1);+ break;+ case 'ArrowUp':+ next = findItemIndex(rows, focusIndex - 1, -1);+ break;+ case 'Home':+ next = findItemIndex(rows, 0, 1);+ break;+ case 'End':+ next = findItemIndex(rows, rows.length - 1, -1);+ break;+ default:+ return;+ }++ event.preventDefault();++ if (next >= 0 && next !== focusIndex) {+ moveFocus(next);+ }+ },+ [focusIndex, moveFocus, rows]+ );+ // Pointer focus updates the roving target so Tab leaves from, and returns to, the row the user last used.+ const handleFocusCapture = useCallback((event: FocusEvent<HTMLDivElement>) => {+ listOwnsFocus.current = true;+ const key = (event.target as HTMLElement).closest('[data-list-row]')?.getAttribute('data-list-row');++ if (key) {+ setFocusKey(key);+ }+ }, []);+ const handleBlurCapture = useCallback((event: FocusEvent<HTMLDivElement>) => {+ listOwnsFocus.current = event.relatedTarget !== null && event.currentTarget.contains(event.relatedTarget);+ }, []);+ const handleScroll = useCallback((event: UIEvent<HTMLDivElement>) => {+ lastScrollOffset.current = event.currentTarget.scrollTop;+ }, []);+ const viewportProps = useMemo(+ () => ({+ 'data-list-viewport': '',+ onBlurCapture: handleBlurCapture,+ onFocusCapture: handleFocusCapture,+ onKeyDown: handleKeyDown,+ onScroll: handleScroll,+ style: hasHeaders ? { scrollPaddingTop: LIST_SECTION_HEADER_HEIGHT_PX } : undefined,+ }),+ [handleBlurCapture, handleFocusCapture, handleKeyDown, handleScroll, hasHeaders]+ );++ useMountEffect(() => () => onScrollOffsetPersist?.(lastScrollOffset.current));++ const rootCss = useMemo(() => ({ '--list-surface': `colors.${surface}` }), [surface]);+ const containerStyle = useMemo<CSSProperties>(+ () => ({ height: virtualizer.totalSize, position: 'relative', width: '100%' }),+ [virtualizer.totalSize]+ );++ let content: ReactNode;++ if (status === 'loading') {+ content = (+ <Flex align="center" aria-label={t('common.loading')} h="full" justify="center" py="8" role="status" w="full">+ <Spinner color="fg.subtle" size="sm" />+ </Flex>+ );+ } else if (status === 'error') {+ content = (+ <Flex align="center" h="full" justify="center" minH="0" overflowY="auto" p="3" w="full">+ {errorState}+ </Flex>+ );+ } else if (itemCount === 0) {+ content = (+ <Flex align="center" h="full" justify="center" minH="0" overflowY="auto" p="3" w="full">+ {emptyState}+ </Flex>+ );+ } else {+ content = (+ <Scrollable h="full" viewportProps={viewportProps} viewportRef={attachViewport}>+ <div aria-busy={isBusy || undefined} aria-label={label} role="list" style={containerStyle}>+ {virtualItems.map((virtualRow) => {+ const row = rows[virtualRow.index];++ if (!row) {+ return null;+ }++ if (row.kind === 'header') {+ const isPinned = virtualRow.index === pinnedIndex;++ return (+ <div+ key={virtualRow.key}+ data-list-pinned-header={isPinned ? '' : undefined}+ role="presentation"+ style={+ isPinned ? pinnedStyle : { ...HEADER_WRAPPER_STYLE, transform: `translateY(${virtualRow.start}px)` }+ }+ >+ <ListSectionHeader count={row.count} label={row.label} />+ </div>+ );+ }++ return (+ <div+ key={virtualRow.key}+ ref={isMeasured ? virtualizer.measureElement : undefined}+ data-index={virtualRow.index}+ role="presentation"+ style={+ isMeasured+ ? { ...MEASURED_ITEM_WRAPPER_STYLE, transform: `translateY(${virtualRow.start}px)` }+ : { ...ITEM_WRAPPER_STYLE, height: itemPitch, transform: `translateY(${virtualRow.start}px)` }+ }+ >+ {renderItem(row.item, {+ density,+ isActive: row.key === activeKey,+ isBusy,+ itemKey: row.key,+ positionInSet: ordinals[virtualRow.index]!,+ setSize: itemCount,+ tabIndex: row.key === resolvedFocusKey ? 0 : -1,+ })}+ {dividers && rows[virtualRow.index + 1]?.kind === 'item' ? <ListDivider placement="in-slot" /> : null}+ </div>+ );+ })}+ </div>+ </Scrollable>+ );+ }++ return (+ <Box css={rootCss} flex="1" h="full" minH="0" position="relative" w="full">+ {content}+ </Box>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsxnew file mode 100644index 0000000000..806613fff4--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx@@ -0,0 +1,218 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act, type ReactElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { List, type ListRowProps } from './List';+import { ListItem } from './ListItem';+import { ListPager } from './ListPager';+import { listRowsFromItems, listRowsFromSections } from './listRows';+import { ListSelectionBar } from './ListSelectionBar';+import { ListStack } from './ListStack';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ options && 'page' in options ? `${key}:${String(options.page)}` : key,+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'display:flex;flex-direction:column;height:300px;width:360px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++const render = async (element: ReactElement) => {+ await act(() => root.render(<ChakraProvider value={system}>{element}</ChakraProvider>));+ await act(async () => {+ await Promise.resolve();+ });+};++const buttonWithText = (text: string): HTMLButtonElement =>+ [...host.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === text)!;++describe('ListPager', () => {+ it('keeps an unavailable control focusable and inert, and announces the page', async () => {+ const onNext = vi.fn();+ const onPrevious = vi.fn();++ await render(<ListPager hasNext hasPrevious={false} page={3} onNext={onNext} onPrevious={onPrevious} />);++ const previous = buttonWithText('common.previousPage');+ const next = buttonWithText('common.nextPage');++ expect(previous.getAttribute('aria-disabled')).toBe('true');+ expect(previous.disabled).toBe(false);+ expect(host.querySelector('[aria-live="polite"]')?.textContent).toBe('common.pageNumber:3');++ await act(() => previous.focus());+ await act(() => previous.click());+ expect(onPrevious).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(previous);++ await act(() => next.click());+ expect(onNext).toHaveBeenCalledTimes(1);++ await render(<ListPager isBusy hasNext hasPrevious page={3} onNext={onNext} onPrevious={onPrevious} />);+ await act(() => buttonWithText('common.nextPage').click());+ expect(onNext).toHaveBeenCalledTimes(1);+ });+});++describe('ListSelectionBar', () => {+ it('reflects a partial selection and shows actions only when given', async () => {+ const onCheckedChange = vi.fn();++ await render(+ <ListSelectionBar+ checked="indeterminate"+ label="Select all"+ summary="2 selected"+ onCheckedChange={onCheckedChange}+ >+ <button type="button">Delete</button>+ </ListSelectionBar>+ );++ const checkbox = host.querySelector<HTMLInputElement>('[aria-label="Select all"] input')!;++ expect(host.querySelector('[aria-label="Select all"]')?.getAttribute('data-state')).toBe('indeterminate');+ expect(host.textContent).toContain('2 selected');+ expect(buttonWithText('Delete')).toBeDefined();++ await act(() => checkbox.click());+ expect(onCheckedChange).toHaveBeenCalledTimes(1);++ await render(<ListSelectionBar checked={false} isDisabled label="Select all" onCheckedChange={onCheckedChange} />);+ expect(host.querySelector<HTMLInputElement>('[aria-label="Select all"] input')!.disabled).toBe(true);+ expect(host.querySelector('[role="separator"]')).toBeNull();+ });+});++describe('List busy state', () => {+ it('announces the list as busy and renders rows inert without dropping focus', async () => {+ const onPress = vi.fn();+ const onCheckedChange = vi.fn();+ const items = [{ id: 'a' }, { id: 'b' }];+ const rows = listRowsFromItems(items, (item) => item.id);+ const renderItem = (item: { id: string }, rowProps: ListRowProps) => (+ <ListItem {...rowProps} title={item.id} onCheckedChange={onCheckedChange} onPress={onPress} />+ );++ await render(<List label="subjects" renderItem={renderItem} rows={rows} />);+ const primary = host.querySelector<HTMLButtonElement>('[data-list-primary]')!;++ await act(() => primary.focus());+ await render(<List isBusy label="subjects" renderItem={renderItem} rows={rows} />);++ expect(host.querySelector('[role="list"]')?.getAttribute('aria-busy')).toBe('true');+ expect(document.activeElement).toBe(host.querySelector('[data-list-primary]'));+ expect(host.querySelector('[data-list-primary]')?.getAttribute('aria-disabled')).toBe('true');+ expect(host.querySelector('[data-list-row]')?.hasAttribute('data-busy')).toBe(true);+ expect(getComputedStyle(host.querySelector('[data-list-row]')!).opacity).toBe('1');+ expect(host.querySelector<HTMLInputElement>('[data-list-row] input')?.disabled).toBe(true);++ await act(() => host.querySelector<HTMLButtonElement>('[data-list-primary]')!.click());+ expect(onPress).not.toHaveBeenCalled();++ await render(<List label="subjects" renderItem={renderItem} rows={rows} />);+ expect(host.querySelector('[role="list"]')?.getAttribute('aria-busy')).toBeNull();+ await act(() => host.querySelector<HTMLButtonElement>('[data-list-primary]')!.click());+ expect(onPress).toHaveBeenCalledTimes(1);+ });+});++describe('list dividers', () => {+ const hairlines = () =>+ [...host.querySelectorAll<HTMLElement>('[aria-hidden="true"]')].filter(+ (element) => Math.round(element.getBoundingClientRect().height) === 1+ );++ it('draws an inset hairline centred in the gap between stacked rows, and none when off', async () => {+ await render(+ <ListStack dividers label="subjects">+ <ListItem title="one" />+ <ListItem title="two" />+ <ListItem title="three" />+ </ListStack>+ );++ const list = host.querySelector<HTMLElement>('[role="list"][aria-label="subjects"]')!;+ const rows = [...list.querySelectorAll<HTMLElement>(':scope > [role="listitem"]')];+ const lines = hairlines();++ expect(rows).toHaveLength(3);+ expect(lines).toHaveLength(2);++ const first = rows[0]!.getBoundingClientRect();+ const second = rows[1]!.getBoundingClientRect();+ const line = lines[0]!.getBoundingClientRect();++ // The row gap is unchanged by the divider, which sits in its middle.+ expect(second.top - first.bottom).toBeCloseTo(4, 0);+ expect(line.top - first.bottom).toBeCloseTo(1.5, 0);+ // Inset from both edges so rounded row corners never touch it.+ expect(line.left - first.left).toBeCloseTo(8, 0);+ expect(first.right - line.right).toBeCloseTo(8, 0);++ await render(+ <ListStack label="subjects">+ <ListItem title="one" />+ <ListItem title="two" />+ </ListStack>+ );+ expect(hairlines()).toHaveLength(0);+ });++ it('draws dividers between virtualized rows of a section but not before a header or after the last row', async () => {+ const rows = listRowsFromSections(+ [+ { items: [{ id: 'a' }, { id: 'b' }], key: 'one', label: 'One' },+ { items: [{ id: 'c' }], key: 'two', label: 'Two' },+ ],+ (item) => item.id+ );++ await render(+ <List+ dividers+ label="subjects"+ renderItem={(item: { id: string }, rowProps: ListRowProps) => <ListItem {...rowProps} title={item.id} />}+ rows={rows}+ />+ );+ await act(async () => {+ await new Promise((resolve) => {+ requestAnimationFrame(() => resolve(undefined));+ });+ });++ // Only a → b shares a section with a following row.+ expect(hairlines()).toHaveLength(1);++ const rowA = host.querySelector<HTMLElement>('[data-list-row="a"]')!.getBoundingClientRect();+ const rowB = host.querySelector<HTMLElement>('[data-list-row="b"]')!.getBoundingClientRect();+ const line = hairlines()[0]!.getBoundingClientRect();++ // Same geometry as stacked rows: centred in the gap, inset from both row edges.+ expect(rowB.top - rowA.bottom).toBeCloseTo(4, 0);+ expect(line.top - rowA.bottom).toBeCloseTo(1.5, 0);+ expect(line.left - rowA.left).toBeCloseTo(8, 0);+ expect(rowA.right - line.right).toBeCloseTo(8, 0);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsxnew file mode 100644index 0000000000..560bb1f36a--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx@@ -0,0 +1,38 @@+import { chakra } from '@chakra-ui/react';++import { LIST_DIVIDER_INSET, LIST_ROW_GAP_PX, LIST_ROW_INSET } from './listLayout';++const HAIRLINE_PX = 1;+/** Softer than a section border: it separates rows, it does not frame them. */+const DIVIDER_COLOR = 'border.subtle/50';+/** Centres the hairline in the row gap. */+const HALF_GAP = `${(LIST_ROW_GAP_PX - HAIRLINE_PX) / 2}px`;++// A border, not a 1px fill: borders snap to whole device pixels at fractional zoom, fills can render 2px.+const HAIRLINE = {+ borderColor: DIVIDER_COLOR,+ borderTopStyle: 'solid',+ borderTopWidth: `${HAIRLINE_PX}px`,+ h: 0,+} as const;++const IN_FLOW_CSS = {+ ...HAIRLINE,+ flexShrink: 0,+ mx: LIST_DIVIDER_INSET,+ my: HALF_GAP,+} as const;++/** For virtualized rows: drawn inside the row slot's bottom gap, clear of the row's own inset. */+const IN_SLOT_CSS = {+ ...HAIRLINE,+ bottom: HALF_GAP,+ insetInline: `calc(${LIST_ROW_INSET} + ${LIST_DIVIDER_INSET})`,+ pointerEvents: 'none',+ position: 'absolute',+} as const;++/** Hairline between two rows; decorative, so hidden from assistive tech. */+export const ListDivider = ({ placement }: { placement: 'in-flow' | 'in-slot' }) => (+ <chakra.div aria-hidden css={placement === 'in-flow' ? IN_FLOW_CSS : IN_SLOT_CSS} />+);diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsxnew file mode 100644index 0000000000..5952be601c--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsx@@ -0,0 +1,109 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act, type ReactElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { ListItem } from './ListItem';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width:320px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++const render = async (element: ReactElement) => {+ await act(() => root.render(<ChakraProvider value={system}>{element}</ChakraProvider>));+};++const primary = () => host.querySelector<HTMLElement>('[data-list-primary]')!;++describe('ListItem', () => {+ it('keeps actions beside the primary button and announces disclosure', async () => {+ const onPress = vi.fn();+ const onAction = vi.fn();++ await render(+ <ListItem+ actions={+ <button type="button" onClick={onAction}>+ Cancel+ </button>+ }+ isExpanded={false}+ title="A prompt"+ onPress={onPress}+ />+ );++ const action = host.querySelector<HTMLButtonElement>('button:not([data-list-primary])')!;++ expect(primary().tagName).toBe('BUTTON');+ expect(primary().getAttribute('aria-expanded')).toBe('false');+ expect(primary().contains(action)).toBe(false);+ expect(action.closest('[role="listitem"]')).not.toBeNull();++ await act(() => action.click());+ expect(onAction).toHaveBeenCalledTimes(1);+ expect(onPress).not.toHaveBeenCalled();+ });++ it('renders a static row without a press handler as plain content, not a button', async () => {+ await render(<ListItem title="Read only" />);++ expect(primary().tagName).toBe('DIV');+ expect(primary().hasAttribute('tabindex')).toBe(false);+ expect(host.querySelector('button')).toBeNull();+ });++ it('warms on hover or focus before the press and truncates prose at the end', async () => {+ const onIntent = vi.fn();+ const longPrompt = 'a very long prompt that keeps going past the width of this narrow row in the harness';++ await render(<ListItem title={longPrompt} titleTruncate="end" onIntent={onIntent} onPress={() => undefined} />);++ await act(() => primary().focus());+ expect(onIntent).toHaveBeenCalledTimes(1);+ await userEvent.hover(primary());+ expect(onIntent).toHaveBeenCalledTimes(2);++ // With end truncation there is no pinned tail: the title is one clipped run holding the whole text.+ const title = host.querySelector<HTMLElement>('[data-list-primary] [title]')!;++ expect(title.children).toHaveLength(1);+ expect(title.children[0]!.textContent).toBe(longPrompt);++ await render(<ListItem title={longPrompt} onIntent={onIntent} onPress={() => undefined} />);+ expect(host.querySelector<HTMLElement>('[data-list-primary] [title]')!.children).toHaveLength(2);+ });++ it('keeps a title with line breaks on one line', async () => {+ await render(<ListItem title="single line" titleTruncate="end" onPress={() => undefined} />);+ const singleLineHeight = host+ .querySelector<HTMLElement>('[data-list-primary] [title]')!+ .getBoundingClientRect().height;++ await render(+ <ListItem title={'first line\nsecond line\nthird line'} titleTruncate="end" onPress={() => undefined} />+ );+ const title = host.querySelector<HTMLElement>('[data-list-primary] [title]')!;++ expect(title.getBoundingClientRect().height).toBe(singleLineHeight);+ expect(title.textContent).toContain('third line');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsxnew file mode 100644index 0000000000..052694da66--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx@@ -0,0 +1,236 @@+import type { MouseEvent, ReactNode } from 'react';++import { Checkbox, chakra, useSlotRecipe } from '@chakra-ui/react';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { listItemSlotRecipe } from '@theme/recipes';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++export type ListDensity = 'compact' | 'regular' | 'comfortable';++export interface ListContextMenuAnchor {+ x: number;+ y: number;+ /**+ * Where keyboard focus belongs once the menu, or a dialog it opened, closes: this row while it exists, otherwise+ * the list's current tab stop. Resolved late because virtualization or the action itself can unmount the row;+ * suits a Dialog's `finalFocusEl`.+ */+ focusTarget: () => HTMLElement | null;+ restoreFocus: () => void;+}++export interface ListItemProps {+ title: string;+ /** Identifiers keep their tail visible; prose keeps its start. */+ titleTruncate?: 'middle' | 'end';+ /** Media or icon before the text; size it for the density (36px at comfortable). */+ leading?: ReactNode;+ /** Inline after the title, e.g. a status badge; keep it short so the title keeps its room. */+ badges?: ReactNode;+ /** Second line: muted text, or a node such as a badge row. */+ description?: ReactNode;+ /** Trailing metadata or badges; string content renders muted. */+ trailing?: ReactNode;+ /** Controls that act on the row, rendered beside the primary button so they never nest inside it. */+ actions?: ReactNode;+ density?: ListDensity;+ /** The one row whose detail is open; announced with aria-current and filled with the accent tone. */+ isActive?: boolean;+ /** Part of a multi-selection; only meaningful with onCheckedChange. */+ isChecked?: boolean;+ /** Shown but inert while its page is being replaced; focus is kept so paging does not lose it. */+ isBusy?: boolean;+ /** The row discloses content below itself; announced with aria-expanded. */+ isExpanded?: boolean;+ /** Accessible name of the checkbox when the title alone is ambiguous; defaults to "Select {title}". */+ checkLabel?: string;+ /** Identifies the row to its owning List for focus management. */+ itemKey?: string;+ /** `presentation` when a caller's own list item wraps this row together with content that belongs to it. */+ role?: 'listitem' | 'presentation';+ /** Roving tabindex from the owning List; standalone rows are tab stops. */+ tabIndex?: number;+ positionInSet?: number;+ setSize?: number;+ /** Makes a standalone row a button; without it, and without a context menu, the row is static content. */+ onPress?: (event: MouseEvent<HTMLButtonElement>) => void;+ /** Fires on hover and focus, ahead of a press, to warm what the press will need. */+ onIntent?: () => void;+ /** Renders the leading checkbox. */+ onCheckedChange?: (checked: boolean) => void;+ onContextMenu?: (anchor: ListContextMenuAnchor) => void;+}++const PRIMARY_SELECTOR = '[data-list-primary]';+const TRUNCATE_CSS = { display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } as const;++/**+ * The checkbox and the actions are siblings of the primary button so nothing nests an interactive control. The+ * whole surface hovers as one; the primary button carries the accessible name and the focus ring wraps the row.+ */+export const ListItem = ({+ actions,+ badges,+ checkLabel,+ density = 'regular',+ description,+ isActive = false,+ isBusy = false,+ isChecked = false,+ isExpanded,+ itemKey,+ leading,+ positionInSet,+ role = 'listitem',+ setSize,+ tabIndex = 0,+ title,+ titleTruncate = 'middle',+ trailing,+ onCheckedChange,+ onContextMenu,+ onIntent,+ onPress,+}: ListItemProps) => {+ const { t } = useTranslation();+ const recipe = useSlotRecipe({ recipe: listItemSlotRecipe });+ const tone = isActive ? 'accent' : isChecked ? 'selected' : 'none';+ const styles = useMemo(() => recipe({ active: tone, density }), [density, recipe, tone]);+ // Inside a List every row is a keyboard stop; a standalone row is a button only when pressing it does something.+ const isInteractive = onPress !== undefined || onContextMenu !== undefined || itemKey !== undefined;++ const handleContextMenu = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ if (!onContextMenu) {+ return;+ }++ event.preventDefault();+ const row = event.currentTarget;+ const viewport = row.closest<HTMLElement>('[data-list-viewport]');+ const key = row.getAttribute('data-list-row');+ // Firefox reports keyboard-invoked menus at (0,0); Chromium reports a point on the element, which the pointer+ // branch anchors just as well.+ const fromKeyboard = event.clientX === 0 && event.clientY === 0;+ const rect = row.getBoundingClientRect();+ const focusTarget = (): HTMLElement | null => {+ if (row.isConnected) {+ return row.querySelector<HTMLElement>(PRIMARY_SELECTOR);+ }++ if (!viewport) {+ return null;+ }++ const byKey =+ key === null+ ? null+ : viewport.querySelector<HTMLElement>(`[data-list-row="${CSS.escape(key)}"] ${PRIMARY_SELECTOR}`);++ return byKey ?? viewport.querySelector<HTMLElement>(`${PRIMARY_SELECTOR}[tabindex="0"]`);+ };++ onContextMenu({+ focusTarget,+ restoreFocus: () => focusTarget()?.focus(),+ x: fromKeyboard ? rect.left + 8 : event.clientX,+ y: fromKeyboard ? rect.bottom : event.clientY,+ });+ },+ [onContextMenu]+ );+ const handleCheckedChange = useCallback(+ (details: { checked: boolean | 'indeterminate' }) => onCheckedChange?.(details.checked === true),+ [onCheckedChange]+ );+ const handlePress = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => {+ if (!isBusy) {+ onPress?.(event);+ }+ },+ [isBusy, onPress]+ );+ // Plain text keeps to its line; a node (badge row, figures) lays itself out.+ const descriptionCss = useMemo(+ () => (typeof description === 'string' ? [styles.description, TRUNCATE_CSS] : styles.description),+ [description, styles.description]+ );+ const trailingCss = useMemo(+ () => (typeof trailing === 'string' ? [styles.trailing, TRUNCATE_CSS] : styles.trailing),+ [styles.trailing, trailing]+ );++ const content = (+ <>+ {leading}+ <chakra.span css={styles.body}>+ <chakra.span css={styles.titleLine}>+ <MiddleTruncate+ as="span"+ css={styles.title}+ tailGraphemes={titleTruncate === 'end' ? 0 : undefined}+ text={title}+ />+ {badges !== undefined && badges !== null ? <chakra.span css={styles.badges}>{badges}</chakra.span> : null}+ </chakra.span>+ {description !== undefined && description !== null ? (+ <chakra.span css={descriptionCss}>{description}</chakra.span>+ ) : null}+ </chakra.span>+ {trailing !== undefined && trailing !== null ? <chakra.span css={trailingCss}>{trailing}</chakra.span> : null}+ </>+ );++ return (+ <chakra.div+ aria-posinset={positionInSet}+ aria-setsize={setSize}+ css={styles.root}+ data-busy={isBusy || undefined}+ data-list-row={itemKey}+ data-static={isInteractive || tone !== 'none' ? undefined : ''}+ role={role}+ onContextMenu={onContextMenu ? handleContextMenu : undefined}+ >+ {onCheckedChange ? (+ <chakra.div css={styles.check}>+ <Checkbox.Root+ aria-label={checkLabel ?? t('common.list.selectItem', { name: title })}+ checked={isChecked}+ colorPalette="accent"+ disabled={isBusy}+ size="xs"+ onCheckedChange={handleCheckedChange}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ </Checkbox.Root>+ </chakra.div>+ ) : null}+ {isInteractive ? (+ <chakra.button+ aria-current={isActive || undefined}+ aria-disabled={isBusy || undefined}+ aria-expanded={isExpanded}+ css={styles.primary}+ data-list-primary=""+ tabIndex={tabIndex}+ type="button"+ onClick={handlePress}+ onFocus={onIntent}+ onPointerEnter={onIntent}+ >+ {content}+ </chakra.button>+ ) : (+ // Static rows (nothing to press, no menu) must not announce themselves as buttons.+ <chakra.div aria-current={isActive || undefined} css={styles.primary} data-list-primary="">+ {content}+ </chakra.div>+ )}+ {actions !== undefined && actions !== null ? <chakra.div css={styles.actions}>{actions}</chakra.div> : null}+ </chakra.div>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListPager.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListPager.tsxnew file mode 100644index 0000000000..ceda80258d--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListPager.tsx@@ -0,0 +1,43 @@+import { HStack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { useTranslation } from 'react-i18next';++export interface ListPagerProps {+ /** 1-based page number shown between the controls. */+ page: number;+ hasPrevious: boolean;+ hasNext: boolean;+ /** Keeps both controls inert while a page loads. */+ isBusy?: boolean;+ onPrevious: () => void;+ onNext: () => void;+}++/**+ * Previous/next footer for server-paged lists. `aria-disabled`, not `disabled`: a disabled button drops the+ * keyboard focus it holds, and paging is usually driven from these buttons.+ */+export const ListPager = ({ hasNext, hasPrevious, isBusy = false, page, onNext, onPrevious }: ListPagerProps) => {+ const { t } = useTranslation();+ const previousUnavailable = !hasPrevious || isBusy;+ const nextUnavailable = !hasNext || isBusy;++ return (+ <HStack borderColor="border.subtle" borderTopWidth="1px" flexShrink={0} justify="center" minH="8">+ <Button+ aria-disabled={previousUnavailable}+ size="2xs"+ variant="ghost"+ onClick={previousUnavailable ? undefined : onPrevious}+ >+ {t('common.previousPage')}+ </Button>+ <Text aria-live="polite" color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums">+ {t('common.pageNumber', { page })}+ </Text>+ <Button aria-disabled={nextUnavailable} size="2xs" variant="ghost" onClick={nextUnavailable ? undefined : onNext}>+ {t('common.nextPage')}+ </Button>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsxnew file mode 100644index 0000000000..e377e8be10--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsx@@ -0,0 +1,18 @@+import { chakra, useSlotRecipe } from '@chakra-ui/react';+import { listSectionHeaderSlotRecipe } from '@theme/recipes';+import { useMemo } from 'react';++/** Fixed so virtualized lists can place headers without measuring them. */+export const LIST_SECTION_HEADER_HEIGHT_PX = 32;++export const ListSectionHeader = ({ count, label }: { count?: number; label: string }) => {+ const recipe = useSlotRecipe({ recipe: listSectionHeaderSlotRecipe });+ const styles = useMemo(() => recipe({}), [recipe]);++ return (+ <chakra.div css={styles.root}>+ <chakra.span css={styles.label}>{label}</chakra.span>+ {count !== undefined ? <chakra.span css={styles.count}>{count}</chakra.span> : null}+ </chakra.div>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsxnew file mode 100644index 0000000000..01337bb76e--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsx@@ -0,0 +1,72 @@+import type { ReactNode } from 'react';++import { Checkbox, HStack, Separator, Text, type StackProps } from '@chakra-ui/react';+import { Children } from 'react';++import { LIST_CHECK_INSET, LIST_ROW_INSET } from './listLayout';++export interface ListSelectionBarProps extends Omit<StackProps, 'children'> {+ /** `'indeterminate'` when some, but not every, matching row is selected. */+ checked: boolean | 'indeterminate';+ isDisabled?: boolean;+ /** Visible and accessible name of the select-all control. */+ label: string;+ onCheckedChange: () => void;+ /** Selection count or estimate, right-aligned; muted so the actions read first. */+ summary?: string;+ /** Lets an action describe itself with the summary via aria-describedby. */+ summaryId?: string;+ /** Actions for the selection, after a separator; omit while nothing is selected. */+ children?: ReactNode;+}++/**+ * Select-all row above a multi-select list. Keep it mounted whatever the selection so rows never shift beneath+ * it; toggle the actions instead. Its insets put the checkbox in the rows' checkbox column.+ */+export const ListSelectionBar = ({+ checked,+ children,+ isDisabled = false,+ label,+ summary,+ summaryId,+ onCheckedChange,+ ...stackProps+}: ListSelectionBarProps) => (+ <HStack+ borderBottomWidth="1px"+ borderColor="border.subtle"+ flexShrink={0}+ gap="2"+ minH="8"+ pe={LIST_ROW_INSET}+ ps={LIST_CHECK_INSET}+ py="1.5"+ {...stackProps}+ >+ <Checkbox.Root+ aria-label={label}+ checked={checked}+ colorPalette="accent"+ disabled={isDisabled}+ size="xs"+ onCheckedChange={onCheckedChange}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label color="fg.muted" fontSize="2xs" fontWeight="600">+ {label}+ </Checkbox.Label>+ </Checkbox.Root>+ <Text color="fg.muted" flex="1" fontSize="2xs" id={summaryId} minW="0" textAlign="end" truncate>+ {summary}+ </Text>+ {Children.toArray(children).length > 0 ? (+ <>+ <Separator borderColor="border.subtle" h="4" orientation="vertical" />+ {children}+ </>+ ) : null}+ </HStack>+);diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListStack.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListStack.tsxnew file mode 100644index 0000000000..8a82ed0e1b--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListStack.tsx@@ -0,0 +1,31 @@+import type { ReactNode } from 'react';++import { Stack, type StackProps } from '@chakra-ui/react';+import { Children } from 'react';++import { ListDivider } from './ListDivider';+import { LIST_ROW_GAP_PX } from './listLayout';++export interface ListStackProps extends Omit<StackProps, 'children' | 'gap' | 'role'> {+ /** Accessible name of the list. */+ label: string;+ /** Hairlines between rows, inset from the edges. */+ dividers?: boolean;+ /** Rows, each rendering `role="listitem"` (ListItem does). */+ children: ReactNode;+}++/**+ * A short list rendered in full, for rows that are few or bounded; long or growing lists use `List`, which+ * virtualizes. Rows keep the family's spacing either way.+ */+export const ListStack = ({ children, dividers = false, label, ...stackProps }: ListStackProps) => (+ <Stack aria-label={label} gap={dividers ? 0 : `${LIST_ROW_GAP_PX}px`} role="list" {...stackProps}>+ {dividers+ ? Children.toArray(children).flatMap((row, index) =>+ // Dividers carry no state, so index keys are safe for them.+ index === 0 ? [row] : [<ListDivider key={`divider-${index}`} placement="in-flow" />, row]+ )+ : children}+ </Stack>+);diff --git a/invokeai/frontend/webv2/src/platform/ui/list/listLayout.ts b/invokeai/frontend/webv2/src/platform/ui/list/listLayout.tsnew file mode 100644index 0000000000..f91333f630--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/listLayout.ts@@ -0,0 +1,14 @@+/** Horizontal inset of rows and headers from the list's edge. */+export const LIST_ROW_INSET = '0.75rem';++/** Start padding of the row checkbox inside the row surface; matches the `check` slot of the list item recipe. */+const LIST_CHECK_PADDING = '0.5rem';++/** Where row checkboxes start relative to the list's edge, so chrome above the list can line up with them. */+export const LIST_CHECK_INSET = `calc(${LIST_ROW_INSET} + ${LIST_CHECK_PADDING})`;++/** Space between rows; a divider, when shown, sits centred in it. */+export const LIST_ROW_GAP_PX = 4;++/** Dividers stop short of the row edges so a filled row's rounded corners never meet the line. */+export const LIST_DIVIDER_INSET = '0.5rem';diff --git a/invokeai/frontend/webv2/src/platform/ui/list/listRows.test.ts b/invokeai/frontend/webv2/src/platform/ui/list/listRows.test.tsnew file mode 100644index 0000000000..b3c947aa31--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/listRows.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { listRowsFromItems, listRowsFromSections } from './listRows';++interface Item {+ id: string;+}++const getId = (item: Item): string => item.id;++describe('listRowsFromSections', () => {+ it('interleaves one header per non-empty section, carrying the item count', () => {+ const rows = listRowsFromSections(+ [+ { items: [{ id: 'a' }, { id: 'b' }], key: 'main', label: 'Main' },+ { items: [], key: 'empty', label: 'Nothing here' },+ { items: [{ id: 'c' }], key: 'lora', label: 'LoRAs' },+ ],+ getId+ );++ expect(rows).toEqual([+ { count: 2, key: 'header:main', kind: 'header', label: 'Main' },+ { item: { id: 'a' }, key: 'a', kind: 'item' },+ { item: { id: 'b' }, key: 'b', kind: 'item' },+ { count: 1, key: 'header:lora', kind: 'header', label: 'LoRAs' },+ { item: { id: 'c' }, key: 'c', kind: 'item' },+ ]);+ });++ it('keeps header keys distinct from item keys that share a section name', () => {+ const rows = listRowsFromSections([{ items: [{ id: 'main' }], key: 'main', label: 'Main' }], getId);++ expect(new Set(rows.map((row) => row.key)).size).toBe(rows.length);+ });+});++describe('listRowsFromItems', () => {+ it('produces item rows only, in order', () => {+ expect(listRowsFromItems([{ id: 'b' }, { id: 'a' }], getId)).toEqual([+ { item: { id: 'b' }, key: 'b', kind: 'item' },+ { item: { id: 'a' }, key: 'a', kind: 'item' },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/listRows.ts b/invokeai/frontend/webv2/src/platform/ui/list/listRows.tsnew file mode 100644index 0000000000..d6aa7f5338--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/listRows.ts@@ -0,0 +1,34 @@+export type ListRow<T> =+ | { kind: 'header'; key: string; label: string; count: number }+ | { kind: 'item'; key: string; item: T };++export interface ListSection<T> {+ key: string;+ label: string;+ items: readonly T[];+}++/** Sections flatten to one row sequence so headers virtualize with their items; empty sections contribute nothing. */+export const listRowsFromSections = <T>(+ sections: readonly ListSection<T>[],+ getItemKey: (item: T) => string+): ListRow<T>[] => {+ const rows: ListRow<T>[] = [];++ for (const section of sections) {+ if (section.items.length === 0) {+ continue;+ }++ rows.push({ count: section.items.length, key: `header:${section.key}`, kind: 'header', label: section.label });++ for (const item of section.items) {+ rows.push({ item, key: getItemKey(item), kind: 'item' });+ }+ }++ return rows;+};++export const listRowsFromItems = <T>(items: readonly T[], getItemKey: (item: T) => string): ListRow<T>[] =>+ items.map((item) => ({ item, key: getItemKey(item), kind: 'item' }));diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.tsindex 29b0b339a7..543406e21e 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts@@ -664,6 +664,8 @@ export const scrollAreaSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.scrollArea.base?.scrollbar,'&[data-orientation="vertical"]:not([data-overflow-y])': { display: 'none' },'&[data-orientation="horizontal"]:not([data-overflow-x])': { display: 'none' },+ // Above sticky content (z-index 1) so opaque pinned headers never cover the thumb.+ zIndex: 2,},},});@@ -860,43 +862,202 @@ export const panelRecipe = defineRecipe({defaultVariants: { tone: 'surface', density: 'none' },});+const rowFocusRing = {+ outline: '2px solid',+ outlineColor: 'accent.solid',+ outlineOffset: '-2px',+} as const;++/** One row surface for every list-like control; `Row` and `ListItem` both build on it. */+const rowSurface = {+ borderRadius: 'sm',+ textAlign: 'start',+ transition: 'background var(--wb-motion-duration-fast) ease, color var(--wb-motion-duration-fast) ease',+ w: 'full',+ // Keep hover below selected emphasis so pointing does not resemble selection.+ _hover: { bg: 'bg.muted/60' },+ _disabled: { cursor: 'not-allowed', opacity: 0.5 },+} as const;++/** Emphasis levels: `accent` marks the one active row, `selected` marks checked rows. */+const rowTones = {+ none: {},+ muted: { bg: 'bg.muted' },+ selected: { bg: 'bg.emphasized/60', _hover: { bg: 'bg.emphasized/60' } },+ emphasized: { bg: 'bg.emphasized', _hover: { bg: 'bg.emphasized' } },+ brand: {+ bg: 'brand.subtle',+ color: 'brand.fg',+ _hover: { bg: 'brand.subtle' },+ },+ accent: {+ bg: 'accent.solid',+ color: 'accent.contrast',+ _hover: { bg: 'accent.solid' },+ },+} as const;+export const rowRecipe = defineRecipe({base: {+ ...rowSurface,alignItems: 'center',- borderRadius: 'sm',display: 'flex',gap: '2',- textAlign: 'start',- transition: 'background var(--wb-motion-duration-fast) ease, color var(--wb-motion-duration-fast) ease',- w: 'full',- // Keep hover below selected emphasis so pointing does not resemble selection.- _hover: { bg: 'bg.muted/60' },- _focusVisible: {- outline: '2px solid',- outlineColor: 'accent.solid',- outlineOffset: '-2px',- },- _disabled: { cursor: 'not-allowed', opacity: 0.5 },+ _focusVisible: rowFocusRing,+ },+ variants: {+ active: rowTones,+ },+ defaultVariants: { active: 'none' },+});++/**+ * A list row: an optional checkbox beside one primary button, never inside it. The ring wraps the whole row when+ * the button has focus; the accent tone recolors muted text so it stays legible on the solid fill.+ */+export const listItemSlotRecipe = defineSlotRecipe({+ slots: ['root', 'check', 'primary', 'body', 'titleLine', 'title', 'badges', 'description', 'trailing', 'actions'],+ base: {+ root: {+ ...rowSurface,+ alignItems: 'stretch',+ display: 'flex',+ minW: 0,+ position: 'relative',+ '&:has([data-list-primary]:focus-visible)': rowFocusRing,+ // Rows of a page being replaced stay readable; only the pointer says the list is working.+ '&[data-busy]': { cursor: 'progress' },+ // Nothing to press: pointing must not look like an affordance.+ '&[data-static]:hover': { bg: 'transparent' },+ },+ check: {+ alignItems: 'center',+ display: 'flex',+ flexShrink: 0,+ ps: '2',+ },+ primary: {+ alignItems: 'center',+ appearance: 'none',+ bg: 'transparent',+ border: 0,+ borderRadius: 'inherit',+ color: 'inherit',+ display: 'flex',+ flex: 1,+ font: 'inherit',+ minW: 0,+ outline: 'none',+ textAlign: 'start',+ },+ body: {+ display: 'flex',+ flex: 1,+ flexDirection: 'column',+ gap: '0.5',+ minW: 0,+ },+ titleLine: {+ alignItems: 'center',+ display: 'flex',+ gap: '1.5',+ minW: 0,+ },+ title: {+ fontSize: 'xs',+ fontWeight: '600',+ lineHeight: 'shorter',+ },+ badges: {+ alignItems: 'center',+ display: 'flex',+ flexShrink: 0,+ gap: '1',+ },+ description: {+ color: 'fg.muted',+ fontSize: '2xs',+ lineHeight: 'shorter',+ minW: 0,+ },+ trailing: {+ alignItems: 'center',+ color: 'fg.muted',+ display: 'flex',+ flexShrink: 0,+ fontSize: '2xs',+ gap: '1.5',+ },+ // Controls beside the primary button, never inside it.+ actions: {+ alignItems: 'center',+ display: 'flex',+ flexShrink: 0,+ gap: '0.5',+ pe: '1',+ },},variants: {active: {none: {},- muted: { bg: 'bg.muted' },- selected: { bg: 'bg.emphasized/60', _hover: { bg: 'bg.emphasized/60' } },- emphasized: { bg: 'bg.emphasized', _hover: { bg: 'bg.emphasized' } },- brand: {- bg: 'brand.subtle',- color: 'brand.fg',- _hover: { bg: 'brand.subtle' },- },+ selected: { root: rowTones.selected },accent: {- bg: 'accent.solid',- color: 'accent.contrast',- _hover: { bg: 'accent.solid' },+ root: rowTones.accent,+ description: { color: 'accent.contrast', opacity: 0.85 },+ trailing: { color: 'accent.contrast' },+ },+ },+ density: {+ compact: {+ root: { minH: '7' },+ primary: { gap: '2', px: '2', py: '1' },+ },+ regular: {+ root: { minH: '10' },+ primary: { gap: '2', px: '2', py: '1.5' },+ },+ comfortable: {+ root: { minH: '13' },+ primary: { gap: '2.5', px: '2', py: '1.5' },},},},- defaultVariants: { active: 'none' },+ defaultVariants: { active: 'none', density: 'regular' },+});++/** Section labels inside lists; the count sits beside the label in a quieter tone. */+export const listSectionHeaderSlotRecipe = defineSlotRecipe({+ slots: ['root', 'label', 'count'],+ base: {+ root: {+ alignItems: 'flex-end',+ display: 'flex',+ gap: '1.5',+ h: '8',+ minW: 0,+ pb: '1.5',+ ps: '2',+ },+ label: {+ color: 'fg.muted',+ fontSize: '2xs',+ fontWeight: '700',+ letterSpacing: '0.04em',+ lineHeight: 'shorter',+ minW: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ textTransform: 'uppercase',+ whiteSpace: 'nowrap',+ },+ count: {+ color: 'fg.muted',+ flexShrink: 0,+ fontSize: '2xs',+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 'shorter',+ },+ },});export const chipRecipe = defineRecipe({