Skip to content

Commit

Permalink
Navigation submenus: Allow Escape key to close the submenu and focus …
Browse files Browse the repository at this point in the history
…trigger (#41774)

* Add escape key functionality for navigation submenus.

* Fix to selector.

* Add missing toggle focus to submenu close function.

* Code comment.
  • Loading branch information
alexstine authored Jun 21, 2022
1 parent df8e783 commit db8b006
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
9 changes: 7 additions & 2 deletions packages/block-library/src/navigation-submenu/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
} );
};

Expand Down Expand Up @@ -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 );
}
} );
Expand Down
9 changes: 7 additions & 2 deletions packages/block-library/src/navigation/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
} );
}

Expand Down Expand Up @@ -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 );
}
} );
Expand Down

0 comments on commit db8b006

Please sign in to comment.