Skip to content

[popups] Keep closing popups out of the a11y tree and focus order - #5537

Draft
michaldudak wants to merge 22 commits into
mui:masterfrom
michaldudak:claude/issue-5519-triage-ce7c69
Draft

michaldudak wants to merge 22 commits into
mui:masterfrom
michaldudak:claude/issue-5519-triage-ce7c69

Conversation

@michaldudak

@michaldudak michaldudak commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

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 its aria-hidden focus guards. axe reports aria-input-field-name and aria-hidden-focus (both serious) mid-exit on Combobox and Select.

The fix

Two mechanisms, both needed: inert alone would strand focus on <body>, and moving focus alone would leave the stale subtree exposed.

  1. Closing popups are inert. usePositioner gets a closed option that applies the HTML inert attribute; Popover, Menu, Select, Combobox and PreviewCard pass closed: !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 renamed disablePointerEvents, because Tooltip and NavigationMenu still need it while open.
  2. Focus returns when open becomes false, not when the popup unmounts.
    • The close request (its event, reason and nesting) is recorded on the floating root store. The focus manager reads it in a microtask after the close commits.
    • This keeps the modality (focus ring after a keyboard close) and the "don't return focus" cases, such as hover-leave and focus moving elsewhere. They survive a consumer that unmounts the popup in onOpenChange and a reopen in the same tick.
    • An outside press waits for the press to finish, so clicking an input keeps focus there. An explicit finalFocus still wins over where the press put focus, unless the press opened another popup: the pressed control reports aria-expanded="true", or focus is already in another open popup.
    • Focus guards and focus-manager listeners only exist while the popup is open.

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:

Commit What it does
[floating-ui] Extract the focus return decision floating-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 The root store owns the close request and its expiry rules; the focus manager no longer coordinates it across four effects.
[popover][menu] Route guard focus through one module floating-ui-react/utils/focusRoute.ts decides where Tab goes from each of the six focus guards (trigger, portal, content), through one routing table. Three internal focus-manager props and useTriggerFocusGuards are 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). syncOnly is removed.
[popover][menu] Remember why a popup opened until it unmounts openReason is latched per open cycle, so readers no longer see the close reason during the exit. A reopen through the open prop alone after a close request starts without one.
[floating-ui] Anchor focus guard navigation on the guard Guards look for the next tabbable element from themselves, not from the active element.
[test] Add a hold-exit seam … + [test] Add closing-popup conformance tests holdExit() keeps a popup in its exit, in jsdom too. One closing-popup conformance suite runs for 11 popups.
[test] Cover keyboard focus scenarios across popups 20 Chromium scenarios (real Tab and Shift+Tab across every popup type, alone and nested) that check focus and open state after each step.

Behavior changes

Closing popups

  • Focus returns when a popup closes, not when its exit animation ends. Tab skips the closing popup, and assistive technology no longer sees it.
  • An input inside a closing popup (Combobox or Autocomplete with the input inside, filterable Menu) can't be typed into during the exit.
  • Fields inside a closing popup lose focus when it closes, so their blur handlers run then. For example, a NumberField in a Dialog commits and reformats its value when Escape closes the dialog; on master it never lost focus.
  • A keyboard-selected Select or Combobox item now returns focus with a focus ring. Their item, dismiss-button and resize closes now go through the same close path as other closes.

Tab order

  • Tab from the element before a hover-opened Popover's trigger reaches the trigger. It used to close the popover and send focus back.
  • Tab from a hover-opened Popover's trigger leaves past the popover. It used to stop on a hidden guard.
  • When a consumer refuses a focus-out close, Tab out of the popover moves on. It used to loop back inside.
  • A Popover or Menu opened without a trigger can be tabbed out of.
  • Tab out of a Popover or Menu nested as the last element of another Popover moves forward. It used to move backwards, which was already the case on master.

onOpenChange and state

  • onOpenChange(false) is no longer called again for a popup that is already closing.
  • A cancelled close no longer emits internal openchange events or records a close request.
  • A Dialog close that was cancelled after calling preventUnmountOnClose() no longer leaves the next close stuck mounted.
  • A hover-opened modal Popover or Menu no longer shows its internal backdrop mid-exit, and its Backdrop part stays click-through during the exit.

Documented in the animation handbook ("Behavior while animating out") and on the Combobox page.

Not covered

  • Not made inert: NavigationMenu, Tooltip and Toast. The handbook says so.
    • NavigationMenu has no close-time focus handoff yet.
    • Tooltip and Toast aren't focus targets in the same way.
  • Accepted edge cases:
    • A non-modal popup opened from a menu item still briefly focuses the menu trigger.
    • A refused close followed by a programmatic close with no user input in between can keep a stale focus ring.
    • An outside press on a control that expands something other than a popup (an Accordion or Collapsible trigger, an inline combobox) also skips an explicit finalFocus, so focus stays on that control.
    • A tap opens a Combobox after a 100 ms delay, later than the return runs, so an explicit finalFocus still takes focus from its input.
    • Narrow cases found in review and left as is: a controlled popup that ignores a close request arriving before its initial focus runs never gets that initial focus; a return deferred by a held outside press still runs if the popup reopened and closed again before the release; re-hovering a submenu trigger while it exits waits the hover delay if a sibling submenu opened in between; with a detached trigger and a refused focus-out close, Shift+Tab from the element after the trigger skips the open content.

Verification

  • Unit and browser tests:

    • jsdom: every popup, floating-ui, field and utils suite passes.
    • Chromium: the same suites pass, except timing flakes that pass when rerun alone (a ContextMenu nested-submenu act warning, PopoverRoot.detached-triggers hover handoff) or also fail on master (MenuList horizontal navigation, MenuFilterRoot pointer tests).
  • Keyboard scenarios: focusRoute.scenarios.test.tsx runs 20 of them; master fails 6 (the Tab-order items above).

  • Playground: the popup-focus-return playground 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:

    • closing an already-closed popup no longer cancelled a pending hover open;
    • an explicit finalFocus could take focus from a popup that the outside press opened;
    • a controlled popup reopened through the open prop 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".

@pkg-pr-new

pkg-pr-new Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

commit: e6b4d32

@code-infra-dashboard

code-infra-dashboard Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+573B(+0.11%) 🔺+548B(+0.33%)

Details of bundle changes

Performance

Total duration: 467.24 ms +50.11 ms(+12.0%) | Renders: 76 (+0) | Paint: 845.84 ms +79.19 ms(+10.3%)

Test Duration Renders
Tabs mount (200 instances) 85.07 ms 🔺+19.01 ms(+28.8%) 3 (+0)
Mixed surface mount (app-like density) 41.60 ms 🔺+7.14 ms(+20.7%) 5 (+0)
Checkbox mount (500 instances) 37.78 ms 🔺+6.77 ms(+21.8%) 1 (+0)
Scroll Area mount (300 instances) 39.18 ms +6.49 ms(+19.9%) 3 (+0)

11 tests within noise — details

Metric alarms

Test Metric Change
Tabs mount (200 instances) bench:paint 🔺 +24.06 ms
Checkbox mount (500 instances) bench:paint 🔺 +12.85 ms
Scroll Area mount (300 instances) bench:paint 🔺 +9.20 ms

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

@netlify

netlify Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit e6b4d32
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6acd2ac52f749186bf925bd4
😎 Deploy Preview https://deploy-preview-5537--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.

@michaldudak
michaldudak force-pushed the claude/issue-5519-triage-ce7c69 branch 2 times, most recently from 925fcc4 to 47f9735 Compare August 19, 2026 10:35
@michaldudak michaldudak changed the title [all components] Keep closing popups out of the a11y tree and focus order [popups] Keep closing popups out of the a11y tree and focus order Aug 19, 2026
@michaldudak michaldudak added component: combobox Changes related to the combobox component. component: autocomplete Changes related to the autocomplete component. component: select Changes related to the select component. component: menu Changes related to the menu component. component: context menu Changes related to the context menu component. component: menubar Changes related to the menubar component. component: popover Changes related to the popover component. component: navigation menu Changes related to the navigation menu component. component: preview card Changes related to the preview card component. component: tooltip Changes related to the tooltip component. component: dialog Changes related to the dialog component. component: alert dialog Changes related to the alert dialog component. component: drawer Changes related to the drawer component. accessibility a11y labels Aug 19, 2026
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
michaldudak force-pushed the claude/issue-5519-triage-ce7c69 branch 9 times, most recently from 048ffe4 to c3a62a6 Compare August 19, 2026 14:04
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.

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

accessibility a11y component: alert dialog Changes related to the alert dialog component. component: autocomplete Changes related to the autocomplete component. component: combobox Changes related to the combobox component. component: context menu Changes related to the context menu component. component: dialog Changes related to the dialog component. component: drawer Changes related to the drawer component. component: menu Changes related to the menu component. component: menubar Changes related to the menubar component. component: navigation menu Changes related to the navigation menu component. component: popover Changes related to the popover component. component: preview card Changes related to the preview card component. component: select Changes related to the select component. component: tooltip Changes related to the tooltip component. PR: out-of-date The pull request has merge conflicts and can't be merged.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[combobox] Prevent inaccessible popup state during exit animations

2 participants