Skip to content
Open
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
4 changes: 4 additions & 0 deletions packages/admin-ui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Enhancements

- `Page`: Give each link in the section navigation a `data-focus-key` attribute, so that `@wordpress/boot` keeps focus on the same link when the section changes.

## 3.2.0 (2026-11-18)

### Internal
Expand Down
3 changes: 3 additions & 0 deletions packages/admin-ui/src/navigation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export const Navigation = ( {
render={
<Link
variant="unstyled"
// Lets an app that replaces the page on navigation, such as
// `@wordpress/boot`, keep focus on the same link.
data-focus-key={ `navigation:${ item.href }` }
aria-current={
item.href === currentHref
? 'page'
Expand Down
12 changes: 12 additions & 0 deletions packages/admin-ui/src/navigation/test/index.jsdom.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ describe( 'Navigation', () => {
expect( overviewLink ).toHaveAttribute( 'href', '' );
expect( overviewLink ).toHaveAttribute( 'aria-current', 'page' );
} );

it( 'should give each link a focus key from its `href`', () => {
render(
<Navigation
items={ [ { label: 'Overview', href: '/overview' } ] }
/>
);

expect(
screen.getByRole( 'link', { name: 'Overview' } )
).toHaveAttribute( 'data-focus-key', 'navigation:/overview' );
} );
} );

describe( 'linkComponent', () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/boot/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Enhancements

- When a navigation removes the focused element, move focus to the element on the new page that has the same `data-focus-key` attribute, such as the same link in a section navigation.

### Bug Fixes

- Move focus to the new page when an in-app navigation removes the focused element, such as a breadcrumb link. Before, focus moved to the document body ([#86701](https://github.com/WordPress/gutenberg/pull/86701)).
Expand Down
10 changes: 10 additions & 0 deletions packages/boot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ Boot's internal shell is private. Consumers can style the mount element and
their own route content. Boot does not provide stable styling hooks or
replacement hooks for its internal layout, navigation, and surface elements.

## Focus after navigation

When a navigation within the application removes the element that has focus, boot moves focus, so that keyboard and screen reader users do not lose their place:

1. If the new page moves focus itself, for example in an effect, boot does nothing.
2. Otherwise, if the element that had focus when the navigation started, or one of its ancestors, has a `data-focus-key` attribute, boot focuses the element on the new page that has the same `data-focus-key`. Use it for a control that each page renders again, such as a link in a section navigation. Each value must be unique on a page.
3. Otherwise, boot focuses the region of the new page that the `Page` component from `@wordpress/admin-ui` renders.

Boot does not move focus on the initial page load.

## Init modules

Init modules are script modules that run a one-time setup step at page startup, after menu items and routes are registered and before the app renders. They are useful for tasks that cannot be expressed in the page's static PHP configuration, such as assigning menu-item icons or registering core-data entities.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { AnchorHTMLAttributes } from 'react';
import { Link } from '@wordpress/route';

export const SECTIONS = [
{ label: 'Main section', href: '/settings' },
{ label: 'General section', href: '/settings/general' },
];

export function SectionLink( {
href,
...props
}: AnchorHTMLAttributes< HTMLAnchorElement > & { href: string } ) {
return <Link to={ href } { ...props } />;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Breadcrumbs, Page } from '@wordpress/admin-ui';
import { Link } from '@wordpress/route';
import { SECTIONS, SectionLink } from './section-navigation';

export const stage = () => (
<Page
ariaLabel="General"
navigation={ { items: SECTIONS, currentHref: '/settings/general' } }
components={ { link: SectionLink } }
breadcrumbs={
<Breadcrumbs
items={ [
Expand Down
3 changes: 3 additions & 0 deletions packages/boot/src/components/app/test/fixtures/settings.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Breadcrumbs, Page } from '@wordpress/admin-ui';
import { SECTIONS, SectionLink } from './section-navigation';

export const stage = () => (
<Page
ariaLabel="Settings"
breadcrumbs={ <Breadcrumbs items={ [ { label: 'Settings' } ] } /> }
navigation={ { items: SECTIONS, currentHref: '/settings' } }
components={ { link: SectionLink } }
>
Settings content
</Page>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,40 @@ describe( 'navigation focus', () => {
);
} );

it( 'moves focus to the same control on the new page', async () => {
await renderAt( '/settings/general' );

const link = await screen.findByRole( 'link', {
name: 'Main section',
} );
link.focus();
await userEvent.keyboard( '{Enter}' );

await waitFor( () => expect( link ).not.toBeInTheDocument() );
await waitFor( () =>
expect(
screen.getByRole( 'link', { name: 'Main section' } )
).toHaveFocus()
);
} );

it( 'ignores a control that lost focus before the navigation', async () => {
await renderAt( '/settings/general' );

const section = await screen.findByRole( 'link', {
name: 'Main section',
} );
section.focus();
section.blur();
// A click that does not move focus, such as a mouse click on a link in
// Safari.
// eslint-disable-next-line testing-library/no-node-access
screen.getByRole( 'link', { name: 'Settings' } ).click();

const page = await screen.findByRole( 'region', { name: 'Settings' } );
await waitFor( () => expect( page ).toHaveFocus() );
} );

it( 'keeps focus on a link that the navigation does not remove', async () => {
await renderAt( '/settings/general' );

Expand Down
44 changes: 37 additions & 7 deletions packages/boot/src/components/app/use-route-focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@ import { privateApis as routePrivateApis } from '@wordpress/route';
import { unlock } from '../../lock-unlock';
import styles from '../root/style.module.scss';

const { useRouterState } = unlock( routePrivateApis );
const { useRouter, useRouterState } = unlock( routePrivateApis );

/**
* Hook that moves focus to the new page when a navigation removes the focused
* element, such as a breadcrumb link that becomes the new page's heading.
* Elements with the same value of this attribute on two pages are the same
* control, such as a section navigation link that each section page renders.
*/
const FOCUS_KEY_ATTRIBUTE = 'data-focus-key';

/**
* Hook that moves focus when a navigation removes the focused element.
* Otherwise focus falls back to the document body, and keyboard and screen
* reader users lose their place.
*
* Focus moves to the element on the new page with the same focus key as the
* removed element, or else to the new page's region, such as when a breadcrumb
* link becomes the new page's heading.
*
* It runs in an effect after the route resolves. Effects of the page content
* run before it, so the page can move focus itself first.
*
Expand All @@ -19,11 +28,26 @@ const { useRouterState } = unlock( routePrivateApis );
export default function useRouteFocus(
layoutRef: RefObject< HTMLElement | null >
) {
const router = useRouter();
const href: string | undefined = useRouterState( {
select: ( state: { resolvedLocation?: { href: string } } ) =>
state.resolvedLocation?.href,
} );
const previousHrefRef = useRef( href );
const focusKeyRef = useRef< string | null >( null );

useEffect(
() =>
// Read the key when the navigation starts, while the focused element
// is still in the document.
router.subscribe( 'onBeforeNavigate', () => {
focusKeyRef.current =
layoutRef.current?.ownerDocument.activeElement
?.closest( `[${ FOCUS_KEY_ATTRIBUTE }]` )
?.getAttribute( FOCUS_KEY_ATTRIBUTE ) ?? null;
} ),
[ router, layoutRef ]
);

useEffect( () => {
const previousHref = previousHrefRef.current;
Expand All @@ -44,10 +68,16 @@ export default function useRouteFocus(
return;
}

layout
.querySelector< HTMLElement >(
const focusKey = focusKeyRef.current;
const target =
( focusKey &&
layout.querySelector< HTMLElement >(
`[${ FOCUS_KEY_ATTRIBUTE }="${ CSS.escape( focusKey ) }"]`
) ) ||
layout.querySelector< HTMLElement >(
`.${ styles.stage } [role="region"]`
)
?.focus();
);

target?.focus();
}, [ href, layoutRef ] );
}
Loading