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.

refactor(webv2): rebuild the model picker on the Picker primitive

joshistoaste1cd06410d7e
diff --git a/invokeai/frontend/webv2/src/features/models/core/baseIdentity.ts b/invokeai/frontend/webv2/src/features/models/core/baseIdentity.ts
index fca945e0cd..32e5e9ac37 100644
--- a/invokeai/frontend/webv2/src/features/models/core/baseIdentity.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/baseIdentity.ts
@@ -7,7 +7,10 @@ export type ModelBaseColorPalette = 'blue' | 'cyan' | 'gray' | 'green' | 'orange
export interface ModelBaseInfo {
base: ModelBase;
+ /** Short form, for badges and filter chips. */
label: string;
+ /** Spelled-out form for list group headers; falls back to `label`. */
+ longLabel?: string;
colorPalette: ModelBaseColorPalette;
description?: string;
supportsDiffusersConversion?: boolean;
@@ -17,29 +20,34 @@ export const MODEL_BASES = {
'sd-1': {
base: 'sd-1',
label: 'SD 1.x',
+ longLabel: 'Stable Diffusion 1.x',
colorPalette: 'green',
supportsDiffusersConversion: true,
},
'sd-2': {
base: 'sd-2',
label: 'SD 2.x',
+ longLabel: 'Stable Diffusion 2.x',
colorPalette: 'teal',
supportsDiffusersConversion: true,
},
sdxl: {
base: 'sdxl',
label: 'SDXL',
+ longLabel: 'Stable Diffusion XL',
colorPalette: 'blue',
supportsDiffusersConversion: true,
},
'sdxl-refiner': {
base: 'sdxl-refiner',
label: 'SDXL Refiner',
+ longLabel: 'Stable Diffusion XL Refiner',
colorPalette: 'blue',
},
'sd-3': {
base: 'sd-3',
label: 'SD 3.x',
+ longLabel: 'Stable Diffusion 3.x',
colorPalette: 'purple',
},
flux: {
@@ -122,6 +130,13 @@ export const getModelBaseInfo = (base: ModelBase): ModelBaseInfo =>
export const getModelBaseLabel = (base: ModelBase): string => getModelBaseInfo(base).label;
+/** Spelled-out base name for list group headers; short bases read the same either way. */
+export const getModelBaseLongLabel = (base: ModelBase): string => {
+ const info = getModelBaseInfo(base);
+
+ return info.longLabel ?? info.label;
+};
+
export const getModelBaseColorPalette = (base: ModelBase): ModelBaseColorPalette => getModelBaseInfo(base).colorPalette;
export const isKnownModelBase = (base: ModelBase): base is KnownModelBase => base in MODEL_BASES;
diff --git a/invokeai/frontend/webv2/src/features/models/core/library.test.ts b/invokeai/frontend/webv2/src/features/models/core/library.test.ts
index ef4d4a0338..76bf5ef24a 100644
--- a/invokeai/frontend/webv2/src/features/models/core/library.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/library.test.ts
@@ -104,24 +104,51 @@ describe('getModelPickerGroups', () => {
});
expect(result.candidates.map((m) => m.key)).toEqual(['a', 'c']);
- expect(result.groups.map((group) => group.type)).toEqual(['lora']);
+ expect(result.groups.map((group) => group.base)).toEqual(['sd-1']);
expect(result.groups[0]?.models.map((m) => m.key)).toEqual(['c']);
});
- it('groups by (type, base) sorted by taxonomy rank, base display order, then name', () => {
+ // Type is not a grouping axis: a cross-type picker would otherwise repeat a
+ // "Main Models" header above every base section.
+ it('groups by base alone, in base display order', () => {
const result = getModelPickerGroups(library, {
modelTypes: ['main', 'lora', 'vae'],
searchTerm: '',
});
expect(result.groups.map((group) => [group.key, group.models.map((m) => m.key)])).toEqual([
- ['main:sdxl', ['a']],
- ['main:flux', ['b']],
- ['lora:sd-1', ['c']],
- ['vae:any', ['d']],
+ ['sd-1', ['c']],
+ ['sdxl', ['a']],
+ ['flux', ['b']],
+ ['any', ['d']],
]);
});
+ it('keeps several types in one base group, ordered by taxonomy rank then name', () => {
+ const mixed = [
+ createModel({ base: 'sdxl', key: 'lora-1', name: 'Alpha LoRA', type: 'lora' }),
+ createModel({ base: 'sdxl', key: 'main-1', name: 'Zulu Main', type: 'main' }),
+ ];
+ const result = getModelPickerGroups(mixed, { modelTypes: ['main', 'lora'], searchTerm: '' });
+
+ expect(result.groups).toHaveLength(1);
+ expect(result.groups[0]?.models.map((m) => m.key)).toEqual(['main-1', 'lora-1']);
+ });
+
+ it('floats models related to the current selection to the top of their group', () => {
+ const related = [
+ createModel({ base: 'sdxl', key: 'aaa', name: 'Aaa', type: 'lora' }),
+ createModel({ base: 'sdxl', key: 'zzz', name: 'Zzz', type: 'lora' }),
+ ];
+ const result = getModelPickerGroups(related, {
+ modelTypes: ['lora'],
+ relatedKeys: new Set(['zzz']),
+ searchTerm: '',
+ });
+
+ expect(result.groups[0]?.models.map((m) => m.key)).toEqual(['zzz', 'aaa']);
+ });
+
it('filters visible models by the selected bases, empty set showing all', () => {
const onlySdxl = getModelPickerGroups(library, {
baseFilter: new Set(['sdxl']),
@@ -137,7 +164,8 @@ describe('getModelPickerGroups', () => {
searchTerm: '',
});
- expect(all.groups.flatMap((group) => group.models.map((m) => m.key))).toEqual(['a', 'b', 'c', 'd']);
+ // Base display order, matching `availableBases`: sd-1, sdxl, flux, any.
+ expect(all.groups.flatMap((group) => group.models.map((m) => m.key))).toEqual(['c', 'a', 'b', 'd']);
});
it('exposes availableBases that stay stable across search and base filtering', () => {
diff --git a/invokeai/frontend/webv2/src/features/models/core/library.ts b/invokeai/frontend/webv2/src/features/models/core/library.ts
index c7eeb12b10..85c7ef6bbc 100644
--- a/invokeai/frontend/webv2/src/features/models/core/library.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/library.ts
@@ -45,17 +45,18 @@ export interface ModelPickerOptions {
/** Extra predicate supplied by the owning form, e.g. base compatibility. */
filter?: (model: ModelConfig) => boolean;
modelTypes: ModelTaxonomyType[];
+ /** Models linked to the current selection, floated to the top of their group. */
+ relatedKeys?: ReadonlySet<string>;
searchTerm: string;
}
/**
- * Picker list group: one per (type, base) pair so items never need a per-row
- * base badge — the header renders the base (and, for multi-type pickers, the
- * type label) from `base`/`type`.
+ * Picker list group: one per base. Type is deliberately NOT a grouping axis —
+ * a cross-type picker would otherwise repeat "Main Models" above every base
+ * section. Rows in a multi-type picker carry their own type badge instead.
*/
export interface ModelPickerGroup {
key: string;
- type: ModelTaxonomyType;
base: string;
models: ModelConfig[];
}
@@ -159,6 +160,9 @@ export const getModelPickerGroups = (models: ModelConfig[], options: ModelPicker
// so the chip row stays stable while the user types or toggles chips.
const availableBases = collectBasesForDisplay(candidates);
const { baseFilter } = options;
+ const { relatedKeys } = options;
+ // Bases order the groups; within a group, related models lead, then category
+ // rank keeps main models above LoRAs in a cross-type picker, then name.
const visibleModels = candidates
.filter(
(model) =>
@@ -167,9 +171,10 @@ export const getModelPickerGroups = (models: ModelConfig[], options: ModelPicker
)
.sort(
(a, b) =>
- getModelCategoryRank(a.type) - getModelCategoryRank(b.type) ||
getBaseDisplayRank(String(a.base)) - getBaseDisplayRank(String(b.base)) ||
String(a.base).localeCompare(String(b.base)) ||
+ Number(relatedKeys?.has(b.key) ?? false) - Number(relatedKeys?.has(a.key) ?? false) ||
+ getModelCategoryRank(a.type) - getModelCategoryRank(b.type) ||
a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
);
@@ -181,17 +186,16 @@ const groupModelsForPicker = (models: ModelConfig[]): ModelPickerGroup[] => {
for (const model of models) {
const base = String(model.base);
- const key = `${model.type}:${base}`;
- const existing = groups.get(key);
+ const existing = groups.get(base);
if (existing) {
existing.models.push(model);
} else {
- groups.set(key, { base, key, models: [model], type: model.type });
+ groups.set(base, { base, key: base, models: [model] });
}
}
- // Insertion order already follows the sorted model list (category, base, name).
+ // Insertion order already follows the sorted model list (base, related, name).
return [...groups.values()];
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx
index 8092406281..e6c9d03f51 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx
@@ -23,8 +23,17 @@ const model = {
source: 'sdxl.safetensors',
type: 'main',
} as ModelConfig;
+const loraModel = {
+ ...model,
+ base: 'sd-1',
+ key: 'sd1-lora',
+ name: 'Detail LoRA',
+ type: 'lora',
+} as ModelConfig;
+const secondSdxlModel = { ...model, key: 'sdxl-other', name: 'Another SDXL' } as ModelConfig;
const MODELS_UI_ADAPTER = { enableModelDescriptions: true, managerProjectId: null };
const MAIN_MODEL_TYPES: ['main'] = ['main'];
+const CROSS_TYPE_MODEL_TYPES: ['main', 'lora'] = ['main', 'lora'];
describe('ModelSelect loading states', () => {
let host: HTMLDivElement;
@@ -60,4 +69,87 @@ describe('ModelSelect loading states', () => {
await expect.poll(() => document.querySelector('[role="option"]')?.textContent).toContain('SDXL Main');
});
+
+ const renderPicker = async (props: Partial<Parameters<typeof ModelSelect>[0]> = {}) => {
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <ModelsUiProvider adapter={MODELS_UI_ADAPTER}>
+ <ModelSelect
+ modelTypes={MAIN_MODEL_TYPES}
+ showManagerButton={false}
+ value={null}
+ onChange={vi.fn()}
+ {...props}
+ />
+ </ModelsUiProvider>
+ </ChakraProvider>
+ );
+ });
+
+ await act(() => host.querySelector<HTMLButtonElement>('[aria-haspopup="listbox"]')?.click());
+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);
+ };
+
+ const optionTexts = (): string[] =>
+ [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');
+
+ // The bug that prompted the rewrite: grouping by (type, base) printed "Main
+ // Models" above every base section of a cross-type picker.
+ it('groups a cross-type picker by base alone, with no type header', async () => {
+ setModelsSnapshotForTests({ error: null, models: [model, loraModel], status: 'loaded' });
+ await renderPicker({ id: 'test-cross-type', modelTypes: CROSS_TYPE_MODEL_TYPES });
+
+ const listbox = document.querySelector('[role="listbox"]')!;
+
+ expect(listbox.textContent).toContain('Stable Diffusion 1.x');
+ expect(listbox.textContent).toContain('Stable Diffusion XL');
+ expect(listbox.textContent).not.toContain('Main Models');
+ // Type is on the row instead, so the two rows stay distinguishable.
+ expect(optionTexts().join(' ')).toContain('LoRA');
+ });
+
+ it('moves the active row across a group boundary and selects with Enter', async () => {
+ const onChange = vi.fn();
+
+ setModelsSnapshotForTests({ error: null, models: [model, loraModel], status: 'loaded' });
+ await renderPicker({ id: 'test-keyboard', modelTypes: CROSS_TYPE_MODEL_TYPES, onChange });
+
+ const search = document
+ .querySelector<HTMLInputElement>('[role="listbox"]')!
+ .closest('[data-scope="popover"]')!
+ .querySelector<HTMLInputElement>('input')!;
+
+ // sd-1 sorts before sdxl, so the LoRA leads and one step lands on the main
+ // model in the next group.
+ await expect.poll(() => document.querySelector('[data-active]')?.textContent).toContain('Detail LoRA');
+
+ await act(() => {
+ search.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'ArrowDown' }));
+ });
+ await expect.poll(() => document.querySelector('[data-active]')?.textContent).toContain('SDXL Main');
+
+ await act(() => {
+ search.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Enter' }));
+ });
+
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ key: 'sdxl-main' }));
+ });
+
+ it('remembers the compact row density across a close and reopen', async () => {
+ setModelsSnapshotForTests({ error: null, models: [model, secondSdxlModel], status: 'loaded' });
+ await renderPicker({ id: 'test-compact' });
+
+ const toggle = document.querySelector<HTMLButtonElement>('button[aria-label="Compact rows"]')!;
+
+ expect(toggle).not.toBeNull();
+ await act(() => toggle.click());
+ await expect.poll(() => document.querySelector('button[aria-label="Full rows"]')).not.toBeNull();
+
+ // Close and reopen: the preference is stored per picker id, not per mount.
+ await act(() => host.querySelector<HTMLButtonElement>('[aria-haspopup="listbox"]')?.click());
+ await act(() => host.querySelector<HTMLButtonElement>('[aria-haspopup="listbox"]')?.click());
+
+ await expect.poll(() => document.querySelector('button[aria-label="Full rows"]')).not.toBeNull();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
index 2c9b50a978..c9c68f9907 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
@@ -1,39 +1,44 @@
-/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */
+/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */
import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';
+import type { PickerGroup, PickerOptionState } from '@platform/ui';
-import {
- Badge,
- Box,
- HStack,
- Icon,
- Input,
- InputGroup,
- Popover,
- Portal,
- ScrollArea,
- Spacer,
- Stack,
- Text,
-} from '@chakra-ui/react';
-import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';
+import { Badge, Box, HStack, Icon, Image, Popover, Portal, Spacer, Stack, Text } from '@chakra-ui/react';
+import { getModelBaseColorPalette, getModelBaseLabel, getModelBaseLongLabel } from '@features/models/core/baseIdentity';
import { getModelPickerGroups } from '@features/models/core/library';
-import { formatBytes, getModelTypePluralLabel } from '@features/models/core/taxonomy';
+import { formatBytes, getModelTypeLabel, getModelTypePluralLabel } from '@features/models/core/taxonomy';
+import { getModelImageUrl, getRelatedModelKeys } from '@features/models/data/api';
import { ensureModelsLoaded, useModelsSelector } from '@features/models/data/modelsStore';
import { useModelsUi } from '@features/models/ui/ModelsUiContext';
+import { setPickerCompactView, useModelsUiSelector } from '@features/models/ui/uiStore';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { Button, CloseButton, IconButton, Tooltip } from '@platform/ui';
+import { Button, CloseButton, IconButton, Picker, Tooltip } from '@platform/ui';
import { Link } from '@tanstack/react-router';
-import { dropdownContent, dropdownGroupLabel, dropdownItem } from '@theme/recipes';
-import { BoxIcon, CheckIcon, ChevronDownIcon, RotateCcwIcon, SearchIcon, XIcon } from 'lucide-react';
-import { useDeferredValue, useMemo, useRef, useState } from 'react';
+import { dropdownContent } from '@theme/recipes';
+import {
+ BoxIcon,
+ CheckIcon,
+ ChevronDownIcon,
+ ChevronsDownUpIcon,
+ ChevronsUpDownIcon,
+ LinkIcon,
+ RotateCcwIcon,
+ XIcon,
+} from 'lucide-react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
const EMPTY_BASES: ReadonlySet<string> = new Set();
+const EMPTY_KEYS: ReadonlySet<string> = new Set();
+
+const getOptionId = (model: ModelConfig): string => model.key;
/**
* Universal single-model picker: a button-triggered searchable list over the
- * installed library. Scope it with `modelTypes` — one type for dedicated
- * pickers (a LoRA picker, a main-model picker) or several for cross-type
- * pickers, in which case results are grouped by type.
+ * installed library, built on the generic {@link Picker}.
+ *
+ * Scope it with `modelTypes` — one type for dedicated pickers (a LoRA picker, a
+ * main-model picker) or several for cross-type pickers. Results group by BASE
+ * only; a cross-type picker marks each row with its type rather than repeating
+ * a type header above every base section.
*/
export const ModelSelect = ({
className,
@@ -74,12 +79,13 @@ export const ModelSelect = ({
const loadError = useModelsSelector((snapshot) => snapshot.error);
const loadStatus = useModelsSelector((snapshot) => snapshot.status);
const [isOpen, setIsOpen] = useState(false);
- const [searchTerm, setSearchTerm] = useState('');
const [selectedBases, setSelectedBases] = useState<ReadonlySet<string>>(EMPTY_BASES);
const [lastDisabled, setLastDisabled] = useState(disabled);
- const deferredSearchTerm = useDeferredValue(searchTerm);
- const searchInputRef = useRef<HTMLInputElement>(null);
- const optionRefs = useRef<HTMLElement[]>([]);
+
+ // Sibling pickers of the same kind share one density preference.
+ const pickerId = id ?? `models:${modelTypes.join('+')}`;
+ const isCompact = useModelsUiSelector((snapshot) => snapshot.pickerCompactViews[pickerId] ?? false);
+ const relatedKeys = useRelatedModelKeys(isOpen ? value : null);
useMountEffect(() => {
void ensureModelsLoaded();
@@ -90,7 +96,6 @@ export const ModelSelect = ({
if (disabled) {
setIsOpen(false);
- setSearchTerm('');
setSelectedBases(EMPTY_BASES);
}
}
@@ -103,22 +108,39 @@ export const ModelSelect = ({
excludeKeys,
filter,
modelTypes,
- searchTerm: deferredSearchTerm,
+ relatedKeys,
+ // The generic Picker owns text search; this pass only scopes and groups.
+ searchTerm: '',
})
: { availableBases: [], candidates: [], groups: [] },
- [deferredSearchTerm, excludeKeys, filter, isOpen, modelTypes, models, selectedBases]
+ [excludeKeys, filter, isOpen, modelTypes, models, relatedKeys, selectedBases]
);
const selectedModel = useMemo(() => models.find((model) => model.key === value) ?? null, [models, value]);
-
+ // Keyed off what is actually installed, not the declared scope: a picker
+ // scoped to main + external API models still lists only main models on most
+ // installs, and badging every row "Main Model" says nothing.
+ const hasMixedTypes = useMemo(() => new Set(candidates.map((model) => model.type)).size > 1, [candidates]);
const scopeLabel =
modelTypes.length === 1 ? getModelTypePluralLabel(modelTypes[0] ?? 'main').toLowerCase() : 'models';
+
+ const pickerGroups = useMemo<PickerGroup<ModelConfig>[]>(
+ () =>
+ groups.map((group) => ({
+ colorPalette: getModelBaseColorPalette(group.base),
+ getCountLabel: (count) => `${count} ${count === 1 ? 'model' : 'models'}`,
+ id: group.key,
+ name: getModelBaseLongLabel(group.base),
+ options: group.models,
+ shortName: getModelBaseLabel(group.base),
+ })),
+ [groups]
+ );
+
const closeAndReset = () => {
setIsOpen(false);
- setSearchTerm('');
setSelectedBases(EMPTY_BASES);
};
-
const toggleBase = (base: string) => {
setSelectedBases((prev) => {
const next = new Set(prev);
@@ -132,41 +154,25 @@ export const ModelSelect = ({
return next;
});
};
- const resetBases = () => {
- setSelectedBases(EMPTY_BASES);
- };
const selectModel = (model: ModelConfig) => {
onChange(model);
closeAndReset();
};
- const clearSelection = () => {
- onChange(null);
- closeAndReset();
- };
- const focusSearchInput = () => {
- window.requestAnimationFrame(() => searchInputRef.current?.focus());
- };
- const focusOption = (edge: 'first' | 'last') => {
- const options = optionRefs.current.filter(Boolean);
-
- options[edge === 'first' ? 0 : options.length - 1]?.focus();
- };
- const focusAdjacentOption = (currentIndex: number, direction: 1 | -1) => {
- const options = optionRefs.current.filter(Boolean);
- const nextIndex = currentIndex + direction;
-
- if (nextIndex < 0) {
- searchInputRef.current?.focus();
- return;
- }
-
- options[nextIndex]?.focus();
- };
-
- optionRefs.current = [];
- let optionIndex = 0;
const canClear = isClearable && Boolean(value);
+ const renderOption = useCallback(
+ (model: ModelConfig, state: PickerOptionState) => (
+ <ModelOptionContent
+ enableDescription={enableModelDescriptions}
+ isRelated={relatedKeys.has(model.key)}
+ model={model}
+ showType={hasMixedTypes}
+ state={state}
+ />
+ ),
+ [enableModelDescriptions, hasMixedTypes, relatedKeys]
+ );
+
return (
<Box className={className} minW="0" w="full">
<Popover.Root
@@ -188,10 +194,8 @@ export const ModelSelect = ({
}
if (event.open) {
- setSearchTerm('');
setSelectedBases(EMPTY_BASES);
setIsOpen(true);
- focusSearchInput();
return;
}
@@ -243,7 +247,8 @@ export const ModelSelect = ({
zIndex="1"
onClick={(event) => {
event.stopPropagation();
- clearSelection();
+ onChange(null);
+ closeAndReset();
}}
onMouseDown={(event) => {
event.stopPropagation();
@@ -257,164 +262,76 @@ export const ModelSelect = ({
<Popover.Positioner>
<Popover.Content
css={dropdownContent}
- maxH="min(18rem, var(--available-height))"
- maxW="min(24rem, calc(100vw - 1rem))"
- minW="min(18rem, calc(100vw - 1rem))"
+ maxH="min(24rem, var(--available-height))"
+ maxW="min(26rem, calc(100vw - 1rem))"
+ minW="min(20rem, calc(100vw - 1rem))"
overflow="hidden"
p="0"
>
- <Stack gap="2" p="2">
- <HStack gap="1">
- <InputGroup flex="1" minW="0" startElement={<Icon as={SearchIcon} size="xs" />}>
- <Input
- ref={searchInputRef}
- aria-label={`Search ${scopeLabel}`}
- placeholder={`Search ${scopeLabel}…`}
- size="xs"
- value={searchTerm}
- onChange={(event) => setSearchTerm(event.currentTarget.value)}
- onKeyDown={(event) => {
- event.stopPropagation();
-
- if (event.key === 'Escape') {
- event.preventDefault();
- closeAndReset();
- return;
- }
-
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- event.preventDefault();
- focusOption(event.key === 'ArrowDown' ? 'first' : 'last');
- }
- }}
- />
- </InputGroup>
- {showManagerButton ? <ModelManagerLinkButton /> : null}
- </HStack>
- {availableBases.length >= 2 ? (
- <HStack alignItems="center" flexWrap="wrap" gap="1">
- {availableBases.map((base) => (
- <BaseChip key={base} base={base} isSelected={selectedBases.has(base)} onToggle={toggleBase} />
- ))}
- <Spacer />
- <IconButton
- aria-label="Reset base filters"
- flexShrink={0}
- opacity={selectedBases.size === 0 ? 0.5 : undefined}
- pointerEvents={selectedBases.size === 0 ? 'none' : undefined}
- size="2xs"
- variant="ghost"
- onClick={resetBases}
- >
- <Icon as={RotateCcwIcon} boxSize="3" />
- </IconButton>
- </HStack>
- ) : null}
- </Stack>
- <HStack borderTopWidth="1px" borderColor="border.subtle" />
- <ScrollArea.Root maxH="14rem" size="xs" variant="hover" w="full">
- <ScrollArea.Viewport maxH="inherit" w="full">
- <ScrollArea.Content maxW="full" py="1" role="listbox" aria-label={`Available ${scopeLabel}`}>
- {loadStatus === 'idle' || loadStatus === 'loading' ? (
- <Text color="fg.subtle" fontSize="2xs" p="2">
- Loading models…
- </Text>
- ) : loadStatus === 'error' ? (
- <Stack alignItems="start" gap="1.5" p="2">
- <Text color="fg.error" fontSize="2xs">
- {loadError ?? 'Failed to load models.'}
- </Text>
- <Button size="2xs" variant="outline" onClick={() => void ensureModelsLoaded()}>
- Retry
- </Button>
- </Stack>
- ) : groups.length === 0 ? (
- <Text color="fg.subtle" fontSize="2xs" p="2">
- {candidates.length === 0
- ? `No compatible ${scopeLabel} installed.`
- : !deferredSearchTerm.trim() && selectedBases.size > 0
- ? `No ${scopeLabel} match the selected bases.`
- : `No ${scopeLabel} match your search.`}
+ <Picker<ModelConfig>
+ emptyMessage={`No compatible ${scopeLabel} installed.`}
+ getOptionId={getOptionId}
+ groups={pickerGroups}
+ isCompact={isCompact}
+ isMatch={matchesModel}
+ listLabel={`Available ${scopeLabel}`}
+ noMatchesMessage={
+ selectedBases.size > 0
+ ? `No ${scopeLabel} match the selected bases.`
+ : `No ${scopeLabel} match your search.`
+ }
+ renderOption={renderOption}
+ searchPlaceholder={`Search ${scopeLabel}…`}
+ searchSlot={
+ <>
+ <CompactViewToggle isCompact={isCompact} pickerId={pickerId} />
+ {showManagerButton ? <ModelManagerLinkButton /> : null}
+ </>
+ }
+ selectedId={value}
+ statusSlot={
+ loadStatus === 'idle' || loadStatus === 'loading' ? (
+ <Text color="fg.subtle" fontSize="2xs" p="2">
+ Loading models…
+ </Text>
+ ) : loadStatus === 'error' ? (
+ <Stack alignItems="start" gap="1.5" p="2">
+ <Text color="fg.error" fontSize="2xs">
+ {loadError ?? 'Failed to load models.'}
</Text>
- ) : null}
- {loadStatus === 'loaded'
- ? groups.map((group) => (
- <Stack key={group.key} gap="0">
- {groups.length > 1 ? (
- <HStack gap="1.5" px="2" py="1">
- {modelTypes.length > 1 ? (
- <Text css={dropdownGroupLabel}>{getModelTypePluralLabel(group.type)}</Text>
- ) : null}
- <Badge
- colorPalette={getModelBaseColorPalette(group.base)}
- fontSize="2xs"
- size="xs"
- variant="surface"
- >
- {getModelBaseLabel(group.base)}
- </Badge>
- </HStack>
- ) : null}
- {group.models.map((model) => {
- const currentOptionIndex = optionIndex;
- optionIndex += 1;
-
- return (
- <Button
- key={model.key}
- ref={(element) => {
- if (element) {
- optionRefs.current[currentOptionIndex] = element;
- }
- }}
- aria-selected={value === model.key}
- borderRadius="0"
- css={dropdownItem}
- gap="2"
- h="auto"
- justifyContent="start"
- minH="6"
- py="1"
- role="option"
- size="2xs"
- variant="ghost"
- w="full"
- onClick={() => selectModel(model)}
- onKeyDown={(event) => {
- if (event.key === 'Escape') {
- event.preventDefault();
- closeAndReset();
- return;
- }
-
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- event.preventDefault();
- focusAdjacentOption(currentOptionIndex, event.key === 'ArrowDown' ? 1 : -1);
- }
- }}
- transitionDuration="faster"
- >
- <Icon
- as={CheckIcon}
- aria-hidden
- boxSize="3"
- color="accent.solid"
- flexShrink={0}
- opacity={value === model.key ? 1 : 0}
- />
- <ModelOptionContent enableDescription={enableModelDescriptions} model={model} />
- </Button>
- );
- })}
- </Stack>
- ))
- : null}
- </ScrollArea.Content>
- </ScrollArea.Viewport>
- <ScrollArea.Scrollbar>
- <ScrollArea.Thumb />
- </ScrollArea.Scrollbar>
- </ScrollArea.Root>
+ <Button size="2xs" variant="outline" onClick={() => void ensureModelsLoaded()}>
+ Retry
+ </Button>
+ </Stack>
+ ) : candidates.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs" p="2">
+ No compatible {scopeLabel} installed.
+ </Text>
+ ) : undefined
+ }
+ toolbarSlot={
+ availableBases.length >= 2 ? (
+ <HStack alignItems="center" flexWrap="wrap" gap="1">
+ {availableBases.map((base) => (
+ <BaseChip key={base} base={base} isSelected={selectedBases.has(base)} onToggle={toggleBase} />
+ ))}
+ <Spacer />
+ <IconButton
+ aria-label="Reset base filters"
+ flexShrink={0}
+ opacity={selectedBases.size === 0 ? 0.5 : undefined}
+ pointerEvents={selectedBases.size === 0 ? 'none' : undefined}
+ size="2xs"
+ variant="ghost"
+ onClick={() => setSelectedBases(EMPTY_BASES)}
+ >
+ <Icon as={RotateCcwIcon} boxSize="3" />
+ </IconButton>
+ </HStack>
+ ) : null
+ }
+ onSelect={selectModel}
+ />
</Popover.Content>
</Popover.Positioner>
</Portal>
@@ -423,6 +340,67 @@ export const ModelSelect = ({
);
};
+/** Search over the facts a user actually types: name, base, type, description. */
+const matchesModel = (model: ModelConfig, searchTerm: string): boolean => {
+ const terms = searchTerm.toLowerCase().split(/\s+/).filter(Boolean);
+ const haystack = `${model.name} ${model.base} ${model.type} ${model.description ?? ''}`.toLowerCase();
+
+ return terms.every((term) => haystack.includes(term));
+};
+
+/**
+ * Models linked to the current selection, so they can lead their group. The
+ * backend exposes only a single-key lookup, so this is scoped to "related to
+ * what is selected here" rather than to everything selected app-wide.
+ */
+const useRelatedModelKeys = (modelKey: string | null): ReadonlySet<string> => {
+ const [relatedKeys, setRelatedKeys] = useState<ReadonlySet<string>>(EMPTY_KEYS);
+
+ useEffect(() => {
+ if (!modelKey) {
+ setRelatedKeys(EMPTY_KEYS);
+ return;
+ }
+
+ const controller = new AbortController();
+
+ getRelatedModelKeys(modelKey, controller.signal)
+ .then((keys) => {
+ if (!controller.signal.aborted) {
+ setRelatedKeys(new Set(keys));
+ }
+ })
+ .catch(() => {
+ // A missing relationship list is not worth surfacing; the picker just
+ // loses its pinning.
+ });
+
+ return () => controller.abort();
+ }, [modelKey]);
+
+ return relatedKeys;
+};
+
+const CompactViewToggle = ({ isCompact, pickerId }: { isCompact: boolean; pickerId: string }) => {
+ const label = isCompact ? 'Full rows' : 'Compact rows';
+ const handleClick = useCallback(() => setPickerCompactView(pickerId, !isCompact), [isCompact, pickerId]);
+
+ return (
+ <Tooltip content={label} showArrow>
+ <IconButton
+ aria-label={label}
+ aria-pressed={isCompact}
+ flexShrink={0}
+ size="xs"
+ variant="ghost"
+ onClick={handleClick}
+ >
+ <Icon as={isCompact ? ChevronsUpDownIcon : ChevronsDownUpIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ );
+};
+
const ModelManagerLinkButton = () => {
const { managerProjectId } = useModelsUi();
const search = useMemo(() => ({ project: managerProjectId ?? undefined }), [managerProjectId]);
@@ -491,22 +469,63 @@ const ModelButtonContent = ({ model }: { model: ModelConfig }) => (
</HStack>
);
-// No per-item base badge: the list is grouped by (type, base), so the group
-// header already carries that information.
-const ModelOptionContent = ({ enableDescription, model }: { enableDescription: boolean; model: ModelConfig }) => (
- <HStack flex="1" gap="2" minW="0" textAlign="left" w="full">
- <Stack flex="1" gap="0" minW="0">
- <Text fontSize="xs" minW="0" truncate>
- {model.name}
- </Text>
- {enableDescription && model.description ? (
- <Text color="fg.subtle" fontSize="2xs" lineClamp={2}>
- {model.description}
- </Text>
+/**
+ * No base badge: the group header already carries it. The type badge appears
+ * only in cross-type pickers, where two rows could otherwise look identical.
+ */
+const ModelOptionContent = ({
+ enableDescription,
+ isRelated,
+ model,
+ showType,
+ state,
+}: {
+ enableDescription: boolean;
+ isRelated: boolean;
+ model: ModelConfig;
+ showType: boolean;
+ state: PickerOptionState;
+}) => {
+ const showDetail = !state.isCompact;
+
+ return (
+ <HStack gap="2" minW="0" textAlign="left" w="full">
+ <Icon
+ as={CheckIcon}
+ aria-hidden
+ boxSize="3"
+ color="accent.solid"
+ flexShrink={0}
+ opacity={state.isSelected ? 1 : 0}
+ />
+ {showDetail && model.cover_image ? (
+ <Image alt="" boxSize="8" flexShrink={0} objectFit="cover" rounded="sm" src={getModelImageUrl(model.key)} />
) : null}
- </Stack>
- <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
- {formatBytes(model.file_size)}
- </Text>
- </HStack>
-);
+ <Stack flex="1" gap="0" minW="0">
+ <HStack gap="1.5" minW="0">
+ {isRelated ? (
+ <Tooltip content="Linked to the current selection">
+ <Icon as={LinkIcon} aria-label="Linked model" boxSize="3" color="accent.solid" flexShrink={0} />
+ </Tooltip>
+ ) : null}
+ <Text fontSize="xs" minW="0" truncate>
+ {model.name}
+ </Text>
+ {showType ? (
+ <Badge colorPalette="gray" flexShrink={0} fontSize="2xs" size="xs" variant="surface">
+ {getModelTypeLabel(model.type)}
+ </Badge>
+ ) : null}
+ </HStack>
+ {showDetail && enableDescription && model.description ? (
+ <Text color="fg.subtle" fontSize="2xs" lineClamp={2}>
+ {model.description}
+ </Text>
+ ) : null}
+ </Stack>
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs" fontStyle="italic">
+ {formatBytes(model.file_size)}
+ </Text>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
index ba130f29c6..f481d4d143 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
@@ -40,6 +40,8 @@ export interface ModelsUiSnapshot {
queueExpanded: boolean;
/** Scroll offsets per library-list instance, restored on remount. */
libraryScrollOffsets: Record<string, number>;
+ /** Compact/full row density per picker id, remembered across opens. */
+ pickerCompactViews: Record<string, boolean>;
}
const createInitialModelsUiSnapshot = (): ModelsUiSnapshot => ({
@@ -48,6 +50,7 @@ const createInitialModelsUiSnapshot = (): ModelsUiSnapshot => ({
filters: { ...DEFAULT_LIBRARY_FILTERS },
hfLookup: null,
libraryScrollOffsets: {},
+ pickerCompactViews: {},
queueExpanded: false,
scan: null,
selectedKeys: new Set(),
@@ -119,6 +122,16 @@ export const saveLibraryScrollOffset = (instanceId: string, offset: number): voi
export const getLibraryScrollOffset = (instanceId: string): number =>
store.getSnapshot().libraryScrollOffsets[instanceId] ?? 0;
+/** Row density is a per-picker preference, so sibling pickers of a kind agree. */
+export const setPickerCompactView = (pickerId: string, isCompact: boolean): void => {
+ const snapshot = store.getSnapshot();
+
+ updateModelsUi({ pickerCompactViews: { ...snapshot.pickerCompactViews, [pickerId]: isCompact } });
+};
+
+export const getPickerCompactView = (pickerId: string): boolean =>
+ store.getSnapshot().pickerCompactViews[pickerId] ?? false;
+
export const useModelsUiSelector = store.useSelector;
export const useModelsUi = (): ModelsUiSnapshot => store.useSnapshot();