diff --git a/packages/block-library/src/navigation-submenu/view.js b/packages/block-library/src/navigation-submenu/view.js index f990729f48af0..d7fda2f8d8809 100644 --- a/packages/block-library/src/navigation-submenu/view.js +++ b/packages/block-library/src/navigation-submenu/view.js @@ -3,6 +3,8 @@ const closeSubmenus = ( element ) => { .querySelectorAll( '[aria-expanded="true"]' ) .forEach( ( toggle ) => { toggle.setAttribute( 'aria-expanded', 'false' ); + // Always focus the trigger, this becomes especially useful in closing submenus with escape key to ensure focus doesn't get trapped. + toggle.focus(); } ); }; @@ -49,13 +51,16 @@ document.addEventListener( 'click', function ( event ) { } } ); } ); -// Close on focus outside. +// Close on focus outside or escape key. document.addEventListener( 'keyup', function ( event ) { const submenuBlocks = document.querySelectorAll( '.wp-block-navigation-submenu' ); submenuBlocks.forEach( ( block ) => { - if ( ! block.contains( event.target ) ) { + if ( + ! block.contains( event.target ) || + ( block.contains( event.target ) && event.key === 'Escape' ) + ) { closeSubmenus( block ); } } ); diff --git a/packages/block-library/src/navigation/view.js b/packages/block-library/src/navigation/view.js index 5116f983b5400..6456babfbf12b 100644 --- a/packages/block-library/src/navigation/view.js +++ b/packages/block-library/src/navigation/view.js @@ -4,6 +4,8 @@ function closeSubmenus( element ) { .querySelectorAll( '[aria-expanded="true"]' ) .forEach( function ( toggle ) { toggle.setAttribute( 'aria-expanded', 'false' ); + // Always focus the trigger, this becomes especially useful in closing submenus with escape key to ensure focus doesn't get trapped. + toggle.focus(); } ); } @@ -55,13 +57,16 @@ window.addEventListener( 'load', () => { } } ); } ); - // Close on focus outside. + // Close on focus outside or escape key. document.addEventListener( 'keyup', function ( event ) { const submenuBlocks = document.querySelectorAll( '.wp-block-navigation-item.has-child' ); submenuBlocks.forEach( function ( block ) { - if ( ! block.contains( event.target ) ) { + if ( + ! block.contains( event.target ) || + ( block.contains( event.target ) && event.key === 'Escape' ) + ) { closeSubmenus( block ); } } );