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.

feat(webv2): search and group the wildcards list

joshistoast8e7412b8af7d
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 492b0a7c79..cdb9909d19 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -973,6 +973,8 @@
"wildcardValuesPlaceholder": "One value per line",
"wildcardHasNoValues": "No values yet",
"noWildcardsYet": "No wildcards yet. Create one to reuse a list of values as __name__.",
+ "searchWildcards": "Search wildcards",
+ "noMatchingWildcards": "No wildcards match your search",
"insertWildcard": "Insert into the prompt",
"couldNotSaveWildcard": "Could not save this wildcard",
"couldNotDeleteWildcard": "Could not delete this wildcard",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts
new file mode 100644
index 0000000000..0a09137c6e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+
+import { filterWildcards, groupWildcardsByPrefix } from './wildcardCatalog';
+
+const wildcard = (name: string, values: string[] = []) => ({ name, values });
+
+describe('filterWildcards', () => {
+ it('returns every wildcard for an empty query', () => {
+ const wildcards = [wildcard('colours'), wildcard('artists')];
+
+ expect(filterWildcards(wildcards, '')).toEqual(wildcards);
+ expect(filterWildcards(wildcards, ' ')).toEqual(wildcards);
+ });
+
+ it('returns a copy rather than the caller’s array', () => {
+ const wildcards = [wildcard('colours')];
+
+ expect(filterWildcards(wildcards, '')).not.toBe(wildcards);
+ });
+
+ it('matches names fuzzily', () => {
+ const wildcards = [wildcard('animals/dogs'), wildcard('colours')];
+
+ expect(filterWildcards(wildcards, 'adg')).toEqual([wildcards[0]]);
+ });
+
+ it('matches values by substring, case-insensitively', () => {
+ const wildcards = [wildcard('moods', ['Cyberpunk', 'serene']), wildcard('colours', ['red'])];
+
+ expect(filterWildcards(wildcards, 'cyberpunk')).toEqual([wildcards[0]]);
+ expect(filterWildcards(wildcards, 'CYBER')).toEqual([wildcards[0]]);
+ });
+
+ it('ranks name matches above value-only matches', () => {
+ const valueOnly = wildcard('moods', ['red mist']);
+ const byName = wildcard('red', ['crimson']);
+
+ expect(filterWildcards([valueOnly, byName], 'red')).toEqual([byName, valueOnly]);
+ });
+
+ it('lists a wildcard once when both its name and its values match', () => {
+ const both = wildcard('red', ['dark red', 'bright red']);
+
+ expect(filterWildcards([both], 'red')).toEqual([both]);
+ });
+
+ it('returns nothing when neither names nor values match', () => {
+ expect(filterWildcards([wildcard('colours', ['red'])], 'zzzz')).toEqual([]);
+ });
+
+ it('finds a match in the last of many values', () => {
+ const long = wildcard('big', [...Array.from({ length: 500 }, (_, index) => `value-${index}`), 'needle']);
+
+ expect(filterWildcards([long], 'needle')).toEqual([long]);
+ });
+});
+
+describe('groupWildcardsByPrefix', () => {
+ it('leaves a flat catalog in one unlabelled group', () => {
+ const wildcards = [wildcard('colours'), wildcard('artists')];
+
+ expect(groupWildcardsByPrefix(wildcards)).toEqual([{ label: null, wildcards }]);
+ });
+
+ it('groups by the segment before the first slash', () => {
+ const dogs = wildcard('animals/dogs');
+ const cats = wildcard('animals/cats');
+
+ expect(groupWildcardsByPrefix([dogs, cats])).toEqual([{ label: 'animals', wildcards: [dogs, cats] }]);
+ });
+
+ it('splits on the first slash only, so deeper names share one header', () => {
+ const elves = wildcard('characters/fantasy/elves');
+ const orcs = wildcard('characters/scifi/orcs');
+
+ expect(groupWildcardsByPrefix([elves, orcs])).toEqual([{ label: 'characters', wildcards: [elves, orcs] }]);
+ });
+
+ it('puts top-level names first, then labelled groups in first-appearance order', () => {
+ const dogs = wildcard('animals/dogs');
+ const colours = wildcard('colours');
+ const warm = wildcard('moods/warm');
+
+ expect(groupWildcardsByPrefix([dogs, colours, warm])).toEqual([
+ { label: null, wildcards: [colours] },
+ { label: 'animals', wildcards: [dogs] },
+ { label: 'moods', wildcards: [warm] },
+ ]);
+ });
+
+ it('omits the unlabelled group when every name is nested', () => {
+ const dogs = wildcard('animals/dogs');
+
+ expect(groupWildcardsByPrefix([dogs])).toEqual([{ label: 'animals', wildcards: [dogs] }]);
+ });
+
+ it('preserves the incoming order within a group', () => {
+ const cats = wildcard('animals/cats');
+ const dogs = wildcard('animals/dogs');
+
+ expect(groupWildcardsByPrefix([dogs, cats])[0]?.wildcards).toEqual([dogs, cats]);
+ });
+
+ it('treats a leading slash as ungrouped rather than an empty label', () => {
+ const odd = wildcard('/leading');
+
+ expect(groupWildcardsByPrefix([odd])).toEqual([{ label: null, wildcards: [odd] }]);
+ });
+
+ it('returns nothing for an empty catalog', () => {
+ expect(groupWildcardsByPrefix([])).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts
new file mode 100644
index 0000000000..09d9edb552
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts
@@ -0,0 +1,104 @@
+/**
+ * Finding one wildcard among many, and giving `a/b` names the shape their author
+ * meant by them.
+ *
+ * Nested names have always been legal — `WILDCARD_NAME_SOURCE` in
+ * `./dynamicPrompts` allows `animals/dogs` — but nothing has ever surfaced the
+ * nesting, so a namespaced catalog reads as a flat list of unrelated rows. Both
+ * helpers here are pure and ordering-preserving: the caller decides what order
+ * the wildcards arrive in (catalog order normally, match order while searching)
+ * and grouping never reshuffles it.
+ */
+
+import fuzzysort from 'fuzzysort';
+
+export interface WildcardListEntry {
+ name: string;
+ values: readonly string[];
+}
+
+/** Matches below this fuzzysort score (0–1) are noise, not results. */
+const NAME_MATCH_THRESHOLD = 0.2;
+
+export interface WildcardGroup<T> {
+ /** `null` for names with no `/` — those render without a header. */
+ label: string | null;
+ wildcards: T[];
+}
+
+/**
+ * Name matches first, ranked fuzzily, then wildcards whose *values* contain the
+ * query.
+ *
+ * The split is deliberate. Names are short slugs, where fuzzy matching earns its
+ * keep (`adg` finds `animals/dogs`); values are free text, where a fuzzy match
+ * would fire on almost anything, so they take a plain substring test. Searching
+ * values at all matters because a wildcard is mostly its values — you remember
+ * that "cyberpunk" is in one of these lists long before you remember which.
+ *
+ * Values are scanned in full rather than sampled: stopping early would silently
+ * hide a match in a long list, which is worse than the scan being slow. `.some`
+ * exits on the first hit.
+ */
+export const filterWildcards = <T extends WildcardListEntry>(wildcards: readonly T[], query: string): T[] => {
+ const trimmed = query.trim();
+
+ if (trimmed.length === 0) {
+ return [...wildcards];
+ }
+
+ const nameMatches = fuzzysort.go(trimmed, wildcards, {
+ key: (wildcard: T) => wildcard.name,
+ threshold: NAME_MATCH_THRESHOLD,
+ });
+ const matched = new Set<T>(nameMatches.map((result) => result.obj));
+ const results = nameMatches.map((result) => result.obj);
+ const needle = trimmed.toLowerCase();
+
+ for (const wildcard of wildcards) {
+ if (!matched.has(wildcard) && wildcard.values.some((value) => value.toLowerCase().includes(needle))) {
+ results.push(wildcard);
+ }
+ }
+
+ return results;
+};
+
+/**
+ * Splits on the *first* `/` only. `characters/fantasy/elves` groups under
+ * `characters`, not `characters/fantasy` — one level of headers keeps the panel
+ * scannable, and a deeper tree would need collapsing to stay usable in a 14rem
+ * box.
+ *
+ * Top-level names come first and unlabelled, so a catalog that uses no `/` at
+ * all renders exactly as it did before grouping existed. Labelled groups follow
+ * in first-appearance order, which is match order during a search — the best hit
+ * stays at the top rather than being sorted away.
+ */
+export const groupWildcardsByPrefix = <T extends { name: string }>(wildcards: readonly T[]): WildcardGroup<T>[] => {
+ const ungrouped: T[] = [];
+ const groups = new Map<string, T[]>();
+
+ for (const wildcard of wildcards) {
+ const separatorIndex = wildcard.name.indexOf('/');
+
+ if (separatorIndex <= 0) {
+ ungrouped.push(wildcard);
+ continue;
+ }
+
+ const label = wildcard.name.slice(0, separatorIndex);
+ const existing = groups.get(label);
+
+ if (existing) {
+ existing.push(wildcard);
+ } else {
+ groups.set(label, [wildcard]);
+ }
+ }
+
+ return [
+ ...(ungrouped.length > 0 ? [{ label: null, wildcards: ungrouped }] : []),
+ ...[...groups].map(([label, grouped]) => ({ label, wildcards: grouped })),
+ ];
+};
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 844ad02543..fc635f36fc 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
@@ -28,7 +28,7 @@ const catalog: WildcardCatalog = {
wildcards: [{ id: 'w1', name: 'colors', values: ['red', 'green'] }],
};
-const renderPanel = async (showSyntaxHighlighting = true) => {
+const renderPanel = async (showSyntaxHighlighting = true, panelCatalog: WildcardCatalog = catalog) => {
host = document.createElement('div');
host.style.width = '380px';
document.body.append(host);
@@ -37,7 +37,7 @@ const renderPanel = async (showSyntaxHighlighting = true) => {
await act(() => {
root?.render(
<ChakraProvider value={system}>
- <WildcardsPanel catalog={catalog} showSyntaxHighlighting={showSyntaxHighlighting} onInsert={vi.fn()} />
+ <WildcardsPanel catalog={panelCatalog} showSyntaxHighlighting={showSyntaxHighlighting} onInsert={vi.fn()} />
</ChakraProvider>
);
});
@@ -150,6 +150,76 @@ describe('wildcard name validation', () => {
});
});
+describe('finding a wildcard', () => {
+ const manyCatalog: WildcardCatalog = {
+ create: vi.fn(),
+ isLoading: false,
+ knownNames: new Set(['colors']),
+ remove: vi.fn(),
+ update: vi.fn(),
+ wildcards: [
+ { id: 'w1', name: 'colors', values: ['red', 'green'] },
+ { id: 'w2', name: 'animals/dogs', values: ['corgi', 'husky'] },
+ { id: 'w3', name: 'animals/cats', values: ['tabby'] },
+ { id: 'w4', name: 'moods', values: ['cyberpunk', 'serene'] },
+ ],
+ };
+
+ const searchInput = () =>
+ [...host!.querySelectorAll('input')].find((input) => input.getAttribute('aria-label')?.includes('searchWildcards'));
+ const referenceLabels = () =>
+ [...host!.querySelectorAll('span')].map((span) => span.textContent).filter((text) => text?.startsWith('__'));
+ const search = async (query: string) => {
+ await act(async () => {
+ await userEvent.fill(searchInput()!, query);
+ });
+ };
+
+ it('offers no search box until there is something to search', async () => {
+ await renderPanel(true, { ...manyCatalog, wildcards: [] });
+
+ expect(searchInput()).toBeUndefined();
+ expect(host!.textContent).toContain('noWildcardsYet');
+ });
+
+ it('matches a name fuzzily', async () => {
+ await renderPanel(true, manyCatalog);
+ await search('adg');
+
+ expect(referenceLabels()).toEqual(['__animals/dogs__']);
+ });
+
+ it('matches a value the name says nothing about', async () => {
+ await renderPanel(true, manyCatalog);
+ await search('cyberpunk');
+
+ expect(referenceLabels()).toEqual(['__moods__']);
+ });
+
+ // "No wildcards yet" would be a lie while four of them are filtered out.
+ it('distinguishes an empty catalog from an empty result', async () => {
+ await renderPanel(true, manyCatalog);
+ await search('zzzz');
+
+ expect(host!.textContent).toContain('noMatchingWildcards');
+ expect(host!.textContent).not.toContain('noWildcardsYet');
+ });
+
+ it('heads nested names with their shared prefix', async () => {
+ await renderPanel(true, manyCatalog);
+
+ expect([...host!.querySelectorAll('p, span')].map((node) => node.textContent)).toContain('animals');
+ });
+
+ // The row is the text you would type, so the header must not shorten it.
+ it('still shows the whole reference under a group header', async () => {
+ await renderPanel(true, manyCatalog);
+
+ expect(referenceLabels()).toContain('__animals/dogs__');
+ expect(referenceLabels()).not.toContain('__dogs__');
+ });
+});
+
describe('deleting a wildcard', () => {
const clickDelete = async () => {
// Insert, edit, delete — the trash is the last control on the row.
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 36b142a88b..8875f727c4 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
@@ -3,8 +3,9 @@ import type { WildcardRecord } from '@features/generation/data/wildcards';
import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
import type { ChangeEvent } from 'react';
-import { HStack, Input, Stack, Text } from '@chakra-ui/react';
+import { HStack, Input, Separator, Stack, Text } from '@chakra-ui/react';
import { getWildcardNameError } from '@features/generation/core/dynamicPrompts';
+import { filterWildcards, groupWildcardsByPrefix } from '@features/generation/core/wildcardCatalog';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';
@@ -15,7 +16,7 @@ import { Field } from '@platform/ui/Field';
import { Scrollable } from '@platform/ui/Scrollable';
import { Tooltip } from '@platform/ui/Tooltip';
import { CheckIcon, PencilIcon, PlusIcon, TrashIcon, XIcon } from 'lucide-react';
-import { useCallback, useId, useState } from 'react';
+import { useCallback, useId, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
/** One value per line: the same shape the user is editing a variant in. */
@@ -50,6 +51,11 @@ export const WildcardsPanel = ({
const [draft, setDraft] = useState<WildcardDraft | null>(null);
const [error, setError] = useState<string | null>(null);
const [pendingDelete, setPendingDelete] = useState<WildcardRecord | null>(null);
+ const [searchTerm, setSearchTerm] = useState('');
+ const groups = useMemo(
+ () => groupWildcardsByPrefix(filterWildcards(catalog.wildcards, searchTerm)),
+ [catalog.wildcards, searchTerm]
+ );
// Renaming to your own current name is not a clash, so the wildcard being
// edited is excluded from the taken-names set.
const nameError = draft
@@ -93,6 +99,11 @@ export const WildcardsPanel = ({
}
}, [catalog, draft, t]);
+ const handleSearchChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value),
+ []
+ );
+
const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);
/**
@@ -189,21 +200,50 @@ export const WildcardsPanel = ({
</Button>
</PromptPanelHeader>
+ {/* Searching an empty catalog would only offer a way to find nothing, so
+ the input appears once there is something to search. */}
+ {catalog.wildcards.length > 0 ? (
+ <>
+ <Input
+ aria-label={t('widgets.generate.dynamicPrompts.searchWildcards')}
+ placeholder={t('widgets.generate.dynamicPrompts.searchWildcards')}
+ size="xs"
+ value={searchTerm}
+ onChange={handleSearchChange}
+ />
+ <Separator />
+ </>
+ ) : null}
+
<Scrollable h="14rem" label={t('widgets.generate.dynamicPrompts.wildcards')}>
- {catalog.wildcards.length === 0 ? (
+ {groups.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">
- {t('widgets.generate.dynamicPrompts.noWildcardsYet')}
+ {catalog.wildcards.length === 0
+ ? t('widgets.generate.dynamicPrompts.noWildcardsYet')
+ : t('widgets.generate.dynamicPrompts.noMatchingWildcards')}
</Text>
) : (
- <Stack gap="0">
- {catalog.wildcards.map((wildcard) => (
- <WildcardRow
- key={wildcard.id}
- wildcard={wildcard}
- onDelete={setPendingDelete}
- onEdit={startEdit}
- onInsert={onInsert}
- />
+ <Stack gap="2">
+ {groups.map((group) => (
+ <Stack gap="0" key={group.label ?? ''}>
+ {group.label === null ? null : (
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="2" textTransform="uppercase">
+ {group.label}
+ </Text>
+ )}
+ {group.wildcards.map((wildcard) => (
+ // The row shows the whole `__animals/dogs__`, header or not:
+ // it is the exact text you would type, so trimming the prefix
+ // to match the header above would make it a lie.
+ <WildcardRow
+ key={wildcard.id}
+ wildcard={wildcard}
+ onDelete={setPendingDelete}
+ onEdit={startEdit}
+ onInsert={onInsert}
+ />
+ ))}
+ </Stack>
))}
</Stack>
)}