Skip to content

Commit

Permalink
Handle Escape on Toolbar Option 1: Add event listeners to all childre…
Browse files Browse the repository at this point in the history
…n via onChildrenKeyDown passed to NavigableToolbar

Note: Due to the use of portals in the toolbar slots, consistently handling event listeners cleanly is difficult.

This method adds event listeners to all children of a toolbar if a `onChildrenKeyDown` prop is passed to the <NavigableToolbar /> via a querySelectorAll( '[data-toolbar-item="true"]' ) on the NavigableToolbar ref, then applying an addEventListener to all the returned buttons.

Pros: Event listener is applied and handled in one location.
Cons: Feels yucky. Feels like crossing our fingers and hoping it works consistently, which it might.
  • Loading branch information
jeryj committed Sep 6, 2023
1 parent 732fabb commit 9acb93d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,13 @@ function BlockContextualToolbar( { focusOnMount, isFixed, ...props } ) {
className={ classes }
/* translators: accessibility text for the block toolbar */
aria-label={ __( 'Block tools' ) }
{ ...props }
onKeyDown={ ( event ) => {
onChildrenKeyDown={ ( event ) => {
if ( event.keyCode === ESCAPE && lastFocus?.current ) {
event.preventDefault();
lastFocus.current.focus();
}
} }
{ ...props }
>
{ ! isCollapsed && <BlockToolbar hideDragHandle={ isFixed } /> }
{ isFixed && isLargeViewport && blockType && (
Expand Down
31 changes: 30 additions & 1 deletion packages/block-editor/src/components/navigable-toolbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,14 @@ function useToolbarFocus(
function NavigableToolbar( {
children,
focusOnMount,
onChildrenKeyDown = () => {},
shouldUseKeyboardFocusShortcut = true,
__experimentalInitialIndex: initialIndex,
__experimentalOnIndexChange: onIndexChange,
...props
} ) {
const ref = useRef();
const isAccessibleToolbar = useIsAccessibleToolbar( ref );

useToolbarFocus(
ref,
focusOnMount,
Expand All @@ -173,6 +173,35 @@ function NavigableToolbar( {
shouldUseKeyboardFocusShortcut
);

useEffect( () => {
const navigableToolbarRef = ref.current;
const toolbarButtons = navigableToolbarRef.querySelectorAll(
'[data-toolbar-item="true"]'
);

if ( onChildrenKeyDown ) {
const handleChildrenKeyDown = ( event ) => {
onChildrenKeyDown( event );
};

toolbarButtons.forEach( ( toolbarButton ) => {
toolbarButton.addEventListener(
'keydown',
handleChildrenKeyDown
);
} );

return () => {
toolbarButtons.forEach( ( toolbarButton ) => {
toolbarButton.removeEventListener(
'keydown',
handleChildrenKeyDown
);
} );
};
}
}, [ onChildrenKeyDown, children ] );

if ( isAccessibleToolbar ) {
return (
<Toolbar label={ props[ 'aria-label' ] } ref={ ref } { ...props }>
Expand Down

0 comments on commit 9acb93d

Please sign in to comment.