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: align wildcard handling with backend syntax

joshistoast15fdb12b4fc9
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
index 2531931f41..29b353ad6d 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -6,6 +6,7 @@ import {
hasDynamicPromptSyntax,
matchesKnownWildcard,
normalizeWildcardValues,
+ scanWildcardReferences,
sanitizeDynamicPromptsConfig,
sanitizeMaxPrompts,
} from './dynamicPrompts';
@@ -23,6 +24,7 @@ describe('hasDynamicPromptSyntax', () => {
expect(hasDynamicPromptSyntax('a __artists/*__ ball')).toBe(true);
expect(hasDynamicPromptSyntax('a __~colors__ ball')).toBe(true);
expect(hasDynamicPromptSyntax('a __outfit(mood=warm)__ ball')).toBe(true);
+ expect(hasDynamicPromptSyntax('a __colou?__ __animals/[dc]ogs__ ball')).toBe(true);
});
// A comment is only stripped by going through the expander, and upstream has
@@ -41,6 +43,29 @@ describe('hasDynamicPromptSyntax', () => {
});
});
+describe('scanWildcardReferences', () => {
+ it('returns the full range and lookup path for sampler overrides and parameters', () => {
+ const prompt = 'a __~outfit(mood=warm)__ beside __animals/[dc]ogs__';
+
+ expect(scanWildcardReferences(prompt)).toEqual([
+ {
+ lookupPath: 'outfit',
+ range: { end: 24, start: 2 },
+ },
+ {
+ lookupPath: 'animals/[dc]ogs',
+ range: { end: 51, start: 32 },
+ },
+ ]);
+ });
+
+ it('does not mistake delimiters inside an ordinary word for a reference', () => {
+ expect(scanWildcardReferences('snake__case and __valid__')).toEqual([
+ { lookupPath: 'valid', range: { end: 25, start: 16 } },
+ ]);
+ });
+});
+
describe('sanitizeMaxPrompts', () => {
it('clamps to the backend bounds and falls back on garbage', () => {
expect(sanitizeMaxPrompts(50)).toBe(50);
@@ -121,6 +146,21 @@ describe('matchesKnownWildcard', () => {
expect(matchesKnownWildcard('colours/*', new Set(['colours']))).toBe(false);
});
+ it('supports question marks, classes, ranges, and negated classes', () => {
+ expect(matchesKnownWildcard('colour?', new Set(['colours']))).toBe(true);
+ expect(matchesKnownWildcard('animals/[dc]ogs', CATALOG)).toBe(true);
+ expect(matchesKnownWildcard('animals/[a-z]ogs', CATALOG)).toBe(true);
+ expect(matchesKnownWildcard('animals/[!c]ogs', CATALOG)).toBe(true);
+ expect(matchesKnownWildcard('animals/[!d]ogs', CATALOG)).toBe(false);
+ });
+
+ it('treats an unclosed or invalid class like Python fnmatch', () => {
+ expect(matchesKnownWildcard('[abc', new Set(['[abc']))).toBe(true);
+ expect(matchesKnownWildcard('[abc', new Set(['a']))).toBe(false);
+ expect(matchesKnownWildcard('[z-a]', new Set(['z', '-', 'a']))).toBe(false);
+ expect(matchesKnownWildcard('[!z-a]', new Set(['q']))).toBe(true);
+ });
+
it('anchors both ends, so the two cannot share characters', () => {
// `ab*ba` needs four characters; matching `ab` and `ba` onto the same `b`
// is what a naive prefix/suffix check gets wrong.
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 558655187a..7bed53913c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -38,80 +38,207 @@ export interface DynamicPromptsConfig {
const WILDCARD_NAME_SEGMENT = '[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?';
const WILDCARD_NAME_SOURCE = `${WILDCARD_NAME_SEGMENT}(?:/${WILDCARD_NAME_SEGMENT})*`;
-/**
- * A referenced path, which is looser than a storable name: `*` may stand
- * anywhere in it, and it may cross `/` while doing so. `__animals/*__`,
- * `__colour*__` and a bare `__*__` are all things the backend resolves.
- */
-const WILDCARD_PATH_SEGMENT = '[A-Za-z0-9*](?:[A-Za-z0-9_*-]*[A-Za-z0-9*])?';
-const WILDCARD_PATH_SOURCE = `${WILDCARD_PATH_SEGMENT}(?:/${WILDCARD_PATH_SEGMENT})*`;
-
-/**
- * `__name__`, the reference form for a wildcard. Shared with the syntax scanner
- * so highlighting and expansion agree on what counts as a wildcard.
- *
- * Three optional parts ride along, all of which the backend accepts and none of
- * which is part of the name being looked up:
- *
- * - a sampler override, `__~name__` (random) or `__@name__` (cyclical);
- * - a glob, `__artists/*__`, resolving to every matching wildcard at once;
- * - parameters, `__name(mood=warm)__`, binding `${mood}` inside the values.
- *
- * Capture group 1 is the path alone — the part to look up.
- */
-export const WILDCARD_REFERENCE_RE = new RegExp(`__[~@]?(${WILDCARD_PATH_SOURCE})(?:\\([^()]*\\))?__`);
-
/** The same rule anchored, for validating a name the user is typing. */
export const WILDCARD_NAME_RE = new RegExp(`^${WILDCARD_NAME_SOURCE}$`);
-/**
- * Whether `name` matches a glob, given the literal runs between its `*`s.
- *
- * Deliberately not a regex. Translating `a*b*c` to `^a.*b.*c$` reads well but
- * makes adjacent stars into `.*.*`, which backtracks exponentially: a dozen of
- * them against one catalog name took a minute to fail. The path comes straight
- * out of whatever the user is typing, so that is a frozen tab, not a slow test.
- *
- * The greedy scan below is the standard `*`-only matcher and is linear in
- * practice: anchor the first run to the start and the last to the end, then take
- * each middle run at its earliest remaining occurrence. Earliest is always safe
- * when the only wildcard is "any run of anything" — consuming less can never
- * turn a match into a miss.
- */
-const matchesGlobLiterals = (literals: readonly string[], name: string): boolean => {
- const first = literals[0] ?? '';
- const last = literals[literals.length - 1] ?? '';
+export interface WildcardReference {
+ /** The path sent to the wildcard manager, without sampler or parameters. */
+ lookupPath: string;
+ /** Full `__…__` span in the authored prompt. */
+ range: { end: number; start: number };
+}
- if (literals.length === 1) {
- return name === first;
+const WILDCARD_GLOB_CHARACTER_RE = /[*?[]/;
+const WILDCARD_REFERENCE_PATH_RE = /^[A-Za-z0-9_/*?[\]!-]+$/;
+const isWildcardBoundaryCharacter = (character: string | undefined): boolean =>
+ character !== undefined && /[A-Za-z0-9_]/.test(character);
+
+const getWildcardLookupPath = (content: string): string | null => {
+ const withoutSampler = content[0] === '~' || content[0] === '@' ? content.slice(1) : content;
+ const parametersStart = withoutSampler.indexOf('(');
+ let lookupPath = withoutSampler;
+
+ if (parametersStart >= 0) {
+ if (
+ !withoutSampler.endsWith(')') ||
+ withoutSampler.slice(parametersStart + 1, -1).includes('(') ||
+ withoutSampler.slice(parametersStart + 1, -1).includes(')')
+ ) {
+ return null;
+ }
+
+ lookupPath = withoutSampler.slice(0, parametersStart);
+ } else if (withoutSampler.includes(')')) {
+ return null;
}
- // Checked before the middle runs so the two anchors cannot overlap and count
- // the same characters twice: `ab*ba` needs four characters, not three.
- if (name.length < first.length + last.length || !name.startsWith(first) || !name.endsWith(last)) {
- return false;
+ if (!lookupPath || !WILDCARD_REFERENCE_PATH_RE.test(lookupPath)) {
+ return null;
}
- const end = name.length - last.length;
- let index = first.length;
+ return WILDCARD_GLOB_CHARACTER_RE.test(lookupPath) || WILDCARD_NAME_RE.test(lookupPath) ? lookupPath : null;
+};
- for (let position = 1; position < literals.length - 1; position++) {
- const literal = literals[position];
+/** Scans every backend-compatible wildcard reference without regex state or backtracking. */
+export const scanWildcardReferences = (prompt: string): WildcardReference[] => {
+ const references: WildcardReference[] = [];
+ let index = 0;
- if (literal === undefined || literal.length === 0) {
+ while (index < prompt.length - 1) {
+ if (prompt[index] !== '_' || prompt[index + 1] !== '_' || isWildcardBoundaryCharacter(prompt[index - 1])) {
+ index++;
continue;
}
- const found = name.indexOf(literal, index);
+ const closing = prompt.indexOf('__', index + 2);
+
+ if (closing < 0) {
+ break;
+ }
+
+ const lookupPath = getWildcardLookupPath(prompt.slice(index + 2, closing));
+
+ if (lookupPath) {
+ references.push({ lookupPath, range: { end: closing + 2, start: index } });
+ index = closing + 2;
+ } else {
+ index += 2;
+ }
+ }
+
+ return references;
+};
+
+type GlobToken =
+ | { kind: 'any' }
+ | { kind: 'star' }
+ | { kind: 'literal'; value: string }
+ | {
+ invalid: boolean;
+ kind: 'class';
+ literals: Set<string>;
+ negated: boolean;
+ ranges: { end: string; start: string }[];
+ };
+
+const parseGlobClass = (pattern: string, start: number): { end: number; token: GlobToken } | null => {
+ let cursor = start + 1;
+ const negated = pattern[cursor] === '!';
+
+ if (negated) {
+ cursor++;
+ }
+ if (pattern[cursor] === ']') {
+ cursor++;
+ }
+
+ const closing = pattern.indexOf(']', cursor);
+
+ if (closing < 0) {
+ return null;
+ }
+
+ const contentStart = start + 1 + (negated ? 1 : 0);
+ const content = pattern.slice(contentStart, closing);
+ const literals = new Set<string>();
+ const ranges: { end: string; start: string }[] = [];
+ let invalid = false;
+
+ for (let index = 0; index < content.length; index++) {
+ const character = content[index]!;
+ const rangeEnd = content[index + 2];
+
+ if (content[index + 1] === '-' && rangeEnd !== undefined) {
+ if (character > rangeEnd) {
+ invalid = true;
+ } else {
+ ranges.push({ end: rangeEnd, start: character });
+ }
+ index += 2;
+ } else {
+ literals.add(character);
+ }
+ }
+
+ return {
+ end: closing + 1,
+ token: { invalid, kind: 'class', literals, negated, ranges },
+ };
+};
+
+const tokenizeGlob = (pattern: string): GlobToken[] => {
+ const tokens: GlobToken[] = [];
+ let index = 0;
+
+ while (index < pattern.length) {
+ const character = pattern[index]!;
+
+ if (character === '*') {
+ if (tokens.at(-1)?.kind !== 'star') {
+ tokens.push({ kind: 'star' });
+ }
+ index++;
+ } else if (character === '?') {
+ tokens.push({ kind: 'any' });
+ index++;
+ } else if (character === '[') {
+ const parsed = parseGlobClass(pattern, index);
+
+ if (parsed) {
+ tokens.push(parsed.token);
+ index = parsed.end;
+ } else {
+ tokens.push({ kind: 'literal', value: character });
+ index++;
+ }
+ } else {
+ tokens.push({ kind: 'literal', value: character });
+ index++;
+ }
+ }
+
+ return tokens;
+};
+
+const globTokenMatches = (token: Exclude<GlobToken, { kind: 'star' }>, character: string): boolean => {
+ if (token.kind === 'any') {
+ return true;
+ }
+ if (token.kind === 'literal') {
+ return token.value === character;
+ }
+
+ const inClass =
+ !token.invalid &&
+ (token.literals.has(character) || token.ranges.some((range) => character >= range.start && character <= range.end));
+
+ return token.negated ? !inClass : inClass;
+};
+
+/** Bounded O(pattern × name) matcher mirroring Python `fnmatchcase`. */
+const matchesGlob = (pattern: string, name: string): boolean => {
+ let reachable = Array.from({ length: name.length + 1 }, (_, index) => index === 0);
- if (found < 0 || found + literal.length > end) {
- return false;
+ for (const token of tokenizeGlob(pattern)) {
+ const next = Array.from({ length: name.length + 1 }, () => false);
+
+ if (token.kind === 'star') {
+ let canReach = false;
+
+ for (let index = 0; index <= name.length; index++) {
+ canReach ||= reachable[index] === true;
+ next[index] = canReach;
+ }
+ } else {
+ for (let index = 0; index < name.length; index++) {
+ next[index + 1] = reachable[index] === true && globTokenMatches(token, name[index]!);
+ }
}
- index = found + literal.length;
+ reachable = next;
}
- return true;
+ return reachable[name.length] === true;
};
/**
@@ -127,14 +254,12 @@ const matchesGlobLiterals = (literals: readonly string[], name: string): boolean
* goes to the model as text.
*/
export const matchesKnownWildcard = (path: string, knownNames: ReadonlySet<string>): boolean => {
- if (!path.includes('*')) {
+ if (!WILDCARD_GLOB_CHARACTER_RE.test(path)) {
return knownNames.has(path);
}
- const literals = path.split('*');
-
for (const name of knownNames) {
- if (matchesGlobLiterals(literals, name)) {
+ if (matchesGlob(path, name)) {
return true;
}
}
@@ -228,7 +353,7 @@ export const getWildcardNameError = (
* which is a worse surprise than the round trip.
*/
export const hasDynamicPromptSyntax = (prompt: string): boolean =>
- /\{[\s\S]*\}/.test(prompt) || prompt.includes('#') || WILDCARD_REFERENCE_RE.test(prompt);
+ /\{[\s\S]*\}/.test(prompt) || prompt.includes('#') || scanWildcardReferences(prompt).length > 0;
export const isDynamicPromptsSeedBehaviour = (value: unknown): value is DynamicPromptsSeedBehaviour =>
value === 'per-iteration' || value === 'per-image';
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts
index 063d00be42..6754e68f29 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts
@@ -1,3 +1,4 @@
+import { scanWildcardReferences } from '@features/generation/core/dynamicPrompts';
import { describe, expect, it } from 'vitest';
import { scanDynamicPromptSyntax } from './dynamicPromptSyntax';
@@ -84,14 +85,27 @@ describe('scanDynamicPromptSyntax', () => {
// Regression: globs, sampler overrides and parameters are all valid, and all
// read as ordinary text — or worse, as errors — before this.
it('annotates the looser reference forms the backend accepts', () => {
- expect(annotate('__artists/*__ __~colours__ __@colours__ __outfit(mood=warm)__')).toEqual([
+ expect(
+ annotate('__artists/*__ __artist?__ __animals/[dc]ogs__ __~colours__ __@colours__ __outfit(mood=warm)__')
+ ).toEqual([
['wildcard', '__artists/*__'],
+ ['wildcard', '__artist?__'],
+ ['wildcard', '__animals/[dc]ogs__'],
['wildcard', '__~colours__'],
['wildcard', '__@colours__'],
['wildcard', '__outfit(mood=warm)__'],
]);
});
+ it('highlights exactly the references returned by the shared scanner', () => {
+ const prompt = '__artist?__ snake__case __~outfit(mood=warm)__ __animals/[!c]ogs__';
+ const highlighted = scanDynamicPromptSyntax(prompt)
+ .filter(({ kind }) => kind === 'wildcard')
+ .map(({ range }) => range);
+
+ expect(highlighted).toEqual(scanWildcardReferences(prompt).map(({ range }) => range));
+ });
+
it('flags a reference no known wildcard answers to', () => {
const known = new Set(['colours', 'animals/dogs']);
const scan = (prompt: string) => scanDynamicPromptSyntax(prompt, known).map(({ kind }) => kind);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
index 11d4bc726c..8756162854 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
@@ -40,7 +40,7 @@
* embedding parser untouched.
*/
-import { matchesKnownWildcard, WILDCARD_REFERENCE_RE } from '@features/generation/core/dynamicPrompts';
+import { matchesKnownWildcard, scanWildcardReferences } from '@features/generation/core/dynamicPrompts';
import type { PromptRange } from './ast';
@@ -238,20 +238,19 @@ export const scanDynamicPromptSyntax = (
annotations[openBrace.annotationIndex].kind = 'error';
}
- const wildcardPattern = new RegExp(WILDCARD_REFERENCE_RE, 'g');
// Concatenated once. Built inside the loop, this allocated a fresh array of
// every variable and comment in the prompt for every wildcard reference in it.
const enclosingRanges = [...variableRanges, ...commentRanges];
- for (let match = wildcardPattern.exec(prompt); match; match = wildcardPattern.exec(prompt)) {
- const wildcardRange = { end: match.index + match[0].length, start: match.index };
+ for (const reference of scanWildcardReferences(prompt)) {
+ const wildcardRange = reference.range;
if (!enclosingRanges.some((outer) => covers(outer, wildcardRange))) {
// An unresolvable wildcard survives expansion as its own literal text, so it earns the
// same treatment as an unbalanced brace rather than looking like ordinary recognised
// syntax. `matchesKnownWildcard` resolves globs, which is why a valid `__artists/*__`
// is no longer flagged for the sin of not being a name.
- const isUnknown = knownWildcards !== undefined && !matchesKnownWildcard(match[1], knownWildcards);
+ const isUnknown = knownWildcards !== undefined && !matchesKnownWildcard(reference.lookupPath, knownWildcards);
annotations.push({ kind: isUnknown ? 'error' : 'wildcard', range: wildcardRange });
}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
index 7981f276b7..fef08ac9c4 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
@@ -1,6 +1,6 @@
import type { WildcardImportEntry, WildcardImportResolution } from '@features/generation/core/wildcardTransfer';
import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
-import type { WildcardExportFormat } from '@features/generation/ui/wildcardFiles';
+import type { WildcardExportFormat, WildcardFileSource } from '@features/generation/ui/wildcardFiles';
import type { ChangeEvent } from 'react';
import { HStack, Menu, Portal } from '@chakra-ui/react';
@@ -86,11 +86,11 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
);
const startImport = useCallback(
- async (files: readonly File[]) => {
+ async (files: readonly File[], source: WildcardFileSource) => {
setIsBusy(true);
try {
- const entries = planWildcardImport(await readWildcardFiles(files), catalog.wildcards);
+ const entries = planWildcardImport(await readWildcardFiles(files, source), catalog.wildcards);
// Nothing to decide and nothing to explain — the file pick was the
// confirmation, so a dialog with only an Import button would be a click
@@ -132,7 +132,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
const files = [...(event.currentTarget.files ?? [])];
if (files.length > 0) {
- void startImport(files);
+ void startImport(files, 'files');
}
event.currentTarget.value = '';
@@ -153,7 +153,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog
return;
}
- void startImport(files);
+ void startImport(files, 'folder');
},
[notifications, startImport, t]
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
index 8adce7e17c..f3b671b699 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
@@ -80,8 +80,15 @@ describe('getActiveTriggerQuery', () => {
expect(query('a __col\nmore')).toBeNull();
});
- it('gives up once the query is longer than a name would be', () => {
- expect(query(`a __${'x'.repeat(60)}`)).toBeNull();
+ it('keeps every valid wildcard-name character in range and closes over the limit', () => {
+ const maximum = 'x'.repeat(128);
+
+ expect(query(`a __${maximum}`)).toEqual({
+ key: '_',
+ query: maximum,
+ range: { end: 132, start: 2 },
+ });
+ expect(query(`a __${maximum}x`)).toBeNull();
});
it('honours the keys the field answers to', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
index f397f7a4ef..cf67e4b6bc 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
@@ -1,3 +1,5 @@
+import { MAX_WILDCARD_NAME_LENGTH } from '@features/generation/core/dynamicPrompts';
+
let positivePromptElement: HTMLTextAreaElement | null = null;
export type PromptTextRange = { end: number; start: number };
@@ -91,7 +93,7 @@ export interface PromptTriggerQuery {
* Past this the user is writing prose, not naming a wildcard, and an
* autocomplete still hanging around is in the way.
*/
-const MAX_TRIGGER_QUERY_LENGTH = 48;
+const MAX_TRIGGER_QUERY_LENGTH = MAX_WILDCARD_NAME_LENGTH + 2;
/**
* The unfinished trigger the caret is sitting inside, or `null`.
@@ -139,7 +141,9 @@ export const getActiveTriggerQuery = (
// `__colours__` with the caret after it: the scan reached the *opening*
// pair, and the closing one is sitting in the query.
- return query.includes('__') ? null : { key: '_', query, range: { end: caret, start: index - 1 } };
+ return query.includes('__') || query.length > MAX_WILDCARD_NAME_LENGTH
+ ? null
+ : { key: '_', query, range: { end: caret, start: index - 1 } };
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts
index 0588c0939b..caa8112030 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts
@@ -14,38 +14,40 @@ const inFolder = (path: string, contents: string): File => {
describe('readWildcardFiles', () => {
it('reads a text file as one wildcard named after it', async () => {
- await expect(readWildcardFiles([file('colours.txt', 'red\n# a note\n\ngreen')])).resolves.toEqual([
+ await expect(readWildcardFiles([file('colours.txt', 'red\n# a note\n\ngreen')], 'files')).resolves.toEqual([
{ name: 'colours', values: ['red', 'green'] },
]);
});
it('reads a nested yaml collection', async () => {
- await expect(readWildcardFiles([file('all.yaml', 'animals:\n dogs:\n - corgi\n')])).resolves.toEqual([
+ await expect(readWildcardFiles([file('all.yaml', 'animals:\n dogs:\n - corgi\n')], 'files')).resolves.toEqual([
{ name: 'animals/dogs', values: ['corgi'] },
]);
});
it('reads a json collection', async () => {
- await expect(readWildcardFiles([file('all.json', '{"moods":["calm"]}')])).resolves.toEqual([
+ await expect(readWildcardFiles([file('all.json', '{"moods":["calm"]}')], 'files')).resolves.toEqual([
{ name: 'moods', values: ['calm'] },
]);
});
it('takes an extensionless file as text', async () => {
- await expect(readWildcardFiles([file('colours', 'red')])).resolves.toEqual([{ name: 'colours', values: ['red'] }]);
+ await expect(readWildcardFiles([file('colours', 'red')], 'files')).resolves.toEqual([
+ { name: 'colours', values: ['red'] },
+ ]);
});
// `accept` on a file input is a hint, not a rule, and a wildcard folder
// routinely has a readme sitting in it. Read as text, that imported as a
// wildcard named `README` whose values were the markdown.
it('refuses a file that is not a supported format', async () => {
- await expect(readWildcardFiles([file('README.md', '# Wildcards\n\nSome notes.')])).rejects.toBeInstanceOf(
+ await expect(readWildcardFiles([file('README.md', '# Wildcards\n\nSome notes.')], 'files')).rejects.toBeInstanceOf(
WildcardFileError
);
});
it('names the file it could not read', async () => {
- await expect(readWildcardFiles([file('broken.json', '{ nope')])).rejects.toMatchObject({
+ await expect(readWildcardFiles([file('broken.json', '{ nope')], 'files')).rejects.toMatchObject({
fileName: 'broken.json',
});
});
@@ -56,7 +58,7 @@ describe('readWildcardFiles', () => {
it('refuses a collection too large to import instead of overflowing', async () => {
const huge = JSON.stringify(Object.fromEntries(Array.from({ length: 25_000 }, (_, i) => [`w${i}`, ['v']])));
- await expect(readWildcardFiles([file('huge.json', huge)])).rejects.toBeInstanceOf(WildcardFileError);
+ await expect(readWildcardFiles([file('huge.json', huge)], 'files')).rejects.toBeInstanceOf(WildcardFileError);
});
// The whole point of picking a folder: a1111 nests wildcards in directories,
@@ -65,11 +67,17 @@ describe('readWildcardFiles', () => {
it('turns a folder`s nesting into `/` names', async () => {
const picked = [inFolder('wildcards/animals/dogs.txt', 'corgi'), inFolder('wildcards/moods/dogs.txt', 'sleepy')];
- await expect(readWildcardFiles(picked)).resolves.toEqual([
- { name: 'wildcards/animals/dogs', values: ['corgi'] },
- { name: 'wildcards/moods/dogs', values: ['sleepy'] },
+ await expect(readWildcardFiles(picked, 'folder')).resolves.toEqual([
+ { name: 'animals/dogs', values: ['corgi'] },
+ { name: 'moods/dogs', values: ['sleepy'] },
]);
});
+
+ it('retains direct file names even when a relative path is present', async () => {
+ const picked = inFolder('ignored/animals/dogs.txt', 'corgi');
+
+ await expect(readWildcardFiles([picked], 'files')).resolves.toEqual([{ name: 'dogs', values: ['corgi'] }]);
+ });
});
describe('isSupportedWildcardFile', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
index 9ffe30db73..68f3733a1b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
@@ -53,9 +53,19 @@ export const WILDCARD_IMPORT_ACCEPT = [
'application/json',
].join(',');
-/** Directory picking supplies a relative path; a plain pick only has a name. */
-const getFilePath = (file: File): string =>
- (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
+export type WildcardFileSource = 'files' | 'folder';
+
+/** Folder picks shed the selected root while direct picks retain their file names. */
+const getFilePath = (file: File, source: WildcardFileSource): string => {
+ if (source === 'files') {
+ return file.name;
+ }
+
+ const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
+ const firstSeparator = relativePath.indexOf('/');
+
+ return firstSeparator < 0 ? relativePath : relativePath.slice(firstSeparator + 1);
+};
const hasExtension = (path: string, ...extensions: string[]): boolean =>
extensions.some((extension) => path.toLowerCase().endsWith(extension));
@@ -111,14 +121,17 @@ const isTextWildcardFile = (path: string): boolean => {
* whole import over one of them would make folder picking useless.
*/
export const isSupportedWildcardFile = (file: File): boolean => {
- const path = getFilePath(file);
+ const path = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
return (
WILDCARD_COLLECTION_FORMATS.some((format) => hasExtension(path, ...format.extensions)) || isTextWildcardFile(path)
);
};
-export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedWildcard[]> => {
+export const readWildcardFiles = async (
+ files: readonly File[],
+ source: WildcardFileSource
+): Promise<ParsedWildcard[]> => {
const parsed: ParsedWildcard[] = [];
const collect = (wildcards: readonly ParsedWildcard[], fileName: string): void => {
@@ -134,7 +147,7 @@ export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedW
};
for (const file of files) {
- const path = getFilePath(file);
+ const path = getFilePath(file, source);
if (file.size > MAX_IMPORT_FILE_BYTES) {
throw new WildcardFileError(file.name);