Skip to content

Commit

Permalink
Navigation block: Only focus submenu trigger on escape key press (#41986
Browse files Browse the repository at this point in the history
)

* Only focus submenu trigger on escape key press.

* Optional focus.
  • Loading branch information
alexstine authored Jul 9, 2022
1 parent 66bd34a commit b40ee4f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
12 changes: 6 additions & 6 deletions packages/block-library/src/navigation-submenu/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ 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 @@ -57,11 +55,13 @@ document.addEventListener( 'keyup', function ( event ) {
'.wp-block-navigation-submenu'
);
submenuBlocks.forEach( ( block ) => {
if (
! block.contains( event.target ) ||
( block.contains( event.target ) && event.key === 'Escape' )
) {
if ( ! block.contains( event.target ) ) {
closeSubmenus( block );
} else if ( event.key === 'Escape' ) {
const toggle = block.querySelector( '[aria-expanded="true"]' );
closeSubmenus( block );
// Focus the submenu trigger so focus does not get trapped in the closed submenu.
toggle?.focus();
}
} );
} );
12 changes: 6 additions & 6 deletions packages/block-library/src/navigation/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ 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 @@ -63,11 +61,13 @@ window.addEventListener( 'load', () => {
'.wp-block-navigation-item.has-child'
);
submenuBlocks.forEach( function ( block ) {
if (
! block.contains( event.target ) ||
( block.contains( event.target ) && event.key === 'Escape' )
) {
if ( ! block.contains( event.target ) ) {
closeSubmenus( block );
} else if ( event.key === 'Escape' ) {
const toggle = block.querySelector( '[aria-expanded="true"]' );
closeSubmenus( block );
// Focus the submenu trigger so focus does not get trapped in the closed submenu.
toggle?.focus();
}
} );
} );
Expand Down

0 comments on commit b40ee4f

Please sign in to comment.