Skip to content
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
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

### Enhancements

- `DropdownMenu`: Focus the menu on pointer opening and enter its items with arrow keys ([#85486](https://github.com/WordPress/gutenberg/pull/85486)).
- `RangeControl`: Use the design system outline for the slider thumb focus ring ([#85536](https://github.com/WordPress/gutenberg/pull/85536)).
- `UnitControl`: Use the design system outline for the unit select focus ring ([#85444](https://github.com/WordPress/gutenberg/pull/85444)).
- `CheckboxControl`, `RadioControl`: Use the design system outline for focus rings ([#85379](https://github.com/WordPress/gutenberg/pull/85379)).
Expand Down
2 changes: 2 additions & 0 deletions packages/components/src/dropdown-menu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ Generally, the parent button should have a triangular icon to the right of the i

The parent button should retain the same visual styling regardless of whether the DropdownMenu is displayed or not.

Opening the menu with a pointer focuses the menu container without highlighting an item. Arrow keys then move focus into the menu. Opening it with Enter, Space, or ArrowDown focuses the first item. Set `popoverProps.focusOnMount` to override this default focus behavior.

#### Placement

The DropdownMenu should typically appear directly below, or below and to the left of, the parent button. If there isn’t enough space below to display the full DropdownMenu, it can be displayed instead above the parent button.
Expand Down
51 changes: 49 additions & 2 deletions packages/components/src/dropdown-menu/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import clsx from 'clsx';
import { menu } from '@wordpress/icons';
import { useEffect, useState } from '@wordpress/element';
import { contextConnectWithoutRef, useContextSystem } from '../context';
import Button from '../button';
import Dropdown from '../dropdown';
Expand Down Expand Up @@ -53,6 +54,12 @@ function UnconnectedDropdownMenu( dropdownMenuProps: DropdownMenuProps ) {
dropdownMenuProps,
'DropdownMenu'
);
const [ focusFirstItem, setFocusFirstItem ] = useState( true );
useEffect( () => {
if ( open === false ) {
setFocusFirstItem( true );
}
}, [ open ] );

if ( ! controls?.length && ! isFunction( children ) ) {
return null;
Expand All @@ -78,11 +85,36 @@ function UnconnectedDropdownMenu( dropdownMenuProps: DropdownMenuProps ) {
},
popoverProps
);
const onPopoverFocusCapture = (
event: React.FocusEvent< HTMLDivElement >
) => {
popoverProps?.onFocusCapture?.( event );

// A consumer's focus handler may already have moved focus elsewhere.
if (
! focusFirstItem &&
popoverProps?.focusOnMount === undefined &&
event.target === event.currentTarget &&
event.currentTarget.ownerDocument.activeElement ===
event.currentTarget
Comment thread
mirka marked this conversation as resolved.
Resolved
) {
// Keep pointer-opened menus focused without highlighting an item.
event.currentTarget
.querySelector< HTMLElement >( '[role="menu"]' )
?.focus( { preventScroll: true } );
}
};

return (
<Dropdown
className={ className }
popoverProps={ mergedPopoverProps }
popoverProps={ {
...mergedPopoverProps,
focusOnMount:
popoverProps?.focusOnMount ??
( focusFirstItem ? 'firstElement' : true ),
onFocusCapture: onPopoverFocusCapture,
} }
renderToggle={ ( { isOpen, onToggle } ) => {
const openOnArrowDown = ( event: React.KeyboardEvent ) => {
// A toggle disabled with `accessibleWhenDisabled` can still be
Expand All @@ -93,6 +125,7 @@ function UnconnectedDropdownMenu( dropdownMenuProps: DropdownMenuProps ) {

if ( ! isOpen && event.code === 'ArrowDown' ) {
event.preventDefault();
setFocusFirstItem( true );
onToggle();
}
};
Expand All @@ -114,6 +147,16 @@ function UnconnectedDropdownMenu( dropdownMenuProps: DropdownMenuProps ) {
icon={ icon }
onClick={
( ( event ) => {
if ( ! isOpen ) {
const nativeEvent = event.nativeEvent;
// Assistive technology can send trusted clicks with
// nonzero detail and an empty pointer type.
setFocusFirstItem(
event.detail === 0 ||
( 'pointerType' in nativeEvent &&
nativeEvent.pointerType === '' )
);
}
onToggle();
if ( mergedToggleProps.onClick ) {
mergedToggleProps.onClick( event );
Expand Down Expand Up @@ -150,7 +193,11 @@ function UnconnectedDropdownMenu( dropdownMenuProps: DropdownMenuProps ) {
);

return (
<NavigableMenu { ...mergedMenuProps } role="menu">
<NavigableMenu
{ ...mergedMenuProps }
role="menu"
tabIndex={ mergedMenuProps.tabIndex ?? -1 }
>
{ isFunction( children ) ? children( props ) : null }
{ controlSets?.flatMap( ( controlSet, indexOfSet ) =>
controlSet.map( ( control, indexOfControl ) => (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest';
import { userEvent } from 'vitest/browser';
import { render } from 'vitest-browser-react';
import DropdownMenu from '..';
import MenuItem from '../../menu-item';
import '../../button/style.scss';
import '../../dropdown/style.scss';
import '../../popover/style.scss';
import '../style.scss';

const menuItems = () => (
<>
<MenuItem>First item</MenuItem>
<MenuItem>Last item</MenuItem>
</>
);

describe( 'DropdownMenu opening focus', () => {
it( 'focuses the menu on pointer opening and enters its first or last item with arrow keys', async () => {
const user = userEvent.setup();
const screen = await render(
<DropdownMenu label="Open menu">{ menuItems }</DropdownMenu>
);
const toggle = screen.getByRole( 'button', { name: 'Open menu' } );
const menu = screen.getByRole( 'menu', { name: 'Open menu' } );

await user.click( toggle );
await expect.element( menu ).toHaveFocus();
await user.keyboard( '[ArrowDown]' );
await expect
.element( screen.getByRole( 'menuitem', { name: 'First item' } ) )
.toHaveFocus();

await user.keyboard( '[Escape]' );
await expect.element( toggle ).toHaveFocus();
await user.click( toggle );
await expect.element( menu ).toHaveFocus();
await user.keyboard( '[ArrowUp]' );
await expect
.element( screen.getByRole( 'menuitem', { name: 'Last item' } ) )
.toHaveFocus();
} );

it.each( [ '[Enter]', '[Space]', '[ArrowDown]' ] )(
'focuses the first item on keyboard opening with %s',
async ( key ) => {
const user = userEvent.setup();
const screen = await render(
<DropdownMenu label="Open menu">{ menuItems }</DropdownMenu>
);

await user.tab();
await user.keyboard( key );
await expect
.element(
screen.getByRole( 'menuitem', { name: 'First item' } )
)
.toHaveFocus();
}
);

it( "preserves a consumer's custom focus target", async () => {
const user = userEvent.setup();
const screen = await render(
<DropdownMenu
label="Open menu"
popoverProps={ {
onFocusCapture: ( event ) => {
if ( event.target === event.currentTarget ) {
screen
.getByRole( 'menuitem', { name: 'Last item' } )
.element()
.focus();
}
},
} }
>
{ menuItems }
</DropdownMenu>
);

await user.click( screen.getByRole( 'button', { name: 'Open menu' } ) );
await expect
.element( screen.getByRole( 'menuitem', { name: 'Last item' } ) )
.toHaveFocus();
} );
} );
16 changes: 11 additions & 5 deletions packages/components/src/navigable-container/container.tsx
Comment thread
ciampo marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function getFocusableContext(
const focusables = finder.find( container );

const index = focusables.indexOf( target as HTMLElement );
if ( index > -1 ) {
if ( index > -1 || ( ! tabbableOnly && target === container ) ) {
return { index, target, focusables };
}
return null;
Expand Down Expand Up @@ -76,7 +76,10 @@ function UnforwardedNavigableContainer(
const targetHasMenuItemRole =
!! targetRole && MENU_ITEM_ROLES.includes( targetRole );

if ( targetHasMenuItemRole ) {
if (
targetHasMenuItemRole ||
( ! onlyBrowserTabstops && event.target === container )
) {
event.preventDefault();
}
}
Expand All @@ -101,9 +104,12 @@ function UnforwardedNavigableContainer(
}

const { index, focusables } = context;
const nextIndex = cycle
? cycleValue( index, focusables.length, offset )
: index + offset;
let nextIndex = index + offset;
if ( index === -1 ) {
nextIndex = offset > 0 ? 0 : focusables.length - 1;
} else if ( cycle ) {
nextIndex = cycleValue( index, focusables.length, offset );
}

if ( nextIndex >= 0 && nextIndex < focusables.length ) {
focusables[ nextIndex ].focus();
Expand Down
6 changes: 5 additions & 1 deletion test/e2e/specs/editor/various/list-view.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1462,8 +1462,10 @@ test.describe( 'List View', () => {
await optionsForFileToggle.click();
await expect(
optionsForFileMenu,
'Pressing Space should also open the menu dropdown'
'Clicking should also open the menu dropdown'
).toBeVisible();
await expect( optionsForFileMenu ).toBeFocused();
await page.keyboard.press( 'ArrowDown' );
await expect( firstMenuItem ).toBeFocused();
await pageUtils.pressKeys( 'access+z' ); // Keyboard shortcut for Delete.
await expect
Expand All @@ -1485,6 +1487,8 @@ test.describe( 'List View', () => {
optionsForFileMenu.getByRole( 'menuitem', { name: 'Delete' } ),
'The delete menu item should be hidden for locked blocks'
).toBeHidden();
await expect( optionsForFileMenu ).toBeFocused();
await page.keyboard.press( 'ArrowDown' );
await expect( firstMenuItem ).toBeFocused();
await pageUtils.pressKeys( 'access+z' );
await expect
Expand Down
4 changes: 4 additions & 0 deletions test/e2e/specs/site-editor/patterns.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ test.describe( 'Patterns', () => {
.getByRole( 'menuitem', {
name: 'add pattern',
} );
await expect(
page.getByRole( 'menu', { name: 'add pattern' } )
).toBeFocused();
await page.keyboard.press( 'ArrowDown' );
await expect( addNewMenuItem ).toBeFocused();
await addNewMenuItem.click();
}
Expand Down
Loading