Skip to content
Closed
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/block-editor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### New Features

- The floating block toolbar is a labelled region, so region navigation can reach it ([#82310](https://github.com/WordPress/gutenberg/pull/82310)).
- `BackgroundImageControl`: Support setting the background image from a URL, through the URL field in the media replace popover ([#82230](https://github.com/WordPress/gutenberg/pull/82230)).

### Enhancements
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import clsx from 'clsx';
import { useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { useEffect, useRef } from '@wordpress/element';
import { useShortcut } from '@wordpress/keyboard-shortcuts';
import { PrivateBlockPopover } from '../block-popover';
Expand Down Expand Up @@ -58,6 +59,9 @@ export default function BlockToolbarPopover( {
resize={ false }
{ ...popoverProps }
__unstableContentRef={ __unstableContentRef }
role="region"
aria-label={ __( 'Block toolbar' ) }
tabIndex={ -1 }
>
<PrivateBlockToolbar
// If the toolbar is being shown because of being forced
Expand Down
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### Enhancements

- `navigateRegions`: Pressing Escape moves focus out onto the surrounding region. On a region, Tab moves to the next one, backwards with Shift, and Enter, or Escape again, goes back in, to the place focus last left the region from or to its first tabbable. Handlers that claim a key first, popovers and modals among them, keep winning. Tab cycles exactly the regions the existing shortcuts visit, in document order, so a region nested in another, like a floating toolbar, comes right after its container ([#82310](https://github.com/WordPress/gutenberg/pull/82310)).
- `Popover`: Widen `offset` to also accept an object with separate main and cross axis offsets. The same applies to `BorderBoxControl`'s `popoverOffset` prop ([#82060](https://github.com/WordPress/gutenberg/pull/82060)).
- `ToolsPanelItem`: Add `defaultShown` to show an optional item that has no value, and an `onShownChange` callback that fires only when the user toggles the item in the panel's menu ([#78010](https://github.com/WordPress/gutenberg/pull/78010)).
- `BorderBoxControl`: render the linked/unlinked toggle in a row alongside the label when a visible label is present, so it lines up with the equivalent toggle on sibling controls. Without a visible label the toggle stays beside the inputs, as before. The visible label is now a `BaseControl.VisualLabel`, so it renders as a `span` rather than a `label` element; it was never associated with an input in either form ([#82163](https://github.com/WordPress/gutenberg/pull/82163)).
Expand Down
162 changes: 157 additions & 5 deletions packages/components/src/higher-order/navigate-regions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@wordpress/compose';
import { isKeyboardEvent } from '@wordpress/keycodes';
import type { WPKeycodeModifier } from '@wordpress/keycodes';
import { focus } from '@wordpress/dom';

const defaultShortcuts = {
previous: [
Expand Down Expand Up @@ -42,8 +43,51 @@ type Shortcuts = {
export function useNavigateRegions( shortcuts: Shortcuts = defaultShortcuts ) {
const ref = useRef< HTMLDivElement >( null );
const [ isFocusingRegions, setIsFocusingRegions ] = useState( false );
const lastFocusPerRegion = useRef(
new WeakMap< HTMLElement, HTMLElement >()
);

// The active element, descending into same-origin frames: within them,
// the document only reports the frame element itself as active.
function getDeepActiveElement() {
let element = ref.current?.ownerDocument?.activeElement ?? null;
while ( element?.tagName === 'IFRAME' ) {
const inner = ( element as HTMLIFrameElement ).contentDocument
?.activeElement;
if ( ! inner ) {
break;
}
element = inner;
}
// Frame documents are other realms, so no instanceof checks here.
return ( element as HTMLElement | null ) ?? null;
}

// Whether the element sits inside the region, crossing same-origin frame
// boundaries upwards.
function isInsideRegion( region: HTMLElement, element: HTMLElement ) {
let node: Element | null = element;
while ( node ) {
if ( region.contains( node ) ) {
return true;
}
node = node.ownerDocument?.defaultView?.frameElement ?? null;
}
return false;
}

function getWrappingRegion() {
// Based off the current element, use closest to determine the wrapping region since this operates up the DOM. Also, match tabindex to avoid edge cases with regions we do not want.
return (
ref.current?.ownerDocument?.activeElement?.closest< HTMLElement >(
'[role="region"][tabindex="-1"]'
) ?? null
);
}

function focusRegion( offset: number ) {
// Document order puts a region nested in another, like the block
// toolbar floating over the content, right after its container.
const regions = Array.from(
ref.current?.querySelectorAll< HTMLElement >(
'[role="region"][tabindex="-1"]'
Expand All @@ -53,11 +97,7 @@ export function useNavigateRegions( shortcuts: Shortcuts = defaultShortcuts ) {
return;
}
let nextRegion = regions[ 0 ];
// Based off the current element, use closest to determine the wrapping region since this operates up the DOM. Also, match tabindex to avoid edge cases with regions we do not want.
const wrappingRegion =
ref.current?.ownerDocument?.activeElement?.closest< HTMLElement >(
'[role="region"][tabindex="-1"]'
);
const wrappingRegion = getWrappingRegion();
const selectedIndex = wrappingRegion
? regions.indexOf( wrappingRegion )
: -1;
Expand Down Expand Up @@ -91,6 +131,118 @@ export function useNavigateRegions( shortcuts: Shortcuts = defaultShortcuts ) {
ref: useMergeRefs( [ ref, clickRef ] ),
className: isFocusingRegions ? 'is-focusing-regions' : '',
onKeyDown( event: React.KeyboardEvent< HTMLDivElement > ) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will overtake the escape key during IME composition. We have a withIgnoreIMEEvents utility to handle that (see also #82263).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I added it to #82314 instead.

// A prevented key closed a popover, cancelled an operation, or
// was otherwise claimed; navigation only gets it after everything
// else has passed on it.
if ( event.defaultPrevented ) {
return;
}

const activeElement = ref.current?.ownerDocument?.activeElement;
const isOnRegion =
activeElement instanceof HTMLElement &&
activeElement.matches( '[role="region"][tabindex="-1"]' ) &&
ref.current?.contains( activeElement );

if (
event.key === 'Escape' &&
! event.ctrlKey &&
! event.metaKey &&
! event.altKey &&
! isOnRegion
) {
const wrappingRegion = getWrappingRegion();

if ( ! wrappingRegion ) {
return;
}

// Listeners delegated at a document level, among them the
// canvas listener undoing an automatic change, run after this
// handler for the same press. Waiting a microtask lets every
// one of them claim the key first: event dispatch is
// synchronous, so by then the native event carries the final
// word.
const { nativeEvent } = event;
queueMicrotask( () => {
if ( nativeEvent.defaultPrevented ) {
return;
}

// Remember where focus came from, so Enter can go back.
const previous = getDeepActiveElement();
if ( previous ) {
lastFocusPerRegion.current.set(
wrappingRegion,
previous
);
}
wrappingRegion.focus();
setIsFocusingRegions( true );
} );
return;
}

if (
isOnRegion &&
event.key === 'Tab' &&
! event.ctrlKey &&
! event.metaKey &&
! event.altKey
) {
// On a region, the page's focus stops are the regions, so Tab
// moves between them: forward, or backward with Shift.
event.preventDefault();
focusRegion( event.shiftKey ? -1 : 1 );
return;
}

if (
isOnRegion &&
( event.key === 'Enter' || event.key === 'Escape' ) &&
! event.ctrlKey &&
! event.metaKey &&
! event.altKey &&
! event.shiftKey
) {
event.preventDefault();

// Enter, or Escape pressed again, goes back to where focus
// was when Escape stepped out of this region, when that
// place still exists.
const remembered =
lastFocusPerRegion.current.get( activeElement );
if (
remembered?.isConnected &&
isInsideRegion( activeElement, remembered )
) {
remembered.focus();
return;
}

// Otherwise onto the region's first tabbable, descending into
// a same-origin frame.
let target: HTMLElement | undefined = focus.tabbable.find(
activeElement
)[ 0 ] as HTMLElement | undefined;
while ( target?.tagName === 'IFRAME' ) {
const frameDocument = ( target as HTMLIFrameElement )
.contentDocument;
if ( ! frameDocument?.body ) {
break;
}
const inner = focus.tabbable.find(
frameDocument.body
)[ 0 ] as HTMLElement | undefined;
if ( ! inner ) {
break;
}
target = inner;
}
target?.focus();
return;
}

if (
shortcuts.previous.some( ( { modifier, character } ) => {
return isKeyboardEvent[ modifier ]( event, character );
Expand Down
26 changes: 19 additions & 7 deletions test/e2e/specs/editor/various/a11y-region-navigation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ test.describe( 'Region navigation (@firefox, @webkit)', () => {
.poll( () => editor.ownsSelection( dummyParagraph ) )
.toBe( true );

// Navigate to first region and check that we made it. Must navigate forward 4 times as initial focus is placed in post title field.
// Navigate to the top bar region and check that we made it. Focus
// starts in the selected paragraph, so five stops lie ahead: the
// block toolbar, settings, publish, footer, then the top bar.
await page.keyboard.press( 'Control+`' );
await page.keyboard.press( 'Control+`' );
await page.keyboard.press( 'Control+`' );
await page.keyboard.press( 'Control+`' );
Expand All @@ -39,22 +42,31 @@ test.describe( 'Region navigation (@firefox, @webkit)', () => {
);
await expect( editorTopBar ).toBeFocused();

// Navigate to next/second region and check that we made it.
// Navigate to the content region and check that we made it.
await page.keyboard.press( 'Control+`' );
const editorContent = page.locator(
'role=region[name="Editor content"i]'
);
await expect( editorContent ).toBeFocused();

// Navigate to previous/first region and check that we made it.
// Navigate to the next region: the selected block's toolbar floats
// within the content region, so it comes right after it.
await page.keyboard.press( 'Control+`' );
await expect(
page.locator( 'role=region[name="Block toolbar"i]' )
).toBeFocused();

// Navigate two regions back and check that we made it.
// Make sure navigating backwards works also with the tilde character,
// as browsers interpret the combination of the crtl+shift+backtick keys
// and assign it to event.key inconsistently.
// See https://github.com/WordPress/gutenberg/pull/45019
if ( testInfo.project.name === 'chromium' ) {
await page.keyboard.press( 'Control+Shift+`' );
} else {
await page.keyboard.press( 'Control+Shift+~' );
for ( let i = 0; i < 2; i++ ) {
if ( testInfo.project.name === 'chromium' ) {
await page.keyboard.press( 'Control+Shift+`' );
} else {
await page.keyboard.press( 'Control+Shift+~' );
}
}

await expect( editorTopBar ).toBeFocused();
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/specs/editor/various/a11y.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ test.describe( 'a11y (@firefox, @webkit)', () => {

// This test assumes the Editor is not in Fullscreen mode. Check the
// first tabbable element within the 'Editor top bar' region is the
// 'Block Inserter' button.
await pageUtils.pressKeys( 'Tab' );
// 'Block Inserter' button. Enter goes into the focused region.
await pageUtils.pressKeys( 'Enter' );
await expect(
page.locator( 'role=button[name=/Block Inserter/i]' )
).toBeFocused();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,15 @@ test.describe( 'Navigating the block hierarchy', () => {
const slider = page.getByRole( 'slider', { name: 'Columns' } );
// Ensure the block is selected and slider control is visible in the inspector.
await expect( slider ).toBeVisible();
await pageUtils.pressKeys( 'Tab', { times: 5 } );
await pageUtils.pressKeys( 'Enter' );
await pageUtils.pressKeys( 'Tab', { times: 4 } );
await expect( slider ).toBeFocused();
await page.keyboard.press( 'ArrowRight' );

// Navigate to the third column in the columns block via List View.
await pageUtils.pressKeys( 'ctrlShift+`', { times: 2 } );
await pageUtils.pressKeys( 'Tab', { times: 3 } );
await pageUtils.pressKeys( 'Enter' );
await pageUtils.pressKeys( 'Tab', { times: 2 } );
await pageUtils.pressKeys( 'ArrowDown', { times: 4 } );

// Insert text in the last column block.
Expand Down
Loading
Loading