An open source design system that's fully customizable and agent ready
TypeScript
fix(typeahead): prevent empty popover from persisting after selection (#1943)
Cindy Zhangc2d88b83b14b
diff --git a/packages/core/src/Layer/useXDSLayer.tsx b/packages/core/src/Layer/useXDSLayer.tsxindex 2e5acbf73c..e962391954 100644--- a/packages/core/src/Layer/useXDSLayer.tsx+++ b/packages/core/src/Layer/useXDSLayer.tsx@@ -280,17 +280,24 @@ export function useXDSLayer(const popoverRef = useRef<HTMLElement | null>(null);const triggerRef = useRef<HTMLElement | null>(null);+ // Ref mirrors isOpen for synchronous reads inside show/hide.+ // State drives re-renders; the ref lets the imperative calls avoid+ // stale-closure reads of the previous isOpen value.+ const isOpenRef = useRef(false);+const show = useCallback(() => {- if (popoverRef.current && !popoverRef.current.matches(':popover-open')) {+ if (popoverRef.current && !isOpenRef.current) {popoverRef.current.showPopover();+ isOpenRef.current = true;setIsOpen(true);onShow?.();}}, [onShow]);const hide = useCallback(() => {- if (popoverRef.current?.matches(':popover-open')) {- popoverRef.current.hidePopover();+ if (isOpenRef.current) {+ popoverRef.current?.hidePopover();+ isOpenRef.current = false;setIsOpen(false);onHide?.();}@@ -316,19 +323,26 @@ export function useXDSLayer(}: undefined;- // Handle popover toggle events (for sync with browser-initiated close)+ // Reconcile browser-initiated closes (light-dismiss, popover="auto" stack+ // eviction). These are the only cases where the DOM mutates without going+ // through our show/hide — we sync React state back to match.+ //+ // No "open" case: the browser never spontaneously opens a popover. Opens+ // only happen via showPopover() which we always call from show().+ //+ // The isOpenRef guard prevents double-firing: when our hide() already set+ // the ref to false, the subsequent toggle event (which the browser fires+ // as a side-effect of hidePopover) sees false and skips.const handleToggle = useCallback((e: Event) => {const toggleEvent = e as ToggleEvent;- if (toggleEvent.newState === 'closed') {+ if (toggleEvent.newState === 'closed' && isOpenRef.current) {+ isOpenRef.current = false;setIsOpen(false);onHide?.();- } else if (toggleEvent.newState === 'open') {- setIsOpen(true);- onShow?.();}},- [onShow, onHide],+ [onHide],);// Ref callback for popover element — sets up toggle listenerdiff --git a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx b/packages/core/src/Tokenizer/XDSTokenizer.test.tsxindex 6ec7186d8a..57b252c3c4 100644--- a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx+++ b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx@@ -627,4 +627,35 @@ describe('XDSTokenizer', () => {expect(screen.queryByText('Create "Alice"')).not.toBeInTheDocument();});});++ describe('popover after selection', () => {+ it('does not show an empty popover after selecting an item with hasEntriesOnFocus', async () => {+ const onChange = vi.fn();+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={onChange}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ // Focus to open bootstrap results+ fireEvent.focus(input);+ await act(async () => {+ await new Promise(r => setTimeout(r, 50));+ });+ expect(input).toHaveAttribute('aria-expanded', 'true');++ // Select an item+ fireEvent.click(screen.getByText('Alice'));+ expect(onChange).toHaveBeenCalled();++ // Popover should not reopen with an empty menu after selection+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });});diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsxindex 22560c352b..d350ac45ec 100644--- a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx@@ -314,6 +314,16 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<// Debounce refconst searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Monotonic counter incremented on selection and query-clear. Async+ // searches that resolve after a selection compare their captured+ // generation to the current value and discard stale results.+ const searchGenRef = useRef(0);+ // The generation at which results were last populated. handleFocus+ // compares this to searchGenRef — if they differ, the cached results+ // in the closure are stale (a selection cleared them) and shouldn't+ // be re-shown.+ const resultsGenRef = useRef(0);+// Layer for dropdownconst handleLayerShow = useCallback(() => {onOpenChange?.(true);@@ -378,20 +388,26 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<const performSearch = useCallback(async (searchQuery: string) => {searchSource.cancel?.();+ const gen = searchGenRef.current;setIsLoading(true);setHasSearched(true);try {const searchResults = await searchSource.search(searchQuery);+ if (searchGenRef.current !== gen) return;+ resultsGenRef.current = gen;setResults(searchResults.slice(0, maxMenuItems));setHighlightedIndex(searchResults.length > 0 ? 0 : -1);if (searchResults.length > 0 || searchQuery.length > 0) {showLayer();}} catch {+ if (searchGenRef.current !== gen) return;setResults([]);setHighlightedIndex(-1);} finally {- setIsLoading(false);+ if (searchGenRef.current === gen) {+ setIsLoading(false);+ }}},[searchSource, maxMenuItems, showLayer],@@ -399,18 +415,24 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<// Perform bootstrapconst performBootstrap = useCallback(async () => {+ const gen = searchGenRef.current;setIsLoading(true);try {const bootstrapResults = await searchSource.bootstrap();+ if (searchGenRef.current !== gen) return;+ resultsGenRef.current = gen;setResults(bootstrapResults.slice(0, maxMenuItems));setHighlightedIndex(bootstrapResults.length > 0 ? 0 : -1);if (bootstrapResults.length > 0) {showLayer();}} catch {+ if (searchGenRef.current !== gen) return;setResults([]);} finally {- setIsLoading(false);+ if (searchGenRef.current === gen) {+ setIsLoading(false);+ }}}, [searchSource, maxMenuItems, showLayer]);@@ -425,6 +447,7 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<}if (newQuery.length === 0 && !hasEntriesOnFocus) {+ searchGenRef.current++;searchSource.cancel?.();setResults([]);setHasSearched(false);@@ -468,6 +491,13 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<// Handle item selectionconst handleSelect = useCallback((item: T) => {+ // Bump generation to invalidate any in-flight async searches+ searchGenRef.current++;+ if (searchTimeoutRef.current) {+ clearTimeout(searchTimeoutRef.current);+ searchTimeoutRef.current = null;+ }+ searchSource.cancel?.();onChange(item);setQuery('');setResults([]);@@ -475,7 +505,7 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<popover.hide();inputRef.current?.focus();},- [onChange, popover],+ [onChange, popover, searchSource],);// Handle focus@@ -483,7 +513,14 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<if (isDisabled) return;if (hasEntriesOnFocus && results.length === 0 && query.length === 0) {performBootstrap();- } else if (results.length > 0 && (query.length > 0 || hasEntriesOnFocus)) {+ } 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();}}, [diff --git a/packages/core/src/Typeahead/XDSTypeahead.test.tsx b/packages/core/src/Typeahead/XDSTypeahead.test.tsxindex 28d51bebaf..bc6607a231 100644--- a/packages/core/src/Typeahead/XDSTypeahead.test.tsx+++ b/packages/core/src/Typeahead/XDSTypeahead.test.tsx@@ -375,6 +375,38 @@ describe('XDSBaseTypeahead hasSearched reset', () => {});});+describe('XDSBaseTypeahead popover after selection', () => {+ it('does not show an empty popover after selecting an item with hasEntriesOnFocus', async () => {+ const onChange = vi.fn();+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={onChange}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');++ // Focus to open bootstrap results+ fireEvent.focus(input);+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ // Select an item — popover should close+ fireEvent.click(screen.getByText('Apple'));+ expect(onChange).toHaveBeenCalledWith(fruits[0]);++ // After selection, input is refocused but popover should NOT reopen+ // with an empty menu. The handleFocus handler should be suppressed.+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });+});+describe('XDSTypeahead edit mode', () => {it('enters edit mode on token container click', () => {const onChange = vi.fn();