Skip to content

Commit

Permalink
Only close inserter on Escape or button press on inserter toggle
Browse files Browse the repository at this point in the history
Remove the useDialog hook, as it was only used for focus outside and escape keypresses to close the inserter. It doesn't appear any semantics were added. This manually implements an escape keypress hook to close the inserter when focus is inside the inserter.
  • Loading branch information
jeryj committed Apr 24, 2024
1 parent 58b8abc commit 35b24a4
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions packages/editor/src/components/inserter-sidebar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import { useDispatch, useSelect } from '@wordpress/data';
import { Button, VisuallyHidden } from '@wordpress/components';
import { __experimentalLibrary as Library } from '@wordpress/block-editor';
import { close } from '@wordpress/icons';
import {
useViewportMatch,
__experimentalUseDialog as useDialog,
} from '@wordpress/compose';
import { useViewportMatch, useRefEffect } from '@wordpress/compose';
import { __ } from '@wordpress/i18n';
import { useEffect, useRef } from '@wordpress/element';
import { store as preferencesStore } from '@wordpress/preferences';
import { ESCAPE } from '@wordpress/keycodes';

/**
* Internal dependencies
Expand All @@ -35,22 +33,34 @@ export default function InserterSidebar( {

const isMobileViewport = useViewportMatch( 'medium', '<' );
const TagName = ! isMobileViewport ? VisuallyHidden : 'div';
const [ inserterDialogRef, inserterDialogProps ] = useDialog( {
onClose: () => setIsInserterOpened( false ),
focusOnMount: null,
} );

const libraryRef = useRef();
useEffect( () => {
libraryRef.current.focusSearch();
}, [] );

const useEscape = useRefEffect( ( element ) => {
function onKeyDown( event ) {
const { keyCode } = event;

if ( event.defaultPrevented ) {
return;
}

if ( keyCode === ESCAPE ) {
event.preventDefault();
setIsInserterOpened( false );
}
}

element.addEventListener( 'keydown', onKeyDown );
return () => {
element.removeEventListener( 'keydown', onKeyDown );
};
}, [] );

return (
<div
ref={ inserterDialogRef }
{ ...inserterDialogProps }
className="editor-inserter-sidebar"
>
<div ref={ useEscape } className="editor-inserter-sidebar">
<TagName className="editor-inserter-sidebar__header">
<Button
icon={ close }
Expand Down

0 comments on commit 35b24a4

Please sign in to comment.