From 7c45fb65fd7194a6280b96d77d8a4649f9c1321a Mon Sep 17 00:00:00 2001 From: Daniel Richards Date: Sat, 16 Dec 2023 03:10:04 +0800 Subject: [PATCH] Fix form token field suggestion list reopening after blurring the input (#57002) * Update boolean logic to ensure suggestions list closes when expandOnFocus prop is false * Improve readability * Add Changelog entry * Fix CHANGELOG, move entry to the "Unreleased" section --------- Co-authored-by: Marcelo Serpa --- packages/components/CHANGELOG.md | 4 ++++ .../components/src/form-token-field/index.tsx | 18 +++++++++++------- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/components/CHANGELOG.md b/packages/components/CHANGELOG.md index 01a31c58d01c81..3010484341d4d5 100644 --- a/packages/components/CHANGELOG.md +++ b/packages/components/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Bug Fix + +- `FormTokenField`: Fix a regression where the suggestion list would re-open after clicking away from the input ([#57002](https://github.com/WordPress/gutenberg/pull/57002)). + ## 25.14.0 (2023-12-13) ### Enhancements diff --git a/packages/components/src/form-token-field/index.tsx b/packages/components/src/form-token-field/index.tsx index bdc3c2a53ae1d0..895cbad033212b 100644 --- a/packages/components/src/form-token-field/index.tsx +++ b/packages/components/src/form-token-field/index.tsx @@ -177,13 +177,17 @@ export function FormTokenField( props: FormTokenFieldProps ) { setInputOffsetFromEnd( 0 ); setIsActive( false ); - // If `__experimentalExpandOnFocus` is true, don't close the suggestions list when - // the user clicks on it (`tokensAndInput` will be the element that caused the blur). - const shouldKeepSuggestionsExpanded = - ! __experimentalExpandOnFocus || - ( __experimentalExpandOnFocus && - event.relatedTarget === tokensAndInput.current ); - setIsExpanded( shouldKeepSuggestionsExpanded ); + if ( __experimentalExpandOnFocus ) { + // If `__experimentalExpandOnFocus` is true, don't close the suggestions list when + // the user clicks on it (`tokensAndInput` will be the element that caused the blur). + const hasFocusWithin = + event.relatedTarget === tokensAndInput.current; + setIsExpanded( hasFocusWithin ); + } else { + // Else collapse the suggestion list. This will result in the suggestion list closing + // after a suggestion has been submitted since that causes a blur. + setIsExpanded( false ); + } setSelectedSuggestionIndex( -1 ); setSelectedSuggestionScroll( false );