Skip to content

Commit

Permalink
Merge pull request #7568 from google/enhancement/7467-follow-up
Browse files Browse the repository at this point in the history
Fix btn label flicker (Follow Up).
  • Loading branch information
kuasha420 authored Sep 12, 2023
2 parents 3c63506 + cb41a4a commit 00ace53
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions assets/js/components/KeyMetrics/MetricsSelectionPanel/Footer.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import PropTypes from 'prop-types';
import {
createInterpolateElement,
useCallback,
useEffect,
useState,
useMemo,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
Expand Down Expand Up @@ -99,15 +101,29 @@ export default function Footer( { savedMetrics } ) {
const { setValue } = useDispatch( CORE_UI );
const { navigateTo } = useDispatch( CORE_LOCATION );

const [ finalButtonText, setFinalButtonText ] = useState( null );

const currentButtonText =
savedMetrics?.length > 0 && haveSettingsChanged
? __( 'Apply changes', 'google-site-kit' )
: __( 'Save selection', 'google-site-kit' );

const onSaveClick = useCallback( async () => {
const { error } = await saveKeyMetricsSettings( {
widgetSlugs: selectedMetrics,
} );

if ( ! error ) {
setValue( KEY_METRICS_SELECTION_PANEL_OPENED_KEY, false );
// lock the button label while panel is closing
setFinalButtonText( currentButtonText );
}
}, [ saveKeyMetricsSettings, selectedMetrics, setValue ] );
}, [
saveKeyMetricsSettings,
selectedMetrics,
setValue,
currentButtonText,
] );

const onCancelClick = useCallback( () => {
setValue( KEY_METRICS_SELECTION_PANEL_OPENED_KEY, false );
Expand All @@ -118,6 +134,28 @@ export default function Footer( { savedMetrics } ) {
[ navigateTo, settingsURL ]
);

const isOpen = useSelect( ( select ) =>
select( CORE_UI ).getValue( KEY_METRICS_SELECTION_PANEL_OPENED_KEY )
);

const [ prevIsOpen, setPrevIsOpen ] = useState( null );

useEffect( () => {
if ( prevIsOpen !== null ) {
// if current isOpen is true, and different from prevIsOpen
// meaning it transitioned from false to true and it is not
// in closing transition, we should reset the button label
// locked when save button was clicked
if ( prevIsOpen !== isOpen ) {
if ( isOpen ) {
setFinalButtonText( null );
}
}
}

setPrevIsOpen( isOpen );
}, [ isOpen, prevIsOpen ] );

return (
<footer className="googlesitekit-km-selection-panel-footer">
{ saveError && (
Expand All @@ -136,9 +174,7 @@ export default function Footer( { savedMetrics } ) {
isSavingSettings
}
>
{ savedMetrics?.length > 0 && haveSettingsChanged
? __( 'Apply changes', 'google-site-kit' )
: __( 'Save selection', 'google-site-kit' ) }
{ finalButtonText || currentButtonText }
</SpinnerButton>
<Link onClick={ onCancelClick } disabled={ isSavingSettings }>
{ __( 'Cancel', 'google-site-kit' ) }
Expand Down

0 comments on commit 00ace53

Please sign in to comment.