ISSUE DESCRIPTION Accessibility: Focus moves to the wrong trigger when using "Open…
- User
ISSUE DESCRIPTION
Accessibility: Focus moves to the wrong trigger when using "Open programmatically" buttons
Current behavior
In the Alert Dialog, Dialog and Popover components, there is a variant that includes the option to use multiple triggers to open the dialogs. When using the "Open Programmatically" button to open the dialog/popup, then closing it, focus moves to a different control than the one that triggered the dialog/popup.
See:
- [Alert Dialog: Controlled mode with multiple triggers](https://base-ui.com/react/components/alert-dialog#controlled-mode-with-multiple-triggers
- Dialog: Controlled mode with multiple triggers
- Popover: Controlled mode with multiple triggers
This could cause failures against WCAG 2.2 Success Criterion 2.4.3 Focus Order when implemented.
Expected behavior
Keyboard focus should move back to the originating control (if available) when closing a dialog as long as a page refresh or redirection is not triggered.
If the control is no longer available, focus should move next to that originating control's position in the DOM.
Reproducible example
- Go to [Alert Dialog: Controlled mode with multiple triggers](https://base-ui.com/react/components/alert-dialog#controlled-mode-with-multiple-triggers
- Using keyboard, move focus to the "open programmatically" button
- Press Enter to activate the control and open the dialog
- Press Esc or activate the close button to close the dialog
- Note focus has moved back to the "Delete" button and not the "open programmatically" button as expected.
Base UI version
v1.2.0
Which browser are you using?
Chrome 145.0.7632.76
Which OS are you using?
Mac OS Tahoe 26.2
Which assistive tech are you using (if applicable)?
Keyboard
Additional context
- Assistant
I’ll first map the repository and locate the shared focus-restoration logic and existing tests for controlled multiple-trigger behavior. Then I’ll reproduce the incorrect target in the relevant test harness, implement the fix at the appropriate shared layer, and run focused plus broader tests.
- Assistant
ripgrepis unavailable, so I’ll usegrep/find. The affected components likely share an internal floating overlay/root implementation; I’ll inspect their roots, triggers, and focus-manager usage along with nearby tests. - Assistant
The popup components delegate close-time behavior to
FloatingFocusManager. I’ll inspect its captured “previously focused” element and fallback algorithm, plus how roots update the reference element when one of several triggers—or a non-trigger programmatic opener—is active. - Assistant
The key defect is visible: default return focus prioritizes
domReferenceoverpreviouslyFocusedElement. In a controlled multi-trigger example,domReferenceremains the selected declarative trigger, while the active element at popup mount is the separate programmatic button. Before changing priority globally, I’ll inspect the focus-history helper and existing tests that define expected behavior, especially cases where opening causes focus to leave the trigger before the manager mounts. - Assistant
The manager captures the correct local origin at mount, but then discards that variable for default resolution and consults the global history only after preferring the reference. The global stack supports nested overlays, while the local value precisely represents this overlay’s opener. I’ll inspect cleanup/fallback-marker behavior and all call sites to ensure using the local origin first preserves nested semantics and the “origin removed → next DOM position” requirement.
- Assistant
There is no close-time marker in this cleanup block; disconnected origins are removed from history, causing fallback to the trigger. The expected behavior explicitly requires the next position in DOM when the origin disappears, so I’ll look for tab-order utilities and upstream Floating UI’s implementation/version history. The likely robust design is to retain the exact origin and record its next tabbable neighbor while it is connected, then resolve origin → neighbor → reference.
- Assistant
The requested fallback can be captured before modal inerting/removal by finding the next tabbable from the origin at manager mount. However, changing the shared manager could affect menus/selects beyond the reported components. A narrower and semantically cleaner approach may be for Dialog/Popover popup defaults to pass the active opener as
returnFocus; I’ll inspect their popup state/store and explicitfinalFocuscontract to determine whether origin tracking belongs in the manager or these components. - Assistant
getNextTabbableis already available, but depends ondocument.activeElement; at the return-tracking layout effect the opener is still active, so it can capture the successor. I’ll implement local-origin-first default resolution, with a captured successor used only if the origin disconnects, then the associated reference/global history as final fallback. ExplicitfinalFocusfallback will remain reference-first to preserve its documented/current semantics. I’ll also update the manager’s default behavior documentation. - Assistant
Python is not installed, so no change was made. I’ll apply the same focused edit with Node, then inspect the diff before testing.
- Assistant
The implementation now preserves the exact active opener per focus-manager instance and captures a successor for removal. I’ll run the focused manager, Dialog popup/root, Popover popup/root, and AlertDialog root suites under jsdom. These should expose regressions in standard trigger return, explicit final focus, nested overlays, and controlled triggers.
- Assistant
pnpm execinvoked Corepack’s interactive download prompt, which this environment cannot answer. Dependencies and local binaries are already present, so I’ll bypass Corepack and invokecross-env/vitestdirectly with a longer timeout. - Assistant
The broad priority change is too aggressive: six tests demonstrate cases where manager mount-time active focus is not a reliable opener (keep-mounted transitions, hover opening, and Popover guard setup). I’ll revert that strategy. Instead, I need capture the origin at the actual controlled closed→open transition, before rendering/focus management. I’ll inspect root state synchronization and event details; programmatic controlled prop changes should have a layout-effect point where
activeElementis still the activating button, while trigger interactions can continue using the reference. - Assistant
The roots use a shared
usePopupRootSync(store, open)hook for controlled prop transitions. That is the right central point for all three components: capturedocument.activeElementonly when the store observes a closed→open transition not initiated by an owned trigger, and expose it to focus return. I’ll inspect this hook and store context extensibility before implementing. - Assistant
The shared store context is suitable for a mutable return target ref without adding public state/API. I’ll inspect
usePopupRootSyncand initial popup context, then add a context ref updated on closed→open controlled synchronization only when the active element is not the associated trigger. Popup components can pass a function toreturnFocusthat respects explicitfinalFocusand otherwise uses this ref. But easiest manager new prop? No interface requested. finalFocus resolved component function wrapping. Need preserve false/function close type. Create helper perhaps.First see sync.
- Assistant
usePopupRootSynconly resets interaction method and runs after render—too late to distinguish reliably if focus manager’s earlier child layout effects move focus. Capturing during render on the closed→open prop transition is safe via a ref/store context mutation (no DOM write), andactiveElementis still the opener. Yet event-driven trigger openings also render there; distinguish by whetheractiveElementequals any registered trigger. I’ll inspect context and owner-document helpers, then addreturnFocusRefto shared popup context and update it in root sync during transition. - Assistant
A reliable discriminator already exists: owned triggers set
openMethod, while external controlled buttons do not. I’ll add two internal context refs (origin and its next tabbable control), capture them synchronously on a closed→open render only whenopenMethodis null, and have Dialog/Popover use that target only whenfinalFocusis unspecified. If no programmatic origin was captured, returningtrueretains all existing manager behavior (including hover/reference and keep-mounted cases). ExplicitfinalFocusremains untouched. - Assistant
The internal flow is implemented without changing public interfaces. Before broader verification, I’ll run Prettier on the six modified files and then rerun the same focused suites. This also validates TypeScript transform/import syntax.
- Assistant
All 363 applicable focused tests pass. The existing controlled-trigger tests only verify payload/opening, not close-time focus, so I’ll create a temporary (removed immediately afterward) regression test that mirrors the report for Dialog, AlertDialog, and Popover. It will also cover removal of the programmatic opener and verify focus moves to its next DOM control.
- Assistant
I’ll now run that temporary reproduction under jsdom. The removal case is important: root render captures the still-connected active control before React reconciles it away, allowing the precomputed next tabbable target to be used on close.
- Assistant
The three reported cases pass. My first removal simulation reinserted the opener on close (
!open), so it did not accurately model “no longer available” and React reconciliation complicated node identity; it nonetheless exposed that fallback was not selected in that artificial cycle. I’ll rerun a correct permanent-removal scenario where opening independently removes the opener and closing does not restore it. - Assistant
The permanent-removal test confirms the fallback still fails. The likely cause is controlled-store synchronization: the root first commits the parent’s DOM removal while its selected
openvalue remains stale, then observes opening on a follow-up render—too late to capture either origin or successor. The connected-origin report still passes because the focus manager itself captures it, and our explicit resolver can retrieve history indirectly only viatrue, so I need move capture earlier: directly into the external button’s click-to-controlled-prop update path is unavailable, but a document-levelfocusinhistory can retain origin and successor before removal. I’ll inspect existing global focus history and controlled prop timing to integrate without broad behavior changes. - Assistant
I’ll inspect
ReactStore.useControlledPropand Dialog root ordering. If the store does expose the new prop during the same render, then the failure is more likely thatopenMethodwas stale/non-null or the next-tabbable capture picked a transient focus guard. Logging the temporary internal refs at close can pinpoint this without guessing. - Assistant
Confirmed: controlled props synchronize in a layout effect, so the shared hook sees the transition only after parent DOM reconciliation. I’ll pass the current
openPropinto the hook and useopenProp ?? storeOpensolely for early origin capture/reset detection. This preserves uncontrolled behavior while capturing controlled transitions during the parent render, before removal. - Assistant
The hook now observes controlled opening at the correct time. I’ll rerun both the permanent-removal reproduction and a compact reported-case check, remove the temporary file, then rerun focused suites if successful.
- Assistant
Both exact-origin and removed-origin reproductions now pass. I’ll rerun all affected focused suites after the controlled-prop timing change, then run TypeScript and ESLint on changed files.
- Assistant
Focused tests remain green (363 passed, 156 environment-skipped). I’ll now run repository TypeScript checking and ESLint only across the eight changed source files, then inspect final diff/status for accidental artifacts.
- Assistant
TypeScript correctly revealed that
PopupStoreContextis shared by Menu, Tooltip, and PreviewCard. These components do not use this behavior, so requiring refs there is unnecessary. I’ll make the internal refs optional at the shared type boundary, guard writes/reads, narrow the captured successor toHTMLElement, and fix import order. This keeps concrete Dialog/Popover stores initialized while avoiding unrelated changes. - Assistant
TypeScript now passes. ESLint only requires this repository’s explicit
| undefinedconvention on optional fields; I’ll apply that, rerun ESLint, and review the complete final diff. - Assistant
Lint passes and no temporary files remain. The prior command’s final
git diffwas accidentally givenint 120as arguments, so it failed only at display time after successful validation. I’ll inspect the diff cleanly, paying particular attention to stale-target clearing across repeated open cycles and explicitfinalFocusbehavior. - Assistant
Review found an important repeated-cycle edge case: after one programmatic opening, a later trigger opening skips capture because
openMethodis set, leaving the old programmatic target in the refs. I’ll clear both refs at the start of every opening transition, then conditionally populate them for programmatic openings. They must not be cleared on closing because the focus manager resolves its target during close cleanup. - Assistant
I’ll verify that repeated sequence explicitly: open/close programmatically, then open/close via the owned trigger, and ensure the second close returns to the trigger rather than the stale external button. Then I’ll do one final TypeScript check and submit.
- Assistant
Implementation and verification are complete.
Checklist:
- If an error was reported, I successfully reproduced it: Yes. Temporary tests reproduced controlled multi-trigger programmatic opening for Dialog, Alert Dialog, and Popover, including the wrong-reference scenario and opener removal. Temporary files were deleted.
- If an error was reported, I confirmed the fix resolves it: Yes. All three components returned focus to the external programmatic opener. When that opener was permanently removed, focus moved to the next tabbable control.
- I thought about edge cases: Yes. The fix handles disconnected openers, explicit
finalFocus, initially open popups, normal trigger/hover opening, uncontrolled mode, and repeated cycles switching from a programmatic opener back to an owned trigger. A dedicated temporary test confirmed stale origins are cleared. - I ran affected existing tests: Yes. The focused suites passed with 363 passed / 156 jsdom-skipped. TypeScript passes, ESLint passes, formatting and
git diff --checkpass.
I’ll submit the nine source-file changes now.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.