Now let me understand the issue better. The problem is about focus management when closing dialogs that were opened "programmatically" (i.e., via a button click that doesn't use the Dialog.Trigger component).
When a dialog is opened via a trigger button (Dialog.Trigger), the activeTriggerElement is set to that trigger. When the dialog is closed, focus returns to this element.
However, when a dialog is opened via "Open programmatically" button (which calls store.setOpen(true, ...) directly), the activeTriggerElement is NOT set to the "Open programmatically" button. Instead, when the dialog is closed, setOpenTriggerState keeps the previous trigger element because the trigger parameter is undefined.
Looking at setOpenTriggerState in /base-ui/packages/react/src/utils/popups/popupStoreUtils.ts:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
This function keeps the previous activeTriggerElement when open is true and trigger is undefined. This means when opening programmatically via a button, the activeTriggerElement should be set to that button.
But looking at how setOpen works in DialogStore, the eventDetails.trigger is what gets passed to setOpenTriggerState. When a button opens the dialog programmatically, eventDetails.trigger is undefined (because the button didn't call store.setOpen with a trigger element), so the activeTriggerElement doesn't get updated.
The issue is that when a button programmatically opens a dialog, we need to capture that button as the activeTriggerElement. The fix should be in the useTriggerDataForwarding or in how the programmatic open is handled.
Let me trace through the flow more carefully:
- User clicks "Open programmatically" button
- This button calls something like
store.setOpen(true, createChangeEventDetails(...))
- Since the button click isn't associated with a trigger element,
eventDetails.trigger is undefined
- In
setOpenTriggerState, since open is true and trigger is undefined, triggerId is null, so triggerId || open is true (because open is true)
- Wait, that should set
activeTriggerElement to null (the fallback)
Actually, let me re-read the code:
if (triggerId || open) {
state.activeTriggerId = triggerId; // null
state.activeTriggerElement = trigger ?? null; // null
}
So when opening programmatically (open=true, trigger=undefined):
triggerId = null (because trigger is undefined)
triggerId || open = null || true = true
state.activeTriggerId = null
state.activeTriggerElement = undefined ?? null = null
So the activeTriggerElement gets cleared to null when opening programmatically. This is correct behavior for the initial open.
But wait, the issue is about CLOSING. When the dialog is closed:
- User presses Escape or clicks Close
store.setOpen(false, ...) is called
- In
DialogStore.setOpen:
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
- Since
nextOpen is false and activeTriggerId was set to null when opening programmatically, this doesn't restore the trigger.
- The
activeTriggerElement remains null.
- In
setOpenTriggerState:
triggerId = null (because trigger is undefined/cleared)
triggerId || open = null || false = false
- So the state is NOT updated, keeping the old values (activeTriggerId and activeTriggerElement remain as they were before, which is null)
Actually wait, let me re-read setOpenTriggerState:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
When closing (open=false, trigger=undefined because eventDetails.trigger is null):
triggerId = null
triggerId || open = null || false = false
- So the
if block is NOT entered, and the state is not updated
But wait, in DialogStore.setOpen, there's this code:
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
// When closing the dialog, pass the old trigger to the onOpenChange event
// so it's not reset too early (potentially causing focus issues in controlled scenarios).
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
This should pass this.state.activeTriggerElement (which is null when opened programmatically) to the event details. So eventDetails.trigger would be undefined, and the above code in setOpenTriggerState would not update the state.
Hmm, so the issue is that when opening programmatically, we need to set activeTriggerElement to the element that triggered the programmatic open. But the problem is that the programmatic open happens from a button click, and that button element is not passed to store.setOpen.
Wait, let me look at the example from the docs more carefully. The issue says:
- 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.
So when the user focuses on "Open programmatically" button and presses Enter, focus is on that button. Then the dialog opens. When the dialog closes, focus should go back to "Open programmatically" button.
The issue is about where focus ends up when the dialog closes. The FloatingFocusManager uses domReference (which is the activeTriggerElement) to determine where to return focus.
Let me trace through more carefully:
-
User opens Dialog with Trigger 1 (e.g., "Delete" button)
activeTriggerId = trigger-1
activeTriggerElement = the "Delete" button
- Dialog opens
- Focus moves inside dialog
-
User closes Dialog with Escape
activeTriggerElement is still the "Delete" button (because we don't clear it when closing)
FloatingFocusManager returns focus to domReference = "Delete" button
- This is correct behavior
-
Now, user is on "Open programmatically" button
- User presses Enter, which opens dialog
- Since this is a programmatic open (not via Dialog.Trigger), the
activeTriggerElement might still be "Delete" button, or it might be null
Let me check the Popover component to see how it handles the same scenario.
Actually, looking at the issue description again, it says focus goes to a DIFFERENT control than the one that opened the dialog. So in the case of the Alert Dialog example, when using "Open programmatically" button, focus goes to the "Delete" button instead of the "Open programmatically" button.
This means the activeTriggerElement is still set to "Delete" button when it was opened by the "Open programmatically" button. This makes sense because:
- When opening programmatically,
trigger is undefined
- In
setOpenTriggerState, triggerId is null, so the condition triggerId || open = null || true = true
state.activeTriggerId = null
state.activeTriggerElement = undefined ?? null = null
Wait, that would set activeTriggerElement to null, not to the "Delete" button. Let me re-check.
Actually, let me look at the Popover to see if it has the same issue.
Let me look at the PopoverRoot.tsx and the Popover store.
Actually, I think the issue might be in the FloatingFocusManager. Let me check how it determines the domReference.
Looking at useSyncedFloatingRootContext:
const referenceElement = popupStore.useState('activeTriggerElement');
// ...
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
// ...
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
So the domReferenceElement is set from activeTriggerElement. If activeTriggerElement is null, the domReferenceElement won't be updated in the FloatingRootStore.
And in FloatingFocusManager.getReturnElement:
if (typeof resolvedReturnFocusValue === 'boolean') {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
If domReference is not connected (or null), it falls back to getPreviouslyFocusedElement().
So when the dialog is opened programmatically:
activeTriggerElement is set to null (because no trigger was involved)
domReferenceElement is not updated in the FloatingRootStore (because referenceElement is null)
- When closing,
domReference in FloatingFocusManager is stale (still points to the old trigger)
Wait, that's the key insight. The domReferenceElement in the FloatingRootStore is not updated when activeTriggerElement changes to null, because the if (isElement(referenceElement)) check fails. So when the dialog closes, domReference in FloatingFocusManager still points to the OLD trigger (e.g., "Delete" button), not the current element that opened the dialog.
The fix should ensure that when a dialog is opened programmatically (via a button click), the activeTriggerElement is set to the button that was clicked.
But how do we know which button was clicked? The button click event should be captured somehow.
Looking at the example from the docs:
<button
type="button"
onClick={() => {
setTriggerId('trigger-2');
setOpen(true);
}}
>
Open programmatically
</button>
The "Open programmatically" button sets the triggerId prop to 'trigger-2' before opening. But this is about which trigger has aria-expanded="true", not about which element to return focus to.
The issue is that the user focused on the "Open programmatically" button, then pressed Enter. At this point, focus is on that button. When the dialog closes, focus should return to the "Open programmatically" button, not to some other trigger.
So the fix should be: when opening programmatically, capture the currently focused element as the activeTriggerElement. This way, when the dialog closes, focus returns to the element that was focused when the programmatic open happened.
Looking at setOpenTriggerState:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
When opening with trigger = undefined:
triggerId = null
triggerId || open = null || true = true
state.activeTriggerId = null
state.activeTriggerElement = undefined ?? null = null
The fix should be to set activeTriggerElement to the currently focused element when trigger is undefined and we're opening. Let me check if there's a way to get the currently focused element.
Actually, looking at this more carefully, I think the issue is that when the dialog is opened programmatically (e.g., via a button click), the activeTriggerElement should be set to the currently focused element (which would be the button that triggered the programmatic open).
Let me look at how setOpen is called. In the DialogHandle:
open(triggerId: string | null) {
const triggerElement = triggerId
? (this.store.context.triggerElements.getById(triggerId) as HTMLElement | undefined)
: undefined;
this.store.setOpen(
true,
createChangeEventDetails(REASONS.imperativeAction, undefined, triggerElement),
);
}
So when calling handle.open('trigger-2'), the triggerElement is looked up from the triggerElements map. When calling handle.open(null), the triggerElement is undefined.
And when the button clicks to open programmatically (without using a handle), the button might be calling store.setOpen(true, ...) directly or through some other mechanism.
The key insight is that the activeTriggerElement should be set to the element that was focused when the dialog was opened, not just the trigger element.
Let me look at how createChangeEventDetails works:
export function createChangeEventDetails(reason: string, event?: Event, trigger?: Element): ChangeEventDetails {
So the trigger parameter is the element that triggered the open/close. When opening programmatically via a button, the trigger should be the button element.
The fix should be to set activeTriggerElement to the element that was focused when opening programmatically, if no trigger element is provided.
Let me look at where setOpenTriggerState is called in the setOpen method:
this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const updatedState: Partial<State<Payload>> = {
open: nextOpen,
};
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
So eventDetails.trigger is passed to setOpenTriggerState. If the button click is the trigger, we need to ensure the trigger element is set to that button.
But the button click doesn't know about the store, so it can't set the trigger element directly.
Actually, I think the issue is different. Let me re-read the issue:
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.
So when using the "Open Programmatically" button:
- User focuses on "Open Programmatically" button
- User presses Enter
- Dialog opens (but
activeTriggerElement is not set to the "Open Programmatically" button)
- User closes dialog
- Focus moves to some other trigger (e.g., "Delete" button) instead of "Open Programmatically" button
The issue is that when opening programmatically, the activeTriggerElement is not updated to reflect the element that opened the dialog.
The fix should be in setOpenTriggerState. When opening (open is true) and trigger is undefined, we should set activeTriggerElement to the currently focused element (i.e., document.activeElement).
Let me verify this by looking at how focus is managed in FloatingFocusManager.getReturnElement:
function getReturnElement() {
// ...
if (typeof resolvedReturnFocusValue === 'boolean') {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
// ...
}
If domReference is not connected, it falls back to getPreviouslyFocusedElement(). But getPreviouslyFocusedElement() returns the last element that was focused before opening the dialog, which would be the "Open Programmatically" button.
Wait, but that should work correctly. Let me trace through again:
- User focuses on "Open Programmatically" button
previouslyFocusedElements = ["Open Programmatically" button]
- User clicks "Open Programmatically" button
- Dialog opens
- In
FloatingFocusManager, domReference = null (or old "Delete" button)
previouslyFocusedElement is recorded: "Open Programmatically" button
- Focus moves to the popup
- User closes dialog
- In
getReturnElement():
domReference = null (or old "Delete" button, which IS connected)
- So it returns
domReference = "Delete" button (or null if domReference is null)
If domReference is null, domReference?.isConnected would be false, so it would return getPreviouslyFocusedElement() = "Open Programmatically" button. This would be correct.
But if domReference is the old "Delete" button, domReference?.isConnected is true, so it returns "Delete" button. This is the bug!
The bug is that domReference is not updated when opening programmatically. The fix should be to update domReference in the FloatingRootStore when the dialog is opened programmatically.
Looking at useSyncedFloatingRootContext:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
The domReferenceElement is only updated when referenceElement (which is activeTriggerElement) is an element. When opening programmatically, activeTriggerElement is set to null, so domReferenceElement is NOT updated.
The fix should be to update domReferenceElement to the currently focused element when opening programmatically.
Let me think about where the fix should go:
Option 1: In setOpenTriggerState, when open is true and trigger is undefined, set activeTriggerElement to document.activeElement.
Option 2: In useSyncedFloatingRootContext, when referenceElement is null and open is true, set domReferenceElement to document.activeElement.
Option 3: In the useTriggerDataForwarding hook, when a trigger opens the popup programmatically, set activeTriggerElement to that trigger.
I think Option 1 is the cleanest solution. When opening programmatically (open=true, trigger=undefined), we should capture the currently focused element as the activeTriggerElement. This ensures that focus returns to the element that was focused when the programmatic open happened.
Wait, but the issue says "if the control is no longer available, focus should move next to that originating control's position in the DOM". This suggests we should prefer the originating control, but fall back to the next DOM position if it's not available.
Let me look at the setOpenTriggerState function again:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
When opening with trigger = undefined:
triggerId = null
triggerId || open = null || true = true
state.activeTriggerId = null
state.activeTriggerElement = undefined ?? null = null
The fix should be:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? document.activeElement ?? null;
}
}
Wait, but this would always set activeTriggerElement to document.activeElement when opening programmatically, even if the popup was opened by some other means (e.g., programmatically but without any user interaction). The issue says "Keyboard focus should move back to the originating control (if available)".
Let me think about this more carefully. The activeTriggerElement is used to determine where focus should return when the popup closes. The issue is that when opening programmatically via a button click, the activeTriggerElement is not set to that button.
The fix should be: when opening (open is true) and trigger is undefined, set activeTriggerElement to the currently focused element (i.e., document.activeElement).
But we also need to handle the case where the popup is being opened without any user interaction (e.g., via a timer or some other means). In that case, document.activeElement might be something unexpected.
Actually, looking at the issue more carefully, it says:
If the control is no longer available, focus should move next to that originating control's position in the DOM.
This suggests that the fix should set activeTriggerElement to the currently focused element when opening programmatically, and if that element is not available, the existing fallback logic in FloatingFocusManager should handle it (falling back to getPreviouslyFocusedElement()).
Let me also check if there are any other places where this needs to be fixed. The issue mentions Alert Dialog, Dialog, and Popover.
For Alert Dialog, it uses the same useRenderDialogRoot as Dialog, so the fix in setOpenTriggerState should apply to both.
For Popover, I need to check if it uses the same store logic.
Actually, let me first check the Popover store.
Let me search for PopoverStore:
Looking at the code structure, I see that the popover uses a similar store pattern. Let me find it.
Actually, I think the best approach is to:
- Fix
setOpenTriggerState to capture document.activeElement when opening programmatically
- Make sure this applies to all popup types (Dialog, Alert Dialog, Popover)
Let me verify this by looking at the Popover component to see if it uses the same setOpenTriggerState function.
Looking at the popups module, I see that setOpenTriggerState is exported from popupStoreUtils.ts and is used by DialogStore.setOpen. Let me check if PopoverStore also uses it.
Actually, let me search for setOpenTriggerState in the codebase to see all its usages:
Let me now proceed with implementing the fix.
Actually, wait. I need to re-read the issue description more carefully.
The issue says:
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.
Looking at the example from the docs:
<button
type="button"
onClick={() => {
setTriggerId('trigger-2');
setOpen(true);
}}
>
Open programmatically
</button>
So the "Open Programmatically" button:
- Sets the
triggerId prop to 'trigger-2' (which means aria-expanded will be on the second trigger)
- Opens the dialog (by setting
open to true)
When the dialog closes:
- The
activeTriggerElement is still the old trigger (e.g., "Delete" button from the previous open)
- Focus returns to that old trigger, not the "Open Programmatically" button
The issue is that the "Open Programmatically" button is not a Dialog.Trigger, so its element is not registered in the triggerElements map. When the dialog is closed, activeTriggerElement is not updated to reflect this button.
The fix should be:
- When opening programmatically (via a button click or any other non-trigger means), capture the currently focused element as the
activeTriggerElement
- This way, when the dialog closes, focus returns to the element that was focused when the programmatic open happened
Let me implement this fix in setOpenTriggerState.
Actually, I realize I need to think about this more carefully. The activeTriggerElement is used for two purposes:
- ARIA relationships (e.g.,
aria-expanded, aria-controls)
- Focus management (returning focus when closing)
For ARIA relationships, we want activeTriggerId to be set to the trigger that should have aria-expanded="true". For focus management, we want activeTriggerElement to be the element that should receive focus when closing.
The current code sets both to the same value (the trigger element or null). But for programmatic opens, we might want to set activeTriggerElement to the currently focused element while keeping activeTriggerId as null (or whatever it was before).
Actually, looking at the code more carefully:
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
// When closing the dialog, pass the old trigger to the onOpenChange event
// so it's not reset too early (potentially causing focus issues in controlled scenarios).
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
This code passes activeTriggerElement to the event details when closing, so it's not reset too early. This is for controlled scenarios where the triggerId might change on close.
OK, I think the fix is correct: in setOpenTriggerState, when opening (open is true) and trigger is undefined, set activeTriggerElement to document.activeElement. This way:
activeTriggerId is set to null (because there's no trigger associated)
activeTriggerElement is set to the currently focused element (the button that was clicked)
- When closing, focus returns to the currently focused element
Let me implement this fix and test it.
Wait, but there's a subtlety here. When opening programmatically via handle.open(null) or handle.openWithPayload(payload), the trigger is undefined. In this case, should we set activeTriggerElement to document.activeElement?
Looking at the DialogHandle:
open(triggerId: string | null) {
const triggerElement = triggerId
? (this.store.context.triggerElements.getById(triggerId) as HTMLElement | undefined)
: undefined;
this.store.setOpen(
true,
createChangeEventDetails(REASONS.imperativeAction, undefined, triggerElement),
);
}
openWithPayload(payload: Payload) {
this.store.set('payload', payload);
this.store.setOpen(
true,
createChangeEventDetails(REASONS.imperativeAction, undefined, undefined),
);
}
So handle.open(null) sets trigger to undefined, and handle.openWithPayload(payload) also sets trigger to undefined. In both cases, document.activeElement might be something unexpected (not necessarily the element that triggered the open).
But wait, handle.open(null) is typically called from a button click handler, so document.activeElement would be that button. And handle.openWithPayload(payload) might be called from anywhere, so document.activeElement might be something else.
For now, let me implement the fix for the case where trigger is undefined and open is true. If document.activeElement is a valid element, we'll set activeTriggerElement to it. This should handle the common case where the programmatic open happens from a button click.
Actually, let me think about this differently. The issue says "focus moves to the wrong trigger". This implies that there are multiple triggers, and focus is going to one of them instead of the "Open Programmatically" button.
Looking at the code again:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
When opening programmatically (open=true, trigger=undefined):
triggerId = null
triggerId || open = null || true = true
state.activeTriggerId = null
state.activeTriggerElement = undefined ?? null = null
So activeTriggerElement is set to null. When the dialog closes, FloatingFocusManager.getReturnElement() checks:
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
But domReference in FloatingFocusManager is the domReferenceElement from the FloatingRootStore, which is NOT updated when activeTriggerElement changes to null (because the if (isElement(referenceElement)) check fails in useSyncedFloatingRootContext).
So domReference is still the old trigger element (e.g., "Delete" button), and it IS connected, so getReturnElement() returns the "Delete" button.
This is the bug! The domReference in the FloatingRootStore is not updated when opening programmatically, so it still points to the old trigger.
The fix should be to update domReferenceElement in the FloatingRootStore when activeTriggerElement changes. Let me look at useSyncedFloatingRootContext again:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
The domReferenceElement is only updated when referenceElement (which is activeTriggerElement) is an element. When referenceElement is null (e.g., when opening programmatically), domReferenceElement is not updated.
So the fix could be:
- Remove the
if (isElement(referenceElement)) check and always update domReferenceElement
- Or, set
activeTriggerElement to document.activeElement when opening programmatically
I think option 1 is simpler and more correct. Let me implement this.
Actually, wait. If we always update domReferenceElement, then when the dialog is opened programmatically (activeTriggerElement = null), domReferenceElement would be set to null. This is correct because there's no trigger associated with the dialog.
But then, when the dialog closes, domReference would be null, and getReturnElement() would fall back to getPreviouslyFocusedElement(), which would be the element that was focused before the dialog opened (e.g., the "Open Programmatically" button). This is the correct behavior!
So the fix is to remove the if (isElement(referenceElement)) check and always update domReferenceElement with the current referenceElement value.
Let me verify this by looking at the FloatingFocusManager code again:
function getReturnElement() {
// ...
if (typeof resolvedReturnFocusValue === 'boolean') {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
// ...
}
If domReference is null (or not connected), it falls back to getPreviouslyFocusedElement(). This is the correct behavior for programmatic opens.
But wait, I need to make sure this doesn't break the existing behavior. When a dialog is opened via a trigger, activeTriggerElement is set to that trigger element, and domReferenceElement should be set to that trigger element. When the dialog closes, domReference should be that trigger element, and focus should return to it.
Let me trace through the existing behavior:
- User clicks "Delete" button (Dialog.Trigger)
- Dialog opens
activeTriggerElement is set to "Delete" button
domReferenceElement is set to "Delete" button
- Dialog closes
domReference is "Delete" button
- Focus returns to "Delete" button
This is correct. Now let's trace through with the fix:
- User clicks "Delete" button (Dialog.Trigger)
- Dialog opens
activeTriggerElement is set to "Delete" button
domReferenceElement is set to "Delete" button (same as before)
- Dialog closes
domReference is "Delete" button
- Focus returns to "Delete" button
This is still correct. Now let's trace through the programmatic open case:
- User focuses on "Open Programmatically" button
- User clicks "Open Programmatically" button
- Dialog opens
activeTriggerElement is set to null (no trigger element)
- With the fix:
domReferenceElement is set to null
- Dialog closes
domReference is null
- Focus falls back to
getPreviouslyFocusedElement() = "Open Programmatically" button
This is correct!
But wait, I need to make sure the domReference in FloatingFocusManager is actually reading from the FloatingRootStore. Let me check:
const domReference = store.useState('domReferenceElement');
Yes, domReference is read from the FloatingRootStore. So if we update domReferenceElement in the FloatingRootStore, domReference in FloatingFocusManager will be updated.
Now let me also think about edge cases:
- What if the "Open Programmatically" button is unmounted before the dialog closes? In this case,
getPreviouslyFocusedElement() would return an element that is not connected, so FloatingFocusManager should handle this case (it already has logic to check if elements are connected).
Actually, looking at the getReturnElement function:
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
If getPreviouslyFocusedElement() returns an element that is not connected, it would still be returned. Let me check how getPreviouslyFocusedElement works:
function getPreviouslyFocusedElement() {
clearDisconnectedPreviouslyFocusedElements();
return previouslyFocusedElements[previouslyFocusedElements.length - 1]?.deref();
}
function clearDisconnectedPreviouslyFocusedElements() {
previouslyFocusedElements = previouslyFocusedElements.filter((entry) => {
return entry.deref()?.isConnected;
});
}
Ah, clearDisconnectedPreviouslyFocusedElements filters out disconnected elements. So if the "Open Programmatically" button is unmounted, getPreviouslyFocusedElement() would return the next element in the list (or null if the list is empty).
This handles the edge case correctly.
OK, let me now implement the fix. I need to modify useSyncedFloatingRootContext.ts to always update domReferenceElement with the current referenceElement value.
Actually wait, I need to re-read the useSyncedFloatingRootContext code more carefully:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
The referenceElement comes from popupStore.useState('activeTriggerElement'). When activeTriggerElement is null, referenceElement is null.
The fix is to remove the if (isElement(referenceElement)) check and always update domReferenceElement:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
domReferenceElement: referenceElement as Element | null,
};
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
Wait, but I need to check if referenceElement is always a valid value. Looking at the code, referenceElement comes from popupStore.useState('activeTriggerElement'), which is defined in the PopupStoreState as:
activeTriggerElement: Element | null;
So referenceElement can be null. And domReferenceElement in FloatingRootState is:
domReferenceElement: Element | null;
So the fix should work.
But wait, there's another consideration. The domReferenceElement in FloatingRootStore is used for:
- Focus management (returning focus when closing)
- Other purposes (e.g., floating UI positioning)
I need to make sure that setting domReferenceElement to null when opening programmatically doesn't break other functionality.
Let me check how domReferenceElement is used elsewhere:
- In
useHover, domReferenceElement is used to check if the hover event is on the reference element.
- In
useDismiss, domReferenceElement is used to check if the dismiss event is on the reference element.
These should not be affected by setting domReferenceElement to null when the popup is opened programmatically.
OK, let me implement the fix.
Actually, wait. I need to think about this more carefully. The issue says "focus moves to the wrong trigger". Let me re-read the issue:
- 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.
So when the user presses Esc to close the dialog, focus moves to the "Delete" button instead of the "Open Programmatically" button. This is because the domReference is still the "Delete" button (from the previous open).
But wait, looking at the issue description again, it says:
In the Alert Dialog, Dialog and Popover components, there is a variant that includes the option to use multiple triggers to open the dialogs.
So the issue is specifically about controlled mode with multiple triggers. Let me re-read the example:
Looking at the Alert Dialog example:
<AlertDialog.Root open={open} onOpenChange={setOpen} triggerId={triggerId}>
<AlertDialog.Trigger id="delete">Delete</AlertDialog.Trigger>
<AlertDialog.Trigger id="archive">Archive</AlertDialog.Trigger>
<AlertDialog.Portal>
<AlertDialog.Popup>
...
</AlertDialog.Popup>
</AlertDialog.Portal>
</AlertDialog.Root>
<button
type="button"
onClick={() => {
setOpen(true);
}}
>
Open programmatically
</button>
Wait, the example in the issue is different from what I saw earlier. Let me look at the actual documentation example.
Actually, I think I need to just look at the code and understand the issue from there. Let me focus on implementing the fix.
The key insight is:
- When a dialog is opened programmatically (not via a trigger), the
activeTriggerElement is set to null
- But the
domReferenceElement in the FloatingRootStore is NOT updated, so it still points to the old trigger element
- When the dialog closes,
domReference in FloatingFocusManager points to the old trigger element
- Focus returns to the old trigger element instead of the element that was focused when the programmatic open happened
The fix is to update domReferenceElement in the FloatingRootStore when activeTriggerElement changes to null.
Let me implement this fix in useSyncedFloatingRootContext.ts.
Wait, actually, let me re-check. Looking at the useSyncedFloatingRootContext code:
const referenceElement = popupStore.useState('activeTriggerElement');
And then:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
The referenceElement is updated when activeTriggerElement changes. So when opening programmatically:
activeTriggerElement is set to null
referenceElement is null
valuesToSync includes referenceElement: null
- But
domReferenceElement is NOT updated because isElement(null) is false
So the fix is to remove the if (isElement(referenceElement)) check and always update domReferenceElement.
But wait, I need to also check if referenceElement is ever set to a non-Element value. Looking at the PopupStoreState:
activeTriggerElement: Element | null;
So activeTriggerElement is always an Element or null. And referenceElement is always an Element or null.
OK, let me implement the fix:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
domReferenceElement: referenceElement as Element | null,
};
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
Hmm, but actually referenceElement can be undefined too? Let me check:
Looking at the PopupStoreState:
activeTriggerElement: Element | null;
So activeTriggerElement is always Element | null, never undefined. And referenceElement is Element | null.
But domReferenceElement in FloatingRootState is:
domReferenceElement: Element | null;
So the types match. The fix should work.
Actually, wait. I need to also check if removing the if (isElement(referenceElement)) check would cause any issues with referenceElement being set to a non-Element value. Looking at the code:
const referenceElement = popupStore.useState('activeTriggerElement');
So referenceElement is always the value of activeTriggerElement from the PopupStore, which is Element | null.
OK, let me also check if there are any other usages of domReferenceElement that might break if we always set it.
Looking at useDismiss:
isEventTargetWithin(event, store.select('domReferenceElement'))
This checks if the event target is within the domReferenceElement. If domReferenceElement is null, this should return false (no target is within null). Let me check the isEventTargetWithin function.
Actually, let me not worry about these edge cases for now. The fix should be correct for the main use case, and any edge cases can be handled separately.
Let me implement the fix.
Actually, I realize I should also check the Popover component to make sure the fix applies to it as well.
Let me look at the Popover store to see if it uses the same useSyncedFloatingRootContext:
Actually, looking at the code structure, I see that useSyncedFloatingRootContext is used by usePopupStore, which is used by Dialog, Alert Dialog, and Popover. So the fix in useSyncedFloatingRootContext should apply to all of them.
Let me now implement the fix.
Wait, actually, I need to re-think this. The issue is about focus management, and the fix I'm proposing is to update domReferenceElement in the FloatingRootStore. But this would affect ALL popup stores, including Popover, which might have different behavior requirements.
Let me re-read the issue:
In the Alert Dialog, Dialog and Popover components, there is a variant that includes the option to use multiple triggers to open the dialogs.
So the issue applies to all three components. And the fix should be the same for all three: when opening programmatically, update domReferenceElement to null (or the currently focused element).
Actually, looking at the issue more carefully:
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.
This suggests that the fix should set activeTriggerElement to the currently focused element when opening programmatically. But my proposed fix sets domReferenceElement to null when activeTriggerElement is null.
These two approaches are slightly different:
- Setting
activeTriggerElement to the currently focused element: This would set domReferenceElement to the currently focused element when opening programmatically.
- Setting
domReferenceElement to null when activeTriggerElement is null: This would cause FloatingFocusManager to fall back to getPreviouslyFocusedElement(), which is the element that was focused before the dialog opened.
Both approaches should work correctly for the issue at hand. The difference is:
- Approach 1: Focus returns to the element that was focused when the programmatic open happened (e.g., the "Open Programmatically" button).
- Approach 2: Focus returns to the element that was focused before the dialog opened (e.g., the "Open Programmatically" button).
In both cases, the result is the same: focus returns to the "Open Programmatically" button.
But approach 2 is simpler because it doesn't require capturing the currently focused element at the time of the programmatic open. It just relies on the existing getPreviouslyFocusedElement() mechanism.
Let me verify this by tracing through the behavior with approach 2:
- User focuses on "Open Programmatically" button
- User clicks "Open Programmatically" button
- Dialog opens
- In
FloatingFocusManager, previouslyFocusedElement = "Open Programmatically" button (recorded before opening)
domReference = null (because domReferenceElement is set to null when opening programmatically)
- Focus moves to the popup
- User closes dialog
- In
getReturnElement():
domReference is null, so domReference?.isConnected is false
- Return
getPreviouslyFocusedElement() = "Open Programmatically" button
- Focus returns to "Open Programmatically" button
This is correct!
Now let me also check approach 1:
- User focuses on "Open Programmatically" button
- User clicks "Open Programmatically" button
- Dialog opens
- In
setOpenTriggerState, activeTriggerElement = document.activeElement = "Open Programmatically" button
- In
FloatingFocusManager, domReference = "Open Programmatically" button
- Focus moves to the popup
- User closes dialog
- In
getReturnElement():
domReference is "Open Programmatically" button, so domReference?.isConnected is true
- Return
domReference = "Open Programmatically" button
- Focus returns to "Open Programmatically" button
This is also correct!
But approach 1 has a subtle issue: document.activeElement might not be the button that was clicked. For example, if the user uses the keyboard to navigate to the button and presses Enter, document.activeElement would be the button. But if the user uses the mouse to click the button, document.activeElement might be the body element (because the click happens before the focus changes).
Actually, no. When a button is clicked with the mouse, the button is focused before the click handler runs. So document.activeElement should be the button.
Let me verify this. Looking at the MDN docs:
The global read-only property activeElement returns the element within the document that currently has focus, or the document body if no element has focus.
And when a button is clicked:
- The button receives the
mousedown event
- The button receives the
mouseup event
- The button receives the
click event
- The click handler runs
So during the click handler, the button should be focused. But I'm not 100% sure about this.
Actually, looking at the HTML spec:
When a user agent is to run a task, it must add the task to the task queue of the associated event loop using the appropriate task source.
And when a button is clicked:
- The
mousedown event is dispatched to the button
- The
mouseup event is dispatched to the button
- The
click event is dispatched to the button
- The click handler runs
The focus changes on mousedown (or focus event) and on click. So during the click handler, the button should be focused.
Actually, I'm not sure about this. Let me just go with approach 2, which is simpler and doesn't rely on document.activeElement.
Wait, actually, I need to re-think this. The issue is that the domReferenceElement in the FloatingRootStore is not updated when activeTriggerElement changes to null. This causes domReference in FloatingFocusManager to still point to the old trigger element.
My proposed fix is to update domReferenceElement to null when activeTriggerElement changes to null. This would cause FloatingFocusManager to fall back to getPreviouslyFocusedElement(), which is the element that was focused before the dialog opened.
But wait, the previouslyFocusedElement is recorded in the FloatingFocusManager when the popup opens, not when the dialog is opened. Let me check:
Looking at the FloatingFocusManager code:
useIsoLayoutEffect(() => {
if (disabled || !floatingFocusElement) {
return undefined;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
addPreviouslyFocusedElement(previouslyFocusedElement);
So previouslyFocusedElement is recorded in the FloatingFocusManager when the popup opens (in the useIsoLayoutEffect callback). This is AFTER the dialog is opened, so activeElement(doc) should be the "Open Programmatically" button (or whatever element has focus when the popup opens).
Actually, wait. The FloatingFocusManager is rendered inside the popup, so it's rendered after the popup is opened. But the useIsoLayoutEffect callback runs on the next layout effect, not on the next paint. So activeElement(doc) should be the element that has focus when the layout effect runs, which should be the popup element (because the popup is focused on open).
Let me check the initialFocus logic in FloatingFocusManager:
function defaultInitialFocus(interactionType: InteractionType) {
if (interactionType === 'touch') {
return store.context.popupRef.current;
}
return true;
}
For dialogs, the initialFocus is set to defaultInitialFocus, which focuses the first tabbable element or the popup element on open. So when the popup opens, focus moves from the "Open Programmatically" button to the popup element.
And the previouslyFocusedElement is recorded AFTER the popup opens (in the useIsoLayoutEffect callback), so it should be the popup element (or whatever element has focus when the layout effect runs).
Wait, but the useIsoLayoutEffect callback runs synchronously on the next layout effect, which is before the initialFocus logic runs (because initialFocus is a prop, not a callback).
Actually, looking at the code more carefully:
useIsoLayoutEffect(() => {
// ...
addPreviouslyFocusedElement(previouslyFocusedElement);
// ...
}, [
// dependencies
]);
The previouslyFocusedElement is recorded when the FloatingFocusManager mounts (or when the disabled prop changes). This is AFTER the popup is opened, so activeElement(doc) should be the element that has focus when the FloatingFocusManager mounts.
Hmm, but the initialFocus logic also runs on mount, and it focuses the first tabbable element. So the order is:
FloatingFocusManager mounts
previouslyFocusedElement is recorded (this is AFTER the popup is opened, so it should be the popup element or the first tabbable element)
initialFocus logic runs (this focuses the first tabbable element)
Actually, I think I'm confusing myself. Let me re-read the code:
Looking at the useIsoLayoutEffect callback:
useIsoLayoutEffect(() => {
if (disabled || !floatingFocusElement) {
return undefined;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
addPreviouslyFocusedElement(previouslyFocusedElement);
// Dismissing via outside press should always ignore `returnFocus` to
// prevent unwanted scrolling.
function onOpenChangeLocal(details: FloatingUIOpenChangeDetails) {
// ...
}
events.on('openchange', onOpenChangeLocal);
// ...
return () => {
// ...
queueMicrotask(() => {
// ...
tabbableReturnElement.focus({ preventScroll: true });
});
// ...
};
}, [/* dependencies */]);
This callback records the previouslyFocusedElement when the FloatingFocusManager mounts. The FloatingFocusManager is rendered inside the popup, so it mounts after the popup is opened. But the initialFocus logic also runs on mount, so the order is:
FloatingFocusManager mounts
- The callback runs (this is a
useIsoLayoutEffect, so it runs synchronously)
previouslyFocusedElement is recorded
initialFocus logic runs (this focuses the first tabbable element)
Wait, no. The initialFocus logic is part of a separate effect, so it runs AFTER the useIsoLayoutEffect callback. So the order is:
FloatingFocusManager mounts
useIsoLayoutEffect callback runs (this records previouslyFocusedElement)
previouslyFocusedElement is recorded (this is the element that has focus when the popup is opened, which should be the "Open Programmatically" button or whatever element was focused when the popup opened)
initialFocus logic runs (this focuses the first tabbable element)
Actually, I need to check when the popup is opened and when the FloatingFocusManager mounts. Looking at the Dialog code:
const shouldRenderInteractions = open || mounted;
// ...
<DialogInteractions store={store} dialogRoot={dialogRoot} />
{typeof children === 'function' ? children({ payload }) : children}
And the children include:
<Dialog.Portal>
<Dialog.Popup>
<FloatingFocusManager ...>
{element}
</FloatingFocusManager>
</Dialog.Popup>
</Dialog.Portal>
So the FloatingFocusManager is rendered inside the Dialog.Popup, which is rendered inside the Dialog.Portal. When the dialog is opened, the Dialog.Popup is rendered (if mounted is true), and the FloatingFocusManager mounts.
But wait, the FloatingFocusManager has a disabled prop:
<FloatingFocusManager
context={floatingRootContext}
openInteractionType={openMethod}
disabled={!mounted}
...
>
So the FloatingFocusManager is disabled when mounted is false. When the popup is opened, mounted is true, so the FloatingFocusManager is enabled.
But the FloatingFocusManager mounts when the Dialog.Popup is rendered, which happens when the dialog is opened. So the FloatingFocusManager mounts at the same time as the popup is opened.
At this point, activeElement(doc) should be the element that has focus when the popup is opened, which should be the "Open Programmatically" button (or whatever element was focused before the popup was opened).
Wait, but the popup is rendered after the dialog is opened. At the time of rendering, activeElement(doc) should be the element that has focus at that moment. If the user clicked the "Open Programmatically" button, the button should have focus (because the click handler runs while the button is focused).
Actually, I'm not sure about this. Let me just assume that activeElement(doc) when the popup is opened is the element that was focused when the user triggered the programmatic open (e.g., the "Open Programmatically" button).
So the fix should be:
- Update
domReferenceElement to null when activeTriggerElement changes to null
- This causes
FloatingFocusManager to fall back to getPreviouslyFocusedElement(), which is the element that was focused when the popup was opened
- Focus returns to the correct element
Let me verify this by running the tests.
Actually, let me just implement the fix and see if it works.
Actually, I just realized something. The FloatingFocusManager records previouslyFocusedElement in the useIsoLayoutEffect callback, which runs when the popup is opened. But the previouslyFocusedElement is stored in the previouslyFocusedElements array, which is a module-level variable. So when the popup closes, the getPreviouslyFocusedElement() function returns the last element that was recorded in the array.
This means the previouslyFocusedElement is the element that has focus when the popup opens, which should be the "Open Programmatically" button (or whatever element was focused when the user triggered the programmatic open).
OK, let me now implement the fix.
Actually, I realize I should also check if there are any existing tests for this behavior. Let me search for tests related to focus management in dialogs:
Let me now implement the fix in useSyncedFloatingRootContext.ts:
The fix is to remove the if (isElement(referenceElement)) check and always update domReferenceElement with the current referenceElement value. This way, when activeTriggerElement changes to null (when opening programmatically), domReferenceElement is also updated to null, causing FloatingFocusManager to fall back to getPreviouslyFocusedElement().
Let me also check if there's a similar fix needed for the positionReference logic. Looking at the code:
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
This updates positionReference when it's equal to referenceElement. This should still work correctly after the fix.
OK, let me implement the fix.
Hmm, actually let me re-read the code one more time to make sure I understand the flow:
-
Dialog opens with a trigger (e.g., "Delete" button)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button
- Focus moves to the popup
-
User clicks "Open Programmatically" button
activeTriggerElement is set to null (because no trigger is involved)
- But
domReferenceElement is NOT updated, so it still points to "Delete" button
- Focus moves to the popup
-
User closes the dialog
domReference in FloatingFocusManager is "Delete" button (stale value)
- Focus returns to "Delete" button (wrong!)
The fix is to update domReferenceElement when activeTriggerElement changes to null. This way:
-
Dialog opens with a trigger (e.g., "Delete" button)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button
-
User clicks "Open Programmatically" button
activeTriggerElement is set to null
domReferenceElement is set to null (with the fix)
- Focus moves to the popup
-
User closes the dialog
domReference in FloatingFocusManager is null (updated value)
- Focus falls back to
getPreviouslyFocusedElement() = "Open Programmatically" button (correct!)
OK, the fix is correct. Let me implement it.
Let me also check if there's a similar issue with positionReference. Looking at the code:
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
This only updates positionReference when it's equal to referenceElement. When referenceElement changes to null, positionReference is NOT updated (because null !== null is false... wait, actually null === null is true).
Hmm, actually store.state.positionReference is the old value, and store.state.referenceElement is also the old value. So if both are null, the condition is true, and positionReference is updated to null.
But if positionReference is the "Delete" button and referenceElement is the "Delete" button, then:
store.state.positionReference = "Delete" button
store.state.referenceElement = "Delete" button
- Condition is true
positionReference is updated to "Delete" button (no change)
Then:
- User clicks "Open Programmatically" button
activeTriggerElement is set to null
referenceElement becomes null
store.state.positionReference = "Delete" button (old value)
store.state.referenceElement = "Delete" button (old value)
- Condition is true
positionReference is updated to null
Wait, that's not right. The store.state.positionReference and store.state.referenceElement are the OLD values (before the update). So after the update:
store.state.positionReference = null (updated)
store.state.referenceElement = null (updated)
Hmm, but the condition is checked BEFORE the update, so:
store.state.positionReference = "Delete" button (old value)
store.state.referenceElement = "Delete" button (old value)
- Condition is true
positionReference is updated to referenceElement = "Delete" button (old value)
store.state.positionReference = "Delete" button (still old value, because the update hasn't happened yet)
Wait, I'm confusing myself. Let me re-read the code:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
At the time of the useIsoLayoutEffect callback, the store state has not been updated yet. So store.state.positionReference and store.state.referenceElement are the OLD values.
When the user clicks "Open Programmatically" button:
activeTriggerElement is set to null (in the DialogStore)
- The
useIsoLayoutEffect callback runs (because referenceElement changed)
referenceElement = null (new value)
store.state.positionReference = "Delete" button (old value)
store.state.referenceElement = "Delete" button (old value)
- Condition
store.state.positionReference === store.state.referenceElement is true
positionReference is updated to referenceElement = null
So positionReference is updated to null. This is correct.
OK, the fix is just to remove the if (isElement(referenceElement)) check and always update domReferenceElement.
Let me also double-check the positionReference logic. Looking at the FloatingRootStore:
export interface FloatingRootState {
// ...
domReferenceElement: Element | null;
referenceElement: ReferenceType | null;
floatingElement: HTMLElement | null;
positionReference: ReferenceType | null;
// ...
}
So positionReference is a ReferenceType, which is different from domReferenceElement (an Element). But looking at the code:
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
This updates positionReference when it's equal to referenceElement. The positionReference is used for positioning (e.g., when the popup should be positioned relative to another element). When referenceElement changes to null, positionReference should also change to null (if it was tracking referenceElement).
So the positionReference logic is correct and doesn't need to be changed.
OK, let me now implement the fix.
Wait, I just thought of another issue. Looking at the code:
const referenceElement = popupStore.useState('activeTriggerElement');
This gets the activeTriggerElement from the PopupStore. When the dialog is opened programmatically, activeTriggerElement is set to null (in setOpenTriggerState).
But wait, I need to check if activeTriggerElement is actually set to null when opening programmatically. Let me trace through the flow:
- User clicks "Open Programmatically" button
- The button's click handler runs (e.g.,
setOpen(true))
- The DialogRoot's
open prop is updated to true
- The DialogStore's
openProp is synced to open
- The popup opens
But where does the activeTriggerElement get set? Looking at the setOpen method in DialogStore:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
// ...
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
};
So setOpen calls setOpenTriggerState with eventDetails.trigger. When the button clicks:
- If the button calls
store.setOpen(true, createChangeEventDetails(...)), the trigger is undefined
setOpenTriggerState sets activeTriggerElement to null (when trigger is undefined)
So yes, activeTriggerElement is set to null when opening programmatically.
OK, let me now implement the fix.
Let me look at the file again to understand exactly what needs to be changed:
useIsoLayoutEffect(() => {
const valuesToSync: Partial<FloatingRootState> = {
open,
floatingId,
referenceElement,
floatingElement,
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store.state.positionReference === store.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store]);
The fix is to change:
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
to:
valuesToSync.domReferenceElement = referenceElement as Element | null;
This way, domReferenceElement is always updated to the current referenceElement value, even if it's null.
Let me verify that referenceElement is always an Element or null:
referenceElement comes from popupStore.useState('activeTriggerElement')
activeTriggerElement is defined in PopupStoreState as Element | null
So referenceElement is always an Element or null, and the fix is correct.
Let me now implement the fix.
Actually, I realize I should also check if removing the if (isElement(referenceElement)) check would cause any issues with referenceElement being undefined. Looking at the code:
const referenceElement = popupStore.useState('activeTriggerElement');
The popupStore.useState('activeTriggerElement') selector is:
activeTriggerElement: createSelector((state: S) =>
state.mounted ? state.activeTriggerElement : null,
),
So it returns state.activeTriggerElement when mounted, or null when not mounted. And state.activeTriggerElement is Element | null (from PopupStoreState). So referenceElement is always Element | null, never undefined.
OK, the fix is safe. Let me implement it.
Hmm, actually I want to also verify that the fix handles all edge cases correctly. Let me think about some scenarios:
Scenario 1: Open dialog with trigger, close it
- User clicks "Delete" button (Dialog.Trigger)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button (same as before)
- Dialog closes
- Focus returns to "Delete" button (correct)
Scenario 2: Open dialog with trigger, open it programmatically, close it
- User clicks "Delete" button (Dialog.Trigger)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button
- Dialog closes
- User focuses on "Open Programmatically" button
- User clicks "Open Programmatically" button
activeTriggerElement = null
domReferenceElement = null (with the fix)
- Dialog opens
- User closes dialog
- Focus returns to "Open Programmatically" button (via getPreviouslyFocusedElement, correct)
Scenario 3: Open dialog programmatically, open it with trigger, close it
- User clicks "Open Programmatically" button
activeTriggerElement = null
domReferenceElement = null (with the fix)
- Dialog opens
- User closes dialog
- Focus returns to "Open Programmatically" button (via getPreviouslyFocusedElement, correct)
- User clicks "Delete" button (Dialog.Trigger)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button
- Dialog opens
- User closes dialog
- Focus returns to "Delete" button (correct)
Scenario 4: Open dialog with trigger, don't close it, open it with another trigger
- User clicks "Delete" button (Dialog.Trigger)
activeTriggerElement = "Delete" button
domReferenceElement = "Delete" button
- Dialog is already open
- User clicks "Archive" button (Dialog.Trigger)
activeTriggerElement = "Archive" button
domReferenceElement = "Archive" button
- Dialog is still open
- User closes dialog
- Focus returns to "Archive" button (correct, because the last trigger was "Archive")
Wait, in scenario 4, when the user clicks "Archive" button while the dialog is already open, does the dialog close and reopen? Or does it just update the trigger?
Looking at the DialogTrigger code:
const click = useClick(floatingContext, { enabled: floatingContext != null });
The useClick hook opens/closes the popup based on click events. So clicking "Archive" button would close the dialog and reopen it with "Archive" as the trigger.
Actually, looking at the test case:
it('opens the dialog with any trigger', async () => {
// ...
await user.click(trigger1);
await waitFor(() => {
expect(screen.queryByText('Dialog Content')).not.toBe(null);
});
await user.click(screen.getByText('Close'));
await waitFor(() => {
expect(screen.queryByText('Dialog Content')).toBe(null);
});
await user.click(trigger2);
await waitFor(() => {
expect(screen.queryByText('Dialog Content')).not.toBe(null);
});
await user.click(screen.getByText('Close'));
await waitFor(() => {
expect(screen.queryByText('Dialog Content')).toBe(null);
});
await user.click(trigger3);
await waitFor(() => {
expect(screen.queryByText('Dialog Content')).not.toBe(null);
});
});
It seems like the dialog is closed and reopened when clicking a different trigger. So my scenario 4 is correct.
OK, the fix handles all scenarios correctly. Let me implement it.
Actually, I want to also think about whether the fix might cause any regressions. Let me think about some edge cases:
Edge case 1: What if referenceElement is a different type (not Element)?
- Looking at the code,
referenceElement comes from popupStore.useState('activeTriggerElement'), which is Element | null
- So
referenceElement is always an Element or null
Edge case 2: What if the popup is opened before any trigger is registered?
- In this case,
activeTriggerElement is null (from createInitialPopupStoreState)
- With the fix,
domReferenceElement is set to null
- When the popup closes,
domReference is null, and focus falls back to getPreviouslyFocusedElement()
- This is correct behavior
Edge case 3: What if the popup is opened programmatically, then closed programmatically?
activeTriggerElement = null
domReferenceElement = null (with the fix)
- When the popup closes,
domReference is null, and focus falls back to getPreviouslyFocusedElement()
- This is correct behavior
Edge case 4: What if there are multiple popups open at the same time?
- Each popup has its own FloatingRootStore, so the fix should not affect other popups
- This is correct behavior
OK, the fix is safe and handles all edge cases correctly. Let me implement it.
Let me now look at the file to make the change:
The file is /base-ui/packages/react/src/floating-ui-react/hooks/useSyncedFloatingRootContext.ts.
I need to change:
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
to:
valuesToSync.domReferenceElement = referenceElement as Element | null;
And I should also remove the import of isElement if it's no longer needed:
import { isElement } from '@floating-ui/utils/dom';
Wait, let me check if isElement is used elsewhere in the file:
grep -n "isElement" /base-ui/packages/react/src/floating-ui-react/hooks/useSyncedFloatingRootContext.ts
Let me run this first.
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -n "isElement" /base-ui/packages/react/src/floating-ui-react/hooks/useSyncedFloatingRootContext.ts
</tool_call>