Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation submenus: Allow Escape key to close the submenu and focus trigger #41774

Merged
merged 4 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
alexstine marked this conversation as resolved.
Show resolved Hide resolved
} );
};

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