Now I understand the issue. Let me trace through the flow:
- User is on the "Open programmatically" button (focus is on this button)
- User presses Enter to click the button
setTriggerId('trigger-2') and setOpen(true) are called
- React re-renders, Dialog.Root gets
open=true and triggerId='trigger-2'
openProp is synced - dialog opens
triggerIdProp is synced to the store
activeTriggerIdSelector returns 'trigger-2' (since triggerIdProp is set)
activeTriggerElement is still null (since no trigger element was passed)
- In
useSyncedFloatingRootContext, referenceElement is activeTriggerElement which is null
domReferenceElement in the floating context is null
- When dialog closes (Escape),
getReturnElement() in FloatingFocusManager checks:
domReference?.isConnected → null?.isConnected → falsy
- Falls back to
getPreviouslyFocusedElement()
getPreviouslyFocusedElement() returns the element that was focused before the popup opened - which should be the "Open programmatically" button...
Wait, but the issue says focus goes to the "Delete" button instead. Let me re-read the issue more carefully.
Actually, I think the issue is different. Let me look at what element is focused when the dialog opens. When the dialog is modal, focus gets trapped inside the dialog. So the "previously focused element" should be whatever was focused before the dialog opened.
But wait - there's a subtle issue. When the user presses Enter on the "Open programmatically" button:
- The button gets focus (it's the active element)
- The onClick handler fires, setting state
- The dialog opens
- Focus is moved to inside the dialog (usually the close button or popup)
- When the user presses Escape to close, focus should return to the "Open programmatically" button
But the issue says focus goes to the "Delete" button instead. This means getPreviouslyFocusedElement() is returning the wrong element, OR domReference is pointing to the "Delete" button.
Let me check if the activeTriggerElement gets set to a different trigger when the controlled mode changes...
Actually, I think I understand now. In the controlled demo:
- The user focuses the "Delete" button (one of the Dialog.Trigger components)
- The user tabs to "Open programmatically" button (focus is now on the button, not on any trigger)
- User presses Enter on "Open programmatically"
setTriggerId('trigger-2') and setOpen(true) are called
- The dialog opens
- But then something changes the
activeTriggerElement to point to a different trigger
Wait, let me look at useTriggerDataForwarding again:
export function useTriggerDataForwarding<State extends PopupStoreState<unknown>>(
triggerId: string | undefined,
triggerElementRef: React.RefObject<Element | null>,
store: ReactStore<State, PopupStoreContext<never>, typeof popupStoreSelectors>,
stateUpdates: Omit<Partial<State>, 'activeTriggerId' | 'activeTriggerElement'>,
) {
const isMountedByThisTrigger = store.useState('isMountedByTrigger', triggerId);
...
const registerTrigger = useStableCallback((element: Element | null) => {
...
const open = store.select('open');
const activeTriggerId = store.select('activeTriggerId');
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
if (activeTriggerId == null && open) {
// If a popup is already open, a detached trigger can mount before any active trigger
// has been established. Claim the first registered trigger so trigger-owned focus
// management and ARIA relationships work.
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
});
AHA! I found it! Look at this code:
if (activeTriggerId == null && open) {
// If a popup is already open, a detached trigger can mount before any active trigger
// has been established. Claim the first registered trigger so trigger-owned focus
// management and ARIA relationships work.
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
This is in useTriggerDataForwarding. When a popup is already open and a new trigger mounts (or a trigger's ref callback fires), if activeTriggerId is null, it claims the first registered trigger.
But wait, in our case, triggerIdProp is set to 'trigger-2', so activeTriggerIdSelector returns 'trigger-2', and activeTriggerId (raw state) might be null.
Let me trace through more carefully:
- User clicks "Open programmatically" button
setTriggerId('trigger-2') and setOpen(true) are called
- React re-renders with
openProp=true and triggerIdProp='trigger-2'
- In DialogRoot,
triggerIdProp='trigger-2' is passed to the store
useControlledProp('triggerIdProp', 'trigger-2') syncs this value
- The store now has
triggerIdProp='trigger-2' and activeTriggerId=null (still)
open becomes true via openProp sync
setOpenTriggerState is called - let me check when...
Let me look at how the controlled prop sync handles opening the popup:
Looking at the useSyncedFloatingRootContext, it's called from usePopupStore:
useSyncedFloatingRootContext({
popupStore: store,
...
onOpenChange: store.setOpen,
});
And in usePopupStore, useSyncedFloatingRootContext creates a FloatingRootStore with referenceElement = popupStore.useState('activeTriggerElement').
When the dialog opens via openProp sync:
activeTriggerElement is null (no trigger element was passed)
- So
referenceElement in the floating context is null
domReferenceElement is set to null
Now, in useTriggerDataForwarding:
- All three Dialog.Trigger components mount
- When the first trigger's
registerTrigger is called with an element:
activeTriggerId (raw) is null
open is true
- So it enters the
if (activeTriggerId == null && open) branch
- And sets
activeTriggerId = triggerId (the trigger's own id) and activeTriggerElement = element
So the first Dialog.Trigger to register itself will claim the activeTriggerElement!
In the demo, the triggers are:
- "Discard" (id: "alert-trigger-1")
- "Delete" (id: "alert-trigger-2")
- "Sign out" (id: "alert-trigger-3")
So "Discard" would be the first trigger to mount and claim the activeTriggerElement. But wait, the issue says focus goes to "Delete" not "Discard"...
Hmm, let me re-read the issue. The issue says:
- "Note focus has moved back to the 'Delete' button"
But looking at the demo, the "Open programmatically" button sets triggerId='trigger-2' which points to the "Open 2" button (in dialog demo) or "Delete" button (in alert-dialog demo). So if the user opens programmatically with triggerId='trigger-2', and focus goes to "Delete", that's actually pointing to the trigger with the same ID as what was passed to triggerId. But wait...
Actually, I think the issue might be that activeTriggerElement gets set to the first registered trigger instead of the one matching triggerIdProp. Let me look more carefully at the useTriggerDataForwarding function:
const registerTrigger = useStableCallback((element: Element | null) => {
baseRegisterTrigger(element);
if (!element) {
return;
}
const open = store.select('open');
const activeTriggerId = store.select('activeTriggerId');
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
if (activeTriggerId == null && open) {
// If a popup is already open, a detached trigger can mount before any active trigger
// has been established. Claim the first registered trigger...
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
});
Wait, activeTriggerId = store.select('activeTriggerId') - let me check what this selector returns. Looking at the popup store:
const activeTriggerIdSelector = createSelector(
(state: S) => state.triggerIdProp ?? state.activeTriggerId,
);
So store.select('activeTriggerId') returns triggerIdProp ?? activeTriggerId.
When the user clicks "Open programmatically":
triggerIdProp = 'trigger-2'
activeTriggerId (raw state) = null
store.select('activeTriggerId') returns 'trigger-2' (since triggerIdProp is set)
Now in registerTrigger:
activeTriggerId = store.select('activeTriggerId') = 'trigger-2'
triggerId = the individual trigger's ID (e.g., 'alert-trigger-1' for "Discard")
activeTriggerId === triggerId → 'trigger-2' === 'alert-trigger-1' → false
activeTriggerId == null → false (since it's 'trigger-2')
- So neither branch is taken!
OK so that's actually correct - the trigger data forwarding doesn't override the active trigger. Let me re-think the problem.
Let me look at where activeTriggerElement gets set when opening via controlled prop:
When openProp syncs to open=true:
- This happens through
useControlledProp which directly sets the state
- The
setOpen method is NOT called in this case
Wait, let me look at the DialogStore to see how openProp sync works:
Looking at DialogStore.setOpen:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
...
this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const updatedState: Partial<State<Payload>> = {
open: nextOpen,
};
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
};
And setOpenTriggerState:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
So when the dialog is opened via setOpen, the trigger parameter is used to set activeTriggerId and activeTriggerElement.
But when opened via controlled prop (openProp), the setOpen method is NOT called. Instead, useControlledProp directly sets the state. Let me check if there's any mechanism that syncs triggerIdProp to activeTriggerId when opened via controlled prop.
Looking at useRenderDialogRoot:
store.useControlledProp('openProp', openProp);
store.useControlledProp('triggerIdProp', triggerIdProp);
These just set openProp and triggerIdProp directly. They don't call setOpen.
So the sequence is:
- User clicks "Open programmatically"
setTriggerId('trigger-2') and setOpen(true) called
- React re-renders Dialog.Root
triggerIdProp='trigger-2' is synced
openProp=true is synced → open becomes true
- In
useSyncedFloatingRootContext, referenceElement = activeTriggerElement = null
domReferenceElement in floating context is null
activeTriggerIdSelector returns 'trigger-2' (from triggerIdProp)
useTriggerDataForwarding for each trigger:
store.select('activeTriggerId') = 'trigger-2' (from triggerIdProp)
- For triggers where
triggerId !== 'trigger-2': neither branch is taken
- For the trigger where
triggerId === 'trigger-2': activeTriggerId === triggerId is true, so it updates activeTriggerElement
- So
activeTriggerElement should be set to the element with id 'trigger-2' (the "Delete" button in alert-dialog demo)
Wait, so in this case, activeTriggerElement IS set to the "Delete" button element! And domReferenceElement in the floating context IS set to the "Delete" button.
So when the dialog closes, getReturnElement() returns domReference (which is the "Delete" button), and focus goes to the "Delete" button.
But the issue is: the "Delete" button is NOT where the user was when they opened the dialog! The user was on the "Open programmatically" button.
The problem is that activeTriggerElement is being set to the trigger that matches triggerIdProp, but the triggerIdProp was set by the user to point to a specific trigger, even though the user's keyboard focus was on the "Open programmatically" button.
Actually, wait. Let me re-read the issue one more time:
"Using keyboard, move focus to the 'open programmatically' button"
"Press Enter to activate the control and open the dialog"
OK so the user's focus is on the "Open programmatically" button when they press Enter.
"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 the user expects focus to go back to the "Open programmatically" button (where their focus was), but it goes to the "Delete" button instead.
Now I understand the issue! The problem is:
- When the dialog opens via controlled mode with
triggerId='trigger-2', domReferenceElement is set to the element with id 'trigger-2' (the "Delete" button).
- When the dialog closes,
FloatingFocusManager.getReturnElement() returns domReference if connected, which is the "Delete" button.
- But the user's focus was on the "Open programmatically" button, not the "Delete" button.
The fix should be:
- When opening programmatically (not via a trigger press), the
domReferenceElement should NOT be set to a specific trigger
- Instead, focus should return to the element that was previously focused (the "Open programmatically" button)
But there's a subtlety here. The triggerIdProp is provided to help with ARIA relationships, not necessarily for focus return. When the user clicks a Dialog.Trigger, the focus should return to that trigger. But when the user clicks a custom "Open programmatically" button, focus should return to that button.
The key insight is: when the dialog is opened via openProp sync (controlled mode), no actual trigger element was involved. The triggerIdProp is just for ARIA purposes, not for focus management.
So the fix should be:
- When
openProp syncs to true and triggerIdProp is set, we should NOT set domReferenceElement to the trigger element matching triggerIdProp
- Instead, we should only update
activeTriggerElement if the dialog was opened by an actual trigger press
Actually, looking at the code again, I think the issue is more nuanced. Let me look at useTriggerDataForwarding:
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
This code sets activeTriggerElement to the trigger element when activeTriggerId === triggerId. But activeTriggerId is store.select('activeTriggerId') which returns triggerIdProp ?? activeTriggerId.
So when triggerIdProp is set to 'trigger-2', the trigger with id='trigger-2' will have its element set as activeTriggerElement, even though the dialog was opened via controlled mode, not by actually pressing that trigger.
The fix could be:
- Only set
activeTriggerElement from useTriggerDataForwarding when the trigger is actually the one that activated the popup (i.e., when activeTriggerId was set by a real trigger press, not by triggerIdProp)
- Or, track the actual trigger element that was used to open the popup separately from the
triggerIdProp-based activeTriggerElement
Looking at the existing code, I see that when setOpen is called with a trigger element:
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
This sets activeTriggerElement to the trigger that actually opened the dialog. The problem is that when the dialog is opened via controlled prop, setOpen is NOT called, so activeTriggerElement never gets set to a meaningful value... until useTriggerDataForwarding kicks in and sets it to whatever trigger matches triggerIdProp.
I think the fix should be in useTriggerDataForwarding. We should NOT set activeTriggerElement when the active trigger was determined by triggerIdProp (controlled mode) rather than by an actual trigger press.
Let me look at how to distinguish between these two cases:
- When a trigger presses the dialog open:
activeTriggerId is set by setOpen with the trigger element
- When the dialog opens via controlled prop:
triggerIdProp is set, but activeTriggerElement is null
We can check if activeTriggerElement was already set (meaning the dialog was opened by a real trigger press) vs. not set (meaning the dialog was opened via controlled prop).
Actually, looking at the code more carefully:
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
This code sets activeTriggerElement for every trigger that matches activeTriggerId. But this happens on every mount/re-render of the trigger, which is not ideal.
I think the fix is to check if activeTriggerElement is already set. If it is, we should not update it (the trigger that actually opened the dialog should keep its element as the active trigger element). If it's not set, we should set it to the trigger that matches activeTriggerId.
But actually, looking at the logic again:
activeTriggerId === triggerId - this is true for the trigger that matches the active trigger
activeTriggerId == null && open - this is for when no active trigger is set but the popup is open
Wait, I think I need to trace through the flow more carefully.
Actually, I think the real issue is this:
When the user clicks "Open programmatically":
setOpen(true) and setTriggerId('trigger-2') are called
- React re-renders Dialog.Root with
openProp=true and triggerIdProp='trigger-2'
- The store's
open becomes true (from openProp sync)
- The store's
triggerIdProp becomes 'trigger-2' (from triggerIdProp sync)
useSyncedFloatingRootContext sees activeTriggerElement = null (raw state)
- So
referenceElement = null in the floating context
domReferenceElement in the floating context is null
- Then, as each trigger mounts/registers:
store.select('activeTriggerId') = triggerIdProp ?? activeTriggerId = 'trigger-2' ?? null = 'trigger-2'
- For trigger with id='trigger-2':
activeTriggerId === triggerId → true
- So it sets
activeTriggerElement = element
So now activeTriggerElement is the "Delete" button, and domReferenceElement in the floating context will be the "Delete" button.
When the dialog closes, getReturnElement() returns domReference (the "Delete" button), and focus goes there.
But the user's focus was on the "Open programmatically" button, not the "Delete" button. So focus should go to the "Open programmatically" button.
The fix should ensure that when a dialog is opened via controlled mode (not via a trigger press), domReferenceElement is NOT set to a trigger element, so that focus returns to the previously focused element.
Actually, I think the root issue is in useTriggerDataForwarding. It should NOT set activeTriggerElement when the dialog was opened via controlled mode (triggered by triggerIdProp). It should only set activeTriggerElement when the dialog was opened by an actual trigger press (triggered by setOpen with a real trigger element).
One way to distinguish these cases is:
- When opened by a trigger press:
activeTriggerElement is set to the trigger element before the triggers mount
- When opened via controlled mode:
activeTriggerElement is null (not set by any trigger press)
So the fix could be: only update activeTriggerElement in useTriggerDataForwarding if it's currently null AND the trigger matches activeTriggerId.
Wait, that's already what happens in the second branch:
if (activeTriggerId == null && open) {
store.update({...});
}
But the problem is the FIRST branch:
if (activeTriggerId === triggerId) {
store.update({...});
return;
}
This branch sets activeTriggerElement for EVERY trigger that matches activeTriggerId, even when the dialog was opened via controlled mode.
I think the fix is to also check if activeTriggerElement is currently null in the first branch. If it's already set, don't update it. If it's null, update it.
Wait no, that's not quite right either. If the dialog was opened by a real trigger press, activeTriggerElement is already set by setOpenTriggerState. We don't want to update it. But if the dialog was opened via controlled mode, activeTriggerElement is null, and we want to set it to the trigger that matches activeTriggerId for ARIA purposes...
Actually, I think the issue is that we're setting activeTriggerElement for focus return purposes. When the dialog is opened via controlled mode, we shouldn't be setting activeTriggerElement at all for focus return - we should just use it for ARIA purposes.
Let me look at how activeTriggerElement is used:
- In
useSyncedFloatingRootContext, it's used as referenceElement for the floating context
- In
FloatingFocusManager, domReferenceElement (which comes from referenceElement) is used for focus return
So activeTriggerElement serves two purposes:
- ARIA relationships (connecting the popup to its trigger)
- Focus return (returning focus to the trigger when closing)
The fix should be:
- When opened via controlled mode,
activeTriggerElement should still be set for ARIA purposes
- But for focus return, we should check if the dialog was opened by a real trigger press, and if not, return focus to the previously focused element
Actually, I think a simpler fix would be:
- In
useTriggerDataForwarding, only set activeTriggerElement when store.state.activeTriggerElement is null (raw state, not selector)
- This means we only set it when no trigger press has already set it
Let me look at the code again:
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
The fix could be:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if it's not already set
// This prevents overwriting a trigger element set by a real trigger press
if (store.state.activeTriggerElement == null) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
Wait, but store.state.activeTriggerElement would be null when opened via controlled mode (no trigger press), and we DO want to set it for ARIA purposes... but we DON'T want focus to return to it.
Hmm, this is getting complicated. Let me think about this differently.
The core issue is: when the dialog opens via controlled mode, domReferenceElement should NOT be the trigger element. It should be null so that focus returns to the previously focused element.
But activeTriggerElement is also used for ARIA purposes, and we DO want to set it for ARIA.
So we need to separate these two concerns:
- ARIA:
activeTriggerElement should be set for the trigger matching activeTriggerProp
- Focus return:
domReferenceElement should be set to the element that actually activated the dialog
Actually, looking at useSyncedFloatingRootContext:
const referenceElement = popupStore.useState('activeTriggerElement');
...
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
So domReferenceElement is set to activeTriggerElement when it's a valid element. The issue is that activeTriggerElement gets set to the wrong element when the dialog opens via controlled mode.
I think the simplest fix is in useTriggerDataForwarding. We should only set activeTriggerElement if the dialog was opened by a real trigger press (i.e., activeTriggerId is set in the raw state, not just via triggerIdProp).
One way to check this: if triggerIdProp is set and the dialog just opened, the activeTriggerId in the raw state would be null. But after the controlled prop sync, triggerIdProp is set.
Actually, let me think about this differently. The issue is that when triggerIdProp is set, store.select('activeTriggerId') returns triggerIdProp. So activeTriggerId === triggerId is true for the matching trigger, and that trigger's element gets set as activeTriggerElement.
But activeTriggerId in the raw state would be null (unless it was set by a real trigger press).
So the fix is:
if (activeTriggerId === triggerId && store.state.activeTriggerElement == null) {
store.update({...});
}
Wait, but this still sets activeTriggerElement when the dialog opens via controlled mode. We DON'T want that for focus return purposes.
OK let me think about this more carefully. The activeTriggerElement is used for two things:
- ARIA relationships (via
triggerPopupId and isOpenedByTrigger)
- Focus return (via
domReferenceElement)
For ARIA, we want activeTriggerElement to be set for the trigger matching triggerIdProp, regardless of how the dialog was opened.
For focus return, we want domReferenceElement to be the element that actually activated the dialog.
So the fix should be:
activeTriggerElement should be set for ARIA purposes (current behavior is fine)
domReferenceElement should NOT be set to activeTriggerElement when the dialog was opened via controlled mode
To implement this, we could:
- In
useSyncedFloatingRootContext, check if the dialog was opened via controlled mode (triggerIdProp was set) and skip setting domReferenceElement
- Or, track a separate "focus return trigger element" that's only set when the dialog is opened by a real trigger press
Option 2 seems cleaner. We could:
- When
setOpen is called with a trigger element, set both activeTriggerElement (for ARIA) and a new focusReturnTriggerElement (for focus return)
- In
useSyncedFloatingRootContext, use focusReturnTriggerElement as domReferenceElement instead of activeTriggerElement
But this would require changes to the store interface, which might be invasive.
Option 1 is simpler: in useSyncedFloatingRootContext, we check if activeTriggerElement was set via controlled prop and skip setting domReferenceElement.
How do we detect if activeTriggerElement was set via controlled prop? If store.state.activeTriggerId (raw state) is null, it means the dialog wasn't opened by a real trigger press.
Actually wait, let me re-check. When the dialog is opened via setOpen with a trigger:
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
This sets activeTriggerId = trigger.id (raw state).
When the dialog is opened via controlled prop:
activeTriggerId (raw state) is null
triggerIdProp is set
So the fix in useTriggerDataForwarding should be:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if the dialog was opened by a real trigger press
// or if no active trigger element is set yet (for controlled mode)
if (store.state.activeTriggerId != null || store.state.activeTriggerElement == null) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
Wait, this is still complicated. Let me think about this more simply.
The key insight is: we want domReferenceElement to be the element that the user activated to open the dialog. If the user clicked a Dialog.Trigger, domReferenceElement should be that trigger. If the user clicked a custom button and used openProp/triggerIdProp, domReferenceElement should NOT be set (so focus returns to the custom button).
The problem is that activeTriggerElement is currently set to the trigger matching triggerIdProp in controlled mode, which causes domReferenceElement to be set to that trigger.
I think the simplest fix is:
- In
useTriggerDataForwarding, only set activeTriggerElement when the dialog was opened by a real trigger press
- For controlled mode, don't set
activeTriggerElement in useTriggerDataForwarding
But wait, activeTriggerElement is still needed for ARIA purposes. Let me check how ARIA is handled...
Looking at the DialogTrigger component:
const popupId = store.useState('triggerPopupId', thisTriggerId);
And in the popup store:
const popupIdSelector = createSelector((state: S) => {
const popupId = state.popupElement?.id ?? state.floatingId;
return popupId || undefined;
});
So triggerPopupId uses the popup element's ID or floating ID, not the active trigger element. ARIA relationships are maintained through triggerIdProp and the trigger's own ID.
Let me also check isOpenedByTrigger:
const isOpenedByThisTrigger = store.useState('isOpenedByTrigger', thisTriggerId);
And the selector:
isOpenedByTrigger: createSelector((state: S, triggerId: string | undefined) =>
triggerOwnsOpenPopup(state, triggerId)
)
With:
function triggerOwnsOpenPopup(state: S, triggerId: string | undefined) {
return (
triggerId !== undefined && openSelector(state) && activeTriggerIdSelector(state) === triggerId
);
}
So isOpenedByTrigger checks if activeTriggerIdSelector(state) === triggerId, which is triggerIdProp ?? activeTriggerId === triggerId. This works correctly for controlled mode.
So the fix could be: in useTriggerDataForwarding, we should NOT set activeTriggerElement when the dialog was opened via controlled mode. The ARIA relationships are handled by isOpenedByTrigger which uses activeTriggerIdSelector (which considers triggerIdProp).
Let me refine the fix:
In useTriggerDataForwarding:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if this trigger actually opened the dialog
// or if no active trigger element is set yet
const isOpenedByRealTrigger = store.state.activeTriggerId != null;
if (isOpenedByRealTrigger || store.state.activeTriggerElement == null) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
Wait, this still sets activeTriggerElement when opened via controlled mode (because store.state.activeTriggerElement == null). And that's the problem!
Let me think about this differently. The issue is that when the dialog opens via controlled mode:
triggerIdProp is set (e.g., 'trigger-2')
activeTriggerId (raw) is null
activeTriggerElement (raw) is null
useTriggerDataForwarding sets activeTriggerElement to the element with id='trigger-2'
domReferenceElement is set to that element
- Focus returns to that element
What we want:
- When the dialog opens via controlled mode,
activeTriggerElement should NOT be set to a trigger element
domReferenceElement should be null, so focus returns to the previously focused element
So the fix is to NOT set activeTriggerElement when the dialog was opened via controlled mode:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if a real trigger activated the dialog
// (detected by checking if activeTriggerId was set by a trigger press, not by triggerIdProp)
const isOpenedByRealTrigger = store.state.activeTriggerId != null;
if (isOpenedByRealTrigger) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
But wait, when the dialog opens via a real trigger press:
- The trigger's
registerTrigger is called (ref callback)
setOpen is called with the trigger element
setOpenTriggerState sets activeTriggerId and activeTriggerElement
- The trigger's ref callback fires AFTER
setOpen is called
- So
store.state.activeTriggerId would be set by step 3 before step 4
Actually, the timing might be different. Let me check...
When a Dialog.Trigger is clicked:
- The click event fires
onPress is called, which triggers store.setOpen(true, createChangeEventDetails(REASONS.triggerPress, undefined, triggerElement))
setOpen in DialogStore calls setOpenTriggerState(updatedState, true, triggerElement)
- This sets
activeTriggerId and activeTriggerElement in the store
- The trigger's ref callback (
registerTrigger) is called
So by the time registerTrigger is called, activeTriggerElement is already set. And in registerTrigger:
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...
});
}
This would set activeTriggerElement again, but to the same value (since element is the trigger's own element). So this is fine.
But when the dialog opens via controlled mode:
triggerIdProp is synced
openProp is synced → open becomes true
activeTriggerId (raw) is null
activeTriggerElement (raw) is null
- Triggers mount and their ref callbacks fire
- For the trigger matching
triggerIdProp: activeTriggerId === triggerId is true (from store.select('activeTriggerId'))
activeTriggerElement is set to this trigger's element
domReferenceElement is set to this element
The fix should prevent step 7 when the dialog was opened via controlled mode.
But we need to be careful: when the dialog opens via a real trigger press, activeTriggerElement is already set by setOpenTriggerState. So we need to check if it's already set before setting it again.
Actually, I think the fix is simpler. The useTriggerDataForwarding function should only update activeTriggerElement if:
- The dialog was opened by a real trigger press (detected by
store.state.activeTriggerId != null)
- OR the dialog was opened via controlled mode AND no active trigger element is set yet
For case 1, we set activeTriggerElement to the trigger's element (even if already set, it's the same element).
For case 2, we DON'T set activeTriggerElement at all (so domReferenceElement stays null and focus returns to the previously focused element).
Wait, but for case 2, we still need activeTriggerElement for... actually, do we? Let me check where activeTriggerElement is used:
useSyncedFloatingRootContext: referenceElement = activeTriggerElement → domReferenceElement
useTriggerDataForwarding: used to track which element corresponds to each trigger
- ARIA: not directly used,
isOpenedByTrigger uses activeTriggerIdSelector
So activeTriggerElement is mainly used for domReferenceElement in the floating context. If we don't set it in controlled mode, domReferenceElement will be null, and focus will return to the previously focused element.
For ARIA purposes, isOpenedByTrigger uses activeTriggerIdSelector (which considers triggerIdProp), so ARIA relationships are maintained correctly.
OK, I think the fix is clear now. In useTriggerDataForwarding, we should NOT set activeTriggerElement when the dialog was opened via controlled mode:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if a real trigger activated the dialog
// (detected by checking raw state.activeTriggerId, not the selector which considers triggerIdProp)
const isOpenedByRealTrigger = store.state.activeTriggerId != null;
if (isOpenedByRealTrigger) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
Hmm wait, but when opened via a real trigger press, store.state.activeTriggerId is already set. And when opened via controlled mode, it's null. So this check is correct.
But there's a subtle issue: when the dialog opens via a real trigger press, the trigger's ref callback fires AFTER setOpenTriggerState sets activeTriggerId. So store.state.activeTriggerId is already set. But what about other triggers that mount later?
Actually, all triggers should be mounted by the time setOpen is called (since the user clicked a trigger to open the dialog). So when setOpen is called, all triggers are already mounted and their ref callbacks have already fired.
Wait, no. The ref callback fires when the element is mounted. So when a trigger is first rendered, its ref callback fires. When the user clicks it, setOpen is called, which sets activeTriggerId and activeTriggerElement. But the ref callback has already fired before setOpen is called.
So in the case of a real trigger press:
- All triggers mount, their ref callbacks fire
- In
registerTrigger, open is false, so neither branch is taken
- User clicks a trigger
setOpen is called with the trigger element
setOpenTriggerState sets activeTriggerId and activeTriggerElement
- Dialog is now open with
activeTriggerElement set correctly
In the case of controlled mode:
- User clicks a custom button, setting
openProp and triggerIdProp
- Dialog.Root re-renders,
useTriggerDataForwarding hooks fire
- For each trigger,
open is true, activeTriggerId (from selector) matches the matching trigger's id
- The matching trigger's
activeTriggerElement is set
domReferenceElement is set to this element
- Focus returns to this element (wrong!)
So the fix is to check if store.state.activeTriggerId != null (raw state, not selector) before setting activeTriggerElement. If it's null, it means the dialog was opened via controlled mode, not a real trigger press.
Actually wait, there's still an issue. Let me re-check the flow for a real trigger press:
- User clicks a Dialog.Trigger
- The trigger's ref callback might fire again? No, the ref is already set.
Hmm, actually I need to check if registerTrigger is called again when the trigger is re-rendered. Looking at useTriggerDataForwarding:
const registerTrigger = useStableCallback((element: Element | null) => {
baseRegisterTrigger(element);
if (!element) {
return;
}
const open = store.select('open');
const activeTriggerId = store.select('activeTriggerId');
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
if (activeTriggerId == null && open) {
store.update({...});
}
});
This callback is called whenever the trigger's ref changes. It's set in the ref prop:
ref: [buttonRef, forwardedRef, registerTrigger, triggerElementRef],
So registerTrigger is called on mount (with the element) and potentially on re-render if the ref changes.
When the trigger is first mounted:
open is false (dialog is closed)
- Neither branch is taken
When the user clicks the trigger and setOpen is called:
activeTriggerId and activeTriggerElement are set by setOpenTriggerState
- React re-renders
registerTrigger might be called again (if the ref changes)
- If so,
open is true, activeTriggerId === triggerId is true
activeTriggerElement is set again to the same element
So the fix should work. Let me also check the second branch:
if (activeTriggerId == null && open) {
store.update({...});
}
This is for when the dialog is already open and a new trigger mounts. In this case, we want to claim the first registered trigger so that focus management and ARIA relationships work. This should still be OK because activeTriggerId (raw) would be null.
OK so the fix is:
In useTriggerDataForwarding, change:
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
To:
if (activeTriggerId === triggerId) {
// Only set activeTriggerElement if a real trigger activated the dialog,
// not when triggered via controlled prop (triggerIdProp)
if (store.state.activeTriggerId != null) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
}
return;
}
Wait, but this would mean that when opened via a real trigger press, activeTriggerElement is set by setOpenTriggerState (in DialogStore.setOpen). And when registerTrigger is called on mount (before the trigger press), activeTriggerId is null and open is false, so nothing happens. After the trigger press, activeTriggerId is set by setOpenTriggerState, and registerTrigger might be called again (re-render), setting activeTriggerElement again.
But the key question is: does activeTriggerElement already have the correct value when registerTrigger is called?
When a trigger is clicked:
setOpen(true, eventDetails) is called
setOpenTriggerState sets activeTriggerId and activeTriggerElement to the trigger element
- Store updates
- React re-renders DialogTrigger
registerTrigger is called with the same element
- Now,
activeTriggerId (selector) = triggerId, so we enter the first branch
- With the fix:
store.state.activeTriggerId != null → true → we set activeTriggerElement again
This is redundant but not harmful, since we're setting it to the same value.
Now for controlled mode:
- User clicks "Open programmatically" button
setOpen(true) and setTriggerId('trigger-2') called
- React re-renders Dialog.Root
useTriggerDataForwarding for each trigger fires
- For trigger with id='trigger-2':
activeTriggerId (selector) = 'trigger-2', so we enter the first branch
- With the fix:
store.state.activeTriggerId != null → false (raw state is null) → we DON'T set activeTriggerElement
domReferenceElement stays null
- Focus returns to the previously focused element (the "Open programmatically" button) ✓
This looks correct!
But wait, there's another scenario: what if the dialog is already open (via controlled mode), and a trigger is re-mounted? Let me think...
Actually, this scenario doesn't really apply because all triggers are mounted when the dialog opens. The useTriggerDataForwarding is called for each trigger's mount, and if the dialog is already open, the second branch handles it:
if (activeTriggerId == null && open) {
store.update({...});
}
This is for when a trigger mounts after the dialog is already open. The check activeTriggerId == null uses the selector, so it checks triggerIdProp ?? activeTriggerId. If both are null, this branch claims the first trigger.
But with our fix, the first branch would also have activeTriggerId === triggerId be false (since activeTriggerId is null from the selector), so this branch wouldn't be entered. And the second branch would claim the first trigger if activeTriggerId == null.
Wait, but activeTriggerId == null && open uses store.select('activeTriggerId'), which is the selector. So if triggerIdProp is null and activeTriggerId is null, the second branch claims the first trigger. This is the correct behavior for when a popup is already open and a detached trigger mounts.
OK I think the fix is correct. Let me also consider the useTriggerDataForwarding usage in the useIsoLayoutEffect:
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
store.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates,
} as Partial<State>);
}
// ...
}, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
This updates activeTriggerElement when isMountedByThisTrigger is true. Let me check what isMountedByThisTrigger returns:
const isMountedByThisTrigger = store.useState('isMountedByTrigger', triggerId);
And the selector:
isMountedByTrigger: createSelector(
(state: S, triggerId: string | undefined) =>
activeTriggerIdSelector(state) === triggerId && popupStoreSelectors.open(state),
)
So isMountedByThisTrigger is true when activeTriggerIdSelector(state) === triggerId && open. This is similar to the first branch in registerTrigger.
With controlled mode:
activeTriggerIdSelector(state) = triggerIdProp = 'trigger-2'
- For trigger with id='trigger-2':
isMountedByThisTrigger is true
activeTriggerElement is set to this trigger's element
So the useIsoLayoutEffect would ALSO set activeTriggerElement even with our fix to registerTrigger. We need to fix this too!
Hmm, but this useIsoLayoutEffect is needed to update activeTriggerElement when the trigger's ref changes (not when it mounts). Without it, activeTriggerElement might be stale.
Let me think about this more carefully. The useIsoLayoutEffect updates activeTriggerElement when isMountedByThisTrigger is true. This happens:
- When the dialog opens and the trigger is the active trigger (via controlled mode)
- When the dialog opens and the trigger is the active trigger (via real trigger press)
For case 1 (controlled mode), we DON'T want to set activeTriggerElement.
For case 2 (real trigger press), we DO want to set activeTriggerElement (or it's already set by setOpenTriggerState).
So the fix for the useIsoLayoutEffect should be:
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
// Only update activeTriggerElement if a real trigger activated the dialog
if (store.state.activeTriggerId != null) {
store.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates,
} as Partial<State>);
}
}
// ...
}, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
Wait, but this would mean that for controlled mode, activeTriggerElement is never updated by useIsoLayoutEffect. And for real trigger press, activeTriggerElement is already set by setOpenTriggerState. So this should be fine.
Actually, let me reconsider. The useIsoLayoutEffect runs after layout. It updates activeTriggerElement when isMountedByThisTrigger is true. This ensures that if the trigger's element changes (e.g., due to ref changes), activeTriggerElement is updated.
For controlled mode, we don't want to set activeTriggerElement at all (so focus returns to the previously focused element).
For real trigger press, activeTriggerElement is already set by setOpenTriggerState.
So the fix is to add the same check to useIsoLayoutEffect:
if (isMountedByThisTrigger && store.state.activeTriggerId != null) {
store.update({...});
}
But wait, there's still an issue. For real trigger press, store.state.activeTriggerId is set by setOpenTriggerState before the trigger's ref callback fires (step 2 → step 3 → step 4 in my earlier analysis). So by the time isMountedByThisTrigger is true and useIsoLayoutEffect runs, store.state.activeTriggerId should already be set.
For controlled mode, store.state.activeTriggerId is null (raw state), so the check store.state.activeTriggerId != null would be false, and activeTriggerElement would not be set.
I think this fix is correct. Let me also check if there are other places where activeTriggerElement is set...
Actually, looking at the code more carefully, I realize there might be other components using useTriggerDataForwarding (Popover, Tooltip, etc.). Let me check:
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -rn "useTriggerDataForwarding" /base-ui/packages/react/src/ 2>/dev/null
</tool_call>