An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead): reopen the dropdown on click when focus never left (#6848)
Ojas Mutrejab79378910f8f
diff --git a/.changeset/base-typeahead-reopen-on-click.md b/.changeset/base-typeahead-reopen-on-click.mdnew file mode 100644index 0000000000..6e73c02e47--- /dev/null+++ b/.changeset/base-typeahead-reopen-on-click.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[fix] `Typeahead`, `Tokenizer`, and `PowerSearch` (which composes `Tokenizer`): clicking the search/combobox input after the dropdown closed without a blur now reopens it.++`BaseTypeahead` only ever opened its dropdown in response to a real `focus` event. Any flow that closes the dropdown while leaving the input focused — selecting a result (which re-focuses the input internally after clearing it), pressing Escape, or a composing component (`PowerSearch`'s token add/remove, e.g.) imperatively re-focusing the same input once it's done — dispatches no new `focus` event, since `focus()` is a no-op on an element that's already the active element. The input looked focused and clickable, but clicking it did nothing until the user clicked elsewhere first and back.++`BaseTypeahead` now also opens on click, specifically when the input was already focused before the click began (checked at `pointerdown`, before the browser's own default action moves focus — a click that itself just caused the input to gain focus is left to the existing focus path, so the two don't double-fire a bootstrap fetch on a single first click).++Only `Typeahead` and `Tokenizer` compose `BaseTypeahead` directly — `Selector`, `MultiSelector`, `CommandPalette`, and `DateTimeInput` use their own separate combobox implementations (which only follow `BaseTypeahead`'s conventions, not its code) and are unaffected by this change.++Fixes #6845.++@HelloOjasMutrejadiff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex af1c2555ce..5170fc5811 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -486,6 +486,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({onPointerDown: onPointerDownProp,onFocus: onFocusProp,onBlur: onBlurProp,+ onClick: onClickProp,id: nativeInputId,'aria-describedby': nativeAriaDescribedBy,'aria-labelledby': nativeAriaLabelledBy,@@ -584,6 +585,23 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({// close it (the click is seen as "outside" the newly-opened popover).const pointerActiveRef = useRef(false);+ // Whether the input was ALREADY the active element the moment the current+ // click gesture began, captured at pointerdown -- before the browser's own+ // focus-on-pointerdown behavior can move focus onto it. pointerdown always+ // fires before focus in a mouse/touch-driven click (pointerdown -> focus ->+ // pointerup -> click), so this reflects the pre-click focus state exactly,+ // with no dependency on event-loop timing between focus and click (a+ // microtask-based flag cleared between the two was tried and measured+ // clearing before the click arrived for an async bootstrap source,+ // double-firing it). A click that itself just caused the input to gain+ // focus reads false here and is left to handleFocus, which already opens+ // it; a click on an input that was already focused -- closing the+ // dropdown (selecting a result, committing a token elsewhere in a+ // composing component) often re-focuses the same input programmatically,+ // which dispatches no focus event at all -- reads true and reopens it in+ // handleClick.+ const wasAlreadyFocusedRef = useRef(false);+// Debounce refconst searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -872,8 +890,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({[onChange, popover, searchSource, setLoading],);- // Handle focus- const handleFocus = useCallback(() => {+ // Shared by handleFocus and handleClick: bootstrap entries if none are+ // loaded yet, or re-show cached results that haven't been invalidated by+ // a selection since (comparing the two generation refs catches that).+ const openIfEligible = useCallback(() => {if (isDisabled) {return;}@@ -882,9 +902,6 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({} else if (results.length > 0 &&(query.length > 0 || hasEntriesOnFocus) &&- // Only re-show cached results if they haven't been invalidated by- // a selection. Refs are always current, so this check isn't affected- // by React's closure staleness the way results.length is.resultsGenRef.current === searchGenRef.current) {showLayer();@@ -898,6 +915,25 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({showLayer,]);+ // Handle focus+ const handleFocus = useCallback(() => {+ openIfEligible();+ }, [openIfEligible]);++ // Handle click — a click that focuses a previously-unfocused input is+ // already covered by handleFocus. A click on an input that was ALREADY+ // focused (the common case right after selecting a result or committing a+ // token elsewhere re-focuses this input programmatically, closing the+ // dropdown) dispatches no focus event at all, so without this the+ // dropdown never reopens until the user clicks away and back (#6845). See+ // wasAlreadyFocusedRef above for how the two cases are told apart.+ const handleClick = useCallback(() => {+ if (!wasAlreadyFocusedRef.current || popover.isOpen) {+ return;+ }+ openIfEligible();+ }, [popover.isOpen, openIfEligible]);+// Handle blur — close the dropdown when focus leaves the input for an// element that is neither inside the field wrapper (anchor) nor inside the// dropdown popover. The native popover="auto" light-dismiss only fires on@@ -1083,6 +1119,11 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({value={query}onChange={handleInputChange}onPointerDown={composeEventHandlers(() => {+ // Captured before the browser's own default action moves focus+ // onto the input as part of this same pointerdown — see+ // wasAlreadyFocusedRef above.+ wasAlreadyFocusedRef.current =+ document.activeElement === inputRef.current;pointerActiveRef.current = true;document.addEventListener('click',@@ -1093,6 +1134,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({);}, onPointerDownProp)}onFocus={composeEventHandlers(handleFocus, onFocusProp)}+ onClick={composeEventHandlers(handleClick, onClickProp)}onBlur={composeEventHandlers(handleBlur, onBlurProp)}onKeyDown={handleKeyDown}placeholder={placeholder}diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 62fcf5e91a..ff1c285d9f 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -1030,6 +1030,75 @@ describe('BaseTypeahead hasEntriesOnFocus', () => {expect(input).toHaveAttribute('aria-expanded', 'true');});});++ it('reopens on click when the input was already focused and the dropdown closed without a blur (#6845)', async () => {+ const user = userEvent.setup();+ render(+ <BaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ // A real click focuses the input (justFocusedRef suppresses the click+ // handler's own open logic here, since handleFocus already opened it).+ await user.click(input);+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ // Escape closes the dropdown via popover.hide() alone — same as+ // selecting a result (which also re-focuses the input internally) or a+ // composing field re-focusing this input after committing something+ // elsewhere, the input is never actually blurred.+ await user.keyboard('{Escape}');+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ expect(input).toHaveFocus();++ // Clicking the still-focused input must reopen it — before the fix,+ // this click dispatched no focus event (the input never lost focus) and+ // nothing else reopened the dropdown.+ await user.click(input);+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });+ });++ it('does not double-fire an async bootstrap source on a single first click (#6848 review)', async () => {+ // A microtask-based "did a focus event just run" flag, tried first,+ // cleared before the click event arrived for an async source — the+ // click path then ran openIfEligible a second time while the first+ // bootstrap call was still in flight. The fix reads document.activeElement+ // at pointerdown instead, which has no event-loop timing dependency.+ const user = userEvent.setup();+ const bootstrap = vi.fn(async (): Promise<SearchableItem[]> => {+ await Promise.resolve();+ return fruits.slice(0, 3);+ });+ render(+ <BaseTypeahead+ searchSource={{search: () => [], bootstrap}}+ value={null}+ onChange={() => {}}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ await user.click(input);+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ expect(bootstrap).toHaveBeenCalledTimes(1);+ });});describe('BaseTypeahead minQueryLength', () => {