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): thin out the dynamic prompts controls

joshistoast387cc01b5673
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 57287d34cc..31630edcc2 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -975,7 +975,9 @@
"noWildcardsYet": "No wildcards yet. Create one to reuse a list of values as __name__.",
"insertWildcard": "Insert into the prompt",
"couldNotSaveWildcard": "Could not save this wildcard",
- "resizeWildcardValues": "Resize wildcard values"
+ "resizeWildcardValues": "Resize wildcard values",
+ "mode": "Mode",
+ "newSeedPerImage": "New seed for every image"
}
},
"upscale": {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
index b7c5772c07..111e3fa285 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
@@ -74,6 +74,13 @@ const openPopover = async () => {
await act(async () => {
await userEvent.click([...host!.querySelectorAll('button')].at(-1)!);
});
+ // The popover opens with a scale transform, and getBoundingClientRect includes
+ // transforms — measuring before it settles reports every box ~5% short.
+ await act(async () => {
+ await new Promise((resolve) => {
+ window.setTimeout(resolve, 300);
+ });
+ });
};
/**
@@ -105,18 +112,20 @@ describe('dynamic prompts popover controls', () => {
it('switches seed behaviour without tearing down the widget', async () => {
// Regression: a Chakra Select here threw `r.options is not iterable` from
// syncSelectElement as the popover opened, taking the Generate widget down
- // with it. A two-option choice is a segmented control now.
+ // with it. The seed choice is a switch now, which has no hidden native
+ // select to sync.
const onChange = vi.fn();
await render(onChange);
await openPopover();
- for (const expected of ['per-image', 'per-iteration'] as const) {
- const target = segmentLabel(expected);
+ const seedSwitch = document.querySelector<HTMLElement>('[data-scope="switch"][data-part="root"]')!;
+
+ expect(seedSwitch, 'seed switch should be rendered').toBeTruthy();
- expect(target, `${expected} should be rendered`).toBeTruthy();
+ for (const expected of ['per-image', 'per-iteration'] as const) {
await act(async () => {
- await userEvent.click(target!);
+ await userEvent.click(seedSwitch);
});
expect(onChange).toHaveBeenCalledWith({ seedBehaviour: expected });
}
@@ -125,29 +134,58 @@ describe('dynamic prompts popover controls', () => {
expect(segmentLabel('preview'), 'popover should still be mounted').toBeTruthy();
});
- it('never lets the shuffle button drive the mode row height', async () => {
- // The button used to be ~8px taller than the segmented control beside it, so
- // switching to Random visibly nudged the row. It is now always rendered (just
- // hidden) and never taller than the control, so the row is governed by the
- // segmented control in both modes.
- await render();
- await openPopover();
+ it('sends a click on the seed label to the switch, not the number input', async () => {
+ // Regression: Chakra derives the switch's label `for` from its own id
+ // counter, which collided with the number input beside it, so clicking the
+ // label focused Max prompts instead of toggling the switch.
+ const onChange = vi.fn();
- const segments = () => segmentLabel('all')!.closest('[data-scope="segment-group"][data-part="root"]')!;
- const row = () => segments().parentElement!;
- const heights = () => [row().getBoundingClientRect().height, segments().getBoundingClientRect().height];
+ await render(onChange);
+ await openPopover();
- const [combinatorialRow, combinatorialSegments] = heights();
+ const label = document.querySelector<HTMLElement>('[data-scope="switch"][data-part="label"]')!;
+ const switchRoot = document.querySelector('[data-scope="switch"][data-part="root"]')!;
+ const hiddenInput = switchRoot.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
+ const numberInput = document.querySelector<HTMLInputElement>('[data-scope="number-input"][data-part="input"]')!;
- expect(combinatorialRow).toBe(combinatorialSegments);
+ // Whether the generated ids actually collide depends on how many other
+ // controls rendered first, so this asserts the condition that caused it —
+ // two controls sharing an id — rather than relying on the ordering that
+ // happened to trip it in the app.
+ expect(hiddenInput.id).toBeTruthy();
+ expect(hiddenInput.id).not.toBe(numberInput.id);
await act(async () => {
- await userEvent.click(segmentLabel('random')!);
+ await userEvent.click(label);
});
- const [randomRow, randomSegments] = heights();
+ expect(onChange).toHaveBeenCalledWith({ seedBehaviour: 'per-image' });
+ expect(document.activeElement).not.toBe(numberInput);
+ });
+
+ it('keeps the settings row the same height in either mode', async () => {
+ // The shuffle button only applies to a random sample, so it is always
+ // rendered and merely hidden; switching modes must not reflow the row.
+ const onChange = vi.fn();
+
+ await render(onChange);
+ await openPopover();
+
+ const row = () =>
+ document.querySelector('[data-scope="menu"][data-part="trigger"]')!.closest('div')!.parentElement!;
+ const combinatorialHeight = row().getBoundingClientRect().height;
+
+ await act(async () => {
+ await userEvent.click(document.querySelector<HTMLElement>('[data-scope="menu"][data-part="trigger"]')!);
+ });
+ await act(async () => {
+ await userEvent.click(
+ [...document.querySelectorAll('[data-scope="menu"][data-part="item"]')].at(-1) as HTMLElement
+ );
+ });
- expect(randomRow).toBe(randomSegments);
+ expect(onChange).toHaveBeenCalledWith({ combinatorial: false });
+ expect(row().getBoundingClientRect().height).toBe(combinatorialHeight);
});
it('keeps the tabs to their content width rather than stretching them', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
index fe1e248695..9b89d5bf98 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
@@ -1,7 +1,7 @@
import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';
import type { DynamicPromptsExpansion } from '@features/generation/ui/useDynamicPrompts';
-import { HStack, NumberInput, SegmentGroup, Stack, Text } from '@chakra-ui/react';
+import { HStack, Menu, NumberInput, Portal, Stack, Switch, Text } from '@chakra-ui/react';
import {
createDynamicPromptsSampleSeed,
DYNAMIC_PROMPTS_MAX_PROMPTS,
@@ -10,15 +10,18 @@ import {
} from '@features/generation/core/dynamicPrompts';
import { HighlightedPrompt } from '@features/generation/ui/promptFields/PromptHighlight';
import { Button, IconButton } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
import { Scrollable } from '@platform/ui/Scrollable';
import { Tooltip } from '@platform/ui/Tooltip';
-import { ShuffleIcon } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
+import { CheckIcon, ChevronDownIcon, ShuffleIcon } from 'lucide-react';
+import { useCallback, useId, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
/** Rendering every row of a 10,000-prompt expansion would cost more than it tells the user. */
const MAX_PREVIEW_ROWS = 200;
const TABULAR_NUMS = { fontVariantNumeric: 'tabular-nums' } as const;
+const MENU_POSITIONING = { placement: 'bottom-start' } as const;
+const SWITCH_CHECKED = { bg: 'accent.solid' } as const;
export interface DynamicPromptsFieldConfig extends DynamicPromptsConfig {
onChange: (patch: Partial<DynamicPromptsConfig>) => void;
@@ -39,11 +42,16 @@ export const DynamicPromptsPanel = ({
}) => {
const { t } = useTranslation();
const { onChange } = config;
+ // Chakra derives the switch's label/input ids from its own counter, which can
+ // collide with the number input beside it and send label clicks to the wrong
+ // control. Explicit ids keep them apart.
+ const seedSwitchId = useId();
+ const seedSwitchIds = useMemo(() => ({ hiddenInput: seedSwitchId, label: `${seedSwitchId}-label` }), [seedSwitchId]);
const visiblePrompts = expansion.prompts.slice(0, MAX_PREVIEW_ROWS);
const hiddenPromptCount = expansion.prompts.length - visiblePrompts.length;
const handleModeChange = useCallback(
- (event: { value: string | null }) => onChange({ combinatorial: event.value !== 'random' }),
+ (event: { value: string }) => onChange({ combinatorial: event.value !== 'random' }),
[onChange]
);
const handleMaxPromptsChange = useCallback(
@@ -55,8 +63,7 @@ export const DynamicPromptsPanel = ({
[onChange]
);
const handleSeedBehaviourChange = useCallback(
- (event: { value: string | null }) =>
- onChange({ seedBehaviour: event.value === 'per-image' ? 'per-image' : 'per-iteration' }),
+ (event: { checked: boolean }) => onChange({ seedBehaviour: event.checked ? 'per-image' : 'per-iteration' }),
[onChange]
);
const handleShuffle = useCallback(() => onChange({ sampleSeed: createDynamicPromptsSampleSeed() }), [onChange]);
@@ -68,13 +75,9 @@ export const DynamicPromptsPanel = ({
],
[t]
);
- const seedItems = useMemo(
- () => [
- { label: t('widgets.generate.dynamicPrompts.seedPerIteration'), value: 'per-iteration' },
- { label: t('widgets.generate.dynamicPrompts.seedPerImage'), value: 'per-image' },
- ],
- [t]
- );
+ const mode = config.combinatorial ? 'all' : 'random';
+ const modeValue = useMemo(() => [mode], [mode]);
+ const modeLabel = modeItems.find((item) => item.value === mode)?.label ?? '';
const maxPromptsLabel = config.combinatorial
? t('widgets.generate.dynamicPrompts.maxPrompts')
: t('widgets.generate.dynamicPrompts.numberOfPrompts');
@@ -96,35 +99,42 @@ export const DynamicPromptsPanel = ({
</Text>
</HStack>
- {/* Shuffle only means anything for a random sample, but it is always
- rendered — merely hidden — so switching modes cannot change the row's
- shape. `visibility: hidden` also takes it out of the tab order. */}
- <HStack gap="2">
- <SegmentGroup.Root
- flex="1"
- size="xs"
- value={config.combinatorial ? 'all' : 'random'}
- onValueChange={handleModeChange}
- >
- <SegmentGroup.Indicator />
- <SegmentGroup.Items items={modeItems} />
- </SegmentGroup.Root>
- <Tooltip content={t('widgets.generate.dynamicPrompts.shuffle')}>
- <IconButton
- aria-label={t('widgets.generate.dynamicPrompts.shuffle')}
- size="2xs"
- variant="ghost"
- visibility={config.combinatorial ? 'hidden' : 'visible'}
- onClick={handleShuffle}
- >
- <ShuffleIcon />
- </IconButton>
- </Tooltip>
- </HStack>
-
<HStack align="end" gap="2">
<Stack flex="1" gap="1" minW="0">
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.subtle" fontSize="2xs" truncate>
+ {t('widgets.generate.dynamicPrompts.mode')}
+ </Text>
+ {/* A menu rather than a Select: Chakra's Select renders a hidden native
+ select whose sync throws inside this popover. */}
+ <Menu.Root positioning={MENU_POSITIONING}>
+ <Menu.Trigger asChild>
+ <Button justifyContent="space-between" minW="0" size="xs" variant="outline" w="full">
+ <Text as="span" truncate>
+ {modeLabel}
+ </Text>
+ <ChevronDownIcon />
+ </Button>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="10rem" py="1">
+ <Menu.RadioItemGroup value={modeValue[0]} onValueChange={handleModeChange}>
+ {modeItems.map((item) => (
+ <Menu.RadioItem key={item.value} value={item.value}>
+ <Menu.ItemText>{item.label}</Menu.ItemText>
+ <Menu.ItemIndicator>
+ <CheckIcon />
+ </Menu.ItemIndicator>
+ </Menu.RadioItem>
+ ))}
+ </Menu.RadioItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </Stack>
+ <Stack gap="1" w="6.5rem">
+ <Text color="fg.subtle" fontSize="2xs" truncate>
{maxPromptsLabel}
</Text>
<NumberInput.Root
@@ -139,24 +149,35 @@ export const DynamicPromptsPanel = ({
<NumberInput.Input aria-label={maxPromptsLabel} paddingStart="2" />
</NumberInput.Root>
</Stack>
- <Stack flex="1" gap="1" minW="0">
- <Text color="fg.subtle" fontSize="2xs">
- {t('widgets.generate.dynamicPrompts.seedBehaviour')}
- </Text>
- {/* A two-option choice reads better as a segmented control than a dropdown:
- one click instead of two, and it matches the mode control above. */}
- <SegmentGroup.Root
- aria-label={t('widgets.generate.dynamicPrompts.seedBehaviour')}
+ {/* Always rendered, merely hidden, so switching modes cannot reflow the row. */}
+ <Tooltip content={t('widgets.generate.dynamicPrompts.shuffle')}>
+ <IconButton
+ aria-label={t('widgets.generate.dynamicPrompts.shuffle')}
size="xs"
- value={config.seedBehaviour}
- onValueChange={handleSeedBehaviourChange}
+ variant="ghost"
+ visibility={config.combinatorial ? 'hidden' : 'visible'}
+ onClick={handleShuffle}
>
- <SegmentGroup.Indicator />
- <SegmentGroup.Items items={seedItems} />
- </SegmentGroup.Root>
- </Stack>
+ <ShuffleIcon />
+ </IconButton>
+ </Tooltip>
</HStack>
+ <Switch.Root
+ checked={config.seedBehaviour === 'per-image'}
+ ids={seedSwitchIds}
+ size="sm"
+ onCheckedChange={handleSeedBehaviourChange}
+ >
+ <Switch.HiddenInput />
+ <Switch.Control _checked={SWITCH_CHECKED}>
+ <Switch.Thumb />
+ </Switch.Control>
+ <Switch.Label color="fg.muted" fontSize="2xs">
+ {t('widgets.generate.dynamicPrompts.newSeedPerImage')}
+ </Switch.Label>
+ </Switch.Root>
+
{expansion.isError ? (
<Text color="fg.error" fontSize="2xs">
{t('widgets.generate.dynamicPrompts.problemGeneratingPrompts')}