Repository navigation
[popups] Keep closing popups out of the a11y tree and focus order - #5537
Draft
michaldudak wants to merge 22 commits into
Draft
michaldudak wants to merge 22 commits into
michaldudak wants to merge 22 commits into
Conversation
commit: |
Bundle size
PerformanceTotal duration: 467.24 ms +50.11 ms(+12.0%) | Renders: 76 (+0) | Paint: 845.84 ms +79.19 ms(+10.3%)
11 tests within noise — details Metric alarms
Check out the code infra dashboard for more information about this PR. |
✅ Deploy Preview for base-ui ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify project configuration. |
michaldudak
force-pushed
the
claude/issue-5519-triage-ce7c69
branch
2 times, most recently
from
August 19, 2026 10:35
925fcc4 to
47f9735
Compare
michaldudak
added a commit
to michaldudak/base-ui
that referenced
this pull request
Aug 19, 2026
`shouldRenderGuards` only checked `disabled` (`!mounted`), so the two focus
guards stayed rendered for the whole exit animation. Each guard hardcodes
`tabIndex={0}` and `aria-hidden="true"`, and axe's `aria-hidden-focus` applies to
`aria-hidden` elements that are themselves focusable, not just ones containing
focusable descendants.
For Positioner-based popups the guards sit inside the subtree that now carries
`inert`, so they were already neutralized. Dialog and Drawer have no Positioner
and apply `inert` to the popup element itself, leaving their guards as siblings
outside it and still focusable while the popup animated out.
Reported by an external reviewer on mui#5537.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
michaldudak
force-pushed
the
claude/issue-5519-triage-ce7c69
branch
9 times, most recently
from
August 19, 2026 14:04
048ffe4 to
c3a62a6
Compare
Tests of a popup between its close and its unmount had to run in Chromium only, with a 10 s keyframe animation, a class on every popup and a `getAnimations().forEach((a) => a.finish())` cleanup copied into each suite. jsdom had no way to keep a popup in its exit at all, so every test of React ordering during the exit (a reopen, a `flushSync` close, nested popups) was browser-only. `holdExit()` holds every exit until the test calls `release()`. It needs no production code: exits already wait on `getAnimations()` in `useAnimationsFinished`, so both adapters work at that existing seam: - `'animation'` (the default in browsers) puts a real CSS animation on every `[data-ending-style]` element. The browser cancels it on a reopen, like any exit animation. - `'manual'` (the default in jsdom, and usable in browsers) makes `getAnimations()` report a pending animation for elements in their ending state. `release()` finishes the exits in progress, including ones that haven't checked their animations yet, and waits for React to commit the unmount inside `act()`. Exits that start afterwards are held again. Everything is undone when the test finishes.
The rules for a popup that is animating out are the same for every popup, but each suite restated them in its own Chromium-only "while closing" block. `closingPopupConformanceTests` now asserts them once, through public behavior only (DOM attributes, the focused element, tabbability and `onOpenChange`), so it keeps guarding refactors of the focus manager and the close bookkeeping: - the popup stays mounted until its exit finishes (replaces the skipped animation case in `popupConformanceTests`); - the positioner, or the popup for Dialog and Drawer, is `inert` while closing and stops being inert when the popup reopens, by prop or by the trigger; - no focus guard stays tabbable; - focus returns to the trigger, with a focus ring after Escape, when the popup closes rather than when it unmounts, and not again at unmount; - in browsers, Tab and Shift+Tab from the trigger skip the closing popup and don't request another close. `popupConformanceTests` runs it for every root that passes a `closing` config (Popover, Menu, Select, Combobox, Dialog, AlertDialog, PreviewCard, Tooltip). It also runs on its own for non-modal Dialog, Drawer and a Combobox with its input inside the popup. Everything except Tab runs in jsdom too, through `holdExit()`. The per-suite tests these cover are removed. Component-specific cases stay. Those that only needed a held exit now run in jsdom as well: the Menu-to-Dialog handoff, Select and Combobox item selection, the Combobox input outside the popup, Dialog's Close button, the submenu filter during its exit, and the focus manager's close-commit reopen, nested Dialog and hover cases. The tests that need real browser behavior stay Chromium-only: native Tab and pointer input, outside-press settlement and the `inert` focus fixup. They use `holdExit()` instead of their own keyframes and cleanup.
The whole return policy lived in a closure inside FloatingFocusManager's return-focus layout effect, so each of its rules (the mui#5733 guard handoff, the mui#2607 "focus moved elsewhere" rule, explicit return focus, the aria-hidden skip, the passive session, the inert-aware target chain) could only be tested by rendering a real popup in Chromium and waiting. `floating-ui-react/utils/returnFocus.ts` now holds that policy as plain functions over sampled facts: - `getCloseIntent(request, interactionType, pressed, preventScroll)`: what the close meant, including how an outside press settles; - `getDefaultReturnTarget(session)` / `getReturnTarget(...)`: the usable target chain, the parent link and the focused-before history; - `getReturnFocusAction(session, intent, ...facts)`: focus with options, blur, or nothing. The focus manager keeps the scheduling and the side effects: the cleanup snapshot, the microtask, the release wait and settle timer, focus()/blur(), and the closed-return-target context. The module header records the React orderings the facts depend on. Platform facts are inputs; the preventScroll probe stays uncached and lazy because tests stub `focus`. A jsdom table test covers plan-c's per-close-path rows, including the negatives that the Chromium suite could only check with `wait(50)`. The Chromium tests stay as integration tests of the timing the table can't see. No behaviour change.
The close request had one writer, `dispatchOpenChange`, but four clearers and four readers spread over three focus manager effects, and its lifetime was an ordering contract between them. A new focus session cleared it, so a reopen whose session started before the close's return job ran (the root store's `open` lags the popup store by a commit) erased it, and the job needed a cleanup snapshot plus a fallback to get it back. The request now lives on `FloatingRootStore`, read and written only through a few functions next to it: - `recordCloseRequest`: the single writer, called by `dispatchOpenChange` for every open change; - `invalidateCloseRequest`, `noteFocusMove`: the input and focus facts the focus manager reports while open; - `markCloseRequest`, `hasCloseRequestSince`: initial focus yields to a newer close; - `takeCloseRequest`: the return job takes it once. A focus session marks the pending request when it starts and takes only a newer one. No session boundary clears the request: one made before a session can't leak into it, and a reopen's session can't erase the request its predecessor's job is about to take. The cleanup snapshot, its fallback, the session-start clear, `focusMovedAfterRequestRef` and `ContextData.closeRequest` are gone. They are functions rather than methods so roots without a focus manager only carry the writer. `FloatingRootStore.test.ts` pins the lifetime as event sequences, including a reopen before the close's job runs and a consumer `flushSync`. No behaviour change, except when a popup closes, reopens and closes again within one synchronous flush: the first close's job takes the latest request once, so the second job falls back to the defaults instead of reusing it.
Where Tab goes around a non-modal popup was decided by six focus guards with
three owners (the trigger, FloatingPortal and FloatingFocusManager), each
hard-coding its neighbour through refs threaded across the popup store
contexts, four FloatingFocusManager props and PortalContext. The outcome fell
out of which guards happened to be mounted.
`floating-ui-react/utils/focusRoute.ts` now owns the route:
- A registry of the six guard slots per popup, keyed by its FloatingRootStore,
which the trigger and the focus manager share. The focus manager hands the
portal its slots and handler, so FloatingPortal no longer imports any routing.
- `getFocusRouteDecision`, a pure table: slot x where focus came from
(content, trigger, outside) x {open, modal, content guards, trigger guards,
follows trigger, closeOnFocusOut} -> where focus goes and whether to close.
- `focusRoute`, which gathers those facts, closes (before moving focus for a
trigger guard, after for a portal guard, as before) and moves focus.
The guards render exactly where they did; their handlers ask the route. The
route's guards count as part of the popup for the focus manager's focus-out,
pointer-inside and aria-hidden checks, which replaces `isRelatedFocusGuard`
and the leading trigger guard in `getInsideElements`.
Removed: `nextFocusableElement`, `previousFocusableElement` and
`beforeContentFocusGuardRef` on FloatingFocusManager (replaced by the boolean
`followsTrigger`), the three guard refs on the Popover and Menu store
contexts, the four guard refs on PortalContext, and `useTriggerFocusGuards`.
`getTabbableNearElement` takes a list of subtrees to skip.
Fixes in the table:
- A forward Tab from before the trigger, while the popup is open and focus is
outside it, focused the trigger's leading guard, which closed the popup and
sent focus back. It now continues to the trigger.
- Tab from the trigger of a hover-opened Popover stranded focus on the
trailing guard, because the content guard it forwarded to wasn't rendered.
It now leaves past the popup and closes it, and Shift+Tab from after the
popup reaches the trigger.
- When the consumer refused the focus-out close, tabbing out through the
trailing trigger guard picked the portal's guard next and looped back into
the content. Leaving now skips the route's own guards.
- A Popover or Menu opened without a trigger stranded Tab on the content's
trailing guard: it targeted a trigger guard that wasn't rendered. It now
leaves through the portal's guard.
Shift+Tab into a portaled popup from the element after it, which lands on the
last tabbable element inside, is now covered by a test.
Popover, Dialog, Menu, Tooltip and PreviewCard each re-implemented the same sequence (accept, record, emit, commit), and the copies had drifted: Popover had no guard against a redundant close, Dialog wrote `preventUnmountingOnClose` before the consumer could cancel, Menu emitted a close it then refused, and Tooltip/PreviewCard used a fourth variant. `runOpenChange` (utils/popups/openChangeTransaction.ts) now owns the order: skip a close of a closed popup, attach `preventUnmountOnClose()`, report the root's trigger on a close that names none, ask the consumer, stop on cancel or on a root refusal, record and emit through `dispatchOpenChange`, then commit through the root's adapter (synchronously for hover where the store did that before). Each root supplies only its committed state, its trigger policy, any refusal and a commit with its reason-specific extras. `applyPopupOpenChange` stays as the shared Tooltip/PreviewCard adapter. Each root keeps its trigger policy and `instantType` mapping. Popover reports the trigger only for a close button, Dialog and Menu for every close, Tooltip and PreviewCard never: unifying them would change `eventDetails.trigger` in `onOpenChange`. Tooltip and PreviewCard treat a trigger press or Escape close as `dismiss`; Popover and Menu only Escape, since a trigger press toggles them closed with their exit transition. `dispatchOpenChange` takes a `record` flag, so Tooltip's `cancelPendingOpen` emits without recording a close request: it clears a pending hover open and closes nothing. Behaviour changes: - Popover, Dialog, Tooltip and PreviewCard ignore a close request while closed or closing, as Menu already did. `onOpenChange(false)` is no longer called again during an exit, or when the pointer leaves a hover trigger before a delayed open, and nothing is emitted or recorded. - Dialog: `preventUnmountOnClose()` from a canceled close no longer stays set, so the next close unmounts the popup again. - Menu: the delayed touch click it ignores after a focus open is no longer emitted or recorded as a close request. The consumer still sees it, as before. - Menu reads its active trigger and the same-trigger reopen guard from the store rather than from the last render. - Tooltip: when another tooltip opens during this one's exit, the exit still ends at once, but `onOpenChange(false)` isn't called a second time. - Tooltip's `cancelPendingOpen` no longer records a close request. - Popover writes `instantType` in the same store update as the open state, so a hover change flushes it synchronously too. - PreviewCard captures the hovered inline rect after the dispatch rather than before it. Nothing that runs on dispatch reads it.
Select and Combobox closed through `FloatingRootStore.setOpen`, which emitted `openchange` and recorded a close request before their consumer could cancel it. Their own closes (an item press, `actionsRef.close()`, the window resize, the trigger's cancel-open) called the root setter directly, so they emitted and recorded nothing, which is why the focus manager's close intent needed a carve-out for them. Both roots now run every request through `runOpenChange`, like the popup stores. That leaves no root for which the floating root store has to emit, so its `syncOnly` mode goes: `setOpen` only forwards a request to the owner of the open state, and the owner emits what it accepts. Navigation menu items have no transaction, so an item dispatches each request itself before filtering it, in the same order as before. The Floating UI test harness emits before calling the test's `onOpenChange`, as Floating UI does. Toast never receives requests. Behaviour changes: - Select and Combobox: a canceled open or close (Escape, outside press, focus out, trigger press) is no longer emitted to the floating interactions or recorded as a close request. An accepted one is emitted after the consumer accepts it rather than before. - Select and Combobox: their own open changes are now emitted, and their own closes recorded: item presses, `actionsRef.close()`, the window resize, cancel-open, the dismiss button, Enter without a highlight, input-change and arrow-key opens. The focus manager now sees why they closed, so a keyboard item selection returns focus with `focusVisible`. - Select: closing a closed Select no longer calls `onOpenChange(false)`. - Combobox: a redundant open that a floating interaction requests is no longer emitted. Combobox already skipped it otherwise.
The focus route, focus return and close request extractions grew every entry that renders a focus manager without a trigger guard, Dialog by about 500 B gzip. Most of it was interface overhead: property names repeated at each construction and read, string unions, an options object, and a WeakMap registry. Make the interfaces cheaper without changing what they decide: - `getFocusRouteDecision` takes its facts positionally, like `getReturnFocusAction`, and where focus came from is a `FROM_*` number instead of a string. - `focusRoute` takes the focus manager's facts positionally instead of an options object. - `focusRoute` dispatches on target ranges. The target constants document the order it relies on. - The route lives in a `FloatingRootStore` field instead of a module `WeakMap`. - `CloseIntent.settle` is `SETTLE_TASK` or `SETTLE_RELEASE` instead of a string. - `getReturnTarget` resolves the explicit target first and falls back once. The result is the same. - `getTabbableNearElement` drops a null check that the anchor lookup already covers. Against the previous commit: -453 B parsed on every focus manager entry; gzip -131 B (Dialog), -113 B (Select, Alert Dialog), -129 B (Combobox), -118 B (Autocomplete), -105 B (Drawer, Popover), -101 B (Context Menu), -125 B (Menu), -105 B (whole package).
…ocument The focus route read the trigger from the floating root's reference, which keeps a trigger that was removed from the page. A popup reopened through the `open` prop after its trigger unmounted sent Shift+Tab from its first item to the detached trigger, leaving focus on a guard instead of the element before the portal. A trigger guard also kept the trigger it read before its `flushSync` close: when the consumer replaced the trigger's element during that close, Tab out of the popup landed on the body. Only a trigger in the document counts now, and a trigger guard whose trigger left the document during the close reads it again.
…nother Tabbing out of a Popover or Menu whose trigger was the last tabbable element of an outer Popover sent focus backwards, onto the inner trigger, instead of past the outer popover. Closing the inner popup unmounts its trigger guard before focus reaches the outer popover's content guard, so that guard's focus event had no `relatedTarget`. The outer route read it as focus arriving from outside and sent it back into the content. Master behaves the same way. While the route calls `focus()`, it now records the element it moves focus on from. A guard reached without a `relatedTarget` uses that element, so the outer route sees focus leaving its content and continues past its trigger.
The experiment was a free-form repro page for three nested popups. It now holds 25 scenarios across Popover, Menu, Select, Combobox, Dialog, NavigationMenu and Menubar, alone and nested. They cover tabbing into, out of and back into popups, hover opens, refused closes, popups without a trigger and custom portal containers. Each scenario lists its steps and where focus should be after each one. The page checks every step as it is performed: which element has focus and which popups are open. It then marks the scenario passed, failed or interrupted, and keeps a trail of every focus move, focus guards included. Steps and results are also exposed in data attributes, so a browser automation can drive the same scenarios. The nested scenarios replace the old "render inside before/after buttons" switch: each nested popup now has a variant where it is the only content of the outer popover.
Ports the step-by-step scenarios from the popup-tabbing experiment into a Chromium test. Each of the 25 scenarios covers Popover, Menu, Select, Combobox, Dialog, NavigationMenu or Menubar, alone or nested. It presses real keys (or clicks and hovers) and checks after every step which element has focus and which popups are open.
The scripted popup-tabbing experiment is replaced by the scenario test. The popup-focus-return playground gains the cases it lacked, for free-form testing: - a keepMounted Popover; - a Popover portaled before its trigger; - a Popover without a trigger; - nested popups, including a Menu as the only content of a Popover; - a non-modal Dialog that stays open; - a NavigationMenu.
An audit of the tests this PR adds found some that verify the same thing
as another test and some that can't fail meaningfully.
- Duplicates removed:
- Chromium guard-route tests that repeat a focus scenario step.
- Scenarios already covered on master: plain Popover, modal Popover,
Menu, Dialog and NavigationMenu Tab order.
- A store-level flushSync "test" whose body only records and takes a
request.
- Return-decision rows that take the same branch as another row.
- Per-store and per-component tests restating the transaction or the
closing conformance suite.
- Vacuous tests removed:
- The backward Tab conformance test, which passes even if the guard
bounces focus back.
- A holdExit test that never reaches the state it is named after.
- Made able to fail:
- "leaves no focus guard tabbable" only runs for popups that have
guards; the Combobox input-inside config now declares its guards.
- The "stays mounted" conformance check waits long enough for an
unheld exit to unmount.
- The keep-mounted transaction test catches a flag leaking into the
next close.
- Canceled-close emission tests assert that the close was requested.
`runOpenChange` returned early on a close of a closed popup, so it no longer emitted `openchange`. The hover interaction clears its delayed open from that event, so `actionsRef.close()` or `handle.close()` during a hover delay stopped canceling it: Popover, Tooltip and PreviewCard opened after the delay anyway, which they didn't before the transaction. A close of a closed popup now still emits `openchange` through `dispatchOpenChange(false, details, false)`. The consumer still isn't asked and no close request is recorded. Menu, which skipped such a close before the transaction too, now also cancels a pending hover open.
An outside press that closes a popup returns focus only after the press has landed, and an explicit `finalFocus` wins over where the press put focus. When the press opened another popup, for example a Dialog behind a button elsewhere on the page, that popup took focus first. The closed popup's `finalFocus` then pulled focus out of it. A Select or Menu that opens on mousedown, or a Combobox or NavigationMenu whose trigger keeps focus, lost focus before its own initial focus landed and closed again. The close intent now keeps the element the outside press landed on. Once the press has settled, the return is skipped, even for an explicit `finalFocus`, when the control the press activated reports itself expanded, or when focus is in an open popup the press didn't land in. The return still runs when focus is in this popup or on the body, and after a press inside a popup that was already open, on an input, or on blank space.
A guard-triggered close can remove both the guard and its trigger, so the focus route can ask for the element next to an anchor that is gone. `getTabbableNearElement` now returns `null` right away instead of collecting every candidate in the document first.
…popup `openReason` survives a close so the exit still reads why the popup opened, and only the unmount cleared it. When a controlled root reopened the popup through the `open` prop before it unmounted (during the exit animation, or after `preventUnmountOnClose()`), the new cycle inherited the previous reason. A Popover that was hover-opened, closed and then reopened this way kept its focus manager disabled, and a modal Popover or Menu skipped its internal backdrop and scroll lock. When a close that follows a close request commits, the reason is now marked stale. The next open request replaces it. If the `open` prop reopens the popup without one, the selector reports no reason from the first open render and the Root clears the stored one. An open request accepted while a controlled close is still pending keeps its reason for the next cycle, and a close request that a controlled root ignores leaves the popup open with its reason, as before. A close made through the `open` prop alone still keeps the reason, as on master.
michaldudak
force-pushed
the
claude/issue-5519-triage-ce7c69
branch
from
October 12, 2026 18:45
133f935 to
e6b4d32
Compare
1 task done
This was referenced Oct 18, 2026
1 task done
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5519.
Note
This PR was rewritten from scratch. The earlier implementation kept surfacing new defects in review, so it has been replaced by a new design; nothing from it carries over. The old branch history is gone, and the commits are now structured as described below.
The problem
A popup that is still mounted for its exit animation is already closed, yet it stayed in the accessibility tree and in the Tab order until it unmounted. During the exit the trigger reports
aria-expanded="false", while the closing popup stays exposed: focus can sit in it, and Tab can land on itsaria-hiddenfocus guards. axe reportsaria-input-field-nameandaria-hidden-focus(both serious) mid-exit on Combobox and Select.The fix
Two mechanisms, both needed:
inertalone would strand focus on<body>, and moving focus alone would leave the stale subtree exposed.inert.usePositionergets aclosedoption that applies the HTMLinertattribute; Popover, Menu, Select, Combobox and PreviewCard passclosed: !open. Dialog and Drawer, which have no positioner, set it on the popup. Drawer waits until a swipe ends. The old pointer-only option is renameddisablePointerEvents, because Tooltip and NavigationMenu still need it while open.openbecomes false, not when the popup unmounts.onOpenChangeand a reopen in the same tick.finalFocusstill wins over where the press put focus, unless the press opened another popup: the pressed control reportsaria-expanded="true", or focus is already in another open popup.Restructuring that came with it
Getting this right exposed how scattered the focus code was, so the PR also reorganizes it. Each piece is its own commit:
[floating-ui] Extract the focus return decisionfloating-ui-react/utils/returnFocus.ts: what a close means and where focus returns, as plain functions with a 42-row jsdom table test.[floating-ui] Give the close request one owner[popover][menu] Route guard focus through one modulefloating-ui-react/utils/focusRoute.tsdecides where Tab goes from each of the six focus guards (trigger, portal, content), through one routing table. Three internal focus-manager props anduseTriggerFocusGuardsare gone.[popups] Run every popup store's open change through one transaction+[select][combobox] …utils/popups/openChangeTransaction.ts: one order for every popup (reduce a redundant close to cancelling a pending hover open, consumer, cancel, record and emit, commit).syncOnlyis removed.[popover][menu] Remember why a popup opened until it unmountsopenReasonis latched per open cycle, so readers no longer see the close reason during the exit. A reopen through theopenprop alone after a close request starts without one.[floating-ui] Anchor focus guard navigation on the guard[test] Add a hold-exit seam …+[test] Add closing-popup conformance testsholdExit()keeps a popup in its exit, in jsdom too. One closing-popup conformance suite runs for 11 popups.[test] Cover keyboard focus scenarios across popupsBehavior changes
Closing popups
Tab order
onOpenChangeand stateonOpenChange(false)is no longer called again for a popup that is already closing.openchangeevents or records a close request.preventUnmountOnClose()no longer leaves the next close stuck mounted.Documented in the animation handbook ("Behavior while animating out") and on the Combobox page.
Not covered
finalFocus, so focus stays on that control.finalFocusstill takes focus from its input.Verification
Unit and browser tests:
ContextMenunested-submenu act warning,PopoverRoot.detached-triggershover handoff) or also fail on master (MenuListhorizontal navigation,MenuFilterRootpointer tests).Keyboard scenarios:
focusRoute.scenarios.test.tsxruns 20 of them; master fails 6 (the Tab-order items above).Playground: the
popup-focus-returnplayground has every popup type, nested ones included, with a focus log, long exit animations and controlled close policies. axe finds no violations mid-exit.Review: an independent adversarial review found one narrow issue: stale trigger resolution in the route. It is fixed, with tests. Later review rounds found three more, each fixed with tests in its own commit:
finalFocuscould take focus from a popup that the outside press opened;openprop before it unmounted kept the previous cycle's open reason, so a hover-opened modal Popover reopened this way had no focus management or backdrop.A final regression review compared PR and master behavior with real input across focus return, Tab order, the open-change transaction, the open-reason latch and inert closing popups. Its remaining findings are the narrow cases listed under "Not covered".