Skip to content

Commit

Permalink
Snackbar: fix focus loss on dismiss (#34736)
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix authored Sep 10, 2021
1 parent 98f1181 commit f7e057b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
4 changes: 4 additions & 0 deletions packages/components/src/snackbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ function Snackbar(
// It is distinct from onRemove, which _looks_ like a callback but is
// actually the function to call to remove the snackbar from the UI.
onDismiss = noop,
listRef,
},
ref
) {
Expand All @@ -63,6 +64,9 @@ function Snackbar(
event.preventDefault();
}

// Prevent focus loss by moving it to the list element.
listRef.current.focus();

onDismiss();
onRemove();
}
Expand Down
5 changes: 4 additions & 1 deletion packages/components/src/snackbar/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { omit, noop } from 'lodash';
* WordPress dependencies
*/
import { useReducedMotion } from '@wordpress/compose';
import { useRef } from '@wordpress/element';

/**
* Internal dependencies
Expand Down Expand Up @@ -56,11 +57,12 @@ const SNACKBAR_REDUCE_MOTION_VARIANTS = {
* @return {Object} The rendered notices list.
*/
function SnackbarList( { notices, className, children, onRemove = noop } ) {
const listRef = useRef();
const isReducedMotion = useReducedMotion();
className = classnames( 'components-snackbar-list', className );
const removeNotice = ( notice ) => () => onRemove( notice.id );
return (
<div className={ className }>
<div className={ className } tabIndex={ -1 } ref={ listRef }>
{ children }
<AnimatePresence>
{ notices.map( ( notice ) => {
Expand All @@ -81,6 +83,7 @@ function SnackbarList( { notices, className, children, onRemove = noop } ) {
<Snackbar
{ ...omit( notice, [ 'content' ] ) }
onRemove={ removeNotice( notice ) }
listRef={ listRef }
>
{ notice.content }
</Snackbar>
Expand Down
4 changes: 4 additions & 0 deletions packages/e2e-tests/specs/widgets/editing-widgets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,10 @@ async function saveWidgets() {
// Close the snackbar.
const savedSnackbar = await find( savedSnackbarQuery );
await savedSnackbar.click();
// Expect focus not to be lost.
await expect(
await page.evaluate( () => document.activeElement.className )
).toBe( 'components-snackbar-list edit-widgets-notices__snackbar' );
await expect( savedSnackbarQuery ).not.toBeFound();
}

Expand Down

0 comments on commit f7e057b

Please sign in to comment.