Skip to content

Commit

Permalink
Widget Editor: Focus toggle button when the global inserter is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
t-hamano committed Dec 21, 2024
1 parent ca24cce commit e1b487c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,47 @@ import {
__experimentalUseDialog as useDialog,
} from '@wordpress/compose';
import { useCallback, useRef } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
import { useSelect, useDispatch } from '@wordpress/data';
import { ESCAPE } from '@wordpress/keycodes';

/**
* Internal dependencies
*/
import useWidgetLibraryInsertionPoint from '../../hooks/use-widget-library-insertion-point';
import { store as editWidgetsStore } from '../../store';
import { unlock } from '../../lock-unlock';

export default function InserterSidebar() {
const isMobileViewport = useViewportMatch( 'medium', '<' );
const { rootClientId, insertionIndex } = useWidgetLibraryInsertionPoint();

const inserterSidebarToggleRef = useSelect( ( select ) => {
return unlock(
select( editWidgetsStore )
).getInserterSidebarToggleRef();
}, [] );

const { setIsInserterOpened } = useDispatch( editWidgetsStore );

const closeInserter = useCallback( () => {
return setIsInserterOpened( false );
}, [ setIsInserterOpened ] );
setIsInserterOpened( false );
inserterSidebarToggleRef.current?.focus();
}, [ setIsInserterOpened, inserterSidebarToggleRef ] );

const closeOnEscape = useCallback(
( event ) => {
if ( event.keyCode === ESCAPE && ! event.defaultPrevented ) {
event.preventDefault();
closeInserter();
}
},
[ closeInserter ]
);

const [ inserterDialogRef, inserterDialogProps ] = useDialog( {
onClose: closeInserter,
focusOnMount: true,
onKeyDown: closeOnEscape,
} );

const libraryRef = useRef();
Expand Down
19 changes: 19 additions & 0 deletions test/e2e/specs/widgets/editing-widgets.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,25 @@ test.describe( 'Widgets screen', () => {
} );
} );

test( 'Should focus the global inserter toggle when the global inserter is closed', async ( {
page,
} ) => {
const blockInserterToggle = page
.getByRole( 'toolbar', { name: 'Document tools' } )
.getByRole( 'button', { name: 'Block Inserter', exact: true } );
await blockInserterToggle.click();
await page
.getByRole( 'button', { name: 'Close Block Inserter' } )
.click();

await expect( blockInserterToggle ).toBeFocused();

await blockInserterToggle.click();
await page.keyboard.press( 'Escape' );

await expect( blockInserterToggle ).toBeFocused();
} );

test( 'Should insert content using the inline inserter', async ( {
page,
widgetsScreen,
Expand Down

0 comments on commit e1b487c

Please sign in to comment.