Skip to content

[popups] Scope queued focus cancellation to its target element - #5293

Open
m2na7 wants to merge 14 commits into
mui:masterfrom
m2na7:fix/enqueue-focus-scoped-cancel
Open

m2na7 wants to merge 14 commits into
mui:masterfrom
m2na7:fix/enqueue-focus-scoped-cancel

Conversation

@m2na7

@m2na7 m2na7 commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #5268

Summary

enqueueFocus keeps a single module-level rAF handle and unconditionally cancels it on entry, so concurrent callers cancel each other's queued focus regardless of target. On keyboard-open of a roving-focus popup, FloatingFocusManager's initial-focus call cancels the option focus queued by useListNavigation — the manager's shouldFocus guard is designed to yield when focus has already moved inside the popup, but the module-level cancel kills the very frame that would move it, so the guard never gets the chance.

Pending frames are now keyed per element (WeakMap<FocusableElement, number>), so a caller only replaces its own target's pending focus. With that in place, the initial-focus guard observes the item focus and yields as designed. When the manager's initial-focus fallback resolves to a different element than the active item (any tabbable rendered before the items), the old code left focus permanently on that element and list navigation dead — the new hook-level test pins that case. useListNavigation retires its own previous queued request before queueing focus for another item, preserving the previous last-wins behavior for consecutive queued requests. A null target is now a no-op instead of cancelling an unrelated caller's pending focus.

The existing TODO in useListNavigation.test.tsx ("the animation frame callback from enqueueFocus sometimes kicking in after the click … causes flakeyness") describes the same mechanism.

Behavior notes

  • Two same-frame enqueues for different elements now both fire in order (last scheduled wins, before paint); previously the earlier one was silently cancelled. Callers whose queued focus can go stale must now guard it with shouldFocus — the modal focus guards in FloatingFocusManager do this, so a guard redirect yields to a newer focus that lands before the frame.
  • Migrating this file to the shared AnimationFrame scheduler was evaluated and deliberately left out: it changes timing under JSDOM's rAF stub and breaks four JSDOM-only FloatingFocusManager tests. [internal] Refactor: remove raw requestAnimationFrame #1901 also left this file's raw rAF in place.

Tests

  • enqueueFocus.test.ts (new): the cancellation semantics unit-tested with faked frames — JSDOM's real cancelAnimationFrame doesn't cancel, so the suite runs on vi.useFakeTimers(). Two cases fail on main (cross-element cancel, null side effect); the rest pin the preserved behavior (same-element replacement, cancel-function guard, sync, shouldFocus), each verified to fail against a mutated implementation.
  • useListNavigation.test.tsx: keyboard-open focuses the active item when the manager's initial focus targets another tabbable (fails on main); consecutive queued requests skip intermediate items.
  • ContextMenuRoot.test.tsx: a queued modal focus-guard redirect doesn't override a newer hover focus on another item (fails without the guard check).
  • Full jsdom suites pass (floating-ui-react, Select, Menu, Combobox — 2,113 tests) and the same suites pass in the Chromium environment, where real rAF cancellation is exercised.

@pkg-pr-new

pkg-pr-new Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

commit: 4a4fcdd

@code-infra-dashboard

code-infra-dashboard Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+290B(+0.06%) 🔺+83B(+0.05%)

Details of bundle changes

Performance

No regressions in 36 benchmarks · ran 3m 53s · details


Check out the code infra dashboard for more information about this PR.

@netlify

netlify Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 4a4fcdd
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6afa4536875c6efec66187dd
😎 Deploy Preview https://deploy-preview-5293--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@zannager zannager added the scope: all components Widespread work has an impact on almost all components. label Jul 24, 2026
@jjenzz jjenzz assigned jjenzz and michaldudak and unassigned jjenzz Aug 20, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 23, 2026
Signed-off-by: Jenna Smith <175330+jjenzz@users.noreply.github.com>
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 25, 2026
@jjenzz

jjenzz commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Thanks for this! The triggerless menu test added in #5645 has been intermittently failing the React 18 browser CI on my PR #5793, and Codex traced it to one queued focus request canceling another. I tried this fix against the failing test and it passed consistently, so it looks like this PR fixes that failure too.

@michaldudak Regardless of the flaky tests, this feels like the more correct behaviour for a shared utility. We can't really know how consumers might sequence focus programmatically, but it does increase the bundle size, so I'm not sure how to weigh it up. Wdyt?

@michaldudak

Copy link
Copy Markdown
Member

Yeah, this looks like a good solution. The bundle size increase isn't that big, so I'm fine with it.
Claude found an issue, though:

🔴 Modal focus-guard redirect overrides a newer hover focus in ContextMenu

Location: packages/react/src/floating-ui-react/components/FloatingFocusManager.tsx:970 and :991 (unchanged lines, broken by enqueueFocus.ts:24-28)

if (modal) {
  // enqueueFocus returns a rAF-cancel function we don't need here.
  void enqueueFocus(getTabbableContent()[0]);

Both modal guards queue a redirect with no shouldFocus check. Before this PR, any later enqueueFocus call cancelled that frame through the module-level rafId. That included the synchronous item focus useListNavigation makes on hover. Now cancellation only applies when both calls target the same element, so a stale redirect to item A survives a newer focus on item B. MenuPopup passes modal={isContextMenu}, so ContextMenu reaches this path.

This also contradicts the PR description's claim that "final focus is unchanged in every reachable call-site ordering".

Failure scenario: I checked this with a throwaway jsdom test using the real ContextMenu and faked frames:

Item A is focused and highlighted.
Tab moves focus onto the after-content guard, which queues a redirect to A.
Before the next frame, a mousemove over B focuses and highlights B synchronously.
The frame runs and focus jumps back to A. A becomes highlighted again while the pointer is over B.

The test fails on the PR head (final focus A) and passes with the base enqueueFocus/useListNavigation (final focus B). The window is one frame, and the next mousemove corrects it, but it is a regression in focus management.

Fix: Only redirect while focus is still on the guard. Use the same shape for the before guard, targeting els[els.length - 1]:

if (modal) {
  const guard = event.currentTarget;
  void enqueueFocus(getTabbableContent()[0], {
    shouldFocus: () => activeElement(ownerDocument(guard)) === guard,
  });

Other notes:

This PR fixes the cross-cancellation, but opening focus still lands on the next frame. Tests that press the next key on the focused element should keep waiting for real DOM focus, not just data-highlighted.

Focus guard redirects are queued for the next frame. Now that queued focus is
only cancelled per element, a newer focus on another element (e.g. a hover
highlight in ContextMenu) no longer cancels the redirect, so it could pull
focus back. Only redirect while focus is still on the guard.
@m2na7

m2na7 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for catching this, @michaldudak — and for the clear repro.

You're right: the modal focus guards queued their redirect unconditionally and relied on the old module-level cancel to get dropped when something else took focus. With per-element cancellation that no longer happened, so a stale redirect could pull focus back from a newer hover focus.

Fixed in 4a070a3: both guards now only redirect if focus is still on the guard when the frame runs (activeElement(ownerDocument(guard)) === guard), as you suggested. Added a ContextMenu regression test for exactly that sequence (focus the after-guard → mousemove onto another item before the next frame → frame runs → focus and highlight stay on the hovered item). It fails without the guard check and passes with it.

I've also corrected the "final focus is unchanged in every reachable call-site ordering" line in the description — that claim was wrong.

Re: opening focus still landing on the next frame — agreed, the new tests wait for real DOM focus rather than just data-highlighted.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Oct 1, 2026
return button;
}

it('focuses the element on the next frame', () => {

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.

Would be nice to wrap all of that inside a describe('enqueueFocus() {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 405e9fa, thanks!

@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Oct 5, 2026
@jjenzz

jjenzz commented Oct 6, 2026

Copy link
Copy Markdown
Member

@michaldudak how relevant are these?

PR review

Nothing here blocks merge. I traced every caller of enqueueFocus (the focus manager's initial focus, its two modal focus guards, and list navigation) through Menu, Menubar, ContextMenu, Select and Combobox. In every case where two different elements are queued for the same frame, focus ends up on the right element. One focus path loses a cancellation it used to get for free; I list it below as a note. I read the code but didn't run the tests.

Tests (1)

1. 🟡 Only the after-guard redirect is covered

Location: packages/react/src/context-menu/root/ContextMenuRoot.test.tsx:342

const afterGuard = menu.nextElementSibling as HTMLElement;

The PR adds shouldFocus: isFocusStillOn(...) to both modal guards in FloatingFocusManager.tsx (around lines 1022 and 1045). The new test only covers the after-guard, which handles Tab off the last item. The before-guard, which handles Shift+Tab off the first item and redirects to the last tabbable, has no test. Removing its shouldFocus would go unnoticed.

The test also locates the guard with nextElementSibling, so it depends on how the popup's DOM is laid out. The data-type="inside" assertion catches a layout change, which helps.

Failure scenario: The before-guard's shouldFocus gets dropped in a later refactor. Shift+Tab onto the guard, then hovering the first item within the same frame, sends focus back to the last item. No test fails.

Fix: Add the mirror case. Focus last, focus menu.previousElementSibling (the before-guard), mouse-move onto first, advance one frame, then assert that first has focus and is highlighted.

Simplifications (1)

1. ℹ️ The target alias is only there to keep TypeScript's null check

Location: packages/react/src/floating-ui-react/utils/enqueueFocus.ts:23

// `exec` is a hoisted function declaration, so the null-guard narrowing
// of `el` is not preserved inside it.
const target = el;

The repo is on TS 6, which keeps a parameter's null-check narrowing inside closures created after its last assignment. It doesn't do this for hoisted function declarations. Writing const exec = () => { ... } would let el be used directly, which removes the alias and its two-line comment.

Failure scenario: None at runtime. It's an extra variable plus a comment explaining a workaround that an arrow function avoids.

Fix: Turn exec into a const arrow function and use el throughout.

Bugs (1)

1. ℹ️ The initial focus can no longer be cancelled by a later focus on a different element when hadFocusInside is true

Location: packages/react/src/floating-ui-react/components/FloatingFocusManager.tsx:753

if (hadFocusInside) {
  return true;
}

Before this PR, any later enqueueFocus call, including a sync one from a hover or arrow key, cancelled the focus manager's queued initial focus. Now only a call for the same element cancels it. When focus was already inside the popup by the time the manager's microtask runs, shouldFocus approves unconditionally, so the queued initial focus fires anyway.

I couldn't find a built-in path that triggers this. On open, list navigation always queues its focus with requestAnimationFrame rather than focusing synchronously, so hadFocusInside stays false in stock components. Reaching it takes consumer code plus input that arrives within one frame.

Failure scenario: A consumer's Popover or Dialog contains a list and focuses an element inside it from a useEffect on open. The manager's initial focus resolves to a different element. If the user hovers or arrows to another item within that frame, focus jumps back to the manager's target. It's more likely when the main thread is busy.

Fix: Optional. Have the initial focus's shouldFocus also yield when the active element has changed since hadFocusInside was recorded, the same idea as isFocusStillOn.

Verdict

Approve after nits - the per-element cancellation is correct for every built-in caller; the only gap is test coverage for the Shift+Tab guard.


🤖 Review generated with Claude Code

@m2na7

m2na7 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks! Addressed the nits:

  • Added the mirror before-guard test (Shift+Tab → hover first item within the frame) in 2b7aed7. Confirmed it fails without the before-guard's shouldFocus.
  • Turned exec into an arrow function and dropped the target alias in be4b1c8.

I left the hadFocusInside note out of scope since it isn't reachable with built-in components. Happy to follow up in a separate PR if you think it's worth it.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Oct 7, 2026
@github-actions github-actions Bot added PR: out-of-date The pull request has merge conflicts and can't be merged. and removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Oct 15, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been inactive for 30 days. Please remove the stale label or leave a comment to keep it open. Otherwise, it will be closed in 15 days.

@github-actions github-actions Bot added the stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update. label Nov 15, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Nov 15, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: all components Widespread work has an impact on almost all components. stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update.

Projects

None yet

5 participants