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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): hold the textarea rather than reading the document
joshistoast949c52f1925d
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsxindex 1822723ade..538a93e56f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx@@ -1,5 +1,8 @@import type { CaretRect } from '@features/generation/ui/promptFields/promptCaret';-import type { PromptTriggerOption } from '@features/generation/ui/promptFields/promptTriggerOptions';+import type {+ PromptTriggerOption,+ PromptTriggerOptionGroup,+} from '@features/generation/ui/promptFields/promptTriggerOptions';import type { MouseEvent } from 'react';import { Box, Portal, Stack, Text } from '@chakra-ui/react';@@ -42,7 +45,24 @@ export const PromptTriggerAutocomplete = ({onSelect: (option: PromptTriggerOption) => void;}) => {const listRef = useRef<HTMLDivElement | null>(null);- const groups = useMemo(() => groupPromptTriggerOptions(options), [options]);+ // Each group carries where it starts in the flat list. The hook selects with+ // `options[activeIndex]`, so the ids have to be numbered the same way — and+ // counting them up as the rows render, which is what this replaced, only+ // agreed with that while grouping happened to be an order-preserving no-op.+ const groups = useMemo(+ () =>+ groupPromptTriggerOptions(options).reduce<(PromptTriggerOptionGroup & { startIndex: number })[]>(+ (numbered, group) => {+ const previous = numbered[numbered.length - 1];++ numbered.push({ ...group, startIndex: previous ? previous.startIndex + previous.options.length : 0 });++ return numbered;+ },+ []+ ),+ [options]+ );// Below the caret when there is room, above it when there is not, and never// off the right edge of a narrow window.@@ -63,8 +83,6 @@ export const PromptTriggerAutocomplete = ({?.scrollIntoView({ block: 'nearest' });}, [activeIndex, optionIdPrefix]);- let renderedIndex = -1;-return (<Portal><Box@@ -91,14 +109,14 @@ export const PromptTriggerAutocomplete = ({<Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="2" textTransform="uppercase" truncate>{group.group}</Text>- {group.options.map((option) => {- renderedIndex++;+ {group.options.map((option, position) => {+ const index = group.startIndex + position;return (<AutocompleteOptionkey={`${option.group}-${option.value}`}- id={`${optionIdPrefix}${renderedIndex}`}- isActive={renderedIndex === activeIndex}+ id={`${optionIdPrefix}${index}`}+ isActive={index === activeIndex}option={option}onSelect={onSelect}/>@@ -124,9 +142,14 @@ const AutocompleteOption = ({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.+ // blur the textarea would close the list out from under the pointer. Primary+ // button only — a right-click is after the context menu, not an insertion.const handleMouseDown = useCallback((event: MouseEvent<HTMLDivElement>) => {+ if (event.button !== 0) {+ return;+ }+event.preventDefault();onSelect(option);},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.tsxindex a80e7f24b7..72da473155 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@@ -228,6 +228,39 @@ describe('the caret autocomplete', () => {expect(textarea().value).toBe('a photo of __moods__');});+ const mouseDownOnFirstOption = (button: number) => {+ const option = listbox()!.querySelector('[role="option"]')!;++ return act(() => {+ option.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button, cancelable: true }));+ });+ };++ it('inserts the option the pointer pressed', async () => {+ await type('a photo of __');+ await mouseDownOnFirstOption(0);++ expect(textarea().value).toBe('a photo of __colors__');+ });++ // The press has to insert from the field the query was read from. Reading it+ // back off the document instead meant a non-textarea gave `undefined` for the+ // current value, and the insert committed the option over the whole prompt.+ it('keeps the rest of the prompt when the pointer selects', async () => {+ await type('a photo of __co');+ textarea().blur();+ await mouseDownOnFirstOption(0);++ expect(textarea().value).toBe('a photo of __colors__');+ });++ it('ignores a right-click on an option', async () => {+ await type('a photo of __');+ await mouseDownOnFirstOption(2);++ expect(textarea().value).toBe('a photo of __');+ });+it('closes on Escape and leaves the prompt exactly as typed', async () => {await type('a photo of __');await press('{Escape}');diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsxindex dd19213c6b..5c1b5588ca 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx@@ -31,6 +31,14 @@ import { useCallback, useId, useMemo, useState } from 'react';interface AutocompleteState {caretRect: CaretRect;query: PromptTriggerQuery;+ /**+ * The field the query was read from. Held rather than looked up again at+ * selection time: `document.activeElement` is only the textarea because the+ * option suppressed its own mousedown, and if that ever stops holding, the+ * insert reads `undefined` for the current value and commits the option on its+ * own — silently replacing the whole prompt.+ */+ textarea: HTMLTextAreaElement;}export interface PromptTriggerAutocompleteApi {@@ -90,21 +98,21 @@ export const usePromptTriggerAutocomplete = ({// 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);+ setState(query && caretRect ? { caretRect, query, textarea } : null);setActiveIndex(0);},[isDisabled, keys]);const selectOption = useCallback(- (option: PromptTriggerOption, textarea: HTMLTextAreaElement | null) => {+ (option: PromptTriggerOption) => {if (state) {insertPromptText({onChange,range: state.query.range,text: option.value,- textarea,- value: textarea?.value ?? '',+ textarea: state.textarea,+ value: state.textarea.value,});}@@ -147,7 +155,7 @@ export const usePromptTriggerAutocomplete = ({if (option) {event.preventDefault();- selectOption(option, event.currentTarget);+ selectOption(option);return true;}}@@ -157,14 +165,6 @@ export const usePromptTriggerAutocomplete = ({[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: {@@ -182,7 +182,7 @@ export const usePromptTriggerAutocomplete = ({listboxId={listboxId}optionIdPrefix={optionIdPrefix}options={matches}- onSelect={handleSelect}+ onSelect={selectOption}/>) : null,handleKeyDown,