Repository navigation
Boot: Maintain focus within page region when router changes page - #86701
Conversation
| layout | ||
| .querySelector< HTMLElement >( | ||
| `.${ styles.stage } [role="region"]` | ||
| ) | ||
| ?.focus(); |
There was a problem hiding this comment.
There's a bit of an implicit dependency here. While it's conventional to use Page in the route stage, there's nothing to say that it must be. And so this query is largely targeting Page's NavigableRegion. But I think even though it's a loose dependency, (a) it's reasonable to use the first matched region as the semantic landmark to target, and (b) it fails gracefully if it can't be found.
There was a problem hiding this comment.
Wondering if the fallback should be [role="main"] or <main>? 🤔 Might be too magical.
There was a problem hiding this comment.
Wondering if the fallback should be
[role="main"]or<main>? 🤔 Might be too magical.
The short answer is: probably not. The longer answer is a huge can of worms 😅 tl;dr is that Page doesn't render <main>, and sometimes <main> doesn't exist at all. Sometimes wp-admin applies role=main on div#wpbody. But main is also unnamed. There's probably some improvements that ought to be done here, since there's cases where no main exists at all, but the short of it here is that we probably want to keep this as focused on the regions. It's also the case that there are multiple "stages" in a page, each one is a region, and each one can render in a way that causes focus loss.
Was there something in particular you were hoping would be improved with that alternative?
There was a problem hiding this comment.
I guess to the original point, if we can't guarantee Page renders a region, but there's a stronger guarantee of a main, then main could be a next logical fallback. But it seems we can't necessarily guarantee there's a main either.
There was a problem hiding this comment.
Page doesn't render
<main>
Related: I discovered that #77628 mentions this as a proposed improvement to Page:
Correct semantics by default.
<main>landmark [...]
🤖 PR meta 🤖🎉 PropsIf you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
Updated as activity occurs, without notifying anyone named here. Add the 📦 Bundle sizeSize Change: +460 B (+0.01%) Total Size: 8.68 MB 📦 View Changed
⚡ PerformanceShow the resultsClient side metrics exclude the server response time. front-end-block-theme
front-end-classic-theme
media-processing
media-upload
post-editor
site-editor
🏁 Flaky testsSome tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information. should allow user to add and remove multiple local font files in
|
|
These might not be worth adding as test, but I checked the logic works also across these scenarios with the router:
|
|
This works nicely with the Settings Page patterns in #86451, which I've aligned to focus the
|
|
The end-to-end test failures demonstrate a real challenge, which is that this can potentially conflict with other focus management that happens. The test failure is related to some DataViews behavior where clicking a "Cancel" button causes a page navigation, but DataViews itself tries to maintain focus, and only in the same reset-to- |
@simison Maybe we could have at least one test covering the "did not actually redirect so don't do anything with focus" scenario. The
@jameskoster My sense here is that there being a region without a label is a problem irrespective of what we do with focus. So something like
@jameskoster That's a good point 👍 It's a good example of a case where the same effective element still exists on the page, so it should be able to keep focus. This might actually be more a problem that the navigation is being entirely re-rendered, and we could solve this by making sure React diffs in a way that keeps the navigation elements intact. |
Hold navigation until a pending save settles, clear the failed save notice once there's nothing to retry, name each adjacent page's region, drop the disabled Save tooltip, and describe focus restoration as something the example provides until #86701 lands. Co-authored-by: Cursor <cursoragent@cursor.com>
t-hamano
left a comment
There was a problem hiding this comment.
The end-to-end test failures demonstrate a real challenge, which is that this can potentially conflict with other focus management that happens. The test failure is related to some DataViews behavior where clicking a "Cancel" button causes a page navigation, but DataViews itself tries to maintain focus
I think this should be fixed on the DataViews side. DataViews decides whether to move focus by checking whether focus fell to the body, not by whether the Cancel button was clicked. Boot reacts to the same state, so both try to recover focus, and Boot wins. #86932 makes DataViews move focus only in response to the interaction, before Boot checks, so it should fix at least this case.
That said, we can't rule out that consumers inject components with their own focus management. What about an approach where Boot only recovers focus if it is still lost after rendering has settled?
Yeah, thanks for splitting that off. I think it makes sense that DataViews can be more direct about handling its own internal expectations and not try to blanket handle focus loss as it is.
Yeah I think we can do this, and as I recall it was a direction my agent was starting to explore when I last left this. I'll pick it up again and see if I can find a solution here. |
26e7625 to
79dea85
Compare
Following-up on this now that I have a better understanding: First, as mentioned above, this is only tangentially related to the pull request, since the fact that there's no guarantee of a label exists already on I think your general proposal is right that we should try to read (or refer via I explored this with a solution that uses React context to pass a heading ID through from Page to the breadcrumb element, and it seems to work alright (see branch). But then I remembered that the fact that we pass If we did this, we could avoid context altogether and page would have access to the title directly, because it'd be passed as a plain object/array that it could reference, e.g. the name is |
This was quite the deep dive 😅 It's a tricky problem for single-page applications in general, as evidenced by having entire sections devoted to it in HTML specification iterations. I ended up opening #86979 as a separate pull request to explore a solution. I think we could potentially move forward with this one as an improvement over the status quo. Falling back to the region is at least better than losing focus entirely. #86979 is meant to be additive and make the focus restoration even better, but it could be a follow-on. I created it as a stack so we can review each independently and merge them either together or as a standalone improvements. |
This was implemented in 79dea85, and it appears judging by the tests that it's working now. I don't think this needs to be blocked by #86932, and #86932 is still a worthwhile improvement in its own respect. These changes make it so that the fallback is more accommodating to any manual focus management like DataViews is doing today. |
There was a problem hiding this comment.
🟡 Changes recommended
Route focus handling can leave focus on the body after sidebar exit animations or delayed destination mounting because it does not retry when those transitions complete.
2 open issues
What changed in this PR
This PR adds route-change focus recovery to @wordpress/boot, addressing #86700 by moving focus to the destination page region when navigation leaves focus on the document body.
Changes:
- Integrates a shared focus hook into both root layouts.
- Adds browser tests for focus recovery, initial loading, retained links, and page-managed focus.
- Adds test dependencies and documents the fix.
| File | Description |
|---|---|
packages/boot/src/components/root/single-page.tsx |
Enables focus recovery in the single-page layout. |
packages/boot/src/components/root/index.tsx |
Enables focus recovery in the main layout. |
packages/boot/src/components/app/use-route-focus.ts |
Adds route-change detection and region focusing. |
packages/boot/src/components/app/test/navigation-focus.browser.test.tsx |
Tests navigation focus behavior. |
packages/boot/src/components/app/test/fixtures/settings.tsx |
Supplies a destination page fixture. |
packages/boot/src/components/app/test/fixtures/settings-general.tsx |
Supplies navigation links for focus tests. |
packages/boot/src/components/app/test/fixtures/own-focus.tsx |
Supplies a page that manages its own focus. |
packages/boot/package.json |
Declares browser-test dependencies. |
packages/boot/CHANGELOG.md |
Documents the focus-recovery fix. |
package-lock.json |
Records the added test dependencies. |
Review effort: Balanced
| const { activeElement, body } = layout.ownerDocument; | ||
| if ( activeElement && activeElement !== body ) { | ||
| return; |
| layout | ||
| .querySelector< HTMLElement >( | ||
| `.${ styles.stage } [role="region"]` | ||
| ) | ||
| ?.focus(); |
|
Those Copilot review comments are yet-more tricky (and real) scenarios to deal with 😅 Both touching on "delayed" rendering of a page. We could still choose to move forward with this as-is for handling the simple case. One possible option for addressing those together could be using a |
Following-up on this separately in #86982 |
I'm not very experienced with SPA routing, so this may be off the mark, but what about adding a focusable wrapper as a fallback for when the region doesn't exist yet? The router Gatsby uses takes a similar approach, focusing a wrapper like this whenever the URL changes: https://github.com/gatsbyjs/reach-router/blob/bc0302d8304282efc496410931e11ed4ded31c42/src/lib/focus-handler.js#L88-L93 The wrapper itself has no accessible name, but as long as the route defines a That said, this PR is already a big improvement over trunk, so it might be fine to handle this in a follow-up PR 🤔 |
I think we could, and it's kinda the idea we're already trying to do here between this pull request and #86979, which is: Try to maintain focus on the same element between page transitions, and fall back up the chain until we can find something that's maintained between the transitions. I had AI sketch out an illustration to help visualize this chain for myself:
The idea with using The fact that the stage wrapper and page components are at almost the same place in the DOM does make me wonder if it'd be better to shift the Another observation with all this is that there's at least 4 different places that "the page's title" can come from in client-side code: (1) the route Another benefit of this is that we wouldn't need the implicit dependency between With the brain dump out of the way, here's what I'd propose:
¹ A separate point to be made here is that the pages probably shouldn't be asynchronously rendered and that we should optimistically render as much as we can, even if there's still resources that need to be fetched; those can be added to the page after initial rendering, so that we keep the application feeling responsive. ² Not every route is guaranteed to be titled unfortunately, as was the case in the very example that motivated this pull request in the first place. We might want to think about having stronger guarantees or enforcement here, since ideally every route should have a title if it can. #86838 improves this slightly with better documentation at least. |
t-hamano
left a comment
There was a problem hiding this comment.
Thanks for the detailed explanation!
We merge this more or less as-is, as an improvement over the complete focus loss that happens today
Agreed. I think we can merge this as-is, continue the broader discussion in #77628, and handle the animation case in a follow-up.
This happens after boot renders in response to location change, which happens later after router resolved event is fired.
79dea85 to
acd3efd
Compare


What?
Fixes #86700
Updates
@wordpress/bootso that if a router navigation would result in a focus loss, focus is instead moved to the new route's stage container.Why?
So that focus is not lost when navigating between pages.
How?
A hook in the
Rootcomponent observes route changes after initial mount and redirects focus to the layout's region if a route change would result in otherwise resetting to the document's body element.Testing Instructions
Repeat Steps to Reproduce in #86700, observing the expected result.
Use of AI Tools
Researched and implemented in coordination with Claude Code + Opus 5.5.