Skip to content

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

fix(webv2): preserve prompt row semantics

joshistoast2344be2116c0
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
index 32a6203e2c..f3f43ee1f0 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
@@ -1,8 +1,17 @@
import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';
-import { ChakraProvider } from '@chakra-ui/react';
+import { Box, ChakraProvider, Text } from '@chakra-ui/react';
import { DynamicPromptsButton } from '@features/generation/ui/promptFields/DynamicPromptsButton';
+import {
+ captureRowInteractionStyles,
+ expectRowInteractionStylesToMatch,
+ getElementBoxMetrics,
+ getRenderedLineCount,
+ getXsButtonDensityStyles,
+ matchElementWidth,
+} from '@features/generation/ui/promptFields/promptFieldsBrowserTestUtils';
import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';
+import { Button } from '@platform/ui/Button';
import { Row } from '@platform/ui/Row';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -36,7 +45,12 @@ const config: DynamicPromptsConfig & { onChange: () => void } = {
seedBehaviour: 'per-iteration',
};
-const render = async (prompt: string, onUsePrompt = vi.fn()) => {
+const render = async (
+ prompt: string,
+ onUsePrompt = vi.fn(),
+ densityBaselinePrompt?: string,
+ showSyntaxHighlighting = true
+) => {
host = document.createElement('div');
host.style.width = '400px';
document.body.append(host);
@@ -46,11 +60,13 @@ const render = async (prompt: string, onUsePrompt = vi.fn()) => {
root?.render(
<QueryClientProvider client={new QueryClient()}>
<ChakraProvider value={system}>
+ <Box aria-hidden bg="bg.muted" data-testid="row-hover-style-probe" />
<Row asChild>
<button aria-label="Row probe" type="button">
Row probe
</button>
</Row>
+ {densityBaselinePrompt ? <DynamicPromptXsButtonBaseline prompt={densityBaselinePrompt} /> : null}
<PromptTextarea
aria-label="Prompt"
defaultHeightPx={100}
@@ -58,14 +74,14 @@ const render = async (prompt: string, onUsePrompt = vi.fn()) => {
minHeightPx={60}
readOnly
resizeHandleAriaLabel="Resize prompt"
- showSyntaxHighlighting
+ showSyntaxHighlighting={showSyntaxHighlighting}
value={prompt}
/>
<DynamicPromptsButton
batchCount={2}
config={config}
positivePrompt={prompt}
- showSyntaxHighlighting
+ showSyntaxHighlighting={showSyntaxHighlighting}
onInsertText={vi.fn()}
onUsePrompt={onUsePrompt}
/>
@@ -132,7 +148,10 @@ describe('dynamic prompts in the positive prompt field', () => {
it('uses the shared Row interaction contract for each selectable expanded prompt', async () => {
const { onUsePrompt } = await render('a {red|green} cat');
const probe = host!.querySelector<HTMLButtonElement>('button[aria-label="Row probe"]')!;
- const expected = await getRowInteractionStyles(probe);
+ const hoverBackgroundColor = getComputedStyle(
+ host!.querySelector('[data-testid="row-hover-style-probe"]')!
+ ).backgroundColor;
+ const expected = await captureRowInteractionStyles(probe, hoverBackgroundColor);
await vi.waitFor(() => expect(findButton().textContent).toContain('2'));
await act(async () => {
@@ -144,7 +163,7 @@ describe('dynamic prompts in the positive prompt field', () => {
button.title === 'widgets.generate.dynamicPrompts.usePrompt' && button.textContent?.includes('a red cat')
)!;
- await expectRowInteractionsToMatch(expected, row);
+ await expectRowInteractionStylesToMatch(expected, row, hoverBackgroundColor);
await act(async () => {
await userEvent.click(row);
@@ -153,6 +172,32 @@ describe('dynamic prompts in the positive prompt field', () => {
expect(onUsePrompt).toHaveBeenCalledWith('a red cat');
});
+ it('preserves the former xs Button density, typography, border, and wrapping', async () => {
+ const longPrompt =
+ 'a documentary portrait of a long-haired golden retriever beside a mountain lake under dramatic evening light';
+ parseDynamicPrompts.mockResolvedValue({ error: null, prompts: [longPrompt, 'a short prompt'] });
+ await render('a {documentary|short} prompt', vi.fn(), longPrompt, false);
+
+ await vi.waitFor(() => expect(findButton().textContent).toContain('2'));
+ await act(async () => {
+ await userEvent.click(findButton());
+ });
+
+ const row = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (button) =>
+ button.title === 'widgets.generate.dynamicPrompts.usePrompt' && button.textContent?.includes(longPrompt)
+ )!;
+ const baseline = host!.querySelector<HTMLButtonElement>('button[aria-label="Dynamic prompt xs Button baseline"]')!;
+ matchElementWidth(baseline, row);
+
+ const rowPrompt = row.children[1] as HTMLElement;
+ const baselinePrompt = baseline.querySelector<HTMLElement>('[data-testid="dynamic-prompt-baseline-text"]')!;
+
+ expect(getXsButtonDensityStyles(row)).toEqual(getXsButtonDensityStyles(baseline));
+ expect(getElementBoxMetrics(row)).toEqual(getElementBoxMetrics(baseline));
+ expect(getRenderedLineCount(rowPrompt)).toBe(getRenderedLineCount(baselinePrompt));
+ });
+
it('colours attention syntax inside the previewed prompts', async () => {
parseDynamicPrompts.mockResolvedValue({ error: null, prompts: ['a (red)1.2 cat', 'a green+ cat'] });
await render('a {(red)1.2|green+} cat');
@@ -187,69 +232,31 @@ describe('dynamic prompts in the positive prompt field', () => {
});
});
-const getRowInteractionStyles = async (probe: HTMLButtonElement) => {
- const probeBackgroundTransition = waitForBackgroundTransition(probe);
- await act(async () => {
- await userEvent.tab();
- await userEvent.hover(probe);
- });
- await probeBackgroundTransition;
- const expected = getInteractionStyles(probe);
-
- await act(async () => {
- await userEvent.unhover(probe);
- });
-
- return expected;
-};
-
-const expectRowInteractionsToMatch = async (
- expected: ReturnType<typeof getInteractionStyles>,
- row: HTMLButtonElement
-) => {
- const rowBackgroundTransition = waitForBackgroundTransition(row);
- await act(async () => {
- await focusWithKeyboard(row);
- await userEvent.hover(row);
- });
- await rowBackgroundTransition;
-
- expect(getInteractionStyles(row)).toEqual(expected);
-};
-
-const focusWithKeyboard = async (element: HTMLButtonElement) => {
- for (let index = 0; index < 12; index += 1) {
- if (document.activeElement === element) {
- return;
- }
- await userEvent.tab();
- }
-
- throw new Error(`Could not focus ${element.title} with the keyboard`);
-};
-
-const getInteractionStyles = (element: HTMLElement) => {
- const styles = getComputedStyle(element);
-
- return {
- backgroundColor: styles.backgroundColor,
- borderRadius: styles.borderRadius,
- outline: styles.outline,
- outlineOffset: styles.outlineOffset,
- transitionDuration: styles.transitionDuration,
- transitionProperty: styles.transitionProperty,
- transitionTimingFunction: styles.transitionTimingFunction,
- };
-};
-
-const waitForBackgroundTransition = (element: HTMLElement) =>
- new Promise<void>((resolve) => {
- const onTransitionEnd = (event: TransitionEvent) => {
- if (event.target === element && event.propertyName === 'background-color') {
- element.removeEventListener('transitionend', onTransitionEnd);
- resolve();
- }
- };
-
- element.addEventListener('transitionend', onTransitionEnd);
- });
+const DynamicPromptXsButtonBaseline = ({ prompt }: { prompt: string }) => (
+ <Button
+ alignItems="start"
+ aria-label="Dynamic prompt xs Button baseline"
+ gap="2"
+ h="auto"
+ justifyContent="start"
+ px="2"
+ py="1.5"
+ size="xs"
+ variant="ghost"
+ >
+ <Text as="span" color="fg.subtle" fontSize="2xs">
+ 1
+ </Text>
+ <Text
+ as="span"
+ color="fg"
+ data-testid="dynamic-prompt-baseline-text"
+ fontFamily="mono"
+ fontSize="0.72rem"
+ textAlign="start"
+ wordBreak="break-word"
+ >
+ {prompt}
+ </Text>
+ </Button>
+);
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 c1d82f0f61..8e9f866e1f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
@@ -245,12 +245,17 @@ const DynamicPromptRow = ({
<Row
alignItems="start"
asChild
+ borderColor="transparent"
+ borderWidth="1px"
+ fontWeight="medium"
gap="2"
h="auto"
justifyContent="start"
px="2"
py="1.5"
+ textStyle="xs"
title={t('widgets.generate.dynamicPrompts.usePrompt')}
+ whiteSpace="nowrap"
>
<button type="button" onClick={handleClick}>
<Text as="span" color="fg.subtle" css={TABULAR_NUMS} fontSize="2xs">
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
index 32182d7746..ecd3ae5a7e 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
@@ -4,6 +4,10 @@ import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTem
import { Box, ChakraProvider } from '@chakra-ui/react';
import { exportPromptTemplates, promptTemplateKeys } from '@features/generation/data/promptTemplates';
+import {
+ expectRowInteractionsToMatch,
+ waitForComputedStyles,
+} from '@features/generation/ui/promptFields/promptFieldsBrowserTestUtils';
import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
import { PromptTemplateImage } from '@features/generation/ui/promptFields/PromptTemplateImage';
import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
@@ -179,6 +183,7 @@ const StatefulPromptTemplatesPanel = ({ catalog }: { catalog: PromptTemplateCata
return (
<>
<Box aria-hidden bg="accent.solid" color="accent.contrast" data-testid="accent-style-probe" />
+ <Box aria-hidden bg="bg.muted" data-testid="row-hover-style-probe" />
<Row asChild>
<button aria-label="Row probe" type="button">
Row probe
@@ -276,15 +281,12 @@ describe('the prompt templates panel', () => {
await act(async () => {
await userEvent.click(activeButton);
});
- await act(
- () =>
- new Promise<void>((resolve) => {
- globalThis.setTimeout(resolve, 200);
- })
- );
const probeStyle = getComputedStyle(host!.querySelector('[data-testid="accent-style-probe"]')!);
const activeText = activeButton.querySelectorAll('span');
+ await waitForComputedStyles(activeButton, { backgroundColor: probeStyle.backgroundColor });
+ await waitForComputedStyles(activeText[0]!, { color: probeStyle.color });
+ await waitForComputedStyles(activeText[1]!, { color: probeStyle.color });
expect(activeButton.getAttribute('aria-current')).toBe('true');
expect(inactiveButton.hasAttribute('aria-current')).toBe(false);
@@ -300,14 +302,17 @@ describe('the prompt templates panel', () => {
const probe = host!.querySelector<HTMLButtonElement>('button[aria-label="Row probe"]')!;
const row = buttonWithText('Cinematic');
- const edit = host!.querySelector<HTMLButtonElement>('button[aria-label="Edit"]')!;
- const remove = host!.querySelector<HTMLButtonElement>('button[aria-label="Delete"]')!;
+ const hoverBackgroundColor = getComputedStyle(
+ host!.querySelector('[data-testid="row-hover-style-probe"]')!
+ ).backgroundColor;
+ const edit = host!.querySelector<HTMLButtonElement>('button[aria-label="Edit: Cinematic"]')!;
+ const remove = host!.querySelector<HTMLButtonElement>('button[aria-label="Delete: Cinematic"]')!;
expect(row.getAttribute('aria-current')).toBeNull();
expect(row.contains(edit)).toBe(false);
expect(row.contains(remove)).toBe(false);
- await expectRowInteractionsToMatch(probe, row);
+ await expectRowInteractionsToMatch(probe, row, hoverBackgroundColor);
});
it('clears the applied template', async () => {
@@ -353,7 +358,7 @@ describe('the prompt templates panel', () => {
);
await act(async () => {
- await userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Delete"]')!);
+ await userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Delete: Cinematic"]')!);
});
// The confirmation is portalled, so it is not under `host`.
const dialog = document.querySelector('[role="alertdialog"]')!;
@@ -369,7 +374,7 @@ describe('the prompt templates panel', () => {
// Built-ins are shipped by the backend and rejected by it for non-admins, so
// offering the controls would only produce a 403.
- it('offers edit and delete on your own templates but not on built-ins', async () => {
+ it('names edit and delete for your own template and omits them from built-ins', async () => {
await render(
<PromptTemplatesPanel
activeTemplate={null}
@@ -384,8 +389,10 @@ describe('the prompt templates panel', () => {
const labels = [...host!.querySelectorAll('button')].map((button) => button.getAttribute('aria-label'));
- expect(labels.filter((label) => label === 'Edit')).toHaveLength(1);
- expect(labels.filter((label) => label === 'Delete')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Edit: Cinematic')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Delete: Cinematic')).toHaveLength(1);
+ expect(labels).not.toContain('Edit: Photography');
+ expect(labels).not.toContain('Delete: Photography');
});
it('finds fuzzy template names', async () => {
@@ -532,8 +539,10 @@ describe('the prompt templates panel', () => {
expect(host!.textContent).toContain('Shared templates');
expect(host!.textContent).toContain('Community');
const labels = [...host!.querySelectorAll('button')].map((button) => button.getAttribute('aria-label'));
- expect(labels.filter((label) => label === 'Edit')).toHaveLength(1);
- expect(labels.filter((label) => label === 'Delete')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Edit: Cinematic')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Delete: Cinematic')).toHaveLength(1);
+ expect(labels).not.toContain('Edit: Community');
+ expect(labels).not.toContain('Delete: Community');
});
});
@@ -833,60 +842,3 @@ describe('prompt template image outlines', () => {
expect(getComputedStyle(image).outlineOffset).toBe('0px');
});
});
-
-const expectRowInteractionsToMatch = async (probe: HTMLButtonElement, row: HTMLButtonElement) => {
- const probeBackgroundTransition = waitForBackgroundTransition(probe);
- await act(async () => {
- await userEvent.tab();
- await userEvent.hover(probe);
- });
- await probeBackgroundTransition;
- const expected = getInteractionStyles(probe);
-
- const rowBackgroundTransition = waitForBackgroundTransition(row);
- await act(async () => {
- await userEvent.unhover(probe);
- await focusWithKeyboard(row);
- await userEvent.hover(row);
- });
- await rowBackgroundTransition;
-
- expect(getInteractionStyles(row)).toEqual(expected);
-};
-
-const focusWithKeyboard = async (element: HTMLButtonElement) => {
- for (let index = 0; index < 12; index += 1) {
- if (document.activeElement === element) {
- return;
- }
- await userEvent.tab();
- }
-
- throw new Error(`Could not focus ${element.textContent} with the keyboard`);
-};
-
-const getInteractionStyles = (element: HTMLElement) => {
- const styles = getComputedStyle(element);
-
- return {
- backgroundColor: styles.backgroundColor,
- borderRadius: styles.borderRadius,
- outline: styles.outline,
- outlineOffset: styles.outlineOffset,
- transitionDuration: styles.transitionDuration,
- transitionProperty: styles.transitionProperty,
- transitionTimingFunction: styles.transitionTimingFunction,
- };
-};
-
-const waitForBackgroundTransition = (element: HTMLElement) =>
- new Promise<void>((resolve) => {
- const onTransitionEnd = (event: TransitionEvent) => {
- if (event.target === element && event.propertyName === 'background-color') {
- element.removeEventListener('transitionend', onTransitionEnd);
- resolve();
- }
- };
-
- element.addEventListener('transitionend', onTransitionEnd);
- });
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
index 115b3fc2f4..d4170547ec 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
@@ -422,7 +422,12 @@ const TemplateRow = ({
</Row>
{onEdit ? (
<Tooltip content={t('common.edit')}>
- <IconButton aria-label={t('common.edit')} size="2xs" variant="ghost" onClick={handleEdit}>
+ <IconButton
+ aria-label={`${t('common.edit')}: ${template.name}`}
+ size="2xs"
+ variant="ghost"
+ onClick={handleEdit}
+ >
<PencilIcon />
</IconButton>
</Tooltip>
@@ -430,7 +435,7 @@ const TemplateRow = ({
{onDelete ? (
<Tooltip content={t('common.delete')}>
<IconButton
- aria-label={t('common.delete')}
+ aria-label={`${t('common.delete')}: ${template.name}`}
colorPalette="red"
size="2xs"
variant="ghost"
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
index 937fda35bd..71549fb5be 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
@@ -1,9 +1,17 @@
import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
-import { ChakraProvider } from '@chakra-ui/react';
+import { Box, ChakraProvider, Stack, Text } from '@chakra-ui/react';
+import {
+ expectRowInteractionsToMatch,
+ getElementBoxMetrics,
+ getRenderedLineCount,
+ getXsButtonDensityStyles,
+ matchElementWidth,
+} from '@features/generation/ui/promptFields/promptFieldsBrowserTestUtils';
import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';
import { WILDCARD_COLLECTION_FORMATS } from '@features/generation/ui/wildcardFiles';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { Button } from '@platform/ui/Button';
import { Row } from '@platform/ui/Row';
import { system } from '@theme/system';
import { act } from 'react';
@@ -47,11 +55,15 @@ const renderPanel = async (
root?.render(
<ChakraProvider value={system}>
{includeRowProbe ? (
- <Row asChild>
- <button aria-label="Row probe" type="button">
- Row probe
- </button>
- </Row>
+ <>
+ <Box aria-hidden bg="bg.muted" data-testid="row-hover-style-probe" />
+ <Row asChild>
+ <button aria-label="Row probe" type="button">
+ Row probe
+ </button>
+ </Row>
+ {panelCatalog.wildcards[0] ? <WildcardXsButtonBaseline wildcard={panelCatalog.wildcards[0]} /> : null}
+ </>
) : null}
<WildcardsPanel catalog={panelCatalog} showSyntaxHighlighting={showSyntaxHighlighting} onInsert={onInsert} />
</ChakraProvider>
@@ -304,11 +316,45 @@ describe('wildcard list interactions', () => {
const selectableWildcardButton = () =>
host!.querySelector<HTMLButtonElement>('button[title="widgets.generate.dynamicPrompts.insertWildcard"]')!;
+ it('names each selectable row with its visible wildcard reference and inserts the matching wildcard', async () => {
+ const onInsert = vi.fn();
+ const panelCatalog: WildcardCatalog = {
+ ...catalog,
+ knownNames: new Set(['colors', 'moods']),
+ wildcards: [
+ { id: 'w1', name: 'colors', values: ['red', 'green'] },
+ { id: 'w2', name: 'moods', values: ['serene', 'brooding'] },
+ ],
+ };
+ await renderPanel(true, panelCatalog, onInsert);
+
+ const rows = [
+ ...host!.querySelectorAll<HTMLButtonElement>('button[title="widgets.generate.dynamicPrompts.insertWildcard"]'),
+ ];
+ const colorsRow = rows.find((row) => row.getAttribute('aria-label')?.includes('__colors__'))!;
+ const moodsRow = rows.find((row) => row.getAttribute('aria-label')?.includes('__moods__'))!;
+
+ expect(colorsRow).toBeTruthy();
+ expect(moodsRow).toBeTruthy();
+ expect(colorsRow.getAttribute('aria-label')).not.toBe(moodsRow.getAttribute('aria-label'));
+
+ await act(async () => {
+ await userEvent.click(colorsRow);
+ await userEvent.click(moodsRow);
+ });
+
+ expect(onInsert).toHaveBeenNthCalledWith(1, '__colors__');
+ expect(onInsert).toHaveBeenNthCalledWith(2, '__moods__');
+ });
+
it('uses the shared Row interaction contract without nesting the edit controls', async () => {
const onInsert = vi.fn();
await renderPanel(true, catalog, onInsert, true);
const probe = host!.querySelector<HTMLButtonElement>('button[aria-label="Row probe"]')!;
+ const hoverBackgroundColor = getComputedStyle(
+ host!.querySelector('[data-testid="row-hover-style-probe"]')!
+ ).backgroundColor;
const row = selectableWildcardButton();
const edit = host!.querySelector<HTMLButtonElement>('button[aria-label="common.edit"]')!;
const remove = host!.querySelector<HTMLButtonElement>('button[aria-label="common.delete"]')!;
@@ -316,7 +362,7 @@ describe('wildcard list interactions', () => {
expect(row.contains(edit)).toBe(false);
expect(row.contains(remove)).toBe(false);
- await expectRowInteractionsToMatch(probe, row);
+ await expectRowInteractionsToMatch(probe, row, hoverBackgroundColor);
await act(async () => {
await userEvent.click(row);
@@ -324,6 +370,37 @@ describe('wildcard list interactions', () => {
expect(onInsert).toHaveBeenCalledWith('__colors__');
});
+
+ it('preserves the former xs Button density, typography, border, and wrapping', async () => {
+ const longWildcard = {
+ id: 'w-long',
+ name: 'collections/animals/photorealistic/long-haired-dogs/portrait-backgrounds',
+ values: ['golden retriever', 'bernese mountain dog'],
+ };
+ await renderPanel(
+ true,
+ {
+ ...catalog,
+ knownNames: new Set([longWildcard.name]),
+ wildcards: [longWildcard],
+ },
+ vi.fn(),
+ true
+ );
+
+ const baseline = host!.querySelector<HTMLButtonElement>('button[aria-label="Wildcard xs Button baseline"]')!;
+ const row = selectableWildcardButton();
+ matchElementWidth(baseline, row);
+
+ const baselineName = baseline.querySelector<HTMLElement>('[data-testid="wildcard-baseline-name"]')!;
+ const rowName = [...row.querySelectorAll<HTMLElement>('span')].find((element) =>
+ element.textContent?.startsWith('__collections/')
+ )!;
+
+ expect(getXsButtonDensityStyles(row)).toEqual(getXsButtonDensityStyles(baseline));
+ expect(getElementBoxMetrics(row)).toEqual(getElementBoxMetrics(baseline));
+ expect(getRenderedLineCount(rowName)).toBe(getRenderedLineCount(baselineName));
+ });
});
describe('deleting a wildcard', () => {
@@ -373,59 +450,25 @@ describe('deleting a wildcard', () => {
});
});
-const expectRowInteractionsToMatch = async (probe: HTMLButtonElement, row: HTMLButtonElement) => {
- const probeBackgroundTransition = waitForBackgroundTransition(probe);
- await act(async () => {
- await userEvent.tab();
- await userEvent.hover(probe);
- });
- await probeBackgroundTransition;
- const expected = getInteractionStyles(probe);
-
- const rowBackgroundTransition = waitForBackgroundTransition(row);
- await act(async () => {
- await userEvent.unhover(probe);
- await focusWithKeyboard(row);
- await userEvent.hover(row);
- });
- await rowBackgroundTransition;
-
- expect(getInteractionStyles(row)).toEqual(expected);
-};
-
-const focusWithKeyboard = async (element: HTMLButtonElement) => {
- for (let index = 0; index < 12; index += 1) {
- if (document.activeElement === element) {
- return;
- }
- await userEvent.tab();
- }
-
- throw new Error(`Could not focus ${element.title} with the keyboard`);
-};
-
-const getInteractionStyles = (element: HTMLElement) => {
- const styles = getComputedStyle(element);
-
- return {
- backgroundColor: styles.backgroundColor,
- borderRadius: styles.borderRadius,
- outline: styles.outline,
- outlineOffset: styles.outlineOffset,
- transitionDuration: styles.transitionDuration,
- transitionProperty: styles.transitionProperty,
- transitionTimingFunction: styles.transitionTimingFunction,
- };
-};
-
-const waitForBackgroundTransition = (element: HTMLElement) =>
- new Promise<void>((resolve) => {
- const onTransitionEnd = (event: TransitionEvent) => {
- if (event.target === element && event.propertyName === 'background-color') {
- element.removeEventListener('transitionend', onTransitionEnd);
- resolve();
- }
- };
-
- element.addEventListener('transitionend', onTransitionEnd);
- });
+const WildcardXsButtonBaseline = ({ wildcard }: { wildcard: WildcardCatalog['wildcards'][number] }) => (
+ <Button
+ alignItems="start"
+ aria-label="Wildcard xs Button baseline"
+ h="auto"
+ justifyContent="start"
+ minW="0"
+ px="2"
+ py="1.5"
+ size="xs"
+ variant="ghost"
+ >
+ <Stack align="start" gap="0" minW="0">
+ <Text as="span" color="fg" data-testid="wildcard-baseline-name" fontFamily="mono" fontSize="0.72rem">
+ __{wildcard.name}__
+ </Text>
+ <Text as="span" color="fg.subtle" fontSize="2xs" truncate>
+ {wildcard.values.join(', ')}
+ </Text>
+ </Stack>
+ </Button>
+);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
index c6893892da..5852e78b34 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
@@ -304,16 +304,21 @@ const WildcardRow = ({
<Row
alignItems="start"
asChild
+ borderColor="transparent"
+ borderWidth="1px"
flex="1"
+ fontWeight="medium"
h="auto"
justifyContent="start"
minW="0"
px="2"
py="1.5"
+ textStyle="xs"
title={t('widgets.generate.dynamicPrompts.insertWildcard')}
+ whiteSpace="nowrap"
>
<button
- aria-label={t('widgets.generate.dynamicPrompts.insertWildcard')}
+ aria-label={`${t('widgets.generate.dynamicPrompts.insertWildcard')}: __${wildcard.name}__`}
type="button"
onClick={() => onInsert(`__${wildcard.name}__`)}
>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFieldsBrowserTestUtils.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFieldsBrowserTestUtils.ts
new file mode 100644
index 0000000000..7c4261b514
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFieldsBrowserTestUtils.ts
@@ -0,0 +1,124 @@
+import { act } from 'react';
+import { expect, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+type FinalComputedStyles = Readonly<Partial<Pick<CSSStyleDeclaration, 'backgroundColor' | 'color'>>>;
+
+export const waitForComputedStyles = async (element: Element, expected: FinalComputedStyles) => {
+ await vi.waitFor(() => {
+ const styles = getComputedStyle(element);
+
+ for (const property of Object.keys(expected) as (keyof FinalComputedStyles)[]) {
+ expect(styles[property]).toBe(expected[property]);
+ }
+ });
+};
+
+export const captureRowInteractionStyles = async (probe: HTMLButtonElement, hoverBackgroundColor: string) => {
+ await act(async () => {
+ await focusWithKeyboard(probe);
+ await userEvent.hover(probe);
+ });
+ await waitForComputedStyles(probe, { backgroundColor: hoverBackgroundColor });
+ const expected = getInteractionStyles(probe);
+
+ await act(async () => {
+ await userEvent.unhover(probe);
+ });
+
+ return expected;
+};
+
+export const expectRowInteractionStylesToMatch = async (
+ expected: ReturnType<typeof getInteractionStyles>,
+ row: HTMLButtonElement,
+ hoverBackgroundColor: string
+) => {
+ await act(async () => {
+ await focusWithKeyboard(row);
+ await userEvent.hover(row);
+ });
+ await waitForComputedStyles(row, { backgroundColor: hoverBackgroundColor });
+
+ expect(getInteractionStyles(row)).toEqual(expected);
+};
+
+export const expectRowInteractionsToMatch = async (
+ probe: HTMLButtonElement,
+ row: HTMLButtonElement,
+ hoverBackgroundColor: string
+) => {
+ const expected = await captureRowInteractionStyles(probe, hoverBackgroundColor);
+ await expectRowInteractionStylesToMatch(expected, row, hoverBackgroundColor);
+};
+
+export const getXsButtonDensityStyles = (element: HTMLElement) => {
+ const styles = getComputedStyle(element);
+
+ return {
+ borderBottomColor: styles.borderBottomColor,
+ borderBottomStyle: styles.borderBottomStyle,
+ borderBottomWidth: styles.borderBottomWidth,
+ borderLeftColor: styles.borderLeftColor,
+ borderLeftStyle: styles.borderLeftStyle,
+ borderLeftWidth: styles.borderLeftWidth,
+ borderRightColor: styles.borderRightColor,
+ borderRightStyle: styles.borderRightStyle,
+ borderRightWidth: styles.borderRightWidth,
+ borderTopColor: styles.borderTopColor,
+ borderTopStyle: styles.borderTopStyle,
+ borderTopWidth: styles.borderTopWidth,
+ fontSize: styles.fontSize,
+ fontWeight: styles.fontWeight,
+ lineHeight: styles.lineHeight,
+ whiteSpace: styles.whiteSpace,
+ };
+};
+
+export const matchElementWidth = (element: HTMLElement, reference: HTMLElement) => {
+ element.style.width = `${reference.offsetWidth}px`;
+};
+
+export const getElementBoxMetrics = (element: HTMLElement) => ({
+ clientHeight: element.clientHeight,
+ clientWidth: element.clientWidth,
+ offsetHeight: element.offsetHeight,
+ offsetWidth: element.offsetWidth,
+ scrollHeight: element.scrollHeight,
+ scrollWidth: element.scrollWidth,
+});
+
+export const getRenderedLineCount = (element: HTMLElement) => {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const lineTops = new Set(
+ [...range.getClientRects()].filter((rect) => rect.width > 0).map((rect) => Math.round(rect.top * 100) / 100)
+ );
+
+ return lineTops.size;
+};
+
+const focusWithKeyboard = async (element: HTMLButtonElement) => {
+ for (let index = 0; index < 12; index += 1) {
+ if (document.activeElement === element) {
+ return;
+ }
+ await userEvent.tab();
+ }
+
+ throw new Error(`Could not focus ${element.title || element.textContent} with the keyboard`);
+};
+
+const getInteractionStyles = (element: HTMLElement) => {
+ const styles = getComputedStyle(element);
+
+ return {
+ backgroundColor: styles.backgroundColor,
+ borderRadius: styles.borderRadius,
+ outline: styles.outline,
+ outlineOffset: styles.outlineOffset,
+ transitionDuration: styles.transitionDuration,
+ transitionProperty: styles.transitionProperty,
+ transitionTimingFunction: styles.transitionTimingFunction,
+ };
+};