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): stop the trigger picker eating the keystroke that opened it

joshistoastf67bc6c7bcad
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
index 951a2a6c6e..6b2111fa26 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next';
import { AddPromptTriggerButton, PromptTriggerPopover } from './PositivePromptActions';
import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';
-import { insertPromptText, type PromptTextRange } from './promptFocus';
+import { getPromptTriggerRange, insertPromptText, type PromptTextRange, type PromptTriggerKey } from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
@@ -33,9 +33,14 @@ interface NegativePromptFieldProps {
type PromptTriggerPickerState = {
anchorRect: { height: number; width: number; x: number; y: number };
+ /** The keystroke the picker consumed, restored if it is dismissed unpicked. */
+ pendingKey?: PromptTriggerKey;
range?: PromptTextRange;
};
+/** No `__name__` here: a negative prompt is never expanded, so it has no wildcards. */
+const NEGATIVE_PROMPT_TRIGGER_KEYS = ['<'] as const;
+
export const NegativePromptField = ({
heightPx,
helpText,
@@ -69,32 +74,62 @@ export const NegativePromptField = ({
[setDraftValue]
);
- const openPromptTriggerPicker = useCallback((anchorElement: HTMLElement, range?: PromptTextRange) => {
- const rect = anchorElement.getBoundingClientRect();
+ const openPromptTriggerPicker = useCallback(
+ (anchorElement: HTMLElement, range?: PromptTextRange, pendingKey?: PromptTriggerKey) => {
+ const rect = anchorElement.getBoundingClientRect();
- setTriggerPickerState({
- anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
- range,
- });
- }, []);
+ setTriggerPickerState({
+ anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
+ pendingKey,
+ range,
+ });
+ },
+ []
+ );
const handlePromptKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (event.key !== '<' || event.altKey || event.ctrlKey || event.metaKey) {
+ if (event.altKey || event.ctrlKey || event.metaKey) {
+ return;
+ }
+
+ const trigger = getPromptTriggerRange(
+ event.currentTarget.value,
+ event.currentTarget.selectionStart,
+ event.currentTarget.selectionEnd,
+ event.key,
+ NEGATIVE_PROMPT_TRIGGER_KEYS
+ );
+
+ if (!trigger) {
return;
}
+ // The keystroke is held rather than typed, so the picked trigger reads as
+ // one edit. `dismissPromptTriggerPicker` puts it back if nothing is picked.
event.preventDefault();
- openPromptTriggerPicker(event.currentTarget, {
- end: event.currentTarget.selectionEnd,
- start: event.currentTarget.selectionStart,
- });
+ openPromptTriggerPicker(event.currentTarget, trigger.range, trigger.key);
},
[openPromptTriggerPicker]
);
const closePromptTriggerPicker = useCallback(() => setTriggerPickerState(null), []);
+ /** Escape or click-away: the swallowed keystroke was the user's, so give it back. */
+ const dismissPromptTriggerPicker = useCallback(() => {
+ if (triggerPickerState?.pendingKey) {
+ insertPromptText({
+ onChange: commitPromptChange,
+ range: triggerPickerState.range,
+ textarea: textareaRef.current,
+ text: triggerPickerState.pendingKey,
+ value: draftValue,
+ });
+ }
+
+ setTriggerPickerState(null);
+ }, [commitPromptChange, draftValue, triggerPickerState]);
+
const selectPromptTrigger = useCallback(
(trigger: string) => {
insertPromptText({
@@ -187,7 +222,7 @@ export const NegativePromptField = ({
open
positioning={triggerPickerPositioning}
selectedModel={selectedModel}
- onClose={closePromptTriggerPicker}
+ onClose={dismissPromptTriggerPicker}
onSelect={selectPromptTrigger}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
index 562b8d60de..5600695ae5 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -13,7 +13,13 @@ import type { DynamicPromptsFieldConfig } from './DynamicPromptsPanel';
import { PositivePromptActions, PromptTriggerPopover } from './PositivePromptActions';
import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';
-import { insertPromptText, type PromptTextRange, registerPositivePromptElement } from './promptFocus';
+import {
+ getPromptTriggerRange,
+ insertPromptText,
+ type PromptTextRange,
+ type PromptTriggerKey,
+ registerPositivePromptElement,
+} from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
@@ -36,9 +42,14 @@ interface PositivePromptFieldProps {
type PromptTriggerPickerState = {
anchorRect: { height: number; width: number; x: number; y: number };
+ /** The keystroke the picker consumed, restored if it is dismissed unpicked. */
+ pendingKey?: PromptTriggerKey;
range?: PromptTextRange;
};
+/** The positive prompt is the only field whose `__name__` references resolve. */
+const POSITIVE_PROMPT_TRIGGER_KEYS = ['<', '_'] as const;
+
export const PositivePromptField = ({
batchCount = 1,
dynamicPrompts = null,
@@ -81,14 +92,18 @@ export const PositivePromptField = ({
[commitDraftValue]
);
- const openPromptTriggerPicker = useCallback((anchorElement: HTMLElement, range?: PromptTextRange) => {
- const rect = anchorElement.getBoundingClientRect();
+ const openPromptTriggerPicker = useCallback(
+ (anchorElement: HTMLElement, range?: PromptTextRange, pendingKey?: PromptTriggerKey) => {
+ const rect = anchorElement.getBoundingClientRect();
- setTriggerPickerState({
- anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
- range,
- });
- }, []);
+ setTriggerPickerState({
+ anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
+ pendingKey,
+ range,
+ });
+ },
+ []
+ );
const handlePromptKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -96,28 +111,43 @@ export const PositivePromptField = ({
return;
}
- // `<` opens the picker outright; `__` does too, on the second underscore,
- // since that is the point where the user has committed to a wildcard.
- const opensPicker =
- event.key === '<' ||
- (event.key === '_' && event.currentTarget.value.slice(0, event.currentTarget.selectionStart).endsWith('_'));
+ const trigger = getPromptTriggerRange(
+ event.currentTarget.value,
+ event.currentTarget.selectionStart,
+ event.currentTarget.selectionEnd,
+ event.key,
+ POSITIVE_PROMPT_TRIGGER_KEYS
+ );
- if (!opensPicker) {
+ if (!trigger) {
return;
}
+ // The keystroke is held rather than typed, so the picked trigger reads as
+ // one edit. `dismissPromptTriggerPicker` puts it back if nothing is picked.
event.preventDefault();
- // The `__` case replaces the underscore already typed, so the inserted
- // `__name__` does not end up with three leading underscores.
- const start = event.key === '_' ? event.currentTarget.selectionStart - 1 : event.currentTarget.selectionStart;
-
- openPromptTriggerPicker(event.currentTarget, { end: event.currentTarget.selectionEnd, start });
+ openPromptTriggerPicker(event.currentTarget, trigger.range, trigger.key);
},
[openPromptTriggerPicker]
);
const closePromptTriggerPicker = useCallback(() => setTriggerPickerState(null), []);
+ /** Escape or click-away: the swallowed keystroke was the user's, so give it back. */
+ const dismissPromptTriggerPicker = useCallback(() => {
+ if (triggerPickerState?.pendingKey) {
+ insertPromptText({
+ onChange: commitPromptChange,
+ range: triggerPickerState.range,
+ textarea: textareaRef.current,
+ text: triggerPickerState.pendingKey === '_' ? '__' : triggerPickerState.pendingKey,
+ value: draftValue,
+ });
+ }
+
+ setTriggerPickerState(null);
+ }, [commitPromptChange, draftValue, triggerPickerState]);
+
const selectPromptTrigger = useCallback(
(trigger: string) => {
insertPromptText({
@@ -225,7 +255,7 @@ export const PositivePromptField = ({
open
positioning={triggerPickerPositioning}
selectedModel={selectedModel}
- onClose={closePromptTriggerPicker}
+ onClose={dismissPromptTriggerPicker}
onSelect={selectPromptTrigger}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx
new file mode 100644
index 0000000000..90148b5a9f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx
@@ -0,0 +1,148 @@
+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+// The actions row and the picker's own contents need Generation's UI port; neither
+// is what these tests are about. The stub records the two ways out of the picker so
+// they can be invoked directly — a real click would have to compete with the
+// textarea for the same coordinates.
+const picker = vi.hoisted(() => ({ current: null as { onClose: () => void; onSelect: (t: string) => void } | null }));
+
+vi.mock('@features/generation/ui/promptFields/PositivePromptActions', () => ({
+ PositivePromptActions: () => null,
+ PromptTriggerPopover: (props: { onClose: () => void; onSelect: (trigger: string) => void }) => {
+ picker.current = props;
+ return null;
+ },
+}));
+
+vi.mock('@features/generation/data/wildcards', () => ({
+ createWildcard: vi.fn(),
+ deleteWildcard: vi.fn(),
+ invalidateWildcardDependents: vi.fn(),
+ updateWildcard: vi.fn(),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const render = async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <PositivePromptField
+ heightPx={120}
+ loras={[]}
+ projectId="project-1"
+ selectedModel={undefined}
+ showSyntaxHighlighting={false}
+ value=""
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </ChakraProvider>
+ </QueryClientProvider>
+ );
+ });
+};
+
+const textarea = () => host!.querySelector('textarea')!;
+const isPickerOpen = () => picker.current !== null;
+
+/** Runs one of the picker's exits, then lets insertPromptText's caret frame settle. */
+const leavePicker = async (exit: (handlers: NonNullable<typeof picker.current>) => void) => {
+ const handlers = picker.current!;
+
+ await act(() => exit(handlers));
+ await act(async () => {
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ });
+ });
+};
+
+const dismissPicker = () => leavePicker((handlers) => handlers.onClose());
+const pickColors = () => leavePicker((handlers) => handlers.onSelect('__colors__'));
+
+const type = async (text: string) => {
+ await act(async () => {
+ await userEvent.click(textarea());
+ });
+ await act(async () => {
+ await userEvent.type(textarea(), text);
+ });
+};
+
+beforeEach(async () => {
+ picker.current = null;
+ await render();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('the prompt trigger picker and the keystroke that opens it', () => {
+ // Regression: the picker opened on any second underscore and swallowed the
+ // keystroke, so an ordinary word containing `__` could not be typed at all.
+ it('leaves an underscore inside a word alone', async () => {
+ await type('a close_up shot');
+
+ expect(textarea().value).toBe('a close_up shot');
+ expect(isPickerOpen()).toBe(false);
+ });
+
+ it('types a double underscore mid-word without opening the picker', async () => {
+ await type('snake__case');
+
+ expect(textarea().value).toBe('snake__case');
+ expect(isPickerOpen()).toBe(false);
+ });
+
+ it('opens on `__` where a wildcard reference could begin', async () => {
+ await type('a photo of __');
+
+ expect(isPickerOpen()).toBe(true);
+ });
+
+ // Regression: dismissing left the prompt one underscore short of what was typed.
+ it('gives the underscores back when the picker is dismissed', async () => {
+ await type('a photo of __');
+ await dismissPicker();
+
+ expect(textarea().value).toBe('a photo of __');
+ });
+
+ it('gives `<` back when the picker is dismissed', async () => {
+ await type('a photo of <');
+ expect(isPickerOpen()).toBe(true);
+
+ await dismissPicker();
+
+ expect(textarea().value).toBe('a photo of <');
+ });
+
+ it('replaces the typed underscores with the picked reference', async () => {
+ await type('a photo of __');
+ await pickColors();
+
+ expect(textarea().value).toBe('a photo of __colors__');
+ });
+});
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 3ef902eb60..526312f61f 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
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
-import { insertTextAtRange } from './promptFocus';
+import type { PromptTriggerKey } from './promptFocus';
+
+import { getPromptTriggerRange, insertTextAtRange } from './promptFocus';
describe('insertTextAtRange', () => {
it('inserts text at a collapsed range', () => {
@@ -19,3 +21,47 @@ describe('insertTextAtRange', () => {
expect(insertTextAtRange('cat', ' fluffy', undefined, 3)).toEqual({ caret: 10, value: 'cat fluffy' });
});
});
+
+describe('getPromptTriggerRange', () => {
+ // The caret sits at the end of `value` unless a test says otherwise.
+ const match = (value: string, key: string, keys: readonly PromptTriggerKey[] = ['<', '_']) =>
+ getPromptTriggerRange(value, value.length, value.length, key, keys);
+
+ it('opens on `<`, replacing nothing', () => {
+ expect(match('a photo of ', '<')).toEqual({ key: '<', range: { end: 11, start: 11 } });
+ });
+
+ it('opens on the second underscore of a reference, replacing the first', () => {
+ expect(match('a photo of _', '_')).toEqual({ key: '_', range: { end: 12, start: 11 } });
+ expect(match('_', '_')).toEqual({ key: '_', range: { end: 1, start: 0 } });
+ // Punctuation is a boundary too — `(__style__)1.2` is ordinary usage.
+ expect(match('(_', '_')).toEqual({ key: '_', range: { end: 2, start: 1 } });
+ });
+
+ // Regression: this swallowed the keystroke, so `__` could not be typed at all.
+ it('stays shut in the middle of a word', () => {
+ expect(match('snake_', '_')).toBeNull();
+ expect(match('close_up_', '_')).toBeNull();
+ expect(match('2_', '_')).toBeNull();
+ });
+
+ it('stays shut on the first underscore', () => {
+ expect(match('a photo of', '_')).toBeNull();
+ });
+
+ it('ignores keys the field does not answer to', () => {
+ expect(match('a photo of _', '_', ['<'])).toBeNull();
+ expect(match('a photo of ', '<', ['_'])).toBeNull();
+ });
+
+ it('ignores every other key', () => {
+ expect(match('a photo of ', 'a')).toBeNull();
+ expect(match('a photo of ', 'Enter')).toBeNull();
+ });
+
+ it('replaces the whole selection, not just the caret', () => {
+ // `a _[cat]` with `cat` selected: typing `_` would overwrite the selection,
+ // so the picked reference has to take the underscore and the selection with it.
+ expect(getPromptTriggerRange('a _cat', 3, 6, '_', ['_'])).toEqual({ key: '_', range: { end: 6, start: 2 } });
+ });
+});
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 14a3bf520a..06dd463c88 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
@@ -71,3 +71,48 @@ export const insertPositivePromptText = ({
text: string;
value: string;
}): void => insertPromptText({ onChange, range, textarea: positivePromptElement, text, value });
+
+/** Which trigger keys a field answers to. Wildcards only exist on the positive prompt. */
+export type PromptTriggerKey = '<' | '_';
+
+export interface PromptTriggerMatch {
+ /** The keystroke the picker consumed, so a dismissal can put it back. */
+ key: PromptTriggerKey;
+ /** The span the picked trigger replaces, including anything already typed. */
+ range: PromptTextRange;
+}
+
+/** `_` is a word character, so `snake__case` must not read as the start of a reference. */
+const isWordCharacter = (character: string | undefined): boolean =>
+ character !== undefined && /[A-Za-z0-9_]/.test(character);
+
+/**
+ * Whether `key` opens the trigger picker, and what it would replace.
+ *
+ * `<` opens outright — it only ever starts an embedding token. `__` opens on the
+ * second underscore, but only where a wildcard reference could actually begin:
+ * after whitespace, punctuation, or the start of the prompt. That leaves
+ * `snake__case` as ordinary text, which the same rule in
+ * `core/dynamicPrompts.ts` already excludes from being a reference.
+ */
+export const getPromptTriggerRange = (
+ value: string,
+ selectionStart: number,
+ selectionEnd: number,
+ key: string,
+ keys: readonly PromptTriggerKey[]
+): PromptTriggerMatch | null => {
+ if (key === '<' && keys.includes('<')) {
+ return { key: '<', range: { end: selectionEnd, start: selectionStart } };
+ }
+
+ if (key === '_' && keys.includes('_') && value[selectionStart - 1] === '_') {
+ return isWordCharacter(value[selectionStart - 2])
+ ? null
+ : // The underscore already typed is part of the reference, so the picked
+ // `__name__` replaces it rather than landing after it.
+ { key: '_', range: { end: selectionEnd, start: selectionStart - 1 } };
+ }
+
+ return null;
+};