From 65e2a9b42fe624151bb5c735865b549647bb8c5e Mon Sep 17 00:00:00 2001 From: Lena Morita Date: Wed, 16 Oct 2024 08:52:10 +0900 Subject: [PATCH] ToggleGroupControl: Don't set value on focus after a reset --- .../toggle-group-control-option-base/component.tsx | 6 +++++- .../toggle-group-control/as-radio-group.tsx | 9 ++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/components/src/toggle-group-control/toggle-group-control-option-base/component.tsx b/packages/components/src/toggle-group-control/toggle-group-control-option-base/component.tsx index b33f53dd706b5..c7de70690d68e 100644 --- a/packages/components/src/toggle-group-control/toggle-group-control-option-base/component.tsx +++ b/packages/components/src/toggle-group-control/toggle-group-control-option-base/component.tsx @@ -141,10 +141,14 @@ function ToggleGroupControlOptionBase( { + const selectedValueIsNullish = + toggleGroupControlContext.value === null || + toggleGroupControlContext.value === ''; + // Conditions ensure that the first visible focus to a radio group // without a selected option will not automatically select the option. if ( - toggleGroupControlContext.value !== null || + ! selectedValueIsNullish || toggleGroupControlContext.activeItemIsNotFirstItem?.() ) { toggleGroupControlContext.setValue( value ); diff --git a/packages/components/src/toggle-group-control/toggle-group-control/as-radio-group.tsx b/packages/components/src/toggle-group-control/toggle-group-control/as-radio-group.tsx index 4481fc9f6138d..0166728dbafba 100644 --- a/packages/components/src/toggle-group-control/toggle-group-control/as-radio-group.tsx +++ b/packages/components/src/toggle-group-control/toggle-group-control/as-radio-group.tsx @@ -9,7 +9,7 @@ import { useStoreState } from '@ariakit/react'; * WordPress dependencies */ import { useInstanceId } from '@wordpress/compose'; -import { forwardRef, useMemo } from '@wordpress/element'; +import { forwardRef, useEffect, useMemo } from '@wordpress/element'; import { isRTL } from '@wordpress/i18n'; /** @@ -73,6 +73,13 @@ function UnforwardedToggleGroupControlAsRadioGroup( const selectedValue = useStoreState( radio, 'value' ); const setValue = radio.setValue; + // Ensures that the active id is also reset after the value is "reset" by the consumer. + useEffect( () => { + if ( selectedValue === '' ) { + radio.setActiveId( undefined ); + } + }, [ radio, selectedValue ] ); + const groupContextValue = useMemo( (): ToggleGroupControlContextProps => ( { activeItemIsNotFirstItem: () =>