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): anchor the trigger picker at the caret

joshistoastd2359b2dfa8f
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 7b2093ac1c..6fa413ea54 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,11 +25,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 112.39999999850988,
+ "domContentLoadedMedianMs": 117.20000000298023,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 112.39999999850988,
- "longestTaskMaxMs": 70,
+ "loadMedianMs": 117.20000000298023,
+ "longestTaskMaxMs": 71,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -56,7 +56,7 @@
"scriptRequestCount": 15,
"totalRawBytes": 1590803
},
- "routeReadyMedianMs": 231.09999999403954,
+ "routeReadyMedianMs": 240.20000000298023,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -83,11 +83,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.20000000298023,
+ "domContentLoadedMedianMs": 116,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.30000000447035,
- "longestTaskMaxMs": 72,
+ "loadMedianMs": 116,
+ "longestTaskMaxMs": 73,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -114,7 +114,7 @@
"scriptRequestCount": 15,
"totalRawBytes": 1590803
},
- "routeReadyMedianMs": 293.1000000014901,
+ "routeReadyMedianMs": 304.69999999552965,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -141,13 +141,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.5,
+ "domContentLoadedMedianMs": 117.30000000447035,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.5,
- "longestTaskMaxMs": 113,
+ "loadMedianMs": 117.30000000447035,
+ "longestTaskMaxMs": 116,
"owner": "workbench",
- "projectSwitchMedianMs": 67.2813270000006,
+ "projectSwitchMedianMs": 66.73783400000138,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -157,9 +157,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -168,11 +168,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 618.8000000044703,
+ "routeReadyMedianMs": 632.6000000014901,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -199,13 +199,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 111.20000000298023,
+ "domContentLoadedMedianMs": 118.79999999701977,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 111.20000000298023,
- "longestTaskMaxMs": 123,
+ "loadMedianMs": 118.79999999701977,
+ "longestTaskMaxMs": 130,
"owner": "workbench",
- "projectSwitchMedianMs": 85.25958499999979,
+ "projectSwitchMedianMs": 96.06867600000078,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -215,9 +215,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -226,11 +226,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 666,
+ "routeReadyMedianMs": 685.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -257,11 +257,11 @@
"scriptRequestCount": 7,
"totalRawBytes": 293334
},
- "domContentLoadedMedianMs": 111.20000000298023,
+ "domContentLoadedMedianMs": 118.59999999403954,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 80.90000000596046,
- "loadMedianMs": 111.20000000298023,
- "longestTaskMaxMs": 113,
+ "layoutSwitchMedianMs": 85.20000000298023,
+ "loadMedianMs": 118.59999999403954,
+ "longestTaskMaxMs": 119,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -273,9 +273,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 99,
- "scriptRawBytes": 3271651,
+ "scriptRawBytes": 3276518,
"scriptRequestCount": 93,
- "totalRawBytes": 3564030
+ "totalRawBytes": 3568897
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -284,11 +284,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 99,
- "scriptRawBytes": 3304368,
+ "scriptRawBytes": 3309284,
"scriptRequestCount": 93,
- "totalRawBytes": 3599671
+ "totalRawBytes": 3604586
},
- "routeReadyMedianMs": 761.3999999985099,
+ "routeReadyMedianMs": 805.3000000044703,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -315,11 +315,11 @@
"scriptRequestCount": 7,
"totalRawBytes": 293334
},
- "domContentLoadedMedianMs": 110.79999999701977,
+ "domContentLoadedMedianMs": 115.10000000149012,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 320.80000000447035,
- "loadMedianMs": 110.89999999850988,
- "longestTaskMaxMs": 372,
+ "layoutSwitchMedianMs": 349.70000000298023,
+ "loadMedianMs": 115.20000000298023,
+ "longestTaskMaxMs": 404,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -331,9 +331,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 99,
- "scriptRawBytes": 3271651,
+ "scriptRawBytes": 3276518,
"scriptRequestCount": 93,
- "totalRawBytes": 3564030
+ "totalRawBytes": 3568897
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -342,11 +342,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 99,
- "scriptRawBytes": 3304368,
+ "scriptRawBytes": 3309284,
"scriptRequestCount": 93,
- "totalRawBytes": 3599671
+ "totalRawBytes": 3604586
},
- "routeReadyMedianMs": 1159,
+ "routeReadyMedianMs": 1248,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -373,11 +373,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 108.5,
+ "domContentLoadedMedianMs": 115.29999999701977,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 72.70000000298023,
- "loadMedianMs": 108.5,
- "longestTaskMaxMs": 114,
+ "layoutSwitchMedianMs": 81.10000000149012,
+ "loadMedianMs": 115.29999999701977,
+ "longestTaskMaxMs": 119,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -389,9 +389,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -400,11 +400,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 763.6000000014901,
+ "routeReadyMedianMs": 774.2999999970198,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -431,11 +431,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 111.5,
+ "domContentLoadedMedianMs": 112.70000000298023,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 124.69999999552965,
- "loadMedianMs": 111.5,
- "longestTaskMaxMs": 426,
+ "layoutSwitchMedianMs": 137.70000000298023,
+ "loadMedianMs": 112.70000000298023,
+ "longestTaskMaxMs": 463,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -447,9 +447,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -458,11 +458,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 956.2999999970198,
+ "routeReadyMedianMs": 1015.9000000059605,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -489,11 +489,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 111.39999999850988,
+ "domContentLoadedMedianMs": 117,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 28.80000000447035,
- "loadMedianMs": 111.39999999850988,
- "longestTaskMaxMs": 113,
+ "layoutSwitchMedianMs": 30.200000002980232,
+ "loadMedianMs": 117,
+ "longestTaskMaxMs": 117,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -505,9 +505,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -516,11 +516,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 722.3999999985099,
+ "routeReadyMedianMs": 740.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -547,11 +547,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 113,
+ "domContentLoadedMedianMs": 117.79999999701977,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 38.600000001490116,
- "loadMedianMs": 113,
- "longestTaskMaxMs": 130,
+ "layoutSwitchMedianMs": 44.79999999701977,
+ "loadMedianMs": 117.89999999850988,
+ "longestTaskMaxMs": 132,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -563,9 +563,9 @@
"largestAssetRawBytes": 737748,
"otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2995457,
+ "scriptRawBytes": 3000324,
"scriptRequestCount": 89,
- "totalRawBytes": 3287836
+ "totalRawBytes": 3292703
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -574,11 +574,11 @@
"largestAssetRawBytes": 745126,
"otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3025412,
+ "scriptRawBytes": 3030328,
"scriptRequestCount": 89,
- "totalRawBytes": 3320715
+ "totalRawBytes": 3325631
},
- "routeReadyMedianMs": 882.1000000014901,
+ "routeReadyMedianMs": 931.7999999970198,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1040,13 +1040,17 @@
"source:src/features/generation/ui/promptFields/PromptTemplatesButton.tsx",
"source:src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx",
"source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",
"source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
+ "source:src/features/generation/ui/promptFields/promptCaret.ts",
"source:src/features/generation/ui/promptFields/promptFocus.ts",
"source:src/features/generation/ui/promptFields/promptHistoryNavigation.ts",
+ "source:src/features/generation/ui/promptFields/promptTriggerOptions.ts",
+ "source:src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx",
"source:src/features/generation/ui/promptTemplateDraftStore.ts",
"source:src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx",
"source:src/features/generation/ui/reference-images/ReferenceImageCard.tsx",
@@ -1837,13 +1841,17 @@
"source:src/features/generation/ui/promptFields/PromptTemplatesButton.tsx",
"source:src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx",
"source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",
"source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
+ "source:src/features/generation/ui/promptFields/promptCaret.ts",
"source:src/features/generation/ui/promptFields/promptFocus.ts",
"source:src/features/generation/ui/promptFields/promptHistoryNavigation.ts",
+ "source:src/features/generation/ui/promptFields/promptTriggerOptions.ts",
+ "source:src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx",
"source:src/features/generation/ui/promptTemplateDraftStore.ts",
"source:src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx",
"source:src/features/generation/ui/reference-images/ReferenceImageCard.tsx",
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 4205520e60..1c5493b7e2 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
@@ -12,9 +12,10 @@ import { useTranslation } from 'react-i18next';
import { AddPromptTriggerButton, PromptTriggerPopover } from './PositivePromptActions';
import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';
-import { getPromptTriggerRange, insertPromptText, type PromptTextRange, type PromptTriggerKey } from './promptFocus';
+import { insertPromptText } from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
+import { usePromptTriggerAutocomplete } from './usePromptTriggerAutocomplete';
const PROMPT_INPUT_DEBOUNCE_MS = 250;
@@ -37,12 +38,8 @@ interface NegativePromptFieldProps {
onResizeEnd: (heightPx: number) => void;
}
-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 `+` button's browsable list, anchored to the button that opened it. */
+type PromptTriggerPickerState = { anchorRect: { height: number; width: number; x: number; y: number } };
/** No `__name__` here: a negative prompt is never expanded, so it has no wildcards. */
const NEGATIVE_PROMPT_TRIGGER_KEYS = ['<'] as const;
@@ -83,18 +80,19 @@ export const NegativePromptField = ({
[setDraftValue]
);
- const openPromptTriggerPicker = useCallback(
- (anchorElement: HTMLElement, range?: PromptTextRange, pendingKey?: PromptTriggerKey) => {
- const rect = anchorElement.getBoundingClientRect();
+ const openPromptTriggerPicker = useCallback((anchorElement: HTMLElement) => {
+ const rect = anchorElement.getBoundingClientRect();
- setTriggerPickerState({
- anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
- pendingKey,
- range,
- });
- },
- []
- );
+ setTriggerPickerState({ anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y } });
+ }, []);
+
+ const autocomplete = usePromptTriggerAutocomplete({
+ isDisabled: isTemplateViewMode,
+ keys: NEGATIVE_PROMPT_TRIGGER_KEYS,
+ loras,
+ onChange: commitPromptChange,
+ selectedModel,
+ });
const handlePromptKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -102,55 +100,24 @@ export const NegativePromptField = ({
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, trigger.range, trigger.key);
+ autocomplete.handleKeyDown(event);
},
- [openPromptTriggerPicker]
+ [autocomplete]
);
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({
onChange: commitPromptChange,
- range: triggerPickerState?.range,
textarea: textareaRef.current,
text: trigger,
value: draftValue,
});
closePromptTriggerPicker();
},
- [closePromptTriggerPicker, commitPromptChange, draftValue, triggerPickerState?.range]
+ [closePromptTriggerPicker, commitPromptChange, draftValue]
);
const handleOpenPromptTriggerPicker = useCallback(
@@ -168,10 +135,16 @@ export const NegativePromptField = ({
}, []);
const handlePromptChange = useCallback(
- (event: ChangeEvent<HTMLTextAreaElement>) => commitPromptChange(event.currentTarget.value),
- [commitPromptChange]
+ (event: ChangeEvent<HTMLTextAreaElement>) => {
+ commitPromptChange(event.currentTarget.value);
+ autocomplete.refresh(event.currentTarget);
+ },
+ [autocomplete, commitPromptChange]
);
+ /** Clicking moves the caret, which may land in — or out of — a trigger. */
+ const handlePromptClick = useCallback(() => autocomplete.refresh(textareaRef.current), [autocomplete]);
+
// The switch shares the Field.Root with the textarea; an explicit id keeps
// its label bound to its own hidden input instead of the Field's control id.
const enableSwitchInputId = useId();
@@ -229,6 +202,7 @@ export const NegativePromptField = ({
<>
<PromptTextarea
{...PROMPT_ATTENTION_TARGET_PROPS}
+ {...autocomplete.comboboxProps}
aria-label={t('widgets.generate.negativePrompt')}
defaultHeightPx={heightPx}
minHeightPx={56}
@@ -241,18 +215,20 @@ export const NegativePromptField = ({
textareaRef={handleTextareaRef}
title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
value={templateChunks ? templateChunks.join('') : draftValue}
+ onBlur={autocomplete.close}
onChange={handlePromptChange}
- onClick={isViewingMerged ? exitViewMode : undefined}
+ onClick={isViewingMerged ? exitViewMode : handlePromptClick}
onKeyDown={handlePromptKeyDown}
onResizeEnd={onResizeEnd}
/>
+ {autocomplete.element}
{triggerPickerState ? (
<PromptTriggerPopover
loras={loras}
open
positioning={triggerPickerPositioning}
selectedModel={selectedModel}
- onClose={dismissPromptTriggerPicker}
+ onClose={closePromptTriggerPicker}
onSelect={selectPromptTrigger}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index 3f3b630cbb..d059a98469 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -11,7 +11,12 @@ import { expandPrompt, imageToPrompt } from '@features/generation/data/promptUti
import { GenerationModelSelect as ModelSelect, useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { DynamicPromptsButton } from '@features/generation/ui/promptFields/DynamicPromptsButton';
import { PromptTemplatesButton } from '@features/generation/ui/promptFields/PromptTemplatesButton';
-import { useWildcards } from '@features/generation/ui/useWildcards';
+import {
+ filterPromptTriggerOptions,
+ groupPromptTriggerOptions,
+ usePromptTriggerOptions,
+ type PromptTriggerOption,
+} from '@features/generation/ui/promptFields/promptTriggerOptions';
import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton, Scrollable, Tooltip } from '@platform/ui';
@@ -124,85 +129,6 @@ export const PositivePromptActions = ({
);
};
-type PromptTriggerOption = {
- group: string;
- label: string;
- value: string;
-};
-
-const getTriggerPhrases = (model: unknown): string[] => {
- if (!model || typeof model !== 'object') {
- return [];
- }
-
- const triggerPhrases = (model as { trigger_phrases?: unknown }).trigger_phrases;
-
- return Array.isArray(triggerPhrases)
- ? triggerPhrases.filter((phrase): phrase is string => typeof phrase === 'string' && phrase.trim().length > 0)
- : [];
-};
-
-const getPromptTriggerOptions = ({
- compatibleEmbeddingsLabel,
- loras,
- mainModelLabel,
- models,
- selectedModel,
- wildcards,
- wildcardsLabel,
-}: {
- compatibleEmbeddingsLabel: string;
- loras: GenerateLora[];
- mainModelLabel: string;
- models: readonly ModelConfig[];
- selectedModel: GenerateModelConfig | undefined;
- wildcards: readonly { name: string; values: string[] }[];
- wildcardsLabel: string;
-}): PromptTriggerOption[] => {
- const options: PromptTriggerOption[] = [];
-
- // A wildcard inserts as `__name__`, which is just another trigger the picker
- // can splice in, so it rides in the same list as embeddings and LoRA phrases.
- for (const wildcard of wildcards) {
- options.push({ group: wildcardsLabel, label: wildcard.name, value: `__${wildcard.name}__` });
- }
-
- for (const phrase of getTriggerPhrases(selectedModel)) {
- options.push({ group: selectedModel?.name ?? mainModelLabel, label: phrase, value: phrase });
- }
-
- for (const lora of loras) {
- if (!lora.isEnabled) {
- continue;
- }
-
- for (const phrase of getTriggerPhrases(lora.model)) {
- options.push({ group: lora.model.name, label: phrase, value: phrase });
- }
- }
-
- if (selectedModel) {
- for (const model of models) {
- if (model.type === 'embedding' && model.base === selectedModel.base) {
- options.push({ group: compatibleEmbeddingsLabel, label: model.name, value: `<${model.name}>` });
- }
- }
- }
-
- const seen = new Set<string>();
-
- return options.filter((option) => {
- const key = `${option.group}:${option.value}`;
-
- if (seen.has(key)) {
- return false;
- }
-
- seen.add(key);
- return true;
- });
-};
-
/**
* Swaps the prompt box between the authored text and the merged result. Quiet
* states only — the icon changes, nothing tints or animates.
@@ -271,49 +197,11 @@ export const PromptTriggerPopover = ({
onSelect: (trigger: string) => void;
}) => {
const { t } = useTranslation();
- const { catalog: models, ensureLoaded: ensureModelsLoaded } = useGenerationUi().models;
- const { wildcards } = useWildcards();
+ const { ensureLoaded: ensureModelsLoaded } = useGenerationUi().models;
const [searchTerm, setSearchTerm] = useState('');
-
- const options = useMemo(
- () =>
- getPromptTriggerOptions({
- compatibleEmbeddingsLabel: t('widgets.generate.compatibleEmbeddings'),
- loras,
- mainModelLabel: t('widgets.generate.mainModel'),
- models,
- selectedModel,
- wildcards,
- wildcardsLabel: t('widgets.generate.dynamicPrompts.wildcards'),
- }),
- [loras, models, selectedModel, t, wildcards]
- );
-
- const filteredOptions = useMemo(
- () =>
- options.filter((option) => {
- const query = searchTerm.trim().toLowerCase();
-
- return !query || option.label.toLowerCase().includes(query) || option.group.toLowerCase().includes(query);
- }),
- [options, searchTerm]
- );
-
- const groupedOptions = useMemo(
- () =>
- filteredOptions.reduce<Array<{ group: string; options: PromptTriggerOption[] }>>((groups, option) => {
- const existingGroup = groups.find((group) => group.group === option.group);
-
- if (existingGroup) {
- existingGroup.options.push(option);
- } else {
- groups.push({ group: option.group, options: [option] });
- }
-
- return groups;
- }, []),
- [filteredOptions]
- );
+ const options = usePromptTriggerOptions(loras, selectedModel);
+ const filteredOptions = useMemo(() => filterPromptTriggerOptions(options, searchTerm), [options, searchTerm]);
+ const groupedOptions = useMemo(() => groupPromptTriggerOptions(filteredOptions), [filteredOptions]);
const popoverPositioning = useMemo(() => ({ ...positioning, placement: 'bottom-start' as const }), [positioning]);
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 5853537b80..4267451f0c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -15,15 +15,10 @@ import type { DynamicPromptsFieldConfig } from './DynamicPromptsPanel';
import { PositivePromptActions, PromptTriggerPopover } from './PositivePromptActions';
import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';
-import {
- getPromptTriggerRange,
- insertPromptText,
- type PromptTextRange,
- type PromptTriggerKey,
- registerPositivePromptElement,
-} from './promptFocus';
+import { insertPromptText, registerPositivePromptElement } from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
+import { usePromptTriggerAutocomplete } from './usePromptTriggerAutocomplete';
const PROMPT_INPUT_DEBOUNCE_MS = 250;
@@ -54,12 +49,8 @@ interface PositivePromptFieldProps {
onUsePrompt: (prompt: PromptHistoryItem) => void;
}
-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 `+` button's browsable list, anchored to the button that opened it. */
+type PromptTriggerPickerState = { anchorRect: { height: number; width: number; x: number; y: number } };
/** The positive prompt is the only field whose `__name__` references resolve. */
const POSITIVE_PROMPT_TRIGGER_KEYS = ['<', '_'] as const;
@@ -111,18 +102,19 @@ export const PositivePromptField = ({
[commitDraftValue]
);
- const openPromptTriggerPicker = useCallback(
- (anchorElement: HTMLElement, range?: PromptTextRange, pendingKey?: PromptTriggerKey) => {
- const rect = anchorElement.getBoundingClientRect();
+ const openPromptTriggerPicker = useCallback((anchorElement: HTMLElement) => {
+ const rect = anchorElement.getBoundingClientRect();
- setTriggerPickerState({
- anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y },
- pendingKey,
- range,
- });
- },
- []
- );
+ setTriggerPickerState({ anchorRect: { height: rect.height, width: rect.width, x: rect.x, y: rect.y } });
+ }, []);
+
+ const autocomplete = usePromptTriggerAutocomplete({
+ isDisabled: isTemplateViewMode,
+ keys: POSITIVE_PROMPT_TRIGGER_KEYS,
+ loras,
+ onChange: commitPromptChange,
+ selectedModel,
+ });
const handlePromptKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -130,55 +122,26 @@ export const PositivePromptField = ({
return;
}
- const trigger = getPromptTriggerRange(
- event.currentTarget.value,
- event.currentTarget.selectionStart,
- event.currentTarget.selectionEnd,
- event.key,
- POSITIVE_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, trigger.range, trigger.key);
+ // The autocomplete gets first refusal: while its list is open the arrow
+ // keys belong to it rather than to prompt history.
+ autocomplete.handleKeyDown(event);
},
- [openPromptTriggerPicker]
+ [autocomplete]
);
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({
onChange: commitPromptChange,
- range: triggerPickerState?.range,
textarea: textareaRef.current,
text: trigger,
value: draftValue,
});
closePromptTriggerPicker();
},
- [closePromptTriggerPicker, commitPromptChange, draftValue, triggerPickerState?.range]
+ [closePromptTriggerPicker, commitPromptChange, draftValue]
);
const handleUsePrompt = useCallback(
@@ -270,10 +233,16 @@ export const PositivePromptField = ({
);
const handlePromptChange = useCallback(
- (event: ChangeEvent<HTMLTextAreaElement>) => commitPromptChange(event.currentTarget.value),
- [commitPromptChange]
+ (event: ChangeEvent<HTMLTextAreaElement>) => {
+ commitPromptChange(event.currentTarget.value);
+ autocomplete.refresh(event.currentTarget);
+ },
+ [autocomplete, commitPromptChange]
);
+ /** Clicking moves the caret, which may land in — or out of — a trigger. */
+ const handlePromptClick = useCallback(() => autocomplete.refresh(textareaRef.current), [autocomplete]);
+
// View mode keeps the same textarea rather than swapping in a preview
// component: `ResizableTextarea` reads its height once on mount, and the
// element is also what `focusPositivePrompt` and the attention hotkeys target,
@@ -296,6 +265,7 @@ export const PositivePromptField = ({
<Field label={t('common.prompt')} labelEnd={labelEnd}>
<PromptTextarea
{...PROMPT_ATTENTION_TARGET_PROPS}
+ {...autocomplete.comboboxProps}
aria-label={t('widgets.generate.positivePrompt')}
defaultHeightPx={heightPx}
minHeightPx={96}
@@ -310,18 +280,20 @@ export const PositivePromptField = ({
textareaRef={handleTextareaRef}
title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
value={isViewingMerged ? effectivePositivePrompt : draftValue}
+ onBlur={autocomplete.close}
onChange={handlePromptChange}
- onClick={isViewingMerged ? exitViewMode : undefined}
+ onClick={isViewingMerged ? exitViewMode : handlePromptClick}
onKeyDown={handlePromptKeyDown}
onResizeEnd={onResizeEnd}
/>
+ {autocomplete.element}
{triggerPickerState ? (
<PromptTriggerPopover
loras={loras}
open
positioning={triggerPickerPositioning}
selectedModel={selectedModel}
- onClose={dismissPromptTriggerPicker}
+ onClose={closePromptTriggerPicker}
onSelect={selectPromptTrigger}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx
new file mode 100644
index 0000000000..1822723ade
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx
@@ -0,0 +1,157 @@
+import type { CaretRect } from '@features/generation/ui/promptFields/promptCaret';
+import type { PromptTriggerOption } from '@features/generation/ui/promptFields/promptTriggerOptions';
+import type { MouseEvent } from 'react';
+
+import { Box, Portal, Stack, Text } from '@chakra-ui/react';
+import { groupPromptTriggerOptions } from '@features/generation/ui/promptFields/promptTriggerOptions';
+import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
+
+const LIST_WIDTH_PX = 260;
+const MAX_LIST_HEIGHT_PX = 220;
+/** Clear of the current line, so the list never covers what is being typed. */
+const CARET_GAP_PX = 4;
+const VIEWPORT_MARGIN_PX = 8;
+const OPTION_HOVER_CSS = { bg: 'bg.emphasized' };
+
+/**
+ * The list that follows the caret while a `__` or `<` is being typed.
+ *
+ * Deliberately not a `Popover`: this must never take focus. The user is typing
+ * in the textarea and the textarea stays the active element throughout — arrow
+ * keys, Enter and Escape are handled there and only reach here as the
+ * `activeIndex` prop. That also makes it a plain positioned surface rather than
+ * a dismissable layer, which is why there is no trigger and no close button.
+ *
+ * The old picker anchored to the whole textarea and opened `bottom-start`, so in
+ * a tall prompt box the list appeared at the bottom-left corner — often hundreds
+ * of pixels from where the user was looking.
+ */
+export const PromptTriggerAutocomplete = ({
+ activeIndex,
+ caretRect,
+ listboxId,
+ onSelect,
+ options,
+ optionIdPrefix,
+}: {
+ activeIndex: number;
+ caretRect: CaretRect;
+ listboxId: string;
+ optionIdPrefix: string;
+ options: readonly PromptTriggerOption[];
+ onSelect: (option: PromptTriggerOption) => void;
+}) => {
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const groups = useMemo(() => groupPromptTriggerOptions(options), [options]);
+
+ // Below the caret when there is room, above it when there is not, and never
+ // off the right edge of a narrow window.
+ const spaceBelow = window.innerHeight - (caretRect.y + caretRect.height);
+ const height = Math.min(MAX_LIST_HEIGHT_PX, Math.max(spaceBelow, caretRect.y) - VIEWPORT_MARGIN_PX - CARET_GAP_PX);
+ const opensBelow = spaceBelow >= height + CARET_GAP_PX + VIEWPORT_MARGIN_PX;
+ const left = Math.max(
+ VIEWPORT_MARGIN_PX,
+ Math.min(caretRect.x, window.innerWidth - LIST_WIDTH_PX - VIEWPORT_MARGIN_PX)
+ );
+ const top = opensBelow ? caretRect.y + caretRect.height + CARET_GAP_PX : caretRect.y - height - CARET_GAP_PX;
+
+ // Keyboard navigation moves a highlight the mouse never touches, so the list
+ // has to follow it rather than waiting to be scrolled.
+ useLayoutEffect(() => {
+ listRef.current
+ ?.querySelector(`#${CSS.escape(`${optionIdPrefix}${activeIndex}`)}`)
+ ?.scrollIntoView({ block: 'nearest' });
+ }, [activeIndex, optionIdPrefix]);
+
+ let renderedIndex = -1;
+
+ return (
+ <Portal>
+ <Box
+ bg="bg.muted"
+ borderColor="border.emphasized"
+ borderRadius="md"
+ borderWidth="1px"
+ boxShadow="md"
+ id={listboxId}
+ left={`${left}px`}
+ maxH={`${height}px`}
+ overflowY="auto"
+ position="fixed"
+ py="1"
+ ref={listRef}
+ role="listbox"
+ top={`${top}px`}
+ w={`${LIST_WIDTH_PX}px`}
+ zIndex="popover"
+ >
+ <Stack gap="1">
+ {groups.map((group) => (
+ <Stack gap="0" key={group.group}>
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="2" textTransform="uppercase" truncate>
+ {group.group}
+ </Text>
+ {group.options.map((option) => {
+ renderedIndex++;
+
+ return (
+ <AutocompleteOption
+ key={`${option.group}-${option.value}`}
+ id={`${optionIdPrefix}${renderedIndex}`}
+ isActive={renderedIndex === activeIndex}
+ option={option}
+ onSelect={onSelect}
+ />
+ );
+ })}
+ </Stack>
+ ))}
+ </Stack>
+ </Box>
+ </Portal>
+ );
+};
+
+const AutocompleteOption = ({
+ id,
+ isActive,
+ onSelect,
+ option,
+}: {
+ id: string;
+ isActive: boolean;
+ option: PromptTriggerOption;
+ onSelect: (option: PromptTriggerOption) => void;
+}) => {
+ // On mousedown, not click, and with the default prevented: letting the press
+ // blur the textarea would close the list out from under the pointer.
+ const handleMouseDown = useCallback(
+ (event: MouseEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ onSelect(option);
+ },
+ [onSelect, option]
+ );
+
+ return (
+ <Box
+ aria-selected={isActive}
+ bg={isActive ? 'bg.emphasized' : undefined}
+ color="fg"
+ cursor="pointer"
+ fontSize="xs"
+ id={id}
+ px="2"
+ py="1"
+ role="option"
+ // Focus stays in the textarea and moves through `aria-activedescendant`;
+ // the options are only ever reachable that way, never by tabbing.
+ tabIndex={-1}
+ truncate
+ _hover={OPTION_HOVER_CSS}
+ onMouseDown={handleMouseDown}
+ >
+ {option.label}
+ </Box>
+ );
+};
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
index 90148b5a9f..8ca067cf29 100644
--- 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
@@ -8,32 +8,38 @@ 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 }));
-
+// The actions row needs Generation's UI port and is not what these tests are
+// about; the caret autocomplete underneath it is entirely real.
vi.mock('@features/generation/ui/promptFields/PositivePromptActions', () => ({
PositivePromptActions: () => null,
- PromptTriggerPopover: (props: { onClose: () => void; onSelect: (trigger: string) => void }) => {
- picker.current = props;
- return null;
- },
+ PromptTriggerPopover: () => null,
+}));
+
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({ models: { catalog: [], ensureLoaded: vi.fn() } }),
}));
+const WILDCARDS = [
+ { id: 'w1', name: 'colors', values: ['red'] },
+ { id: 'w2', name: 'moods', values: ['calm'] },
+];
+
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'] }),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve(WILDCARDS), 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;
+/** Tall on purpose: the old picker anchored to the whole box, which is the bug. */
+const TEXTAREA_HEIGHT_PX = 320;
+
const render = async () => {
host = document.createElement('div');
document.body.append(host);
@@ -44,7 +50,7 @@ const render = async () => {
<QueryClientProvider client={new QueryClient()}>
<ChakraProvider value={system}>
<PositivePromptField
- heightPx={120}
+ heightPx={TEXTAREA_HEIGHT_PX}
loras={[]}
projectId="project-1"
selectedModel={undefined}
@@ -58,25 +64,18 @@ const render = async () => {
</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));
+ // The option list is fed by the wildcard query, which resolves a tick later.
await act(async () => {
await new Promise((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
+ setTimeout(resolve, 0);
});
});
};
-const dismissPicker = () => leavePicker((handlers) => handlers.onClose());
-const pickColors = () => leavePicker((handlers) => handlers.onSelect('__colors__'));
+const textarea = () => host!.querySelector('textarea')!;
+const listbox = () => document.querySelector('[role="listbox"]');
+const optionLabels = () => [...(listbox()?.querySelectorAll('[role="option"]') ?? [])].map((o) => o.textContent);
const type = async (text: string) => {
await act(async () => {
@@ -87,8 +86,18 @@ const type = async (text: string) => {
});
};
+const press = async (key: string) => {
+ await act(async () => {
+ await userEvent.keyboard(key);
+ });
+ await act(async () => {
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ });
+ });
+};
+
beforeEach(async () => {
- picker.current = null;
await render();
});
@@ -99,50 +108,124 @@ afterEach(async () => {
root = null;
});
-describe('the prompt trigger picker and the keystroke that opens it', () => {
+describe('the caret autocomplete', () => {
// 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);
+ expect(listbox()).toBeNull();
});
- it('types a double underscore mid-word without opening the picker', async () => {
+ it('types a double underscore mid-word without opening', async () => {
await type('snake__case');
expect(textarea().value).toBe('snake__case');
- expect(isPickerOpen()).toBe(false);
+ expect(listbox()).toBeNull();
});
it('opens on `__` where a wildcard reference could begin', async () => {
await type('a photo of __');
- expect(isPickerOpen()).toBe(true);
+ expect(optionLabels()).toEqual(['colors', 'moods']);
});
- // Regression: dismissing left the prompt one underscore short of what was typed.
- it('gives the underscores back when the picker is dismissed', async () => {
+ // The whole point: nothing is swallowed, so there is nothing to give back.
+ it('leaves the typed characters in the prompt while it is open', 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);
+ it('narrows as the name is typed, where the user is already looking', async () => {
+ await type('a photo of __mo');
+
+ expect(optionLabels()).toEqual(['moods']);
+ });
- await dismissPicker();
+ it('closes when nothing matches, rather than showing an empty list', async () => {
+ await type('a photo of __zzz');
- expect(textarea().value).toBe('a photo of <');
+ expect(listbox()).toBeNull();
+ expect(textarea().value).toBe('a photo of __zzz');
});
- it('replaces the typed underscores with the picked reference', async () => {
+ it('opens beside the caret, not at the bottom of a tall box', async () => {
await type('a photo of __');
- await pickColors();
+
+ const box = textarea().getBoundingClientRect();
+ const list = listbox()!.getBoundingClientRect();
+
+ expect(box.height).toBeGreaterThan(200);
+ // On the first line of the prompt, so the list belongs at the top of the box.
+ expect(list.top - box.top).toBeLessThan(80);
+ });
+
+ // The complaint this whole thing exists to answer: the list used to open at
+ // the bottom-left of the box no matter where you were typing.
+ it('follows the caret down the box', async () => {
+ await type('one\ntwo\nthree\nfour\nfive\nsix __');
+
+ const box = textarea().getBoundingClientRect();
+ const list = listbox()!.getBoundingClientRect();
+
+ expect(list.top - box.top).toBeGreaterThan(60);
+ });
+
+ it('inserts the highlighted option on Enter', async () => {
+ await type('a photo of __');
+ await press('{Enter}');
expect(textarea().value).toBe('a photo of __colors__');
+ expect(listbox()).toBeNull();
+ });
+
+ it('moves the highlight with the arrow keys', async () => {
+ await type('a photo of __');
+ await press('{ArrowDown}');
+ await press('{Enter}');
+
+ expect(textarea().value).toBe('a photo of __moods__');
+ });
+
+ it('wraps the highlight around the ends of the list', async () => {
+ await type('a photo of __');
+ await press('{ArrowUp}');
+ await press('{Enter}');
+
+ expect(textarea().value).toBe('a photo of __moods__');
+ });
+
+ it('replaces what was typed, not just the trigger', async () => {
+ await type('a photo of __mo');
+ await press('{Enter}');
+
+ expect(textarea().value).toBe('a photo of __moods__');
+ });
+
+ it('closes on Escape and leaves the prompt exactly as typed', async () => {
+ await type('a photo of __');
+ await press('{Escape}');
+
+ expect(listbox()).toBeNull();
+ expect(textarea().value).toBe('a photo of __');
+ });
+
+ it('tells assistive tech the textarea is a combobox over the list', async () => {
+ await type('a photo of __');
+
+ const activeId = textarea().getAttribute('aria-activedescendant');
+
+ expect(textarea().getAttribute('role')).toBe('combobox');
+ expect(textarea().getAttribute('aria-expanded')).toBe('true');
+ expect(textarea().getAttribute('aria-controls')).toBe(listbox()!.id);
+ expect(document.getElementById(activeId!)?.getAttribute('aria-selected')).toBe('true');
+ });
+
+ it('closes once the reference is finished', async () => {
+ await type('a photo of __colors__');
+
+ expect(listbox()).toBeNull();
});
});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts
new file mode 100644
index 0000000000..9337f54839
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts
@@ -0,0 +1,98 @@
+/**
+ * Where the caret is on screen, so a list can open beside it.
+ *
+ * A textarea gives no geometry for a position within its text, so the standard
+ * trick is to lay the same text out again in a hidden element that copies every
+ * property affecting how it wraps, and read the offset of a marker placed at the
+ * caret. The prompt textarea already renders a mirror for syntax highlighting,
+ * but only when highlighting is on — this builds its own so caret anchoring
+ * works with the setting off too.
+ *
+ * Measured on demand rather than tracked: it is read while a picker is opening
+ * or its query is growing, which is a handful of times per keystroke at most,
+ * and never while the user is only typing.
+ */
+
+export interface CaretRect {
+ height: number;
+ width: number;
+ x: number;
+ y: number;
+}
+
+/** Everything that decides where a character lands, copied onto the mirror. */
+const MIRRORED_STYLES = [
+ 'borderBottomWidth',
+ 'borderLeftWidth',
+ 'borderRightWidth',
+ 'borderTopWidth',
+ 'boxSizing',
+ 'fontFamily',
+ 'fontSize',
+ 'fontStretch',
+ 'fontStyle',
+ 'fontVariant',
+ 'fontWeight',
+ 'letterSpacing',
+ 'lineHeight',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'paddingRight',
+ 'paddingTop',
+ 'tabSize',
+ 'textIndent',
+ 'textTransform',
+ 'width',
+ 'wordSpacing',
+] as const;
+
+/**
+ * The caret's viewport rectangle, or `null` when the element is not laid out.
+ *
+ * The returned box is a zero-width line at the caret: callers place a popover
+ * against it, so its height is what decides whether the list sits above or below
+ * the current line rather than on top of it.
+ */
+export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: number): CaretRect | null => {
+ const textareaRect = textarea.getBoundingClientRect();
+
+ if (textareaRect.width === 0 && textareaRect.height === 0) {
+ return null;
+ }
+
+ const computed = window.getComputedStyle(textarea);
+ const mirror = document.createElement('div');
+ const marker = document.createElement('span');
+
+ for (const property of MIRRORED_STYLES) {
+ mirror.style[property] = computed[property];
+ }
+
+ // Off-screen rather than `display: none`, which would give every offset zero.
+ mirror.style.position = 'absolute';
+ mirror.style.top = '0';
+ mirror.style.left = '-9999px';
+ mirror.style.visibility = 'hidden';
+ mirror.style.whiteSpace = 'pre-wrap';
+ mirror.style.overflowWrap = 'break-word';
+ mirror.style.overflow = 'hidden';
+
+ mirror.textContent = textarea.value.slice(0, index);
+ // A zero-width space so the marker still occupies a line when the caret sits
+ // at the very end of the text, or straight after a newline.
+ marker.textContent = textarea.value.slice(index) || '​';
+ mirror.append(marker);
+ document.body.append(mirror);
+
+ const lineHeight = Number.parseFloat(computed.lineHeight);
+ const rect: CaretRect = {
+ height: Number.isFinite(lineHeight) ? lineHeight : Number.parseFloat(computed.fontSize) * 1.6,
+ width: 0,
+ x: textareaRect.left + marker.offsetLeft - textarea.scrollLeft,
+ y: textareaRect.top + marker.offsetTop - textarea.scrollTop,
+ };
+
+ mirror.remove();
+
+ return rect;
+};
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 526312f61f..e652ce906b 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
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { PromptTriggerKey } from './promptFocus';
-import { getPromptTriggerRange, insertTextAtRange } from './promptFocus';
+import { getActiveTriggerQuery, insertTextAtRange } from './promptFocus';
describe('insertTextAtRange', () => {
it('inserts text at a collapsed range', () => {
@@ -22,46 +22,59 @@ describe('insertTextAtRange', () => {
});
});
-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);
+describe('getActiveTriggerQuery', () => {
+ const query = (value: string, keys: PromptTriggerKey[] = ['<', '_']) =>
+ getActiveTriggerQuery(value, value.length, keys);
- it('opens on `<`, replacing nothing', () => {
- expect(match('a photo of ', '<')).toEqual({ key: '<', range: { end: 11, start: 11 } });
+ it('opens on the second underscore, with nothing typed yet', () => {
+ expect(query('a photo of __')).toEqual({ key: '_', query: '', range: { end: 13, 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 } });
+ it('narrows as the name is typed', () => {
+ expect(query('a photo of __col')).toEqual({ key: '_', query: 'col', range: { end: 16, start: 11 } });
});
- // 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('opens on an angle bracket and narrows the same way', () => {
+ expect(query('a photo <emb')).toEqual({ key: '<', query: 'emb', range: { end: 12, start: 8 } });
});
- it('stays shut on the first underscore', () => {
- expect(match('a photo of', '_')).toBeNull();
+ it('takes the trigger nearest the caret', () => {
+ expect(query('__one__ and <two')).toMatchObject({ key: '<', query: 'two' });
});
- it('ignores keys the field does not answer to', () => {
- expect(match('a photo of _', '_', ['<'])).toBeNull();
- expect(match('a photo of ', '<', ['_'])).toBeNull();
+ // The reference is finished; re-opening over it would fight the user.
+ it('stays shut after a closed reference', () => {
+ expect(query('a __colours__')).toBeNull();
+ expect(query('a <embedding>')).toBeNull();
});
- it('ignores every other key', () => {
- expect(match('a photo of ', 'a')).toBeNull();
- expect(match('a photo of ', 'Enter')).toBeNull();
+ it('stays shut inside an ordinary word', () => {
+ expect(query('a snake__case word')).toBeNull();
+ expect(query('a photo of a cat')).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 } });
+ it('ends at a space, so a sentence does not keep it open', () => {
+ expect(query('a __col our')).toBeNull();
+ });
+
+ it('ends at a newline', () => {
+ 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('honours the keys the field answers to', () => {
+ expect(query('a __col', ['<'])).toBeNull();
+ expect(query('a <emb', ['_'])).toBeNull();
+ });
+
+ it('reads from the caret, not the end of the text', () => {
+ expect(getActiveTriggerQuery('a __col and more', 7, ['_'])).toEqual({
+ key: '_',
+ query: 'col',
+ range: { end: 7, 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 06dd463c88..0cff97c6aa 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
@@ -75,43 +75,63 @@ export const insertPositivePromptText = ({
/** 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. */
+/** `_` 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);
+
+export interface PromptTriggerQuery {
key: PromptTriggerKey;
- /** The span the picked trigger replaces, including anything already typed. */
+ /** What has been typed since the trigger, for narrowing the list. */
+ query: string;
+ /** The span a picked option replaces, trigger and typed query included. */
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);
+/**
+ * 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;
/**
- * Whether `key` opens the trigger picker, and what it would replace.
+ * The unfinished trigger the caret is sitting inside, or `null`.
+ *
+ * This replaced an open-on-keystroke picker that swallowed the `__` or `<` and
+ * gave the user a separate search box to type into. Here the trigger is typed
+ * into the prompt like any other character and whatever follows it narrows the
+ * list, so you type where you are already looking — and there is nothing to hand
+ * back when the list is dismissed.
*
- * `<` 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.
+ * Scanning stops at a newline, at whitespace, and at anything that closes the
+ * token, so a finished `__colours__` or `<embedding>` behind the caret does not
+ * re-open the list, and a space ends the attempt rather than leaving it open
+ * over a sentence.
*/
-export const getPromptTriggerRange = (
+export const getActiveTriggerQuery = (
value: string,
- selectionStart: number,
- selectionEnd: number,
- key: string,
+ caret: number,
keys: readonly PromptTriggerKey[]
-): PromptTriggerMatch | null => {
- if (key === '<' && keys.includes('<')) {
- return { key: '<', range: { end: selectionEnd, start: selectionStart } };
- }
+): PromptTriggerQuery | null => {
+ const limit = Math.max(0, caret - MAX_TRIGGER_QUERY_LENGTH);
+
+ for (let index = caret - 1; index >= limit; index--) {
+ const char = value[index];
+
+ if (char === undefined || char === '\n' || char === '>' || /\s/.test(char)) {
+ return null;
+ }
+
+ if (char === '<' && keys.includes('<')) {
+ return { key: '<', query: value.slice(index + 1, caret), range: { end: caret, start: index } };
+ }
+
+ if (char === '_' && value[index - 1] === '_' && keys.includes('_') && !isWordCharacter(value[index - 2])) {
+ const query = value.slice(index + 1, caret);
- 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 } };
+ // `__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 null;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts
new file mode 100644
index 0000000000..08f1ff6320
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts
@@ -0,0 +1,148 @@
+/**
+ * What `<` and `__` can insert: wildcards, the selected model's and each enabled
+ * LoRA's trigger phrases, and embeddings compatible with the base.
+ *
+ * Shared by the two ways of reaching that list — the `+` button's browsable
+ * popover and the caret-anchored autocomplete — so the two can never drift into
+ * offering different things.
+ */
+
+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
+import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
+
+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
+import { useWildcards } from '@features/generation/ui/useWildcards';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+export interface PromptTriggerOption {
+ group: string;
+ label: string;
+ value: string;
+}
+
+export interface PromptTriggerOptionGroup {
+ group: string;
+ options: PromptTriggerOption[];
+}
+
+const getTriggerPhrases = (model: unknown): string[] => {
+ if (!model || typeof model !== 'object') {
+ return [];
+ }
+
+ const triggerPhrases = (model as { trigger_phrases?: unknown }).trigger_phrases;
+
+ return Array.isArray(triggerPhrases)
+ ? triggerPhrases.filter((phrase): phrase is string => typeof phrase === 'string' && phrase.trim().length > 0)
+ : [];
+};
+
+export const getPromptTriggerOptions = ({
+ compatibleEmbeddingsLabel,
+ loras,
+ mainModelLabel,
+ models,
+ selectedModel,
+ wildcards,
+ wildcardsLabel,
+}: {
+ compatibleEmbeddingsLabel: string;
+ loras: GenerateLora[];
+ mainModelLabel: string;
+ models: readonly ModelConfig[];
+ selectedModel: GenerateModelConfig | undefined;
+ wildcards: readonly { name: string; values: string[] }[];
+ wildcardsLabel: string;
+}): PromptTriggerOption[] => {
+ const options: PromptTriggerOption[] = [];
+
+ // A wildcard inserts as `__name__`, which is just another trigger the picker
+ // can splice in, so it rides in the same list as embeddings and LoRA phrases.
+ for (const wildcard of wildcards) {
+ options.push({ group: wildcardsLabel, label: wildcard.name, value: `__${wildcard.name}__` });
+ }
+
+ for (const phrase of getTriggerPhrases(selectedModel)) {
+ options.push({ group: selectedModel?.name ?? mainModelLabel, label: phrase, value: phrase });
+ }
+
+ for (const lora of loras) {
+ if (!lora.isEnabled) {
+ continue;
+ }
+
+ for (const phrase of getTriggerPhrases(lora.model)) {
+ options.push({ group: lora.model.name, label: phrase, value: phrase });
+ }
+ }
+
+ if (selectedModel) {
+ for (const model of models) {
+ if (model.type === 'embedding' && model.base === selectedModel.base) {
+ options.push({ group: compatibleEmbeddingsLabel, label: model.name, value: `<${model.name}>` });
+ }
+ }
+ }
+
+ const seen = new Set<string>();
+
+ return options.filter((option) => {
+ const key = `${option.group}:${option.value}`;
+
+ if (seen.has(key)) {
+ return false;
+ }
+
+ seen.add(key);
+ return true;
+ });
+};
+
+export const filterPromptTriggerOptions = (
+ options: readonly PromptTriggerOption[],
+ search: string
+): PromptTriggerOption[] => {
+ const query = search.trim().toLowerCase();
+
+ return options.filter(
+ (option) => !query || option.label.toLowerCase().includes(query) || option.group.toLowerCase().includes(query)
+ );
+};
+
+export const groupPromptTriggerOptions = (options: readonly PromptTriggerOption[]): PromptTriggerOptionGroup[] =>
+ options.reduce<PromptTriggerOptionGroup[]>((groups, option) => {
+ const existing = groups.find((group) => group.group === option.group);
+
+ if (existing) {
+ existing.options.push(option);
+ } else {
+ groups.push({ group: option.group, options: [option] });
+ }
+
+ return groups;
+ }, []);
+
+/** The live option list for a field, already localized. */
+export const usePromptTriggerOptions = (
+ loras: GenerateLora[],
+ selectedModel: GenerateModelConfig | undefined
+): PromptTriggerOption[] => {
+ const { t } = useTranslation();
+ const { catalog: models } = useGenerationUi().models;
+ const { wildcards } = useWildcards();
+
+ return useMemo(
+ () =>
+ getPromptTriggerOptions({
+ compatibleEmbeddingsLabel: t('widgets.generate.compatibleEmbeddings'),
+ loras,
+ mainModelLabel: t('widgets.generate.mainModel'),
+ models,
+ selectedModel,
+ wildcards,
+ wildcardsLabel: t('widgets.generate.dynamicPrompts.wildcards'),
+ }),
+ [loras, models, selectedModel, t, wildcards]
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx
new file mode 100644
index 0000000000..86bd33de8d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx
@@ -0,0 +1,192 @@
+/**
+ * Type-as-you-filter trigger insertion, anchored at the caret.
+ *
+ * The old behaviour swallowed the `__` or `<` keystroke, opened a popover
+ * anchored to the whole textarea, and gave you a separate search box: in a tall
+ * prompt box the list appeared at the bottom-left corner, and you typed in one
+ * place while looking at another. Here the trigger is typed like any other
+ * character, whatever follows it narrows the list, and the list sits beside the
+ * caret. Nothing is swallowed, so there is nothing to give back on dismissal.
+ *
+ * Focus never leaves the textarea. That is what makes this a hook returning an
+ * element rather than a `Popover`: the list is a passive surface, and every key
+ * that drives it is handled on the textarea itself.
+ */
+
+import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
+import type { CaretRect } from '@features/generation/ui/promptFields/promptCaret';
+import type { PromptTriggerKey, PromptTriggerQuery } from '@features/generation/ui/promptFields/promptFocus';
+import type { PromptTriggerOption } from '@features/generation/ui/promptFields/promptTriggerOptions';
+import type { KeyboardEvent, ReactNode } from 'react';
+
+import { getTextareaCaretRect } from '@features/generation/ui/promptFields/promptCaret';
+import { getActiveTriggerQuery, insertPromptText } from '@features/generation/ui/promptFields/promptFocus';
+import { PromptTriggerAutocomplete } from '@features/generation/ui/promptFields/PromptTriggerAutocomplete';
+import {
+ filterPromptTriggerOptions,
+ usePromptTriggerOptions,
+} from '@features/generation/ui/promptFields/promptTriggerOptions';
+import { useCallback, useId, useMemo, useState } from 'react';
+
+interface AutocompleteState {
+ caretRect: CaretRect;
+ query: PromptTriggerQuery;
+}
+
+export interface PromptTriggerAutocompleteApi {
+ /** Spread onto the textarea so assistive tech sees a combobox. */
+ comboboxProps: {
+ 'aria-activedescendant': string | undefined;
+ 'aria-autocomplete': 'list';
+ 'aria-controls': string | undefined;
+ 'aria-expanded': boolean;
+ role: 'combobox';
+ };
+ element: ReactNode;
+ isOpen: boolean;
+ /** Close without inserting, for anything that invalidates the caret. */
+ close: () => void;
+ /** Re-read the trigger under the caret. Call on input, and on click. */
+ refresh: (textarea: HTMLTextAreaElement | null) => void;
+ /** `true` when the key drove the list and the field should not also act on it. */
+ handleKeyDown: (event: KeyboardEvent<HTMLTextAreaElement>) => boolean;
+}
+
+export const usePromptTriggerAutocomplete = ({
+ isDisabled = false,
+ keys,
+ loras,
+ onChange,
+ selectedModel,
+}: {
+ keys: readonly PromptTriggerKey[];
+ loras: GenerateLora[];
+ selectedModel: GenerateModelConfig | undefined;
+ isDisabled?: boolean;
+ onChange: (value: string) => void;
+}): PromptTriggerAutocompleteApi => {
+ const listboxId = useId();
+ const optionIdPrefix = `${listboxId}-option-`;
+ const [state, setState] = useState<AutocompleteState | null>(null);
+ const [activeIndex, setActiveIndex] = useState(0);
+ const options = usePromptTriggerOptions(loras, selectedModel);
+
+ const matches = useMemo(
+ () => (state ? filterPromptTriggerOptions(options, state.query.query) : []),
+ [options, state]
+ );
+ const isOpen = state !== null && matches.length > 0;
+ const close = useCallback(() => setState(null), []);
+
+ const refresh = useCallback(
+ (textarea: HTMLTextAreaElement | null) => {
+ if (!textarea || isDisabled) {
+ setState(null);
+ return;
+ }
+
+ const query = getActiveTriggerQuery(textarea.value, textarea.selectionStart, keys);
+ // Anchored at the trigger rather than the caret, so the list holds still
+ // while the name is typed instead of creeping sideways with it.
+ const caretRect = query ? getTextareaCaretRect(textarea, query.range.start) : null;
+
+ setState(query && caretRect ? { caretRect, query } : null);
+ setActiveIndex(0);
+ },
+ [isDisabled, keys]
+ );
+
+ const selectOption = useCallback(
+ (option: PromptTriggerOption, textarea: HTMLTextAreaElement | null) => {
+ if (state) {
+ insertPromptText({
+ onChange,
+ range: state.query.range,
+ text: option.value,
+ textarea,
+ value: textarea?.value ?? '',
+ });
+ }
+
+ setState(null);
+ },
+ [onChange, state]
+ );
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLTextAreaElement>): boolean => {
+ if (!isOpen) {
+ return false;
+ }
+
+ // A caret jump leaves the query behind, so the list goes with it — but the
+ // key still belongs to the textarea.
+ if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
+ setState(null);
+ return false;
+ }
+
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ // Otherwise the popover or dialog this prompt sits in closes too.
+ event.stopPropagation();
+ setState(null);
+ return true;
+ }
+
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ const step = event.key === 'ArrowDown' ? 1 : -1;
+
+ event.preventDefault();
+ setActiveIndex((current) => (current + step + matches.length) % matches.length);
+ return true;
+ }
+
+ if (event.key === 'Enter' || event.key === 'Tab') {
+ const option = matches[activeIndex];
+
+ if (option) {
+ event.preventDefault();
+ selectOption(option, event.currentTarget);
+ return true;
+ }
+ }
+
+ return false;
+ },
+ [activeIndex, isOpen, matches, selectOption]
+ );
+
+ // The option list has no focus of its own, so a click on it arrives as a
+ // mousedown the option itself has already suppressed; this only ever runs with
+ // the textarea's own element.
+ const handleSelect = useCallback(
+ (option: PromptTriggerOption) => selectOption(option, document.activeElement as HTMLTextAreaElement | null),
+ [selectOption]
+ );
+
+ return {
+ close,
+ comboboxProps: {
+ 'aria-activedescendant': isOpen ? `${optionIdPrefix}${activeIndex}` : undefined,
+ 'aria-autocomplete': 'list',
+ 'aria-controls': isOpen ? listboxId : undefined,
+ 'aria-expanded': isOpen,
+ role: 'combobox',
+ },
+ element:
+ isOpen && state ? (
+ <PromptTriggerAutocomplete
+ activeIndex={activeIndex}
+ caretRect={state.caretRect}
+ listboxId={listboxId}
+ optionIdPrefix={optionIdPrefix}
+ options={matches}
+ onSelect={handleSelect}
+ />
+ ) : null,
+ handleKeyDown,
+ isOpen,
+ refresh,
+ };
+};