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
Recommend keeping track of focus and returning it to the originating control.
Assistant
Let me start by exploring the repository structure to understand what we're working with.
Assistant
Now let me understand how focus is being managed on close. Let me look at the Floating UI useDismiss and related focus management code.
Assistant
Let me search for the focus restoration logic when dialog/popover closes.
Assistant
Now let me look at the FloatingFocusManager to see how focus restoration works:
Assistant
Let me look at how focus is restored on close (i.e., the actual focus restoration logic):
Assistant
Now I can see the relevant code. The
getReturnElement()function choosesdomReferenceif it's connected, otherwisegetPreviouslyFocusedElement().Now let's understand what
domReferenceis - this is thereferenceElementfrom the floating context. Let me see how it's set in our popups:Assistant
Now let me look at the Demo example to understand the "Open programmatically" use case:
Assistant
Now I see the situation. When the user clicks "Open programmatically", the dialog opens via state change with
triggerIdset to 'trigger-2'. SoactiveTriggerElementshould be 'trigger-2'. But the actual focus when opening is on the "Open programmatically" button, NOT the 'trigger-2' button.Let me trace through what's happening:
- User focuses "Open programmatically" button (focus state is there)
- User clicks it. The onClick opens the dialog with
triggerId='trigger-2' activeTriggerElementis set to 'trigger-2' (the "Open 2" button) viatriggerIdProp->useTriggerDataForwarding->setOpenTriggerState- Dialog opens, focus moves into dialog content (initial focus)
- User closes the dialog.
- The focus restoration logic uses
domReference?.isConnectedwhich is theactiveTriggerElement= 'trigger-2' button. - But wait - the user's last interaction was with the "Open programmatically" button. The previous focus was on "Open programmatically".
Let me check the logic more carefully - especially the
useImplicitActiveTrigger:Assistant
Now let me look at the useDismiss more carefully and how it tracks the trigger:
Assistant
Now let me look at the
useDismisscode to see howtriggeris passed during dismissal:Assistant
Now let me find the actual trigger focus logic:
Assistant
Let me focus on the actual issue: when "Open programmatically" is clicked, the dialog's
activeTriggerElementis set to "Open 2" (sincetriggerId='trigger-2'is the trigger ID prop), but the actual focused element was the "Open programmatically" button.Let me look at the relevant test for this scenario:
Assistant
Now let me understand the issue completely. When the dialog opens via
triggerIdprop (controlled mode), the trigger element is identified by ID. Let me check howtriggerIdPropis used:Assistant
Now let me look at the
useTriggerDataForwardingfunction. This is what handles the trigger data when there's atriggerIdprop:Assistant
Now let me understand
useTriggerDataForwardingmore carefully:Assistant
Now let me trace the actual scenario. When using "Open programmatically" button:
- User clicks "Open programmatically" button (this is focused)
- The state updates:
open=true, triggerId='trigger-2' - The DialogTrigger with
id='trigger-2'callsregisterTriggerwhich seesactiveTriggerId='trigger-2'(fromtriggerIdProp) and updatesactiveTriggerElementto be the "Open 2" button. - Dialog opens, focus moves into dialog content
- User closes the dialog (Esc key)
- The
FloatingFocusManager.getReturnElement()looks atdomReference(which isreferenceElement=activeTriggerElement= "Open 2" button) - Since "Open 2" is connected, focus returns there.
But the user expected focus to return to "Open programmatically" since that's where they clicked!
The fix needs to remember the original focused element when the dialog opens. Let me look at how the current code remembers focus:
The
previouslyFocusedElementis captured in theuseIsoLayoutEffectinFloatingFocusManager. Let me re-read this code:Assistant
Now let me understand the issue better. Looking at the
useDismissreturn value:Assistant
OK so the
dismiss.referencereturns thereferenceelement. Looking at the FloatingFocusManager:Assistant
Now I see the focus logic clearly:
- When
resolvedReturnFocusValueistrue(default):- If
domReference?.isConnectedreturnsdomReference - Otherwise falls back to
getPreviouslyFocusedElement()
- If
So the issue is that
domReferenceis theactiveTriggerElementwhich is "Open 2" button (since that's whattriggerIdProppoints to).But the actual focus needs to go back to the "Open programmatically" button because that's what the user actually interacted with.
Let me check what happens when the user uses the keyboard to open the dialog by pressing Enter on the "Open programmatically" button:
- User tabs to "Open programmatically" button (focus is there)
- User presses Enter, the button's
onClickfires - The handler updates state:
- When
Assistant
Now let me think about the right approach. The fundamental problem is:
When the dialog opens via
triggerIdprop, theactiveTriggerElementis set to the element with that ID, but that's NOT the element that initiated the open action. The actual element that initiated the action is whatever was focused before the dialog opened (and may or may not be one of the registered triggers).Looking at the issue description again:
"Keyboard focus should move back to the originating control (if available) when closing a dialog" "If the control is no longer available, focus should move next to that originating control's position in the DOM."
The originating control is the actual element that was interacted with to open the dialog. This needs to be tracked separately from
activeTriggerElement.Let me look at how the store handles this:
Assistant
Now let me look at how the FloatingFocusManager is used:
Assistant
Let me look at how DialogPopup passes returnFocus:
Assistant
Now let me think about the best approach.
Approach 1: Track the actual element that opened the popup
We could track the element that was active when the popup opened (e.g., the actual button that was clicked, not the trigger element). This should take priority over
domReferencefor focus return.Approach 2: When triggerIdProp is set, don't use activeTriggerElement for focus return
If
triggerIdPropis set (controlled mode), theactiveTriggerElementis potentially incorrect for focus return. We should use the previously focused element instead.Let me look at the dispatchOpenChange in FloatingRootStore:
Assistant
Now let me check what
triggerElementis in the openchange event. Looking at the code:When the "Open programmatically" button is clicked:
triggerIdbecomes'trigger-2'(a string)openbecomestrue- The store's
triggerIdPropis set, andactiveTriggerIdis selected astriggerIdProp ?? activeTriggerId = 'trigger-2' - The
useTriggerDataForwardingfinds the trigger element with id 'trigger-2' and setsactiveTriggerElementto that element ("Open 2" button)
The issue: The
activeTriggerElementis the registered trigger element for the dialog, NOT the element that the user actually clicked to open the dialog.The fix should make sure focus returns to the element that was focused before the dialog opened, IF that element is different from the active trigger element AND was actually focused when the dialog was opened.
Let me check the existing tests for the dialog focus return behavior:
Assistant
Now let me check the existing test about detached triggers and focus:
Assistant
Let me understand the simpler test for the issue. The
activeTriggerElementis set byuseTriggerDataForwarding. Let me trace through what happens when the dialog is opened via the "Open programmatically" button:- Click "Open programmatically"
- State:
open=true, triggerId='trigger-2' - The dialog trigger with
id='trigger-2'has itsregisterTriggercalled, which seesactiveTriggerId === triggerId(both'trigger-2'), so updatesactiveTriggerElementto its own element - The store's
activeTriggerElementis now "Open 2" button - The dialog renders, focus moves to popup content (via
initialFocuswhich defaults to true → first tabbable) - User closes dialog
getReturnElementreturns "Open 2" button sincedomReferenceis connected
Now let me think about the fix.
The simplest and most accurate approach is to track the originating element separately. The originating element is the element that was the activeElement when the dialog was opened, AND it should be a connected element that's not part of the popup.
Let me look at
addPreviouslyFocusedElement:Assistant
Assistant
Now let me set up a test to reproduce the issue. Let me create a small test file:
Assistant
Let me look at how to run tests:
Assistant
Let me write a temporary test that reproduces the issue:
Assistant
Let me look at how a test is structured:
Assistant
Let me run a test to verify the issue first:
Assistant
Let me look at the existing test file to understand structure better:
Assistant
Let me look at the test for "returns focus to the menu trigger when a detached dialog trigger unmounts":
Assistant
Now let me run the existing tests to verify the environment works:
Assistant
Let me first run the existing test to verify:
Assistant
Need to run at the root level:
Assistant
Now let me create a test that reproduces the issue:
Assistant
Assistant
Now let me design the fix:
In the
getReturnElement()function, I need to check ifpreviouslyFocusedElement(the actual element that was focused when the popup opened) is connected and different fromdomReference. If so, prefer the previously focused element.Wait, but we need to capture the originating element. Let me re-read the code to make sure I understand:
The
useIsoLayoutEffectruns when the floating element is set. When the popup opens, this effect capturespreviouslyFocusedElementand callsaddPreviouslyFocusedElement(previouslyFocusedElement).So the originating element is captured at this moment. We can save it in a local ref and use it in
getReturnElement.Let me look at the full flow once more:
Assistant
Now let me write the fix. The approach:
- Add a ref
originatingElementRefto track the originating element captured when the popup opens. - In the
useIsoLayoutEffectthat captures the previously focused element, store it in this ref. - In
getReturnElement, preferoriginatingElementRefoverdomReferenceif they differ AND the originating element is connected and not inside the popup.
Let me look at where the originating element should be captured:
- Add a ref
Assistant
OK so let me look at the whole structure. The runs when:
Assistant
Now let me think about the edge cases:
-
Normal case (click trigger): User clicks Trigger 1 →
domReference= "Trigger 1" button =previouslyFocusedElement= "Trigger 1" button → return focus to "Trigger 1" ✓ -
Open programmatically (no trigger clicked): User clicks "Open programmatically" →
domReference= "Trigger 2" button (viatriggerIdProp),previouslyFocusedElement= "Open programmatically" button → they differ → return focus to "Open programmatically" ✓ -
One trigger, controlled (triggerId prop): User clicks "Open programmatically" →
domReference= the trigger element (viatriggerIdProp),previouslyFocusedElement= "Open programmatically" → they differ → return focus to "Open programmatically" ✓ -
No trigger, programmatic open: Hmm, this is unusual, but if
triggerIdPropis null and the popup opens, what's thedomReference? It's probably null. Let me check.
Let me look at when
domReferenceis set:-
Assistant
So
domReferenceElementis set toreferenceElementwhich isactiveTriggerElement. So in our scenario,domReference=activeTriggerElement= "Trigger 2".Now let me implement the fix:
Assistant
Now let me think about the cleanest approach.
Looking at the existing code, the originating element concept is partially handled by the
previouslyFocusedElementsglobal list. The issue is thatgetReturnElementdoesn't consult the local previously focused element captured in the effect.Let me write the fix:
Assistant
Let me think more about the approach. I should add a local ref to track the originating element. The originating element should be:
- The active element when the popup first opened
- Should remain stable until the popup closes
Now let me look at where the previouslyFocusedElement is captured:
Assistant
Now let me implement the fix. I'll add a ref
originatingElementRefand modify thegetReturnElementfunction:Assistant
Let me now apply the fix:
Assistant
Actually, let me directly modify the file. Let me first do a careful look at the existing
getReturnElement:Assistant
Now let me apply the fix:
Assistant
Now let me apply the fix. I'll modify the FloatingFocusManager:
Assistant
Now I'll make the changes:
Assistant
Now I need to add the ref declaration. Let me first see the ref section:
Assistant
I see there's a duplicate. Let me fix it:
Assistant
I see there's still a duplicate. Let me fix that:
Assistant
Now I need to update the
getReturnElementfunction. Let me look at it again:Assistant
Now let me update the
getReturnElementfunction to preferoriginatingElementRef:Assistant
Now let me run the test to see if it passes:
Assistant
The test passes! But there are some unrelated errors that I see - those errors are about
pointerDownOutsideRef. Wait, those are pre-existing issues with the test. Let me look at the line:Assistant
Hmm, that error suggests
pointerDownOutsideRefis not defined here. Let me search:Assistant
Oh I see! Looking at the refs,
pointerDownOutsideRefwas declared at line 297 originally. But looking at my edits, did I accidentally remove it? Let me check:Assistant
I see - I accidentally removed
pointerDownOutsideRefwhen fixing the duplicates! Let me restore it:Assistant
I see the duplicate
preventReturnFocusRefwas caused by my edit. Let me fix it:Assistant
Now let me run the test again:
Assistant
Now let me run the existing tests to make sure I didn't break anything:
Assistant
All dialog tests pass. Let me also run popover tests:
Assistant
Let me also run alert-dialog tests:
Assistant
Now let me also run the FloatingFocusManager tests:
Assistant
All existing FloatingFocusManager tests pass. Now let me think about edge cases.
Edge cases to consider:
-
The originating element is the body - already handled by the
getNodeName(originatingElement) !== 'body'check. -
The originating element is inside the popup - already handled by the
!contains(floating, originatingElement)check. -
The originating element is no longer in the DOM - already handled by the
originatingElement.isConnectedcheck. -
The originating element equals the domReference - handled (when user clicks trigger directly).
-
The originating element is a tooltip/popover child that opened another popup - might need consideration. Let me think about this.
-
Assistant
Now I realize there's a subtle issue. The Dialog's
activeTriggerElementIS the Menu.Item in this case (since the Menu.Item has the Dialog.Trigger). SodomReference === originatingElementfor this case. So my fix would not change behavior here.Let me think more about edge cases. What if the originating element is removed from the DOM after the popup opened? For example:
Assistant
So the effect re-runs when:
disabledchangesfloatingchanges (the floating element itself)floatingFocusElementchanges (computed from floating)returnFocusRefchangeseventschangestreechangesdomReferencechangesgetNodeIdchangesgetResolvedInsideElementschanges
So if
domReferencechanges while the popup is open, the effect re-runs and theoriginatingElementRef.currentis reset! That's a problem.Assistant
OK so when clicking an inactive trigger while open, the popup stays open and switches to the new trigger. The focus might be on the new trigger or remain in the dialog.
Actually let me trace more carefully. Let me look at how the active trigger changes:
Assistant
OK, my fix might have an issue with re-renders. Let me think about this carefully:
The effect re-runs when
domReferencechanges. When this happens,originatingElementRef.currentis reset to the currentpreviouslyFocusedElement.If
domReferencechanges from trigger 1 to trigger 2 (user clicks trigger 2), and at that moment the previously focused element is trigger 2 (because user just clicked it), then:originatingElementRef.current= trigger 2 (newly captured)domReference= trigger 2 (new)hasDistinctOriginatingElement= false (they're the same)getReturnElementreturnsdomReference= trigger 2
That seems correct.
But what if
domReferencechanges for other reasons? Like ifreferenceElementchanges viasetReferenceElement? Let me look:Assistant
The
domReferenceElementis only set inside an effect. So it changes wheneverreferenceElementchanges.Now let me also think about another edge case. What if the popup re-renders during open (e.g., the payload changes)? Let me check what
floatingFocusElementlooks like:Assistant
Assistant
OK so the dialog trigger does use useClick. With toggle=true and clicked on active trigger, it would close. But that's separate from my concern.
Let me run my test again to verify the fix works:
Assistant
Now let me think about more edge cases. What about with the Esc key? Let me add more tests:
Assistant
All 3 tests pass. Now let me also test with Popover and AlertDialog:
Assistant
All tests pass. Now let me also think about additional edge cases:
-
What if the originating element is removed? My fix correctly handles this with
isConnectedcheck. -
What if there are multiple dialogs? Need to make sure the originating element is per-dialog.
-
What about tooltips, menus, selects? These should also benefit from the fix.
Let me check what components use FloatingFocusManager:
-
Assistant
Let me also check if the fix handles the case where the originating element is a menu item that opens a dialog:
Assistant
Now let me also test the existing test scenario that worked before but uses menu/dialog combo:
Assistant
That test is
isJSDOMskipped. Let me try in chromium:Assistant
Chromium needs more setup. Let me skip that and just look at the relevant code to confirm my fix is correct.
Let me also look at the FloatingFocusManager behavior when the popup closes by outside press. Let me check the test:
Assistant
Let me run the floating focus manager test now:
Assistant
Now let me also think about what happens when there's no DOM reference (no trigger registered). Let me look at one more edge case - the originating element being inside the popup somehow (which shouldn't happen but just in case):
Assistant
Excellent! The test for "originating control has been removed from DOM" works correctly - it falls back to the trigger.
Now let me run all tests in the affected directories to make sure I didn't break anything:
Assistant
All 1767 tests pass. Let me also check the drawer:
Assistant
Let me now run all the tests to be thorough:
Assistant
All 6106 tests pass. Now let me clean up the temporary test:
Assistant
Now let me review my changes more carefully to ensure correctness. Let me look at the final state of the file:
Assistant
The diff looks clean. Let me verify the indentation is consistent:
Assistant
Wait, I notice there's an issue with formatting. Let me check the original:
Assistant
Let me fix the indentation to match the original:
Assistant
I see I removed the
useIsoLayoutEffect(() => {line. Let me add it back:Assistant
Good. Let me verify with the diff:
Assistant
The diff looks clean. Now let me verify everything still passes by running my test scenarios again:
Assistant
All tests pass. Let me also test with Popover to ensure it works for it too:
Assistant
Now let me clean up the test:
Assistant
Let me also test what happens when the originating element is the same as domReference but the focus might have moved within the popup (e.g., after clicking another trigger while open). Let me look at the situation more carefully:
Looking at the code flow once more:
const originatingElement = originatingElementRef.current; const hasDistinctOriginatingElement = originatingElement != null && originatingElement !== domReference && // <-- only when they DIFFER originatingElement.isConnected && !contains(floating, originatingElement) && getNodeName(originatingElement) !== 'body';Assistant
Let me think about this case more carefully. The test "returns focus to the menu trigger when a detached dialog trigger unmounts":
- User clicks menu trigger → menu opens, focus is on menu trigger
- User clicks menu item (which has Dialog.Trigger) → menu closes, dialog opens
- User presses Escape → dialog closes
- Focus should return to menu trigger
In this case:
- When dialog opens,
domReferenceis the menu item (because the Dialog.Trigger is on the menu item) originatingElementis also the menu item (because that was focused when dialog opened)- So
hasDistinctOriginatingElementis false (they're equal) getReturnElementreturnsdomReference= menu item → focus goes to menu item ✓
But wait, there's a subtle issue. In this case, the menu item is gone (menu closed). So
domReference.isConnectedwould be false. Let me trace:domReference?.isConnectedreturns false (menu item is unmounted)- Falls back to
getPreviouslyFocusedElement()which should return... what?
Let me look at the test more carefully:
Assistant
This test is skipped in JSDOM. So I can't run it. But based on the logic:
domReference= dialog trigger (Menu.Item), but menu is closed so it's not connectedoriginatingElement= dialog trigger (same)hasDistinctOriginatingElement= false (they're equal)- Falls through to
domReference?.isConnected= false - Falls back to
getPreviouslyFocusedElement()which should be the menu trigger (added when menu was opened)
OK so the existing logic handles this case via the
getPreviouslyFocusedElement()fallback. My fix preserves this.Now let me also consider another edge case. The test "keeps trigger focus guards when
truewithout a close part" - I see this in Popover. Let me check it:Assistant
Let me look at the test runner result to make sure no test breaks. Let me run a broader test suite once more to be sure:
Assistant
All 269 tests pass. Let me also check that the existing tests related to popover/dialog detached triggers still work:
Assistant
These tests are JSDOM skipped. Let me look at the dialog detached triggers:
Assistant
Let me now check all the relevant places that this fix could affect:
Assistant
All 1495 tests pass. Let me also do a broader test to ensure nothing else is affected:
Assistant
All 6103 tests pass. Now let me look at my final diff one more time to confirm correctness:
Assistant
The diff is clean and minimal. Let me also verify the issue is fully fixed by running my reproduction test one more time:
Assistant
Both tests pass. Let me clean up the test:
Assistant
Let me also do one final check on what tests pass:
Assistant
All 710 tests pass. Let me also check git status:
Assistant
Only the FloatingFocusManager.tsx file is modified. The fix is:
- Added
originatingElementRef- a ref to track the originating element (the element that was focused when the popup opened) - Captures the originating element in the
useIsoLayoutEffectwhen the popup mounts - Modified
getReturnElementto prefer the originating element when:- It exists
- It's different from the registered trigger (
domReference) - It's connected to the DOM
- It's not inside the popup
- It's not the body element
This ensures that when a popup is opened via a control other than its registered trigger (e.g., the "Open programmatically" button with controlled
triggerId), focus returns to the actual originating control when the popup closes.Let me do one final summary check:
- Added
Assistant
Now let me address the checklist:
Checklist:
-
If an error was reported in the issue description, I have successfully reproduced it. ✅
- I created a temporary test file that reproduced the issue: clicking "Open programmatically" causes focus to move to the wrong trigger ("Trigger 2" instead of "Open programmatically" button) when the dialog closes.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error. ✅
- After my fix, the same test passes: focus correctly returns to the "Open programmatically" button when the dialog closes (both via close button and via Esc key).
-
Assistant
All 6103 tests pass.
Let me also make sure the eslint rules pass:
Assistant
ESLint passes.
Let me also verify TypeScript compiles:
Assistant
These are pre-existing build errors not related to my changes. Let me try with the test tsconfig:
Assistant
These are pre-existing test errors. Let me focus on the FloatingFocusManager.tsx file only:
Assistant
These are pre-existing module resolution issues not related to my changes. The TS check from the vitest test infrastructure was successful for my changes. Let me also use a different test approach to validate:
Assistant
No errors specific to my changes. The TS errors are about build output missing, not about my changes. The lint passes.
Let me also verify the diff once more is clean:
Assistant
A clean 20-line addition to fix the issue. Let me submit:
Assistant
Now let me provide my checklist review:
Checklist Review:
-
If an error was reported in the issue description, I have successfully reproduced it. ✅
- The issue reported focus moving to "Trigger 2" (the wrong trigger) instead of the "Open programmatically" button. I reproduced this exact issue with a temporary test that clicked the "Open programmatically" button and verified that focus ended up on the wrong trigger.
-
Assistant
The fix is clean and complete. Let me submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.