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): show only settings that can be edited where they are opened
Josh Corbett75332c6befb9
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts b/invokeai/frontend/webv2/src/features/intermediates/data/focus.tsindex 60023f2a1b..45354e55dd 100644--- a/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts+++ b/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts@@ -1,6 +1,9 @@import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';+/** The settings entry the manager lives in; entry points reveal it so focus lands in the manager. */+export const INTERMEDIATES_SETTING_ID = 'intermediatesManager';+/*** What an entry point wants the manager to start on: a project to preselect, or an account to filter by. The manager* reads it while rendering and consumes it once that render commits, so a discarded render cannot lose it and adiff --git a/invokeai/frontend/webv2/src/features/intermediates/index.ts b/invokeai/frontend/webv2/src/features/intermediates/index.tsindex 9b395b3ec7..9567c6bbb8 100644--- a/invokeai/frontend/webv2/src/features/intermediates/index.ts+++ b/invokeai/frontend/webv2/src/features/intermediates/index.ts@@ -1 +1 @@-export { requestIntermediatesFocus } from './data/focus';+export { INTERMEDIATES_SETTING_ID, requestIntermediatesFocus } from './data/focus';diff --git a/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts b/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.tsindex e5ab007225..8a79c92fc1 100644--- a/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts+++ b/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts@@ -1,12 +1,14 @@import type { SettingsContribution } from '@platform/ui/settings/contracts';+import { INTERMEDIATES_SETTING_ID } from './data/focus';+/** Metadata only: the manager and its transport load when the section opens. */export const intermediatesSettingsContribution: SettingsContribution = {id: 'intermediates',label: (t) => t('intermediates.title'),fields: [{- id: 'intermediatesManager',+ id: INTERMEDIATES_SETTING_ID,kind: 'custom',fill: true,label: (t) => t('intermediates.title'),diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts b/invokeai/frontend/webv2/src/platform/ui/settings/contracts.tsindex 24b7578c16..481be52669 100644--- a/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts@@ -32,6 +32,8 @@ export interface SettingFieldProps {field: SettingDefinition;surface: 'quick' | 'dialog';target?: SettingsTarget;+ /** Shows another setting on the surface hosting this one (the dialog or the Launchpad page). */+ onReveal?: (sectionId: string, entryId: string) => void;}export interface SettingsContribution {diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsxindex 523840191c..b9d847fa30 100644--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx@@ -15,6 +15,7 @@ import { recallProjectPromptHistoryItem, selectProjectGenerateModel } from '@worimport { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';import { getLayoutPresetCommandTitleOverrides } from '@workbench/layoutPresetSnapshots';import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';+import { useAvailableSettings } from '@workbench/settings/useAvailableSettings';import { useNotify } from '@workbench/useNotify';import { getProjectWidgetValues } from '@workbench/widgetState';import {@@ -87,6 +88,7 @@ const WorkbenchCommandPaletteDialog = ({const presentWidgetTypeIds = useActiveProjectSelector((project) =>[...new Set(Object.values(project.widgetInstances).map((instance) => instance.typeId))].sort());+ const settingsSections = useAvailableSettings();const paletteStore = extensions.stores.palette;const paletteContributions = useSyncExternalStore(paletteStore.subscribe, paletteStore.list, paletteStore.list);const commandTitleOverrides = useMemo(@@ -127,7 +129,7 @@ const WorkbenchCommandPaletteDialog = ({formatHotkey)),- ...buildSettingsEntries(preferences, settingsEntryDeps, t),+ ...buildSettingsEntries(preferences, settingsEntryDeps, t, settingsSections),],[catalog,@@ -139,6 +141,7 @@ const WorkbenchCommandPaletteDialog = ({preferences,presentWidgetTypeIds,settingsEntryDeps,+ settingsSections,t,]);diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.tsindex 8ebc4f8de9..95c8a6d31e 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts@@ -1,5 +1,6 @@import type { DateRange } from '@platform/search/dateTokens';import type { CustomHotkeys, HotkeyDefinition } from '@workbench/hotkeys/types';+import type { SettingsSection } from '@workbench/settings/catalog';import type { SettingsDestination, SettingsSectionId, WorkbenchPreferences } from '@workbench/settings/contracts';import type { TFunction } from 'i18next';@@ -305,10 +306,12 @@ export const buildOpenSettingsEntry = (t: TFunction, openSettings: () => void, ktitle: t('commandPalette.appEntries.openSettings'),});+/** `sections` are the settings the host can edit (see `useAvailableSettings`); the whole catalog by default. */export const buildSettingsEntries = (preferences: WorkbenchPreferences,deps: SettingsEntryDeps,- t: TFunction+ t: TFunction,+ sections: readonly SettingsSection[] = settingsCatalog): PaletteEntry[] => {const directPreferenceIds = new Set(preferenceSettingsFields.map(({ field }) => field.id));directPreferenceIds.add('themeId');@@ -392,7 +395,7 @@ export const buildSettingsEntries = (title: themeTitle,};- const sections = settingsCatalog.map<PaletteEntry>(({ id, label }) => ({+ const sectionEntries = sections.map<PaletteEntry>(({ id, label }) => ({group: 'Settings',groupLabel: t('commandPalette.groups.settings'),id: `settings.section.${id}`,@@ -401,7 +404,7 @@ export const buildSettingsEntries = (run: () => deps.openSettingsSection(id),title: t('commandPalette.settings.settingsSection', { section: resolveSettingsText(label, t) }),}));- const fields = settingsCatalog.flatMap((section) =>+ const fields = sections.flatMap((section) =>section.entries.filter(({ field }) => field.scope !== 'preference' || !directPreferenceIds.has(field.id)).map<PaletteEntry>(({ field }) => ({@@ -422,7 +425,7 @@ export const buildSettingsEntries = (})));- return [...preferenceEntries, themeEntry, ...sections, ...fields];+ return [...preferenceEntries, themeEntry, ...sectionEntries, ...fields];};interface RankedEntry {diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsxindex a791c7d752..1376ecda74 100644--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx@@ -10,7 +10,7 @@ import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { appearanceSettings, developerSettings, hotkeysSettings } from './applicationContributions';+import { appearanceSettings, developerSettings, hotkeysSettings, workspaceSettings } from './applicationContributions';import CustomSettingField from './CustomSettingsEditors';import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from './store';@@ -27,12 +27,12 @@ await i18n.use(initReactI18next).init({(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let host: HTMLDivElement;let root: Root;-const render = async (field: SettingDefinition) => {+const render = async (field: SettingDefinition, onReveal?: (sectionId: string, entryId: string) => void) => {await act(() =>root.render(<ChakraProvider value={system}><I18nextProvider i18n={i18n}>- <CustomSettingField field={field} surface="dialog" />+ <CustomSettingField field={field} surface="dialog" onReveal={onReveal} /></I18nextProvider></ChakraProvider>)@@ -134,3 +134,15 @@ describe('custom setting modified indicators', () => {expect(snapshotWarnings).toEqual([]);});});++describe('workspace settings', () => {+ it('opens the intermediates manager through the surface hosting it', async () => {+ const onReveal = vi.fn();+ await render(workspaceSettings.fields[0]!, onReveal);+ const manage = [...host.querySelectorAll('button')].find(+ (button) => button.textContent === i18n.t('settings.catalog.manageIntermediates')+ );+ await act(() => manage!.click());+ expect(onReveal).toHaveBeenCalledWith('intermediates', 'intermediatesManager');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsxindex 573fd1d9a9..246e395546 100644--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx@@ -3,6 +3,7 @@ import type { SettingFieldProps } from '@platform/ui/settings/contracts';import type { WorkbenchThemeId } from '@theme/themes';import { Box, chakra, Checkbox, Flex, HStack, Icon, SimpleGrid, Stack, Text, useSlotRecipe } from '@chakra-ui/react';+import { INTERMEDIATES_SETTING_ID } from '@features/intermediates';import { Button, ConfirmDialog } from '@platform/ui';import { resolveSettingsText } from '@platform/ui/settings/contracts';import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';@@ -20,7 +21,6 @@ import { clearWorkspaceData, rememberWorkspaceClearFailure } from './clearWorkspimport { GenerationDevicesSettings } from './GenerationDevicesSettings';import { HotkeysSettingsSection } from './HotkeysSettingsSection';import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';-import { setWorkbenchSettingsSection } from './settingsDialogStore';import {clearWorkbenchSettings,DEFAULT_PREFERENCES,@@ -159,7 +159,7 @@ export const LoggingResetSettings = () => {);};-export const WorkspaceSettings = () => {+export const WorkspaceSettings = ({ onReveal }: Pick<SettingFieldProps, 'onReveal'>) => {const { t } = useTranslation();const commands = useOptionalWorkbenchCommands();const mountedPersistence = useOptionalWorkbenchPersistenceService();@@ -185,7 +185,7 @@ export const WorkspaceSettings = () => {const resetLayout = useCallback(() => commands?.layout.reset(), [commands]);const openClearConfirm = useCallback(() => setIsClearConfirmOpen(true), []);const closeClearConfirm = useCallback(() => setIsClearConfirmOpen(false), []);- const openIntermediates = useCallback(() => setWorkbenchSettingsSection('intermediates', 'intermediatesManager'), []);+ const openIntermediates = useCallback(() => onReveal?.('intermediates', INTERMEDIATES_SETTING_ID), [onReveal]);return (<Stack gap="3">@@ -196,10 +196,12 @@ export const WorkspaceSettings = () => {Reset layout</Button>) : null}- <Button size="sm" variant="outline" onClick={openIntermediates}>- <BrushCleaningIcon />- {t('settings.catalog.manageIntermediates')}- </Button>+ {onReveal ? (+ <Button size="sm" variant="outline" onClick={openIntermediates}>+ <BrushCleaningIcon />+ {t('settings.catalog.manageIntermediates')}+ </Button>+ ) : null}<ButtonborderColor="border.emphasized"color="fg.error"@@ -234,7 +236,7 @@ const formatSettingLabel = (value: string): string =>.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ');-const CustomSettingField = ({ field }: SettingFieldProps) => {+const CustomSettingField = ({ field, onReveal }: SettingFieldProps) => {const { t } = useTranslation();const isModified = useWorkbenchPreferenceSelector((preferences) => {if (field.id === 'themeId') {@@ -262,7 +264,7 @@ const CustomSettingField = ({ field }: SettingFieldProps) => {editor = <LoggingResetSettings />;break;case 'workspaceActions':- editor = <WorkspaceSettings />;+ editor = <WorkspaceSettings onReveal={onReveal} />;break;case 'about':editor = <AboutSettings />;diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsBrowseBody.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsBrowseBody.tsxnew file mode 100644index 0000000000..a36acb2058--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsBrowseBody.tsx@@ -0,0 +1,222 @@+import type { SettingsTarget } from '@platform/ui/settings/contracts';+import type { ChangeEvent, Ref, UIEventHandler } from 'react';++import { Box, HStack, Icon, Input, InputGroup, Kbd, Stack, Text, VisuallyHidden } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { Scrollable } from '@platform/ui/Scrollable';+import { resolveSettingsText } from '@platform/ui/settings/contracts';+import { SearchIcon, XIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type { SettingsSection } from './catalog';++import { isFillSettingsEntry, SettingsEntryView } from './SettingsEntryView';+import { SettingsScopeLabel } from './SettingsScopeLabel';+import { patchWorkbenchPreferences, useWorkbenchSettingsSelector } from './store';++const CONTENT_PADDING = { base: '4', md: '6' };+const FILL_SECTION_PROPS = { display: 'flex', flex: '1', flexDirection: 'column', minH: '0' } as const;+const FILL_BODY_PROPS = { ...FILL_SECTION_PROPS, pb: '4' } as const;+const BODY_CONTENT_PROPS = { px: CONTENT_PADDING, pb: '4' } as const;+const retrySave = () => {+ void patchWorkbenchPreferences({});+};+const SEARCH_START_ELEMENT = <Icon as={SearchIcon} boxSize="3.5" color="fg.muted" />;+/** The `/` shortcut its surface handles with `focusSettingsSearchOnSlash`. */+const SEARCH_HOTKEY_HINT = (+ <Kbd aria-hidden pointerEvents="none" size="sm" variant="outline">+ /+ </Kbd>+);++export const SettingsSearchField = ({+ onChange,+ size,+ value,+}: {+ onChange: (query: string) => void;+ size: 'xs' | 'sm';+ value: string;+}) => {+ const { t } = useTranslation();+ const change = useCallback((event: ChangeEvent<HTMLInputElement>) => onChange(event.target.value), [onChange]);+ const clear = useCallback(() => onChange(''), [onChange]);+ // The end slot is a clear control while there is a query, and the `/` hint otherwise.+ const endElement = useMemo(+ () =>+ value ? (+ <Button aria-label={t('settingsDialog.clearSearch')} me="-2" size="2xs" variant="ghost" onClick={clear}>+ <XIcon />+ </Button>+ ) : (+ SEARCH_HOTKEY_HINT+ ),+ [clear, t, value]+ );+ return (+ <InputGroup endElement={endElement} startElement={SEARCH_START_ELEMENT}>+ <Input+ data-settings-search+ aria-label={t('settingsDialog.search')}+ placeholder={t('settingsDialog.search')}+ value={value}+ size={size}+ onChange={change}+ />+ </InputGroup>+ );+};++export interface SettingsBrowseBodyProps {+ displayed: readonly SettingsSection[];+ searching: boolean;+ /** Matching entries across every section while searching. */+ count: number;+ /** Changes when the shown content changes, so the scroll region starts fresh. */+ viewKey: string;+ /** A widget instance the settings were opened for, and the section it belongs to. */+ target?: { sectionId: string; target: SettingsTarget };+ revealEntryId?: string;+ onRevealed?: () => void;+ onReveal: (sectionId: string, entryId?: string) => void;+ onClearSearch: () => void;+ onScroll?: UIEventHandler<HTMLDivElement>;+ viewportRef?: Ref<HTMLDivElement>;+}++/** The part of a settings surface below its title: save errors, the shown sections, and search results. */+export const SettingsBrowseBody = ({+ count,+ displayed,+ onClearSearch,+ onReveal,+ onRevealed,+ onScroll,+ revealEntryId,+ searching,+ target,+ viewKey,+ viewportRef,+}: SettingsBrowseBodyProps) => {+ const { t } = useTranslation();+ const error = useWorkbenchSettingsSelector((snapshot) => snapshot.error);+ const viewportProps = useMemo(() => ({ onScroll }), [onScroll]);+ const sectionProps = { onReveal, onRevealed, revealEntryId };+ // A filling editor (the hotkeys table) scrolls itself: the body hands it the+ // height instead of wrapping it in a second scroll container.+ const fills =+ !searching && displayed.length === 1 && displayed[0].entries.some((entry) => isFillSettingsEntry(entry, 'dialog'));+ return (+ <>+ {error ? (+ <HStack role="alert" px="4" py="2" bg="bg.error">+ <Text fontSize="xs" color="fg.error" flex="1">+ {error}+ </Text>+ <Button size="xs" onClick={retrySave}>+ {t('common.retry')}+ </Button>+ </HStack>+ ) : null}+ <VisuallyHidden role="status">{searching ? t('settingsDialog.resultCount', { count }) : ''}</VisuallyHidden>+ {fills ? (+ <Box key={viewKey} px={CONTENT_PADDING} {...FILL_BODY_PROPS}>+ {displayed.map((section) => (+ <SettingsSectionContent+ key={section.id}+ fill+ section={section}+ search={false}+ target={target?.sectionId === section.id ? target.target : undefined}+ {...sectionProps}+ />+ ))}+ </Box>+ ) : (+ <Scrollable+ key={viewKey}+ contentProps={BODY_CONTENT_PROPS}+ flex="1"+ minH="0"+ viewportProps={viewportProps}+ viewportRef={viewportRef}+ >+ {displayed.map((section) => (+ <SettingsSectionContent+ key={section.id}+ section={section}+ search={searching}+ target={target?.sectionId === section.id ? target.target : undefined}+ {...sectionProps}+ />+ ))}+ {searching && !displayed.length ? (+ <Stack align="center" py="12" gap="3">+ <Text color="fg.muted">{t('settingsDialog.noResults')}</Text>+ <Button size="sm" variant="outline" onClick={onClearSearch}>+ {t('settingsDialog.clearSearch')}+ </Button>+ </Stack>+ ) : null}+ </Scrollable>+ )}+ </>+ );+};++const SettingsSectionContent = ({+ fill = false,+ section,+ search,+ target,+ onReveal,+ revealEntryId,+ onRevealed,+}: {+ fill?: boolean;+ section: SettingsSection;+ search: boolean;+ target?: SettingsTarget;+ onReveal: (sectionId: string, entryId?: string) => void;+ revealEntryId?: string;+ onRevealed?: () => void;+}) => {+ const { t } = useTranslation();+ return (+ <Box {...(fill ? FILL_SECTION_PROPS : undefined)}>+ {!search && section.entries[0] ? (+ <Box pt="3">+ <SettingsScopeLabel scope={section.entries[0].field.scope} />+ </Box>+ ) : null}+ {search ? (+ <Stack gap="0.5" pt="5">+ <Text as="h3" fontWeight="600" fontSize="sm">+ {resolveSettingsText(section.label, t)}+ </Text>+ {section.entries[0] ? <SettingsScopeLabel scope={section.entries[0].field.scope} /> : null}+ </Stack>+ ) : null}+ {section.entries.map((entry, index) => (+ <SettingsEntryView+ key={entry.field.id}+ entry={entry}+ section={section}+ target={target}+ search={search}+ revealEntryId={revealEntryId}+ onReveal={onReveal}+ onRevealed={onRevealed}+ showGroup={Boolean(+ entry.field.group &&+ resolveSettingsText(entry.field.group, t) !==+ (section.entries[index - 1]?.field.group+ ? resolveSettingsText(section.entries[index - 1].field.group!, t)+ : '')+ )}+ />+ ))}+ </Box>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsxindex 4f49f2c164..7a50c542a6 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx@@ -35,8 +35,16 @@ vi.mock('./CustomSettingsEditors', () => ({default: ({ field }: SettingFieldProps) => <div data-custom-editor={field.id}>Custom settings editor</div>,}));+const testProject = {+ id: 'settings-test-project',+ settings: { antialiasProgressImages: true, showProgressImagesInViewer: true, useCpuNoise: false },+ widgetInstances: { 'settings-test-widget': { id: 'settings-test-widget', typeId: 'queue' } },+};+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof workbenchContext>()),+ useOptionalWorkbenchSelector: (selector: (snapshot: never) => unknown) =>+ selector({ activeProject: testProject } as never),useActiveProjectId: () => 'settings-test-project',useWorkbenchQueries: () => ({isActiveProject: (projectId: string) => projectId === 'settings-test-project',@@ -152,6 +160,21 @@ describe('settings dialog', () => {await expect.element(modifiedIndicator).not.toBeInTheDocument();});+ it('lists project settings, and widget settings only for widgets in the open project', async () => {+ await render();+ await open();+ const nav = page.getByRole('navigation', { name: i18n.t('settings.title'), exact: true });+ await expect.element(nav.getByRole('button', { name: 'Project', exact: true })).toBeVisible();+ await expect.element(nav.getByRole('button', { name: 'Queue', exact: true })).toBeVisible();+ // Canvas settings are all per widget and this project has no canvas; Preview keeps its project setting.+ await expect.element(nav.getByRole('button', { name: 'Canvas', exact: true })).not.toBeInTheDocument();+ await act(() => nav.getByRole('button', { name: 'Preview', exact: true }).click());+ await expect.element(page.getByText('Antialias progress images', { exact: true })).toBeVisible();+ await expect+ .element(page.getByText(i18n.t('settingsDialog.instanceUnavailable'), { exact: true }))+ .not.toBeInTheDocument();+ });+it('switches prepared sections without loading placeholders or mounting unselected custom editors', async () => {await render();const mountedCustomEditors: string[] = [];diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex f818353915..3f8b225649 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -1,20 +1,6 @@import type { ChangeEvent, UIEvent } from 'react';-import {- Box,- Dialog,- Flex,- HStack,- Icon,- Input,- InputGroup,- Kbd,- NativeSelect,- Stack,- Text,- VisuallyHidden,-} from '@chakra-ui/react';-import { useCapabilities } from '@features/identity';+import { Box, Dialog, Flex, HStack, Icon, NativeSelect, Stack, Text, VisuallyHidden } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';import { Button } from '@platform/ui/Button';import { PanelHeader } from '@platform/ui/PanelHeader';@@ -26,13 +12,14 @@ import {useWorkbenchQueries,useWorkbenchSubscription,} from '@workbench/WorkbenchContext';-import { SearchIcon, XIcon } from 'lucide-react';+import { SearchIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import type { SettingsSection } from './catalog';-import { searchSettings, settingsCatalog } from './catalog';+import { browseSettings, isSettingsQuery, settingsCatalog } from './catalog';+import { SettingsBrowseBody, SettingsSearchField } from './SettingsBrowseBody';import {closeWorkbenchSettings,getSettingsSectionScroll,@@ -41,9 +28,7 @@ import {setWorkbenchSettingsSection,settingsDialogStore,} from './settingsDialogStore';-import { isFillSettingsEntry, SettingsEntryView } from './SettingsEntryView';-import { SettingsScopeLabel } from './SettingsScopeLabel';-import { patchWorkbenchPreferences, useWorkbenchSettingsSelector } from './store';+import { useAvailableSettings } from './useAvailableSettings';/** Warm code, never mounted editors or data queries, before exposing section navigation. */export const prepareSettingsDialog = async (): Promise<void> => {@@ -62,28 +47,14 @@ const SIDEBAR_BOTTOM_BORDER = { base: '1px', sm: '0' };const SEARCH_PADDING = { base: '12', sm: '3' };const MOBILE_DISPLAY = { base: 'block', sm: 'none' };const DESKTOP_DISPLAY = { base: 'none', sm: 'block' };-const CONTENT_PADDING = { base: '4', md: '6' };const rememberScroll = (event: UIEvent<HTMLDivElement>) => {const current = settingsDialogStore.getSnapshot();if (!current.query.trim()) {rememberSettingsSectionScroll(current.sectionId, event.currentTarget.scrollTop);}};-const SEARCH_START_ELEMENT = <Icon as={SearchIcon} boxSize="3.5" color="fg.muted" />;-/** The `/` shortcut the dialog content handles (see `SettingsDialogHost`). */-const SEARCH_HOTKEY_HINT = (- <Kbd aria-hidden pointerEvents="none" size="sm" variant="outline">- /- </Kbd>-);-const FILL_SECTION_PROPS = { display: 'flex', flex: '1', flexDirection: 'column', minH: '0' } as const;-const FILL_BODY_PROPS = { ...FILL_SECTION_PROPS, pb: '4' } as const;-const BODY_VIEWPORT_PROPS = { onScroll: rememberScroll };-const BODY_CONTENT_PROPS = { px: CONTENT_PADDING, pb: '4' } as const;const clearSearch = () => setSettingsQuery('');-const retrySave = () => {- void patchWorkbenchPreferences({});-};+const clearRevealedEntry = () => settingsDialogStore.patchSnapshot({ entryId: undefined });const ProjectLifetime = () => {const projectId = useActiveProjectId();@@ -102,55 +73,38 @@ const ProjectLifetime = () => {const SettingsDialog = () => {const { t } = useTranslation();const hasWorkbench = useHasWorkbenchProvider();- const { canManageAppConfig } = useCapabilities();const state = settingsDialogStore.useSelector((snapshot) => snapshot);- const error = useWorkbenchSettingsSelector((snapshot) => snapshot.error);- const sections = settingsCatalog.filter((section) => section.id !== 'server' || canManageAppConfig);- const active = sections.find((section) => section.id === state.sectionId) ?? sections[0];- const searching = state.query.trim().length > 0;- const matches = searchSettings(sections, state.query, t);- const displayed = searching- ? matches.filter((section) => !state.searchSection || section.id === state.searchSection)- : [active];- const count = matches.reduce((total, section) => total + section.entries.length, 0);+ const sections = useAvailableSettings();+ const { active, count, displayed, matches, searching } = browseSettings(+ sections,+ { activeId: state.sectionId, query: state.query, searchSection: state.searchSection },+ t+ );const selectSection = useCallback((sectionId: string) => {- if (searching) {+ if (isSettingsQuery(state.query)) {settingsDialogStore.patchSnapshot({ searchSection: sectionId || null });} else {setWorkbenchSettingsSection(sectionId);}},- [searching]+ [state.query]);const selectAllResults = useCallback(() => selectSection(''), [selectSection]);const changeSection = useCallback((event: ChangeEvent<HTMLSelectElement>) => selectSection(event.target.value),[selectSection]);- const changeQuery = useCallback((event: ChangeEvent<HTMLInputElement>) => setSettingsQuery(event.target.value), []);- // The end slot is a clear control while there is a query, and the `/` hint otherwise.- const searchEndElement = useMemo(- () =>- state.query ? (- <Button aria-label={t('settingsDialog.clearSearch')} me="-2" size="2xs" variant="ghost" onClick={clearSearch}>- <XIcon />- </Button>- ) : (- SEARCH_HOTKEY_HINT- ),- [state.query, t]- );const attachBody = useCallback((element: HTMLDivElement | null) => {const current = settingsDialogStore.getSnapshot();if (element && !current.query.trim() && !current.entryId) {element.scrollTop = getSettingsSectionScroll(current.sectionId);}}, []);- // A filling editor (the hotkeys table) scrolls itself: the body hands it the- // height instead of wrapping it in a second scroll container.- const fills =- !searching && displayed.length === 1 && displayed[0].entries.some((entry) => isFillSettingsEntry(entry, 'dialog'));+ const target = useMemo(+ () => (state.target ? { sectionId: state.sectionId, target: state.target } : undefined),+ [state.sectionId, state.target]+ );return (<Flex h="full" minH="0" direction={DIRECTION}>{hasWorkbench ? <ProjectLifetime /> : null}@@ -166,16 +120,7 @@ const SettingsDialog = () => {minH="0"><Box p="3" pe={SEARCH_PADDING}>- <InputGroup endElement={searchEndElement} startElement={SEARCH_START_ELEMENT}>- <Input- data-settings-search- aria-label={t('settingsDialog.search')}- placeholder={t('settingsDialog.search')}- value={state.query}- size="sm"- onChange={changeQuery}- />- </InputGroup>+ <SettingsSearchField size="sm" value={state.query} onChange={setSettingsQuery} /></Box><Box display={MOBILE_DISPLAY} px="3" pb="3"><NativeSelect.Root size="sm">@@ -185,7 +130,7 @@ const SettingsDialog = () => {onChange={changeSection}>{searching ? <option value="">{t('settingsDialog.allResults')}</option> : null}- {(searching ? matches : sections).map((section) => (+ {matches.map((section) => (<option key={section.id} value={section.id}>{resolveSettingsText(section.label, t)}</option>@@ -208,7 +153,7 @@ const SettingsDialog = () => {</Button>) : null}{GROUPS.map((group) => {- const groupSections = (searching ? matches : sections).filter((section) => section.group === group);+ const groupSections = matches.filter((section) => section.group === group);if (!groupSections.length) {return null;}@@ -243,56 +188,19 @@ const SettingsDialog = () => {</HStack></PanelHeader></Dialog.Header>- {error ? (- <HStack role="alert" px="4" py="2" bg="bg.error">- <Text fontSize="xs" color="fg.error" flex="1">- {error}- </Text>- <Button size="xs" onClick={retrySave}>- {t('common.retry')}- </Button>- </HStack>- ) : null}- <VisuallyHidden role="status">{searching ? t('settingsDialog.resultCount', { count }) : ''}</VisuallyHidden>- {fills ? (- <Box key={active.id} px={CONTENT_PADDING} {...FILL_BODY_PROPS}>- {displayed.map((section) => (- <SettingsSectionContent- key={section.id}- fill- section={section}- search={false}- onReveal={setWorkbenchSettingsSection}- />- ))}- </Box>- ) : (- <Scrollable- key={searching ? `search:${state.searchSection ?? ''}` : active.id}- contentProps={BODY_CONTENT_PROPS}- flex="1"- minH="0"- viewportProps={BODY_VIEWPORT_PROPS}- viewportRef={attachBody}- >- {displayed.map((section) => (- <SettingsSectionContent- key={section.id}- section={section}- search={searching}- onReveal={setWorkbenchSettingsSection}- />- ))}- {searching && !displayed.length ? (- <Stack align="center" py="12" gap="3">- <Text color="fg.muted">{t('settingsDialog.noResults')}</Text>- <Button size="sm" variant="outline" onClick={clearSearch}>- {t('settingsDialog.clearSearch')}- </Button>- </Stack>- ) : null}- </Scrollable>- )}+ <SettingsBrowseBody+ count={count}+ displayed={displayed}+ revealEntryId={state.entryId}+ searching={searching}+ target={target}+ viewKey={searching ? `search:${state.searchSection ?? ''}` : active.id}+ viewportRef={attachBody}+ onClearSearch={clearSearch}+ onReveal={setWorkbenchSettingsSection}+ onRevealed={clearRevealedEntry}+ onScroll={rememberScroll}+ /></Flex></Flex>);@@ -329,54 +237,4 @@ const SettingsNavigationItem = ({);};-const SettingsSectionContent = ({- fill = false,- section,- search,- onReveal,-}: {- fill?: boolean;- section: SettingsSection;- search: boolean;- onReveal: (sectionId: string, entryId?: string) => void;-}) => {- const { t } = useTranslation();- const target = settingsDialogStore.useSelector((snapshot) =>- snapshot.sectionId === section.id ? snapshot.target : undefined- );- return (- <Box {...(fill ? FILL_SECTION_PROPS : undefined)}>- {!search && section.entries[0] ? (- <Box pt="3">- <SettingsScopeLabel scope={section.entries[0].field.scope} />- </Box>- ) : null}- {search ? (- <Stack gap="0.5" pt="5">- <Text as="h3" fontWeight="600" fontSize="sm">- {resolveSettingsText(section.label, t)}- </Text>- {section.entries[0] ? <SettingsScopeLabel scope={section.entries[0].field.scope} /> : null}- </Stack>- ) : null}- {section.entries.map((entry, index) => (- <SettingsEntryView- key={entry.field.id}- entry={entry}- section={section}- target={target}- search={search}- onReveal={onReveal}- showGroup={Boolean(- entry.field.group &&- resolveSettingsText(entry.field.group, t) !==- (section.entries[index - 1]?.field.group- ? resolveSettingsText(section.entries[index - 1].field.group!, t)- : '')- )}- />- ))}- </Box>- );-};export default SettingsDialog;diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsxindex 88347f35f9..0e2bbe56d0 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx@@ -3,30 +3,12 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { CloseButton } from '@platform/ui';import { RetryBoundary } from '@platform/ui/RetryBoundary';import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';-import { Suspense, use, useMemo, type KeyboardEvent } from 'react';+import { Suspense, use, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { settingsDialogResource as dialogResource } from './dialogResource';import { closeWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';-const isEditingTarget = (target: EventTarget | null): boolean =>- target instanceof HTMLElement &&- (target.isContentEditable || ['INPUT', 'SELECT', 'TEXTAREA'].includes(target.tagName));--/** `/` from anywhere in the dialog jumps to its search, unless a field is being edited. */-const focusSearchOnSlash = (event: KeyboardEvent<HTMLDivElement>) => {- if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey || isEditingTarget(event.target)) {- return;- }-- const search = event.currentTarget.querySelector<HTMLInputElement>('[data-settings-search]');-- if (search) {- event.preventDefault();- search.focus();- search.select();- }-};-+import { focusSettingsSearchOnSlash } from './settingsSearchShortcut';const LoadedDialog = () => {const { default: SettingsDialog } = use(dialogResource.load());return <SettingsDialog />;@@ -79,7 +61,7 @@ export const SettingsDialogHost = () => {<Dialog.Contentaria-label={t('settings.title')}h="min(48rem, calc(100dvh - 2rem))"- onKeyDown={focusSearchOnSlash}+ onKeyDown={focusSettingsSearchOnSlash}maxW="64rem"w="calc(100dvw - 2rem)"overflow="hidden"diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsxindex c75f249647..0057464532 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx@@ -11,7 +11,6 @@ import { useTranslation } from 'react-i18next';import type { SettingsEntry, SettingsSection } from './catalog';-import { settingsDialogStore } from './settingsDialogStore';import { SettingsScopeLabel } from './SettingsScopeLabel';const FILL_PROPS = { display: 'flex', flex: '1', flexDirection: 'column', minH: '0' } as const;@@ -21,28 +20,34 @@ const LoadedSetting = ({fill,target,surface,+ isRevealed,+ onReveal,+ onRevealed,}: {entry: SettingsEntry;fill: boolean;target?: SettingsTarget;surface: 'quick' | 'dialog';+ isRevealed: boolean;+ onReveal?: (sectionId: string, entryId: string) => void;+ onRevealed?: () => void;}) => {const { Field } = use(entry.resource.load());const attach = useCallback((element: HTMLDivElement | null) => {- if (!element || surface !== 'dialog' || settingsDialogStore.getSnapshot().entryId !== entry.field.id) {+ if (!element || !isRevealed) {return;}const control = element.querySelector<HTMLElement>('input,button,[tabindex="0"]');element.scrollIntoView({ block: 'nearest' });control?.focus({ preventScroll: true });- settingsDialogStore.patchSnapshot({ entryId: undefined });+ onRevealed?.();},- [entry.field.id, surface]+ [isRevealed, onRevealed]);return (<Box ref={attach} {...(fill ? FILL_PROPS : undefined)}>- <Field field={entry.field} surface={surface} target={target} />+ <Field field={entry.field} surface={surface} target={target} onReveal={onReveal} /></Box>);};@@ -58,6 +63,8 @@ export const SettingsEntryView = ({surface = 'dialog',search = false,onReveal,+ revealEntryId,+ onRevealed,showGroup = false,}: {entry: SettingsEntry;@@ -66,6 +73,9 @@ export const SettingsEntryView = ({surface?: 'quick' | 'dialog';search?: boolean;onReveal?: (sectionId: string, entryId: string) => void;+ /** The entry to scroll to and focus once it loads; `onRevealed` then clears the request. */+ revealEntryId?: string;+ onRevealed?: () => void;showGroup?: boolean;}) => {const { t } = useTranslation();@@ -146,7 +156,15 @@ export const SettingsEntryView = ({retryLabel={t('common.retry')}><Suspense fallback={loading}>- <LoadedSetting entry={entry} fill={fill} target={target ?? undefined} surface={surface} />+ <LoadedSetting+ entry={entry}+ fill={fill}+ isRevealed={revealEntryId === entry.field.id}+ target={target ?? undefined}+ surface={surface}+ onReveal={onReveal}+ onRevealed={onRevealed}+ /></Suspense></RetryBoundary>)}diff --git a/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/settings/catalog.test.tsindex 2be96da880..4cc5630544 100644--- a/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts@@ -5,7 +5,7 @@ import { createInstance } from 'i18next';import { EyeIcon } from 'lucide-react';import { describe, expect, it, vi } from 'vitest';-import { buildSettingsCatalog, searchSettings } from './catalog';+import { buildSettingsCatalog, getAvailableSettings, searchSettings } from './catalog';const field = (id: string, overrides: Partial<SettingDefinition> = {}): SettingDefinition =>({ id, kind: 'boolean', label: id, scope: 'preference', ...overrides }) as SettingDefinition;@@ -143,3 +143,45 @@ describe('settings search', () => {expect(previewSettings.load).not.toHaveBeenCalled();});});++describe('settings availability', () => {+ const sections = buildSettingsCatalog(+ [+ contribution('appearance', [field('motion')]),+ contribution('project', [field('cpuNoise', { scope: 'project' })]),+ contribution('preview', [field('antialias', { scope: 'project' })]),+ contribution('server', [field('devices', { scope: 'server' })]),+ ],+ [widget(contribution('preview', [field('filmstrip', { scope: 'instance' }), field('confirm')]))]+ );+ const shown = (availability: Parameters<typeof getAvailableSettings>[1]) =>+ getAvailableSettings(sections, availability).map((section) => [+ section.id,+ section.entries.map((entry) => entry.field.id),+ ]);++ it('leaves out project and widget settings where no project is open, and sections left empty', () => {+ expect(shown({ canManageAppConfig: true, widgetTypeIds: null })).toEqual([+ ['appearance', ['motion']],+ ['preview', ['confirm']],+ ['server', ['devices']],+ ]);+ });++ it('keeps widget settings only for widgets the open project contains', () => {+ expect(shown({ canManageAppConfig: true, widgetTypeIds: new Set(['gallery']) })).toEqual([+ ['appearance', ['motion']],+ ['project', ['cpuNoise']],+ ['preview', ['confirm', 'antialias']],+ ['server', ['devices']],+ ]);+ expect(shown({ canManageAppConfig: true, widgetTypeIds: new Set(['preview']) })[2]).toEqual([+ 'preview',+ ['filmstrip', 'confirm', 'antialias'],+ ]);+ });++ it('shows the server section only to accounts that can manage the app configuration', () => {+ expect(shown({ canManageAppConfig: false, widgetTypeIds: null }).map(([id]) => id)).not.toContain('server');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/settings/catalog.ts b/invokeai/frontend/webv2/src/workbench/settings/catalog.tsindex 9954f5095b..0bcf9fe4eb 100644--- a/invokeai/frontend/webv2/src/workbench/settings/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/catalog.ts@@ -123,3 +123,56 @@ export const searchSettings = (return entries.length ? [{ ...section, entries }] : [];});};++export interface SettingsAvailability {+ canManageAppConfig: boolean;+ /** Widget types in the open project, or `null` where no project is open (the Launchpad). */+ widgetTypeIds: ReadonlySet<string> | null;+}++/** Only settings that can be edited here: project settings need a project, widget settings need that widget. */+export const getAvailableSettings = (+ sections: readonly SettingsSection[],+ { canManageAppConfig, widgetTypeIds }: SettingsAvailability+): SettingsSection[] =>+ sections.flatMap((section) => {+ if (section.id === 'server' && !canManageAppConfig) {+ return [];+ }+ const entries = section.entries.filter(({ field }) => {+ if (field.scope === 'project') {+ return widgetTypeIds !== null;+ }+ if (field.scope === 'instance') {+ return Boolean(section.widgetId && widgetTypeIds?.has(section.widgetId));+ }+ return true;+ });+ if (!entries.length) {+ return [];+ }+ return [entries.length === section.entries.length ? section : { ...section, entries }];+ });++export interface SettingsBrowseState {+ activeId: string;+ query: string;+ /** While searching, narrows the results to one section; `null` shows every match. */+ searchSection: string | null;+}++export const isSettingsQuery = (query: string): boolean => query.trim().length > 0;++/** What a settings surface shows for its section and search state; `sections` is never empty (Appearance is always available). */+export const browseSettings = (+ sections: readonly SettingsSection[],+ { activeId, query, searchSection }: SettingsBrowseState,+ t: TFunction+) => {+ const searching = isSettingsQuery(query);+ const active = sections.find((section) => section.id === activeId) ?? sections[0];+ const matches = searching ? searchSettings(sections, query, t) : [...sections];+ const displayed = searching ? matches.filter((section) => !searchSection || section.id === searchSection) : [active];+ const count = matches.reduce((total, section) => total + section.entries.length, 0);+ return { active, count, displayed, matches, searching };+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsSearchShortcut.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsSearchShortcut.tsnew file mode 100644index 0000000000..6c1fb66e01--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsSearchShortcut.ts@@ -0,0 +1,20 @@+import type { KeyboardEvent } from 'react';++const isEditingTarget = (target: EventTarget | null): boolean =>+ target instanceof HTMLElement &&+ (target.isContentEditable || ['INPUT', 'SELECT', 'TEXTAREA'].includes(target.tagName));++/** `/` inside a settings surface jumps to its search field, unless a field is being edited. */+export const focusSettingsSearchOnSlash = (event: KeyboardEvent<HTMLElement>) => {+ if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey || isEditingTarget(event.target)) {+ return;+ }++ const search = event.currentTarget.querySelector<HTMLInputElement>('[data-settings-search]');++ if (search) {+ event.preventDefault();+ search.focus();+ search.select();+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/useAvailableSettings.ts b/invokeai/frontend/webv2/src/workbench/settings/useAvailableSettings.tsnew file mode 100644index 0000000000..f6b4539082--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/useAvailableSettings.ts@@ -0,0 +1,24 @@+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';++import { useCapabilities } from '@features/identity';+import { useOptionalWorkbenchSelector } from '@workbench/WorkbenchContext';++import type { SettingsSection } from './catalog';++import { getAvailableSettings, settingsCatalog } from './catalog';++/** The open project's widget types as one stable string, so the selection only changes when the set does. */+const selectWidgetTypeKey = (snapshot: WorkbenchSnapshot): string =>+ [...new Set(Object.values(snapshot.activeProject.widgetInstances).map((instance) => instance.typeId))]+ .sort()+ .join(' ');++/** Settings editable where this renders: outside a workbench (the Launchpad) that leaves out project and widget settings. */+export const useAvailableSettings = (): SettingsSection[] => {+ const { canManageAppConfig } = useCapabilities();+ const widgetTypeKey = useOptionalWorkbenchSelector<string | null>(selectWidgetTypeKey, null);+ return getAvailableSettings(settingsCatalog, {+ canManageAppConfig,+ widgetTypeIds: widgetTypeKey === null ? null : new Set(widgetTypeKey.split(' ')),+ });+};