Skip to content

Commit

Permalink
Components: Fix the Snackbar auto-dismissal timers (#58604)
Browse files Browse the repository at this point in the history
* Components: Fix the Snackbar auto-dismissal timers
* Add changelog entry
* Use the latest ref pattern

Co-authored-by: Mamaduka <mamaduka@git.wordpress.org>
Co-authored-by: ciampo <mciampini@git.wordpress.org>
  • Loading branch information
3 people authored Feb 2, 2024
1 parent cabd2ed commit 4076bb1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- `Placeholder`: Fix Placeholder component padding when body text font size is changed ([#58323](https://github.com/WordPress/gutenberg/pull/58323)).
- `Placeholder`: Fix Global Styles typography settings bleeding into placeholder component ([#58303](https://github.com/WordPress/gutenberg/pull/58303)).
- `PaletteEdit`: Fix palette item accessibility in details view ([#58214](https://github.com/WordPress/gutenberg/pull/58214)).
- `Snackbar`: Fix the auto-dismissal timers ([#58604](https://github.com/WordPress/gutenberg/pull/58604)).

### Experimental

Expand Down
23 changes: 18 additions & 5 deletions packages/components/src/snackbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ import classnames from 'classnames';
* WordPress dependencies
*/
import { speak } from '@wordpress/a11y';
import { useEffect, forwardRef, renderToString } from '@wordpress/element';
import {
useEffect,
useLayoutEffect,
useRef,
forwardRef,
renderToString,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import warning from '@wordpress/warning';

Expand Down Expand Up @@ -88,17 +94,24 @@ function UnforwardedSnackbar(

useSpokenMessage( spokenMessage, politeness );

// Only set up the timeout dismiss if we're not explicitly dismissing.
// The `onDismiss/onRemove` can have unstable references,
// trigger side-effect cleanup, and reset timers.
const callbackRefs = useRef( { onDismiss, onRemove } );
useLayoutEffect( () => {
callbackRefs.current = { onDismiss, onRemove };
} );

useEffect( () => {
// Only set up the timeout dismiss if we're not explicitly dismissing.
const timeoutHandle = setTimeout( () => {
if ( ! explicitDismiss ) {
onDismiss?.();
onRemove?.();
callbackRefs.current.onDismiss?.();
callbackRefs.current.onRemove?.();
}
}, NOTICE_TIMEOUT );

return () => clearTimeout( timeoutHandle );
}, [ onDismiss, onRemove, explicitDismiss ] );
}, [ explicitDismiss ] );

const classes = classnames( className, 'components-snackbar', {
'components-snackbar-explicit-dismiss': !! explicitDismiss,
Expand Down

0 comments on commit 4076bb1

Please sign in to comment.