Accessibility: Focus moves to the wrong trigger when using "Open programmatically" buttons
Current behavior
In the Alert Dialog, Dialog and Popover components, there is a variant that includes the option to use multiple triggers to open the dialogs. When using the "Open Programmatically" button to open the dialog/popup, then closing it, focus moves to a different control than the one that triggered the dialog/popup.
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.
Using keyboard, move focus to the "open programmatically" button
Press Enter to activate the control and open the dialog
Press Esc or activate the close button to close the dialog
Note focus has moved back to the "Delete" button and not the "open programmatically" button as expected.
Base UI version
v1.2.0
Which browser are you using?
Chrome 145.0.7632.76
Which OS are you using?
Mac OS Tahoe 26.2
Which assistive tech are you using (if applicable)?
Keyboard
Additional context
Assistant
Let me analyze this issue. The problem is about focus management in Alert Dialog, Dialog, and Popover components. When using "Open Programmatically" buttons to open dialogs, the focus should return to the originating control when closing, but instead it moves to a different trigger.
Let me first explore the repository structure to understand how it's organized.
Assistant
Let me explore the structure more, specifically looking at the Alert Dialog, Dialog, and Popover components.
Assistant
Let me explore the alert-dialog component structure.
Assistant
The issue is about focus returning to the wrong trigger when closing dialogs opened programmatically. Let me look at the dialog/root component to understand the current focus management implementation.
Assistant
Now I understand the issue. When using "Open Programmatically" buttons to open dialogs, focus should return to the originating control when closing. Let me look at the dialog root component to understand how focus is currently managed.
Assistant
Let me now look at the DialogRoot.tsx and useDialogRoot.ts to understand the current focus management implementation.
Assistant
Let me use the bash_terminal command to read the file instead.
Assistant
The file has been displayed, now I need to look at the useDialogRoot.ts which contains the actual implementation logic.
Assistant
Now let me look at the usePopupInteractionProps function which handles focus management for popups.
Assistant
The file seems to be a .tsx file or in a different location. Let me search for it.
Assistant
I need to look for the usePopupInteractionProps function which handles focus management. Let me search for it.
Assistant
I need to search for the usePopupInteractionProps function to understand how focus is being managed. Let me search for it.
Assistant
Let me look at the popupStoreUtils.ts file to understand how focus management is implemented.
Assistant
Now let me look at where focus is being returned when the popup closes. Let me check the store implementation.
Assistant
Let me look at the FloatingFocusManager to understand how focus is returned when the popup closes:
Assistant
Let me look at the FloatingFocusManager more closely to understand how domReference is determined and how it handles programmatic opens:
Assistant
Let me look at how the domReference element is set and tracked in the floating tree store:
Assistant
Let me understand how the FloatingRootStore is used. The domReferenceElement is set based on referenceElement. Let me now look at how referenceElement is synchronized and what happens when a dialog is opened programmatically vs via a trigger.
I need to understand the core issue:
When a dialog is opened by pressing a trigger (e.g., "Delete" button), focus should return to that trigger when closing.
When a dialog is opened programmatically (e.g., "Open Programmatically" button), focus should return to that button when closing.
Currently, it seems like focus is returning to the wrong trigger when closing dialogs opened programmatically.
Let me look at the sync mechanism and how domReferenceElement is updated when the popup is opened programmatically.
Assistant
Let me continue analyzing the issue. I need to understand how focus is managed when a dialog is opened programmatically.
The issue is:
When a dialog is opened programmatically (e.g., via "Open Programmatically" button), focus should return to that button when closing.
Currently, focus is returning to a different trigger (e.g., "Delete" button instead of "Open Programmatically" button).
Let me look at how the domReferenceElement is set when a dialog is opened programmatically. The key is in the FloatingFocusManager's getReturnElement() function, which uses domReference to determine where to return focus.
Let me trace through the code:
When FloatingFocusManager closes, it calls getReturnElement() which returns domReference if connected, or falls back to getPreviouslyFocusedElement().
domReference is obtained from store.useState('domReferenceElement') which is the FloatingRootStore.
The domReferenceElement is initialized to in the .
Assistant
Let me look at how the DialogHandle works and how the activeTriggerElement is set when opening programmatically:
Assistant
Now I can see the issue more clearly. When a dialog is opened programmatically via DialogHandle.open(), it creates a ChangeEventDetails with the trigger parameter set to the triggerElement (if provided). Let me trace how this trigger flows through the system.
Let me look at createChangeEventDetails to understand the details structure.
Assistant
Now I understand the issue better. Let me look at how the DialogStore handles the setOpen call and whether it properly sets activeTriggerElement when opening programmatically. The key is that when opening via DialogHandle.open(), the triggerElement is passed to createChangeEventDetails, but I need to check if this is used to set the activeTriggerElement in the store.
Assistant
Now I understand the issue better. Let me look at how the Dialog.Popup component uses the FloatingFocusManager:
Assistant
Let me look at the DialogPopup component to see how it uses FloatingFocusManager.
Assistant
Now I need to understand the actual use case. Let me look at the docs example for "Controlled mode with multiple triggers":
Assistant
Let me search for the documentation examples more broadly.
Assistant
Now I need to understand the issue. Let me look at one of these demo files to understand how the "Open Programmatically" button works.
Assistant
Assistant
Let me look at how triggerIdProp is synced and how the store determines the active trigger.
Assistant
Assistant
Let me run the test to see what it's testing.
Assistant
Let me continue reading the test file to understand more about the expected behavior, especially around focus management.
Assistant
Let me look at how isMountedByTrigger is used and then write a test to reproduce the issue.
Assistant
Let me look at the specific code to understand how isMountedByTrigger is used:
Assistant
Now I have a good understanding of the issue. Let me trace through the code flow and implement a fix.
Root Cause Analysis
When a Dialog is opened programmatically (via a button that's NOT a Dialog.Trigger):
setOpen(true) is called from React state, which triggers onOpenChange
Since no trigger element was involved, eventDetails.trigger is undefined
setOpenTriggerState sets activeTriggerId = null and activeTriggerElement = null
BUT in controlled mode, triggerIdProp is synced to the store (e.g., 'trigger-2')
In useTriggerDataForwarding, activeTriggerId comes from store.select('activeTriggerId') which uses activeTriggerIdSelector = triggerIdProp ?? activeTriggerId
So activeTriggerId returns 'trigger-2' (from triggerIdProp)
Assistant
Assistant
Let me find the correct path for useStableCallback.
Assistant
Assistant
Now I understand useStableCallback - it stabilizes the callback reference so it's always the same between renders, while updating the implementation in an effect. When the callback runs, it uses the latest closure variables from the last render.
Let me now implement the fix. I need to:
Change isMountedByTrigger in store.ts to use state.activeTriggerId instead of activeTriggerIdSelector(state)
Change the callback in popupStoreUtils.ts to use store.state.activeTriggerId instead of store.select('activeTriggerId'), and add a check for triggerIdProp in the "first registered trigger" condition
Assistant
Let me look at the code in the popupStoreUtils.ts file more closely to understand the exact changes needed.
Assistant
Now I understand the issue clearly. Let me trace through the bug:
When a dialog is opened programmatically via the "Open Programmatically" button, triggerIdProp is set to a value like 'trigger-2' (from the controlled mode prop)
isMountedByTrigger uses activeTriggerIdSelector(state) which returns state.triggerIdProp ?? state.activeTriggerId
So isMountedByThisTrigger becomes true for trigger-2 because triggerIdProp === 'trigger-2'
The useIsoLayoutEffect in useTriggerDataForwarding then sets activeTriggerElement to trigger-2's element
When the dialog closes, FloatingFocusManager returns focus to domReference (which is activeTriggerElement)
But activeTriggerElement is trigger-2's element, not the "Open Programmatically" button
The fix is to change isMountedByTrigger to use state.activeTriggerId (the actual trigger that opened the dialog) instead of activeTriggerIdSelector(state) (which includes triggerIdProp).
Assistant
The edit failed because I didn't provide proper line ranges. Let me first see what's at those line numbers.
Assistant
I need to see the exact lines around isMountedByTrigger in store.ts to make a proper edit.
Let me view the exact lines around the isMountedByTrigger selector.
Assistant
Now I understand the issue. The isMountedByTrigger selector uses activeTriggerIdSelector(state) which includes triggerIdProp. This causes isMountedByTrigger to return true even when the popup was opened programmatically with a triggerIdProp, because the selector returns triggerIdProp ?? activeTriggerId.
The fix is to change isMountedByTrigger to use state.activeTriggerId directly (not through activeTriggerIdSelector), so it only returns true when the popup was actually opened by a registered trigger.
Assistant
The edit command is failing. Let me check the format of the tool call. I need to use the correct tool call format.
Assistant
Let me use sed to make the change:
Assistant
Let me check if the change was applied correctly:
Assistant
The sed didn't work because of the multi-line pattern. Let me try a different approach using sed with a simpler pattern:
Assistant
The sed command didn't work because the pattern spans multiple lines. Let me use sed with a different approach - I'll replace just the specific part of the line that uses activeTriggerIdSelector(state) with state.activeTriggerId.
Assistant
Let me verify my change and then continue with the fix.
Assistant
Oops, the sed command replaced ALL occurrences, not just the one in isMountedByTrigger. I need to revert and only change line 207. Let me check the current state and fix it properly.
Assistant
I see - the sed replaced ALL occurrences, but I only want to change the isMountedByTrigger selector (line 207). The other two (triggerOwnsOpenPopup and isTriggerActive) should still use activeTriggerIdSelector for controlled mode compatibility. Let me revert and only change line 207.
Assistant
Good, I've reverted the store.ts file. Now let me implement the fix more carefully. I only need to change the isMountedByTrigger selector to use state.activeTriggerId instead of activeTriggerIdSelector(state).
Assistant
Let me implement the fix step by step. First, I'll create a script to reproduce the issue.
Assistant
Now I need to implement the actual fix. Let me carefully change only line 207 in store.ts to use state.activeTriggerId instead of activeTriggerIdSelector(state) in the isMountedByTrigger selector.
Assistant
Let me verify my change was applied correctly.
Assistant
Good, the first fix is in place. Now I need to verify the git diff and also handle the second part of the fix - the callback in useTriggerDataForwarding.
Assistant
Assistant
I need to see the callback code in popupStoreUtils.ts to understand how to fix it.
Assistant
Now I understand the issue completely. The problem is that domReferenceElement is not updated when referenceElement (which is activeTriggerElement from the popup store) becomes null. This causes domReferenceElement to still point to a previously registered trigger's element.
I need to fix useSyncedFloatingRootContext to always update domReferenceElement, even when referenceElement is null.
Assistant
Let me see the full context around line 85.
Assistant
Now I understand the issue. The domReferenceElement is only updated when referenceElement is an element. When referenceElement becomes null (e.g., when a popup is opened programmatically without a registered trigger), domReferenceElement is not updated and stays pointing to the previous trigger's element.
Let me fix this by always updating domReferenceElement, including setting it to null when referenceElement is not an element.
Assistant
Let me check what happened and fix it properly.
Assistant
I see the sed command created duplicates. Let me fix this properly.
Assistant
Let me apply the fix to useSyncedFloatingRootContext.ts properly. I need to change the conditional that only updates domReferenceElement when referenceElement is an element, to always update it.
Assistant
Let me view the file more carefully and then apply the fix:
Assistant
Now I can see the exact lines. I need to replace lines 85-87 (the conditional) with a single line that always sets domReferenceElement.
Assistant
Let me verify the fix was applied correctly.
Assistant
Good, the fix is in place. Now let me verify both changes are complete and run the existing tests to ensure the fix doesn't break anything.
Assistant
Let me see the full diff of my changes:
Assistant
Now let me run the existing tests to ensure my changes don't break anything. Let me start with the dialog-related tests.
Assistant
Let me continue watching the test output:
Assistant
All Dialog tests passed. Now let me run the Popover tests to ensure the fix works for Popover as well.
Assistant
Popover tests passed. Now let me run the Alert Dialog tests:
Assistant
All Alert Dialog tests passed. Now let me run the popup store utilities tests to ensure my changes don't break the core popup functionality:
Assistant
Let me also run the FloatingFocusManager tests to ensure focus management still works correctly:
Assistant
All tests pass! Let me run a broader set of tests to ensure my changes don't break anything else:
Assistant
Let me run a broader set of tests to ensure nothing is broken:
Assistant
Looking at my changes, let me verify they are complete and correct:
Assistant
Now let me create a simple test file to verify that the fix works for the specific scenario described in the issue:
Assistant
Let me clean up the test files I created and remove them:
Assistant
I need to also fix the registerTrigger callback in popupStoreUtils.ts to prevent it from setting activeTriggerElement when the popup is opened programmatically. Let me check the current code:
Assistant
I need to also fix the registerTrigger callback in popupStoreUtils.ts to use store.state.activeTriggerId instead of store.select('activeTriggerId'). This is necessary because the callback might run when a trigger mounts after the popup opens programmatically, and store.select('activeTriggerId') includes triggerIdProp.
Assistant
Let me verify the change was applied correctly:
Assistant
Good. But now I need to also add a check for triggerIdProp in the second condition to prevent the "first registered trigger" logic from triggering when triggerIdProp is set:
Assistant
I need to add a check for triggerIdProp in the second condition. Let me apply the fix:
Assistant
Let me verify the changes:
Assistant
Now let me run the tests again to verify all changes work correctly:
Assistant
All tests passed. Let me also run the alert dialog and popup store utils tests to ensure complete coverage:
Assistant
All tests pass. Let me now review the complete set of changes I've made:
Assistant
Let me summarize the changes I've made and submit them:
Summary of Changes
The issue is that when a Dialog, Alert Dialog, or Popover is opened programmatically (via a button that's not a registered trigger), focus incorrectly returns to a different trigger when closing.
Root Cause
The problem had two parts:
domReferenceElement was not being updated to null when referenceElement (the active trigger element) became null, so it retained the stale value from a previous trigger.
The registerTrigger callback was using a selector that included triggerIdProp, causing triggers to incorrectly claim themselves when the popup was opened programmatically with a triggerIdProp.
Changes Made
Assistant
Let me call submit properly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Recommend keeping track of focus and returning it to the originating control.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /base-ui, current file: none) bash-$
referenceElement
FloatingRootStore
The problem is that when opening programmatically, the referenceElement/domReferenceElement may not be set to the programmatic trigger. Let me check how this works in the popup store context.
Let me look at the useSyncedFloatingRootContext hook to understand how it syncs state.
Now I understand the issue clearly. Let me summarize:
The demo has multiple triggers (trigger-1, trigger-2, trigger-3) and a "Open programmatically" button
When "Open programmatically" is clicked, it sets triggerId to 'trigger-2' and open to true
The handleOpenChange callback is called, which sets setTriggerId(eventDetails.trigger?.id ?? null)
When the dialog is closed, focus should return to the "Open programmatically" button (the one that triggered the open)
But focus is returning to 'trigger-2' instead, because that's what triggerId was set to
The issue is in how focus is tracked. Let me trace the flow:
User clicks "Open programmatically" button
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Root receives open={true} and triggerId="trigger-2"
The Dialog opens
When closing, the onOpenChange handler sets setTriggerId(eventDetails.trigger?.id ?? null)
But eventDetails.trigger is the element that was last clicked (trigger-2 in the DOM), not the "Open programmatically" button
Wait, let me re-read the issue. The problem is:
User presses Enter on "Open programmatically" button (focus is on it)
Dialog opens
User closes dialog (Esc or Close button)
Focus should return to "Open programmatically" button, but it goes to "Delete" button (or "trigger-2" in the demo)
Let me trace through what happens:
The "Open programmatically" button is clicked
The dialog opens
When opened programmatically (via setOpen(true)), the onOpenChange handler is called
In the handler, triggerId is set based on eventDetails.trigger?.id, but since this was opened programmatically, the trigger might be incorrectly determined
Actually wait, let me look more carefully at the DialogStore.setOpen method:
typescript
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;
}
So when closing, it correctly passes the active trigger element. But when opening programmatically, the eventDetails.trigger should be the "Open programmatically" button.
The trigger is set to triggerElement which is looked up from the triggerElements map using the triggerId. But this is NOT the "Open programmatically" button - it's the trigger element registered with the Dialog component.
But wait, in the demo, the "Open programmatically" button is NOT a Dialog.Trigger, so it won't be registered in triggerElements. Let me look at what happens:
User clicks "Open programmatically" button
setTriggerId('trigger-2') and setOpen(true) are called
This calls onOpenChange(true, eventDetails) in the DialogRoot
In the store's setOpen, setOpenTriggerState is called which sets activeTriggerId and activeTriggerElement based on the trigger parameter
The issue is that when opening programmatically with setOpen(true) (not via DialogHandle), there's no trigger in the eventDetails. So setOpenTriggerState won't set the active trigger.
setOpenTriggerState is called with eventDetails.trigger. If no trigger is provided (as in programmatic open via React state), then activeTriggerId won't be set to the new trigger.
But the issue says focus moves to the wrong trigger. Let me look at where triggerIdProp is used to determine the active trigger.
Let me look at useTriggerDataForwarding to see if it uses triggerIdProp.
Actually, I need to look at how triggerIdProp is synchronized with the store. Let me search for where it's set.
Let me look at the rendered popup component and see how triggerId is used.
Actually, the key insight is in the FloatingFocusManager. When closing, it returns focus to domReference. The domReference is synced from activeTriggerElement via useSyncedFloatingRootContext.
The question is: what is activeTriggerElement when the dialog is closed?
Looking at usePopupStore and how the triggerIdProp is handled...
Actually, let me look at the popup store more carefully. The triggerIdProp comes from props and is synced via useSyncedValues. Let me find where it's synced.
Actually, let me look at how the Popup component handles triggerId.
Now I can see the flow. Let me trace through what happens:
When triggerIdProp is set on Dialog.Root, it's synced to the store via useControlledProp
The store uses activeTriggerIdSelector which is state.triggerIdProp ?? state.activeTriggerId
When opening programmatically without a Dialog.Trigger (i.e., the "Open programmatically" button in the demo), eventDetails.trigger is undefined
So setOpenTriggerState won't update activeTriggerId or activeTriggerElement
The triggerIdProp is synced separately, so the active trigger is determined by triggerIdProp
But the issue is about focus. When the dialog closes, FloatingFocusManager returns focus to domReference, which is synced from activeTriggerElement via useSyncedFloatingRootContext.
Let me trace through what happens:
"Open programmatically" button is clicked
setOpen(true) is called
The dialog opens
activeTriggerElement is determined by... what?
When setOpenTriggerState is called with trigger being undefined:
So if open is true and trigger is undefined, activeTriggerId would be undefined and activeTriggerElement would be null.
But wait, the activeTriggerIdSelector uses triggerIdProp ?? activeTriggerId. So if triggerIdProp is set, the active trigger ID would be the triggerIdProp value.
But activeTriggerElement is NOT derived from triggerIdProp. It's set by setOpenTriggerState and updated when triggers are registered.
So the issue might be:
When opening via "Open programmatically" button, activeTriggerElement is set to null (since no trigger is involved)
But activeTriggerId (from selector) might be the triggerIdProp value
When closing, FloatingFocusManager returns focus to domReference, which is derived from activeTriggerElement (not the selector)
But activeTriggerElement might still be null, or it might be pointing to the wrong element
Wait, let me look at useSyncedFloatingRootContext again:
So domReferenceElement is only set if activeTriggerElement is an Element. If it's null, domReferenceElement won't be updated.
And in FloatingFocusManager, the getReturnElement() function:
typescript
if (resolvedReturnFocusValue === true) {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
So if domReference is not connected (or is null), it falls back to getPreviouslyFocusedElement().
The issue is that domReference (which is domReferenceElement from the FloatingRootStore) might be stale from a previous open. If the dialog was opened previously by clicking "trigger-1", domReference would be "trigger-1". Then when opening programmatically, activeTriggerElement is null, but domReference isn't updated (because the sync effect doesn't update it when activeTriggerElement is not an element).
Actually, wait. Let me look at the sync effect more carefully:
When referenceElement (which is activeTriggerElement) is null, the effect only updates open, floatingId, referenceElement, and floatingElement. The domReferenceElement is NOT updated.
So if domReferenceElement was previously set to "trigger-1", and then the dialog is opened programmatically (setting activeTriggerElement to null), domReferenceElement still points to "trigger-1".
This is the bug! When the dialog is opened programmatically (via a button that's not a Dialog.Trigger), the domReferenceElement is not updated, so it still points to the previous trigger.
The fix should be: when opening programmatically, we need to update domReferenceElement to reflect that the open wasn't triggered by a registered trigger. The question is what to set it to.
Looking at the issue description:
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.
So the expected behavior is:
If the dialog was opened by a trigger, return focus to that trigger
If the dialog was opened programmatically (by a button that's not a trigger), return focus to that button
The problem is that when opening programmatically, the button that triggered the open is not a registered trigger, so its element is not known to the popup store.
I think the fix should be in one of these places:
In useSyncedFloatingRootContext: When open changes from false to true and referenceElement (activeTriggerElement) is null, don't update domReferenceElement to preserve the previous value... no wait, that's the opposite of what we want.
In FloatingFocusManager: When returning focus, check if the popup was opened programmatically and if so, return focus to the previously focused element instead of the reference element.
In the popup store: When opening programmatically, track the "programmatic trigger" element separately.
Actually, I think the cleanest fix is to update domReferenceElement to null when referenceElement becomes null (meaning the popup was opened programmatically without a registered trigger). Then, FloatingFocusManager will fall back to getPreviouslyFocusedElement(), which should be the button that was clicked.
Let me think about this more carefully:
When "Open programmatically" button is clicked:
The user's focus is on the "Open programmatically" button
The button's onClick handler calls setOpen(true) and setTriggerId('trigger-2')
The dialog opens with activeTriggerElement = null (since no trigger was involved in the open)
The user closes the dialog
FloatingFocusManager tries to return focus to domReference, which is still pointing to the previous trigger
The fix: when activeTriggerElement is null and the popup opens, we should NOT update domReferenceElement to preserve... wait, no. The issue is that domReferenceElement is stale.
Actually, I think the fix is simpler. When the popup opens programmatically (without a registered trigger), the domReferenceElement should be set to null (or the previously focused element). Then FloatingFocusManager will fall back to getPreviouslyFocusedElement().
But how do we know the popup was opened programmatically? We could check if activeTriggerElement is null when open changes from false to true.
The issue is that when referenceElement is null (or not an Element), we don't update domReferenceElement. So if it was previously set to something else, it stays as is.
The fix: we should always update domReferenceElement, setting it to null when referenceElement is not an Element:
When nextOpen is true, the condition !nextOpen is false, so eventDetails.trigger is not set from activeTriggerElement. And setOpenTriggerState is called with eventDetails.trigger which is undefined.
So activeTriggerId = undefined (from trigger?.id) and activeTriggerElement = null.
But wait, the store also has triggerIdProp which is synced from props. And activeTriggerIdSelector uses triggerIdProp ?? activeTriggerId.
So when the popup is open, activeTriggerIdSelector returns triggerIdProp which is 'trigger-2'. But activeTriggerElement is still null.
In useSyncedFloatingRootContext, referenceElement is activeTriggerElement which is null, so domReferenceElement is not updated. It remains pointing to the previous trigger.
So the fix is to update domReferenceElement to null when referenceElement is not an Element, OR to find another way to handle this case.
Actually, I realize now that the activeTriggerElement should be set when the popup opens via triggerIdProp. Let me look at how triggerIdProp is used to set activeTriggerElement.
Looking at useTriggerDataForwarding:
typescript
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 so trigger-owned focus
// management and ARIA relationships work.
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
});
So when a trigger is registered and its ID matches the activeTriggerId (which could be from triggerIdProp), it updates activeTriggerElement.
But the issue is: what if there's no trigger registered for the triggerIdProp value? In the demo, triggerId='trigger-2' but when opening programmatically, the "trigger-2" button is not clicked, so the trigger is registered but not set as active.
Actually wait, triggers are registered when they mount, regardless of whether they're clicked. So trigger-2's trigger element IS registered in triggerElements, but activeTriggerElement is not set to it because setOpenTriggerState is called with trigger being undefined.
Hmm, but in useTriggerDataForwarding, when the trigger is registered:
typescript
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
This checks if activeTriggerId === triggerId. The activeTriggerId comes from activeTriggerIdSelector which is triggerIdProp ?? activeTriggerId. So if triggerIdProp is 'trigger-2' and this is trigger-2's registration callback with triggerId='trigger-2', then activeTriggerId === triggerId would be true, and activeTriggerElement would be set.
But the issue is timing: when does the trigger get registered relative to when the popup opens?
If the trigger is already registered when the popup opens, and triggerIdProp is set, then useTriggerDataForwarding's effect should update activeTriggerElement... let me check.
Actually, looking at useTriggerDataForwarding more carefully:
So isMountedByThisTrigger is true when the popup is mounted and was opened by this trigger. If the popup was opened programmatically (not by any registered trigger), then isMountedByTrigger would be false for all triggers.
Hmm, but activeTriggerIdSelector returns triggerIdProp ?? activeTriggerId. If triggerIdProp is set to 'trigger-2', then isMountedByTrigger('trigger-2') would return true (assuming the popup is mounted).
Wait, but when opening programmatically:
triggerIdProp is set to 'trigger-2' (from the parent component)
activeTriggerId (the store state, not the selector) is undefined (because setOpenTriggerState was called with undefined trigger)
activeTriggerIdSelector returns triggerIdProp which is 'trigger-2'
isMountedByTrigger('trigger-2') returns true
So the trigger-2 component's isMountedByThisTrigger becomes true, and its effect runs, setting activeTriggerElement to trigger-2's element.
But wait, this is wrong! The popup was opened programmatically, not by clicking trigger-2. The triggerIdProp is just for controlled mode to know which trigger "owns" the popup, not to indicate that the popup was opened BY that trigger.
I think I need to understand the purpose of triggerIdProp better. Looking at the docs:
ID of the trigger that the dialog is associated with. This is useful in conjunction with the open prop to create a controlled dialog.
So triggerIdProp is for controlled mode to indicate which trigger the dialog is "associated with" for rendering purposes, not necessarily which trigger opened it.
But the issue is that useTriggerDataForwarding uses triggerIdProp (via activeTriggerIdSelector) to determine which trigger to set as active. This is wrong for programmatic opens.
Actually wait, let me re-read useTriggerDataForwarding:
typescript
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;
}
...
});
This runs when a trigger is registered. It sets activeTriggerElement to the registered element if activeTriggerId === triggerId.
So when the popup opens with triggerIdProp='trigger-2':
The popup opens
Trigger components re-render
When trigger-2 mounts/registers, activeTriggerId (from selector) is 'trigger-2'
activeTriggerElement is set to trigger-2's element
This means activeTriggerElement IS set to trigger-2's element, not null. And domReferenceElement is set to trigger-2's element. So when the popup closes, focus returns to trigger-2.
But the user clicked the "Open programmatically" button, not trigger-2. So focus should return to the "Open programmatically" button.
Now I understand the bug! The issue is that:
triggerIdProp is used to associate the dialog with a trigger for controlled mode
But when the dialog opens programmatically (without a trigger click), triggerIdProp is incorrectly used to determine which trigger element is the "active" one
This causes focus to return to the wrong trigger when closing
The fix should be to NOT set activeTriggerElement from triggerIdProp when the dialog was opened programmatically. Instead, we should set it based on the actual trigger that opened the dialog.
Let me look at the code flow more carefully. The key issue is in useSyncedFloatingRootContext:
This gets activeTriggerElement from the popup store. When the popup is opened programmatically with triggerIdProp='trigger-2', activeTriggerElement ends up being trigger-2's element (via useTriggerDataForwarding).
The fix could be in useTriggerDataForwarding: don't set activeTriggerElement based on triggerIdProp. Instead, only set it when the trigger actually opened the popup.
But wait, there's another place where activeTriggerElement is set: setOpenTriggerState. When opening via DialogHandle.open(triggerId), this sets activeTriggerElement to the trigger element from triggerElements.getById(triggerId). So the correct trigger element IS set.
The issue is when opening via React state (controlled mode without DialogHandle). In this case, setOpenTriggerState is called with trigger being undefined, so activeTriggerElement is not set. But then useTriggerDataForwarding sets it based on triggerIdProp.
I think the fix should be:
When opening programmatically (without a trigger), activeTriggerElement should be null (or the previously focused element)
useTriggerDataForwarding should NOT set activeTriggerElement based on triggerIdProp alone
Let me look at the purpose of useTriggerDataForwarding again:
typescript
if (activeTriggerId === triggerId) {
store.update({
activeTriggerElement: element,
...(open ? stateUpdates : null),
} as Partial<State>);
return;
}
This sets activeTriggerElement to the registered element if the registered trigger's ID matches the active trigger ID. This is used to forward the element reference from the DOM to the store.
The issue is that activeTriggerId uses triggerIdProp when set. So even if the popup was opened programmatically, if triggerIdProp is set to a specific trigger ID, activeTriggerElement will be set to that trigger's element.
I think the fix should be to distinguish between:
activeTriggerId - the ID of the trigger that actually opened the popup
triggerIdProp - the ID of the trigger associated with the popup (for controlled mode)
And only set activeTriggerElement based on activeTriggerId (the actual opening trigger), not triggerIdProp.
But looking at the code, activeTriggerIdSelector uses triggerIdProp ?? activeTriggerId, which means they're treated as equivalent. This seems wrong.
Actually, let me look at what activeTriggerIdSelector is used for:
isOpenedByTrigger: checks if the popup is open and was activated by a trigger with the given ID
isTriggerActive: checks if the trigger is currently active
isMountedByTrigger: checks if the popup is mounted and was activated by a trigger with the given ID
triggerProps: gets the props for a trigger (active vs inactive)
triggerPopupId: gets the popup id for the active trigger
For most of these, using triggerIdProp ?? activeTriggerId makes sense for controlled mode. The issue is specifically with focus management.
I think the fix should be to NOT use triggerIdProp for determining activeTriggerElement in useTriggerDataForwarding. Instead, only use the actual activeTriggerId (the store state).
Wait, but store.select('activeTriggerId') uses the selector which includes triggerIdProp. So I need to access the store state directly.
Let me think about this differently. The core issue is:
When opening programmatically, activeTriggerElement should reflect the actual trigger element (or be null if there's no trigger)
triggerIdProp is for controlled mode to associate the popup with a trigger
These two concepts are being conflated
The fix could be:
In useTriggerDataForwarding, check if the trigger actually opened the popup (not just if triggerIdProp matches)
In useSyncedFloatingRootContext, use a different approach to determine domReferenceElement
Actually, looking at this more, I think the cleanest fix is in useTriggerDataForwarding. The effect that runs when isMountedByThisTrigger becomes true should NOT run when the popup was opened programmatically.
But how do we know if the popup was opened programmatically? We could check if activeTriggerId (the store state, not the selector) equals triggerId.
Actually, I realize now that the issue might be simpler. Let me look at the sync effect in useTriggerDataForwarding:
typescript
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
store.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates,
} as Partial<State>);
}
}, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
This runs when isMountedByThisTrigger changes. isMountedByThisTrigger is based on isMountedByTrigger(triggerId) which uses activeTriggerIdSelector(state) === triggerId.
If triggerIdProp is set to 'trigger-2' and the popup opens, isMountedByThisTrigger for trigger-2 becomes true (because activeTriggerIdSelector returns 'trigger-2' from triggerIdProp).
So the fix could be to use activeTriggerId (the store state) instead of activeTriggerIdSelector for determining isMountedByThisTrigger. This way, if the popup was opened programmatically (without a trigger), activeTriggerId would be null/undefined, and no trigger would have isMountedByThisTrigger true.
This would mean isMountedByTrigger is true only when the popup was opened by a specific trigger (i.e., activeTriggerId was set by that trigger). If the popup was opened programmatically, activeTriggerId would be null/undefined, and isMountedByTrigger would be false for all triggers.
But wait, isMountedByTrigger is used for isMountedByThisTrigger in useTriggerDataForwarding, which is also used for rendering the popup (deciding which trigger's popup to render). Let me check how it's used elsewhere.
Looking at the grep output:
code
isMountedByTrigger: createSelector(
It seems like it's used in useTriggerDataForwarding. Let me also check the popover component since the issue mentions it too.
Actually, I think the issue is broader. The activeTriggerIdSelector is used in multiple places to determine the "active" trigger, and it includes triggerIdProp because in controlled mode, the triggerIdProp indicates which trigger owns the popup.
But for focus management, we should use the actual trigger that opened the popup, not the triggerIdProp.
I think the fix should be:
Add a new selector that returns activeTriggerId (the store state, not the selector)
Use this new selector for focus management purposes
Keep using activeTriggerIdSelector (which includes triggerIdProp) for other purposes like rendering
Let me also check if there are other places where this matters.
Actually, let me step back and think about the fix more holistically.
The issue is:
User clicks "Open programmatically" button
Dialog opens with triggerIdProp='trigger-2' (set by the parent component)
useTriggerDataForwarding sets activeTriggerElement to trigger-2's element
When closing, focus returns to trigger-2 instead of the "Open programmatically" button
The fix should be:
When opening programmatically, activeTriggerElement should be null (or the "Open programmatically" button's element)
Since the "Open programmatically" button is not a registered trigger, we can't easily get its element
So activeTriggerElement should be null, and FloatingFocusManager should fall back to getPreviouslyFocusedElement()
The simplest fix is to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state). This way, activeTriggerElement won't be set based on triggerIdProp alone.
But wait, I need to be careful about side effects. Let me check all uses of isMountedByTrigger:
isMountedByTrigger is used in useTriggerDataForwarding to determine isMountedByThisTrigger
isMountedByThisTrigger is used to:
Update activeTriggerElement in useTriggerDataForwarding
Possibly for rendering purposes (deciding which trigger's popup to render)
For (1), we want to only set activeTriggerElement when the popup was actually opened by the trigger.
For (2), I'm not sure if there's rendering logic based on isMountedByTrigger. Let me search.
Actually, let me look at the DialogRoot test to understand the expected behavior:
<tool_call>
<function=bash_terminal>
<parameter=command>
cat /base-ui/packages/react/src/dialog/root/DialogRoot.test.tsx | head -200
</tool_call>
The registerTrigger callback sets activeTriggerElement to trigger-2's element
When the dialog closes, FloatingFocusManager returns focus to trigger-2 instead of the "Open programmatically" button
Fix Plan
The fix involves two changes:
In store.ts: Change isMountedByTrigger to use state.activeTriggerId (the actual trigger that opened the popup) instead of activeTriggerIdSelector(state) (which includes triggerIdProp)
In popupStoreUtils.ts: Change the fallback condition in registerTrigger to not apply when triggerIdProp is set, so programmatic opens don't claim a trigger
Let me re-examine the root cause more carefully.
Looking at the code flow:
When a popup is opened programmatically (via setOpen(true) from React state), the onOpenChange callback is called
In DialogStore.setOpen, setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger) is called
Since eventDetails.trigger is undefined (programmatic open), activeTriggerId and activeTriggerElement are set to the values based on undefined
But wait, triggerId would be undefined, not a string. Let me re-read the code...
Actually, triggerId is defined as const triggerId = trigger?.id ?? null;. So if trigger is undefined, triggerId = null.
So when open is true and trigger is undefined:
triggerId = null
Condition if (triggerId || open) is if (null || true) = true
state.activeTriggerId = null
state.activeTriggerElement = null
So activeTriggerId (the store state) is null, not 'trigger-2'.
But then activeTriggerIdSelector returns triggerIdProp ?? activeTriggerId = 'trigger-2' ?? null = 'trigger-2'.
Now in useTriggerDataForwarding:
typescript
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;
}
...
});
Here, store.select('activeTriggerId') uses activeTriggerIdSelector, which returns 'trigger-2'.
If this is trigger-2's registration callback, then triggerId is 'trigger-2'.
So activeTriggerId === triggerId is 'trigger-2' === 'trigger-2', which is true.
And activeTriggerElement is set to trigger-2's element.
So the bug is in useTriggerDataForwarding: it uses store.select('activeTriggerId') which includes triggerIdProp, so it incorrectly sets activeTriggerElement to a registered trigger's element even when the popup was opened programmatically.
Now I need to think about the fix. The fix should be to NOT set activeTriggerElement based on triggerIdProp. Instead, only set it based on the actual trigger that opened the popup (activeTriggerId the store state, not the selector).
One approach: Change useTriggerDataForwarding to access the store state directly instead of using the selector.
But wait, there's also the effect:
typescript
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
store.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates,
} as Partial<State>);
}
}, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
isMountedByThisTrigger is based on isMountedByTrigger(triggerId), which uses activeTriggerIdSelector(state).
So the fix should be to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state).
But wait, I also need to consider the effect inside registerTrigger. Let me check if that's also affected...
Actually, the registerTrigger callback is used for the trigger ref. When the trigger element is registered, this callback is called. The callback checks activeTriggerId === triggerId and if true, sets activeTriggerElement.
But store.select('activeTriggerId') uses the selector which includes triggerIdProp. So if triggerIdProp is set to a specific trigger ID, even if the popup was opened programmatically, activeTriggerElement will be set to that trigger's element.
The fix should be to access the store state directly in the callback, not through the selector. But wait, we can't easily access the store state in a callback...
Actually, let me think about this differently. The issue is that activeTriggerElement should be set based on the actual trigger that opened the popup, not based on triggerIdProp.
When a trigger is registered and triggerIdProp matches its ID, we should NOT set activeTriggerElement unless the popup was actually opened by that trigger.
But how do we know if the popup was opened by a trigger? We can check if activeTriggerId (the store state) matches the trigger's ID.
So the fix is to change store.select('activeTriggerId') to store.state.activeTriggerId (or store.select('activeTriggerId') if we remove triggerIdProp from the selector for this purpose).
Wait, but activeTriggerIdSelector is used in many places:
isOpenedByTrigger - to check if the popup was opened by a specific trigger
isTriggerActive - to check if a trigger is active
isMountedByTrigger - to check if the popup is mounted and opened by a specific trigger
triggerProps - to get the correct props for a trigger
triggerPopupId - to get the popup ID for the active trigger
For most of these, using triggerIdProp ?? activeTriggerId makes sense for controlled mode. But for isMountedByTrigger (used in useTriggerDataForwarding), we should use activeTriggerId only.
So the fix is to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state).
Let me also check if there are other places that need to be fixed...
Actually, looking at the registerTrigger callback again:
This uses activeTriggerIdSelector, which includes triggerIdProp. So this is also affected.
But wait, the effect:
typescript
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
store.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates,
} as Partial<State>);
}
}, [isMountedByThisTrigger, ...]);
isMountedByThisTrigger is based on isMountedByTrigger, which uses activeTriggerIdSelector. If I change isMountedByTrigger to use state.activeTriggerId, then this effect will only run when the popup was actually opened by the trigger.
And for the registerTrigger callback, I should also change store.select('activeTriggerId') to access the store state directly.
Actually wait, let me re-think. The registerTrigger callback is called when a trigger element is registered. At this point, we want to set activeTriggerElement if this trigger is the one that opened the popup.
If the popup was opened programmatically (with triggerIdProp), activeTriggerId (store state) is null/undefined. So we should NOT set activeTriggerElement in the callback.
If I change the callback to use state.activeTriggerId instead of store.select('activeTriggerId'), then the callback will only set activeTriggerElement when the popup was actually opened by a trigger.
But there's a problem: in a callback, we can't easily access state.activeTriggerId. We'd need to use store.state.activeTriggerId.
Actually, looking at the code again:
typescript
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;
}
...
});
We're already using store.select('activeTriggerId'). The issue is that this selector includes triggerIdProp.
I think the cleanest fix is to change isMountedByTrigger in store.ts to use state.activeTriggerId instead of activeTriggerIdSelector(state). This way:
isMountedByTrigger only returns true when the popup was actually opened by a registered trigger
The effect in useTriggerDataForwarding only runs when the popup was actually opened by the trigger
isMountedByThisTrigger only becomes true when the popup was actually opened by the trigger
But what about the registerTrigger callback? It uses store.select('activeTriggerId') which still includes triggerIdProp. Should I change this too?
Looking at the callback, it sets activeTriggerElement to the registered element if activeTriggerId === triggerId. If I change isMountedByTrigger to use state.activeTriggerId, then the effect won't run for programmatic opens. But the callback might still run when the trigger is registered.
Actually, let me think about this more carefully. When does the callback run?
When the trigger element mounts, registerTrigger(element) is called
The callback checks if activeTriggerId === triggerId
If true, it sets activeTriggerElement
So even if the effect doesn't run (because isMountedByThisTrigger is false), the callback might still set activeTriggerElement when the trigger mounts.
But wait, the callback is inside useStableCallback, so it captures the closure variables. Let me check what variables are captured...
Looking at useStableCallback usage:
typescript
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;
}
...
});
This callback is created in the component body, so it's recreated on every render. The useStableCallback hook keeps the callback reference stable by storing the latest implementation in a ref.
So every time the component re-renders (e.g., when the popup opens), the callback is recreated and captures the latest values. When the trigger mounts, the callback runs with the latest values.
The issue is that store.select('activeTriggerId') uses the selector which includes triggerIdProp. So even when the popup was opened programmatically, activeTriggerId returns triggerIdProp.
I think the fix should be:
Change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state)
Change the callback in registerTrigger to also use state.activeTriggerId instead of store.select('activeTriggerId')
But wait, accessing store.state in a callback might cause issues because the state is readonly...
Actually, looking at the store type:
typescript
export class DialogStore<Payload> extends ReactStore<
Readonly<State<Payload>>,
Context,
typeof selectors
>
The state is readonly. So I can read store.state.activeTriggerId but can't write to it directly.
Hmm, but we're reading in a callback, which should be fine. Let me check if the callback runs synchronously...
Actually, the callback is stored in a ref by useStableCallback, and it's called when the trigger element is registered. At that point, the callback captures the closure variables including store.select('activeTriggerId').
Wait, store.select('activeTriggerId') is called inside the callback, so it reads the current state. If the state is updated before the callback runs, it will read the updated value.
Actually, no. Looking at how useStableCallback works, it stores the callback implementation in a ref. When the callback is called, it calls the latest implementation. The closure variables in the implementation are evaluated when the implementation is created (i.e., when the component re-renders).
So store.select('activeTriggerId') is evaluated when the callback implementation is created, not when it's called. This means the callback captures the value at the time of the render.
Wait, that's not right either. Let me look at useStableCallback:
Alright, let me just directly implement the fix. I'll edit the store.ts file to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state).
The key change is:
In store.ts, change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state)
This will ensure that isMountedByTrigger only returns true when the popup was actually opened by a registered trigger (i.e., when activeTriggerId was set by a trigger click), not when it was opened programmatically with triggerIdProp.
Wait, but I need to be careful. Let me re-examine the issue.
The issue is about focus management when closing a dialog that was opened programmatically. The "Open programmatically" button is NOT a Dialog.Trigger, so its element is not registered in triggerElements.
When the dialog is opened via the "Open programmatically" button:
setOpen(true) is called from React state
Dialog.Root receives open={true} and triggerId='trigger-2'
Dialog.Store opens with activeTriggerId=null (since no trigger was involved)
triggerIdProp is synced to the store as 'trigger-2'
When trigger-2 mounts/registers, activeTriggerId (from selector) is 'trigger-2'
So activeTriggerElement is set to trigger-2's element
When the dialog closes, focus returns to trigger-2
The fix should be to NOT set activeTriggerElement based on triggerIdProp. Only set it based on the actual trigger that opened the popup.
So the fix is to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state).
But wait, I also need to consider the callback in useTriggerDataForwarding:
This also uses the selector. I need to change this to use state.activeTriggerId.
But there's a subtle issue. The callback is called when the trigger mounts, and it reads store.select('activeTriggerId'). If I change it to store.state.activeTriggerId, it should work the same way (since state is the current state).
Actually, wait. Let me check if store.state is accessible. Looking at the ReactStore type:
typescript
export class DialogStore<Payload> extends ReactStore<
Readonly<State<Payload>>,
Context,
typeof selectors
>
The state is Readonly<State<Payload>>, so I can read from it but not write to it. So store.state.activeTriggerId should be accessible.
But I'm not sure if store.state is the correct way to access the state in a callback. Let me think about this...
This directly accesses the store state, which is the raw activeTriggerId field (not including triggerIdProp).
But wait, I need to check if store has a state property. Let me look at the ReactStore type...
Actually, I realize that I can also change the selector itself. But that would affect all uses of activeTriggerIdSelector, not just the ones in isMountedByTrigger.
Let me think about this more carefully. The activeTriggerIdSelector is used for:
isOpenedByTrigger - should include triggerIdProp for controlled mode
isTriggerActive - should include triggerIdProp for controlled mode
isMountedByTrigger - should NOT include triggerIdProp (only true if the popup was actually opened by the trigger)
triggerProps - should include triggerIdProp for controlled mode
triggerPopupId - should include triggerIdProp for controlled mode
So the fix is to change isMountedByTrigger to use state.activeTriggerId directly, not through activeTriggerIdSelector.
This is the cleanest fix because it only affects the specific use case that's causing the issue.
Now, for the callback in useTriggerDataForwarding, I need to also change it to use state.activeTriggerId. Let me think about how to do this...
Looking at the callback:
typescript
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({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
});
This callback is created in the component body and uses useStableCallback to keep the reference stable. The closure variables include store, triggerId, stateUpdates, etc.
When the callback runs, it reads store.select('activeTriggerId'). If I change it to read store.state.activeTriggerId, it should give me the raw activeTriggerId field.
But wait, I need to check if store in the closure is the same as the store passed to useStableCallback. Looking at the usage:
useStableCallback takes a function and returns a stable reference to it. The function captures the closure variables at the time it's created. Each time the component re-renders, a new function is created, but useStableCallback stores the latest implementation in a ref.
So when the callback runs (e.g., when the trigger mounts), it calls the latest implementation, which was created during the last render. At that point, store is the current store, and store.select('activeTriggerId') reads the current state.
If I change it to store.state.activeTriggerId, it should read the current state as well.
OK, let me now write the fix. I'll make two changes:
In store.ts, change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state)
In popupStoreUtils.ts, change the callback in useTriggerDataForwarding to use store.state.activeTriggerId instead of store.select('activeTriggerId')
Wait, but I also need to consider the second condition in the callback:
typescript
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 condition handles the case where a detached trigger mounts before any active trigger has been established. If I change activeTriggerId to be the raw state (which would be null for programmatic opens), this condition would trigger for all triggers, claiming the first registered trigger as the active one.
This is the behavior described in the comment: "a detached trigger can mount before any active trigger has been established". In the case of a programmatic open, the activeTriggerId is null, so all triggers would claim themselves.
But wait, this condition is only for the case where activeTriggerId == null. If the popup was opened programmatically, activeTriggerId is null, and the first registered trigger would claim itself.
But in the demo, when the "Open programmatically" button is clicked, the dialog opens with triggerIdProp='trigger-2'. If I change isMountedByTrigger to use state.activeTriggerId (which is null), then:
isMountedByTrigger('trigger-2') would be true && null === 'trigger-2' && true = false
isMountedByTrigger('trigger-3') would be true && null === 'trigger-3' && true = false
So isMountedByThisTrigger would be false for all triggers. The effect in useTriggerDataForwarding would not run for any trigger.
But the callback in registerTrigger would still run. And if I don't change the callback, it would use store.select('activeTriggerId') which returns triggerIdProp (i.e., 'trigger-2'). So trigger-2 would still set activeTriggerElement to its element.
So I also need to change the callback to use store.state.activeTriggerId.
With this change:
When trigger-1 mounts, the callback checks store.state.activeTriggerId === 'trigger-1' = null === 'trigger-1' = false
The callback then checks store.state.activeTriggerId == null && open = null == null && true = true
So trigger-1 would claim itself: store.update({ activeTriggerId: 'trigger-1', activeTriggerElement: element, ... })
But this is wrong! The first registered trigger (trigger-1) would claim itself, even though the dialog was opened with triggerIdProp='trigger-2'.
Hmm, this is more complicated than I thought. The issue is that when the popup is opened programmatically with triggerIdProp='trigger-2', we don't want any trigger to claim itself.
But the current code has logic to handle the case where a detached trigger mounts before any active trigger has been established. In this case, the first registered trigger claims itself.
The issue is that this logic doesn't account for triggerIdProp. When triggerIdProp is set, we shouldn't let any trigger claim itself just because activeTriggerId is null.
Wait, actually, let me re-read the condition:
typescript
if (activeTriggerId == null && open) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
This condition is for the case where activeTriggerId (from the selector, which includes triggerIdProp) is null. But if triggerIdProp is set to a non-null value, activeTriggerId would not be null, so this condition wouldn't trigger.
But if I change the condition to use store.state.activeTriggerId, then for a programmatic open with triggerIdProp='trigger-2', store.state.activeTriggerId is null, and the first registered trigger would claim itself.
So I need a different approach. Let me think about this more carefully.
Actually, I think the issue is that the triggerIdProp mechanism is fundamentally incompatible with programmatic opens. When triggerIdProp is set, it indicates which trigger owns the popup for controlled mode. But it shouldn't affect focus management if the popup was opened programmatically.
The fix should be:
For focus management, only consider the actual trigger that opened the popup (i.e., activeTriggerId from the store state, not the selector)
triggerIdProp is for ARIA relationships and rendering, not for focus management
So the fix is:
Change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state)
Change the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId')
But for the callback's second condition, I need to be careful not to claim the trigger when triggerIdProp is set (i.e., when the popup was opened with a controlled triggerIdProp but not by a specific trigger).
Hmm, actually, let me re-think. The second condition in the callback is for the case where a detached trigger mounts before any active trigger has been established. This is needed because in detached trigger mode, triggers are not necessarily rendered inside the popup. So when a detached trigger mounts, it needs to register itself.
But in the demo, all triggers are detached triggers that are rendered outside the popup. So when the popup opens with triggerIdProp='trigger-2', all triggers are already registered.
Actually wait, let me look at the demo again:
tsx
<Dialog.Trigger
handle={demoDialog}
id="trigger-1"
payload={1}
>
Open 1
</Dialog.Trigger>
<Dialog.Trigger
handle={demoDialog}
id="trigger-2"
payload={2}
>
Open 2
</Dialog.Trigger>
<Dialog.Trigger
handle={demoDialog}
id="trigger-3"
payload={3}
>
Open 3
</Dialog.Trigger>
All three triggers are detached triggers. When the component mounts, all three triggers register themselves. So all three triggers are already registered before the popup opens.
Now, when the "Open programmatically" button is clicked:
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Root receives triggerIdProp='trigger-2' and openProp=true
Dialog.Store opens
activeTriggerId (store state) is null (since no trigger was involved)
triggerIdProp is synced to the store as 'trigger-2'
At this point, all three triggers are already registered. When they register, their callbacks run:
Trigger-1: store.select('activeTriggerId') = 'trigger-2' (from selector). activeTriggerId === triggerId = 'trigger-2' === 'trigger-1' = false. activeTriggerId == null && open = false (because activeTriggerId is 'trigger-2' from selector).
Trigger-2: store.select('activeTriggerId') = 'trigger-2'. activeTriggerId === triggerId = 'trigger-2' === 'trigger-2' = true. So activeTriggerElement is set to trigger-2's element.
Trigger-3: Similar to trigger-1.
So trigger-2 sets activeTriggerElement to its element, and focus returns to trigger-2 when the popup closes.
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Root receives triggerIdProp='trigger-2' and openProp=true
Dialog.Store.open is called with trigger=trigger-2's element
setOpenTriggerState sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
onOpenChange callback is called
setTriggerId('trigger-2') and setOpen(true) are called (no change)
So in this case, triggerIdProp is 'trigger-2', and activeTriggerId (store state) is 'trigger-2'. Both match, so there's no issue.
Now, when the "Open programmatically" button is clicked:
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Root receives triggerIdProp='trigger-2' and openProp=true
Dialog.Store.open is called with trigger=undefined
setOpenTriggerState sets activeTriggerId=null and activeTriggerElement=null
onOpenChange callback is called
setTriggerId(null) and setOpen(true) are called (since eventDetails.trigger is undefined)
Wait, step 6 is important. After the dialog opens, the onOpenChange callback is called with eventDetails.trigger being undefined (since no trigger was involved). So setTriggerId(null) is called.
But setTriggerId(null) is a React state update, so it doesn't happen immediately. The dialog has already opened with triggerIdProp='trigger-2' at this point.
So the flow is:
"Open programmatically" button is clicked
setTriggerId('trigger-2') and setOpen(true) are called (first render)
Dialog.Root re-renders with triggerIdProp='trigger-2' and openProp=true
Dialog.Store opens (synchronously during render, or during an effect)
So no trigger claims itself. activeTriggerElement remains null. When the dialog closes, FloatingFocusManager falls back to getPreviouslyFocusedElement(), which should be the "Open programmatically" button.
But wait, I need to also consider the case where the popup is opened by clicking trigger-2 (not programmatically). Let me trace through:
User clicks trigger-2
Trigger-2's onClick handler calls store.setOpen(true, { trigger: trigger-2's element })
Dialog.Store.setOpen is called
setOpenTriggerState sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
Dialog opens
triggerIdProp might be synced from props
If the dialog is uncontrolled, triggerIdProp is undefined. If controlled, triggerIdProp is set by the parent component.
For uncontrolled mode:
After step 4, activeTriggerId = 'trigger-2'
triggerIdProp = undefined
When trigger-2's callback runs: store.state.activeTriggerId = 'trigger-2', store.state.triggerIdProp = undefined. activeTriggerId === triggerId = 'trigger-2' === 'trigger-2' = true. So activeTriggerElement is set to trigger-2's element. This is correct.
For controlled mode (after clicking trigger-2):
After step 4, activeTriggerId = 'trigger-2'
The onOpenChange callback sets triggerIdProp = 'trigger-2'
When trigger-2's callback runs: store.state.activeTriggerId = 'trigger-2', store.state.triggerIdProp = 'trigger-2'. activeTriggerId === triggerId = 'trigger-2' === 'trigger-2' = true. So activeTriggerElement is set to trigger-2's element. This is correct.
OK, so my proposed fix should work for both cases:
When opened by clicking trigger-2: activeTriggerId = 'trigger-2', so trigger-2 claims itself.
When opened programmatically: activeTriggerId = null, so no trigger claims itself.
But I need to also consider the case where the popup is already open when a detached trigger mounts. This is handled by the "first registered trigger" logic. Let me think about this case:
Dialog is already open (opened by clicking trigger-1)
So trigger-2 doesn't claim itself. This seems correct, because the active trigger is 'trigger-1'.
But what if the popup is opened with triggerIdProp='trigger-2' and then trigger-2 mounts? This is the case described in the code comment:
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.
Hmm, this is a bit confusing. Let me re-read the comment.
I think the "any active trigger" refers to the case where the popup is opened with triggerIdProp set, but no trigger has registered itself yet. In this case, the popup is open, and the first trigger to mount should claim itself so that focus management works correctly.
But with my proposed fix, if triggerIdProp='trigger-2', then no trigger would claim itself (because store.state.activeTriggerId is null and we check triggerIdProp == null).
This could be a problem. Let me think about this...
Actually, I think the "first registered trigger" logic is for the case where the popup is opened with defaultTriggerId but no actual trigger has been clicked yet. For example:
In this case, the popup is initially open with defaultTriggerId='trigger-2'. When the popup opens, activeTriggerId is 'trigger-2'. But if trigger-2 hasn't mounted yet, its element is not registered. When trigger-2 eventually mounts, it needs to claim itself as the active trigger.
But wait, if activeTriggerId is 'trigger-2', then trigger-2's callback would match activeTriggerId === triggerId and set activeTriggerElement. So the "first registered trigger" logic is not needed for this case.
Let me re-read the code comment again:
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.
I think "any active trigger has been established" means the case where the popup is open but no trigger has set itself as active. For example:
Popup is opened programmatically with triggerIdProp='trigger-2'
No trigger has registered yet (or all triggers have registered but none have claimed themselves)
In this case, the first registered trigger would claim itself. This is needed for the popup to have a valid activeTriggerElement for focus management.
But with my proposed fix, if triggerIdProp='trigger-2', no trigger would claim itself. This would mean the popup has no activeTriggerElement, and focus management would fall back to getPreviouslyFocusedElement().
Is this the desired behavior? Let me think about it...
If the popup is opened with triggerIdProp='trigger-2' (controlled mode), the expectation is that focus should return to trigger-2 when the popup closes. But if no trigger has claimed itself, focus would fall back to getPreviouslyFocusedElement().
Actually, wait. Let me re-read the original 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.
The issue is that focus moves to the wrong trigger (trigger-2) instead of the "Open programmatically" button. So the fix is to NOT set activeTriggerElement to trigger-2's element when the popup is opened programmatically.
So my proposed fix is correct. When the popup is opened programmatically with triggerIdProp='trigger-2', activeTriggerElement should remain null (or be set to the "Open programmatically" button's element, if known). Since the "Open programmatically" button is not a registered trigger, we can't easily set activeTriggerElement to it. So activeTriggerElement should remain null, and focus should fall back to getPreviouslyFocusedElement().
But this might cause issues in other cases. Let me think about what happens when the popup is opened by clicking trigger-2 (not programmatically):
User clicks trigger-2
store.setOpen(true, { trigger: trigger-2's element }) is called
Dialog.Store.setOpen sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
Dialog opens
onOpenChange callback is called, which sets triggerIdProp='trigger-2'
When trigger-2's callback runs: store.state.activeTriggerId = 'trigger-2'. activeTriggerId === triggerId = true. So activeTriggerElement is set to trigger-2's element (which is already set).
This is correct. Trigger-2 claims itself (redundantly, but that's fine).
And when the popup closes:
Focus is currently inside the popup
FloatingFocusManager's cleanup runs
getReturnElement() is called
domReference is trigger-2's element (since it was set as activeTriggerElement)
domReference.isConnected is true
Focus returns to trigger-2
This is correct.
Now, what about the case where the popup is already open and a detached trigger mounts?
Popup is open with triggerIdProp='trigger-2' and activeTriggerId='trigger-2'
Trigger-3 mounts (it was conditionally rendered)
Trigger-3's callback runs: store.state.activeTriggerId = 'trigger-2'. activeTriggerId === triggerId = 'trigger-2' === 'trigger-3' = false. activeTriggerId == null && open = false. So no action.
This is correct. Trigger-3 doesn't claim itself.
Trigger-2 mounts (it was conditionally rendered)
Trigger-2's callback runs: store.state.activeTriggerId = 'trigger-2'. activeTriggerId === triggerId = true. So activeTriggerElement is set to trigger-2's element.
This is correct. Trigger-2 claims itself.
OK, so my proposed fix seems correct. Let me also think about edge cases:
Popup is opened programmatically, then a trigger mounts
activeTriggerId = null
No trigger claims itself (since store.state.activeTriggerId is null)
Focus falls back to getPreviouslyFocusedElement() (the "Open programmatically" button)
Correct!
Popup is opened programmatically with triggerIdProp=null, then a trigger mounts
activeTriggerId = null, triggerIdProp = null
First trigger to mount would claim itself (since store.state.activeTriggerId == null && open && triggerIdProp == null is true)
But wait, should any trigger claim itself in this case?
Hmm, let me think about this. If the popup is opened programmatically with triggerIdProp=null, it means no trigger is associated with the popup. So no trigger should claim itself.
But the current code says "Claim the first registered trigger so trigger-owned focus management and ARIA relationships work." This is for the case where a detached trigger mounts before any active trigger has been established.
I think the key insight is that the "first registered trigger" logic is only needed when the popup is opened by a Dialog.Trigger (not programmatically). When the popup is opened programmatically, no trigger should claim itself.
So the fix is to check if triggerIdProp is null/undefined AND activeTriggerId is null. If both are null, then no trigger should claim itself (because the popup was opened programmatically).
But if activeTriggerId is non-null (i.e., the popup was opened by a trigger), then the first registered trigger should claim itself (if no active trigger has been established yet).
Wait, but activeTriggerId being non-null means the popup was opened by a trigger. In that case, the first registered trigger matching the activeTriggerId would claim itself. If the first registered trigger doesn't match the activeTriggerId, it would try to claim itself (which is wrong).
Hmm, let me re-read the code:
typescript
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>);
}
The second condition only triggers when activeTriggerId is null. So if activeTriggerId is non-null (the popup was opened by a trigger), the second condition doesn't trigger. This means the first registered trigger would NOT claim itself if the popup was opened by a different trigger.
So the "first registered trigger" logic is only needed when:
The popup is open
No active trigger has been established (activeTriggerId is null)
A detached trigger mounts
In this case, the first registered trigger claims itself.
Now, with my proposed fix:
store.state.activeTriggerId is null (for programmatic opens)
store.state.triggerIdProp might be set (for controlled mode)
The question is: should any trigger claim itself in this case?
If triggerIdProp is set, it means the popup is associated with a specific trigger. But that trigger hasn't registered itself yet. So the first registered trigger should NOT claim itself, because it might not be the trigger associated with triggerIdProp.
If triggerIdProp is null/undefined, it means the popup is not associated with any trigger. So the first registered trigger should claim itself.
So the fix is to add a check for triggerIdProp:
typescript
if (activeTriggerId == null && open && triggerIdProp == null) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
This way, the first registered trigger only claims itself if:
No active trigger has been established (activeTriggerId is null)
The popup is open
No trigger is associated via triggerIdProp
For programmatic opens with triggerIdProp='trigger-2', triggerIdProp is not null, so no trigger claims itself.
For uncontrolled opens, triggerIdProp is null, so the first registered trigger claims itself. This is the existing behavior and should continue to work.
But wait, for controlled opens where the popup is opened by clicking trigger-2, triggerIdProp is synced to 'trigger-2' in the onOpenChange callback. So triggerIdProp would be 'trigger-2' when the popup opens.
Hmm, but the triggerIdProp is synced to the store during the render (via useControlledProp). So when the popup opens, triggerIdProp is already set.
Let me trace through again:
User clicks trigger-2
store.setOpen(true, { trigger: trigger-2's element }) is called
Dialog.Store.setOpen sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
onOpenChange callback is called: setOpen(true) and setTriggerId('trigger-2')
Dialog.Root re-renders with openProp=true and triggerIdProp='trigger-2'
Dialog.Store syncs triggerIdProp to 'trigger-2'
At step 3, activeTriggerId = 'trigger-2'. triggerIdProp is not yet synced (it's synced during the render). So during the store's setOpen, triggerIdProp might be null/undefined.
Actually, the triggerIdProp sync happens during the render, which might be after the setOpen call. Let me think about the timing...
When store.setOpen(true, { trigger: trigger-2's element }) is called:
this.context.onOpenChange?.(nextOpen, eventDetails) is called
This triggers the onOpenChange callback, which calls setOpen(true) and setTriggerId('trigger-2')
But React batches state updates, so the actual re-render happens after all state updates are processed
Meanwhile, setOpenTriggerState sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
store.update applies these state changes
After the re-render (triggered by the state updates in step 2):
6. useRenderDialogRoot is called again
7. store.useControlledProp('triggerIdProp', triggerIdProp) syncs triggerIdProp to the store
8. The store now has triggerIdProp='trigger-2'
So at step 3-5, triggerIdProp is still the previous value (from before the click). After the click, triggerIdProp might be null/undefined (if the previous dialog was closed without setting a trigger).
OK, this is getting complicated. Let me take a step back.
The key issue is: when the popup is opened programmatically (via a button that's not a Dialog.Trigger), activeTriggerElement should not be set to a registered trigger's element.
The fix is to change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state). This ensures that isMountedByThisTrigger only becomes true when the popup was actually opened by a registered trigger.
And I also need to change the callback in useTriggerDataForwarding to use store.state.activeTriggerId instead of store.select('activeTriggerId').
For the "first registered trigger" logic, I need to be careful not to break the existing behavior. Let me add a check for triggerIdProp:
Actually, wait. Let me re-think the "first registered trigger" logic. This logic is in the callback, which is called when a trigger element is registered. The callback checks:
If activeTriggerId === triggerId: set activeTriggerElement to this trigger's element
Else if activeTriggerId == null && open: claim this trigger as the active one
For programmatic opens, activeTriggerId (store state) is null. So the second condition might trigger for the first registered trigger.
But if triggerIdProp is set (controlled mode), the first registered trigger should NOT claim itself. So I need to add a check for triggerIdProp.
Actually, looking at this more carefully, I realize that the "first registered trigger" logic is for the case where:
The popup is open
No trigger has been set as active (either because the popup was opened uncontrolled, or because activeTriggerId was reset to null)
A detached trigger mounts
In this case, the first registered trigger claims itself so that focus management works.
For controlled mode, triggerIdProp is set to a specific trigger ID. The first registered trigger should NOT claim itself because it might not be the trigger associated with triggerIdProp.
So the fix is to add a check for triggerIdProp in the "first registered trigger" logic:
typescript
if (activeTriggerId == null && open && triggerIdProp == null) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
But where do I get triggerIdProp from? I can access it via store.state.triggerIdProp.
Wait, but in the callback, store is the store instance. So store.state.triggerIdProp should give me the current value.
But actually, I need to check if triggerIdProp is set in the callback closure. Let me look at the code again:
The callback captures store, triggerId, and stateUpdates. To add a check for triggerIdProp, I can access store.state.triggerIdProp.
But wait, store.state gives me the current state. If I access store.state.triggerIdProp inside the callback, I'll get the latest value.
Hmm, but the callback is created in the component body, so the closure captures store. The store is stable across renders (since it's passed as a parameter or created in usePopupStore). So store.state should give me the current state.
Let me check if store.state is accessible:
Looking at the useTriggerDataForwarding function, store is of type ReactStore<State, ...>. Let me check if ReactStore has a state property.
Actually, I realize I don't need to modify the callback. I only need to modify isMountedByTrigger in store.ts. The reason is that the callback checks store.select('activeTriggerId'), but this is only used for the first condition (activeTriggerId === triggerId). The second condition (activeTriggerId == null && open) would still trigger for the first registered trigger when the popup is opened programmatically.
Wait, but if I change isMountedByTrigger to use state.activeTriggerId, then isMountedByThisTrigger would be false for all triggers when the popup is opened programmatically. The effect in useTriggerDataForwarding would not run for any trigger.
But the callback in registerTrigger is still called when the trigger mounts. And if I don't change the callback, it would use store.select('activeTriggerId') which returns triggerIdProp (from the selector). So trigger-2 would still set activeTriggerElement to its element.
So I DO need to change the callback as well. Let me also change store.select('activeTriggerId') to store.state.activeTriggerId.
But for the second condition, I need to be careful not to break the "first registered trigger" logic. So I'll add a check for triggerIdProp:
typescript
if (activeTriggerId == null && open && store.state.triggerIdProp == null) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
Actually, wait. Let me think about this differently. The issue is that activeTriggerIdSelector includes triggerIdProp, which causes store.select('activeTriggerId') to return triggerIdProp even when the popup was opened programmatically.
The fix is to not use activeTriggerIdSelector in places where we care about the actual trigger that opened the popup. Specifically:
isMountedByTrigger should use state.activeTriggerId
The callback in useTriggerDataForwarding should use store.state.activeTriggerId
For the second condition in the callback, I need to check if triggerIdProp is set. If it is, no trigger should claim itself. If it's not set, the first registered trigger should claim itself.
Actually, I just realized something. The "first registered trigger" logic is for the case where the popup is open but no trigger has been set as active. This can happen when:
The popup is opened with defaultOpen=true and defaultTriggerId='trigger-2'
Trigger-2 hasn't mounted yet
In this case, activeTriggerId is 'trigger-2' (set from defaultTriggerId). So the second condition (activeTriggerId == null && open) would not trigger.
But what if the popup is opened with defaultOpen=true and no defaultTriggerId? In this case, activeTriggerId is null (or undefined), and the first registered trigger would claim itself.
Hmm, but this is the uncontrolled case. In controlled mode, triggerIdProp is set. So the "first registered trigger" logic should only apply to uncontrolled mode.
Wait, but the issue is with controlled mode (the demo uses controlled mode). Let me re-read the demo:
The demo passes handle, open, onOpenChange, and triggerId to Dialog.Root. This is controlled mode.
When the "Open programmatically" button is clicked:
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Root re-renders with triggerId='trigger-2' and open=true
Dialog.Store opens
activeTriggerId is set to null (since no trigger was involved)
triggerIdProp is synced to 'trigger-2'
So at step 3, activeTriggerId is null and triggerIdProp is 'trigger-2'.
Now, when trigger-2's callback runs:
Without my fix: store.select('activeTriggerId') = 'trigger-2'. activeTriggerId === triggerId = 'trigger-2' === 'trigger-2' = true. So activeTriggerElement is set to trigger-2's element.
With my fix: store.state.activeTriggerId = null. activeTriggerId === triggerId = null === 'trigger-2' = false. activeTriggerId == null && open = true && true = true. So trigger-2 would claim itself!
Wait, this is a problem! With my fix, trigger-2 would still claim itself because the second condition triggers.
So I need to also change the second condition. Let me add a check for triggerIdProp:
typescript
if (activeTriggerId == null && open && store.state.triggerIdProp == null) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
With this change:
activeTriggerId = null, open = true, store.state.triggerIdProp = 'trigger-2'
This is correct. Trigger-2 does not claim itself because triggerIdProp is set.
But what about the case where the popup is opened uncontrolled? In that case, triggerIdProp is null/undefined. So the second condition would trigger, and the first registered trigger would claim itself. This is the existing behavior, which should continue to work.
Wait, but there's another case. What if the popup is opened by clicking trigger-2 (not programmatically)? In that case:
store.setOpen(true, { trigger: trigger-2's element }) is called
setOpenTriggerState sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
activeTriggerId (store state) is 'trigger-2'
triggerIdProp is synced to 'trigger-2' (after the re-render)
So activeTriggerElement is set to trigger-2's element (redundantly, but that's fine)
This is correct.
OK, so the fix is:
Change isMountedByTrigger in store.ts to use state.activeTriggerId instead of activeTriggerIdSelector(state)
Change the callback in useTriggerDataForwarding to use store.state.activeTriggerId instead of store.select('activeTriggerId')
Add a check for triggerIdProp in the second condition of the callback
Let me also think about edge cases:
What if triggerIdProp changes after the popup is open? For example, the user closes the popup and opens it with a different triggerIdProp?
In this case, activeTriggerId would be set based on the new triggerIdProp (if the popup is opened by clicking that trigger) or null (if opened programmatically).
The first condition (activeTriggerId === triggerId) would still work correctly.
The second condition would check if triggerIdProp is null/undefined. If it's not null, no trigger would claim itself.
I think this fix is correct. Let me implement it.
Actually wait, I realize there might be an issue with accessing store.state in the callback. Let me check if this is allowed...
The store state is Readonly<State<Payload>>, so I can read from it but not write to it. Accessing store.state.activeTriggerId should be fine.
But I need to make sure the callback doesn't cause a re-render or infinite loop. Since the callback only reads from store.state, it shouldn't cause a re-render.
OK, let me now implement the fix. I'll make two changes:
In store.ts, change isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state)
In popupStoreUtils.ts, change the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId'), and add a check for store.state.triggerIdProp in the second condition
Let me start with the changes.
OK, I've made the first fix in store.ts. Now I need to also fix the callback in popupStoreUtils.ts. Let me check what else needs to be changed.
The issue is that even with the isMountedByTrigger fix, the registerTrigger callback in useTriggerDataForwarding still uses store.select('activeTriggerId') which includes triggerIdProp. This means when trigger-2's callback runs, it would still set activeTriggerElement to trigger-2's element.
Wait, let me trace through the flow again after my fix:
Popup is opened programmatically with triggerIdProp='trigger-2' and activeTriggerId=null
So activeTriggerElement is set to trigger-2's element
This is still wrong! I need to also fix the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId').
But I also need to be careful about the second condition:
typescript
if (activeTriggerId == null && open) {
// Claim the first registered trigger
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
If I change activeTriggerId to use store.state.activeTriggerId (which is null for programmatic opens), then this condition would trigger for the first registered trigger, causing it to claim itself.
So I also need to add a check for triggerIdProp in this condition. Only let a trigger claim itself if triggerIdProp is not set.
Let me implement both changes:
Change the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId')
Add a check for store.state.triggerIdProp in the second condition
Actually, wait. Let me think about this more carefully.
The registerTrigger callback is called when a trigger element is registered (i.e., when the trigger component mounts). At this point, we want to set activeTriggerElement if this trigger is the one that opened the popup.
With my first fix (changing isMountedByTrigger to use state.activeTriggerId), the effect in useTriggerDataForwarding won't run for any trigger when the popup is opened programmatically. But the registerTrigger callback is still called when the trigger mounts.
So I need to also fix the callback.
But wait, there's another consideration. The callback is created inside useStableCallback, which means it captures the closure variables at the time the callback implementation is created (i.e., during the render). The callback runs when the trigger element is registered (which might be during the render or in an effect).
When the callback runs, it calls store.select('activeTriggerId'), which returns the current value (since the store is reactive). So it should read the latest activeTriggerId.
If I change store.select('activeTriggerId') to store.state.activeTriggerId, it would read the raw state (without the triggerIdProp fallback).
But there's a subtlety. store.state is the current state, and store.select uses a selector that might compute a different value. For activeTriggerIdSelector, it returns state.triggerIdProp ?? state.activeTriggerId.
So if I change the callback to use store.state.activeTriggerId, it would read the raw activeTriggerId (which is null for programmatic opens), not the computed value from the selector.
This is the fix I need. Let me implement it.
Also, for the second condition, I need to be careful. If I change the callback to use store.state.activeTriggerId, then for programmatic opens, activeTriggerId is null, and the second condition would trigger for the first registered trigger.
To prevent this, I need to check if triggerIdProp is set. If it is, no trigger should claim itself (because the popup was opened programmatically with a specific triggerIdProp).
Let me implement both changes:
In the callback, change store.select('activeTriggerId') to store.state.activeTriggerId
In the second condition, add a check for store.state.triggerIdProp == null
But wait, accessing store.state.triggerIdProp in the callback might not be the right approach. The callback is created inside useStableCallback, so it captures the closure variables. store is one of the closure variables.
The store is passed as a parameter. So I can access store.state.activeTriggerId and store.state.triggerIdProp inside the callback.
But I need to be careful. The callback is created inside useStableCallback, which stabilizes the callback reference. The callback implementation is stored in a ref and updated in an effect. So the callback captures the closure variables at the time the implementation is created.
When the callback runs (when the trigger mounts), it uses the latest implementation (which was updated in the effect). So the closure variables are from the last render.
At the time of the render, store.state.activeTriggerId and store.state.triggerIdProp would have the latest values. So accessing them in the callback should work correctly.
But there's a timing issue. The callback might run before the state is updated. For example, if the popup is opened programmatically:
setOpen(true) is called
Dialog.Store.setOpen updates the state
Dialog.Store calls onOpenChange callback
The callback sets setTriggerId(null) (since no trigger was involved)
React re-renders with triggerIdProp=null
At step 4, triggerIdProp might still be the previous value (e.g., 'trigger-2'). At step 5, triggerIdProp is synced to null.
But the registerTrigger callback might run during step 4 (when the state is updated but before the re-render). At this point, store.state.triggerIdProp might be 'trigger-2'.
Hmm, this is getting complicated. Let me think about the timing more carefully.
setTriggerId('trigger-2') and setOpen(true) are called
React batches the state updates and re-renders
Dialog.Root re-renders with triggerIdProp='trigger-2' and openProp=true
Dialog.Store detects openProp changed to true and opens
Dialog.Store calls onOpenChange callback with eventDetails.trigger undefined
The callback sets setTriggerId(null) and setOpen(true) (but setOpen(true) doesn't change anything)
React batches the state updates and re-renders
Dialog.Root re-renders with triggerIdProp=null and openProp=true
At step 4, Dialog.Store opens. The store's setOpen method is called, which sets activeTriggerId=null and activeTriggerElement=null. Then it calls onOpenChange, which triggers the handleOpenChange callback.
At step 4-5, the registerTrigger callback might or might not have run yet. If the trigger components were already mounted (which they are in the demo), the registerTrigger callback was already called when the trigger components first mounted.
So the sequence is:
Component mounts, all three triggers register themselves
User clicks "Open programmatically" button
setTriggerId('trigger-2') and setOpen(true) are called
onOpenChange callback is called, which sets setTriggerId(null) and setOpen(true)
Dialog.Root re-renders with triggerIdProp=null and openProp=true
At step 4, when Dialog.Store opens, the triggers are already registered (from step 1). The registerTrigger callback was already called for all three triggers when they mounted.
When was the registerTrigger callback called? It was called when each trigger's ref was set (i.e., when the trigger component mounted and its ref callback was executed).
So at step 1, when the trigger components mount, their registerTrigger callback is called. At this point, store.select('activeTriggerId') might return undefined (since the popup hasn't opened yet). So activeTriggerId === triggerId is false for all triggers, and activeTriggerId == null && open is false (since open is false). So no trigger claims itself.
At step 4, when the popup opens, the triggers are already registered. The registerTrigger callback was already called, but it didn't claim any trigger.
So the issue is that the registerTrigger callback doesn't run again when the popup opens. It only runs when the trigger component mounts.
But wait, the useStableCallback hook updates the callback implementation in an effect. So when the component re-renders (e.g., when the popup opens), the callback implementation is updated with the latest closure variables.
But the callback itself is not re-called. It's only called when the trigger ref is set (i.e., when the trigger component mounts or its ref changes).
So the issue is that when the popup opens, the registerTrigger callback is not re-called. The triggers are already registered, and the callback doesn't need to be called again.
But then how does activeTriggerElement get set when the popup is opened by clicking a trigger?
setOpenTriggerState sets activeTriggerId and activeTriggerElement from eventDetails.trigger. So when the popup is opened by clicking a trigger, activeTriggerElement is set directly.
And when the popup is opened programmatically (without a trigger), eventDetails.trigger is undefined, so setOpenTriggerState sets activeTriggerId=null and activeTriggerElement=null.
So the issue is not in the registerTrigger callback. The issue is in useSyncedFloatingRootContext.
Let me look at useSyncedFloatingRootContext again:
When the popup opens, referenceElement is activeTriggerElement from the popup store. If activeTriggerElement is null, domReferenceElement is not updated.
So if domReferenceElement was previously set to trigger-2's element (from a previous dialog open), it stays that way.
But wait, how was domReferenceElement set to trigger-2's element in the first place? Let me trace through again.
When the popup is opened by clicking trigger-1:
store.setOpen(true, { trigger: trigger-1's element }) is called
setOpenTriggerState sets activeTriggerId='trigger-1' and activeTriggerElement=trigger-1's element
domReferenceElement is synced from activeTriggerElement to trigger-1's element
When the popup is opened by clicking trigger-2:
store.setOpen(true, { trigger: trigger-2's element }) is called
setOpenTriggerState sets activeTriggerId='trigger-2' and activeTriggerElement=trigger-2's element
domReferenceElement is synced from activeTriggerElement to trigger-2's element
When the popup is opened programmatically:
setOpen(true) is called from React state
setOpenTriggerState is called with eventDetails.trigger undefined
activeTriggerId=null and activeTriggerElement=null
referenceElement is null, so domReferenceElement is not updated (stays at trigger-2's element from previous open)
Wait, but referenceElement is synced from activeTriggerElement. If activeTriggerElement is null, referenceElement is null. And in the sync effect, domReferenceElement is only updated if referenceElement is an element:
typescript
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
So if referenceElement is null, domReferenceElement is not updated. It stays at the previous value (trigger-2's element).
But this is only an issue if the popup was previously opened by a trigger and then opened programmatically. If the popup is opened programmatically for the first time, domReferenceElement would be null (since it was initialized to null).
Hmm, but in the demo, the popup is opened programmatically after clicking a trigger (e.g., trigger-1 or trigger-2). So domReferenceElement might still be pointing to the previous trigger.
This effect runs when any of the dependencies change. When referenceElement changes from trigger-2's element to null (because activeTriggerElement became null), the effect runs and syncs referenceElement=null to the floating root store. But domReferenceElement is not updated (since referenceElement is not an element).
So domReferenceElement stays at trigger-2's element. This is the bug!
The fix should be to update domReferenceElement to null when referenceElement is not an element:
This way, when the popup is opened programmatically (and activeTriggerElement is null), domReferenceElement is set to null. Then, FloatingFocusManager will fall back to getPreviouslyFocusedElement(), which should be the "Open programmatically" button.
But wait, this might have side effects. Let me think about it...
If I always update domReferenceElement, then:
When the popup is opened by clicking trigger-1, domReferenceElement is set to trigger-1's element.
When the popup is closed, domReferenceElement might change to null (because activeTriggerElement becomes null when the popup closes).
When the popup is opened again by clicking trigger-2, domReferenceElement is set to trigger-2's element.
This should be fine. The key is that domReferenceElement should reflect the current activeTriggerElement when the popup is open, and should be null when the popup is closed (or when activeTriggerElement is null).
Actually, wait. Let me look at the FloatingFocusManager's return focus logic again:
So if domReference is connected, it returns domReference. Otherwise, it falls back to getPreviouslyFocusedElement().
The issue is that domReference (which is domReferenceElement from the FloatingRootStore) might be stale from a previous open.
If I fix the sync effect to always update domReferenceElement (including setting it to null when referenceElement is not an element), then domReferenceElement would be null when the popup is opened programmatically. And FloatingFocusManager would fall back to getPreviouslyFocusedElement().
This seems like the correct fix!
But wait, I need to make sure this doesn't break other cases. Let me think about what happens in different scenarios:
Popup opened by clicking trigger-1:
activeTriggerElement = trigger-1's element
domReferenceElement = trigger-1's element
When closed, activeTriggerElement might become null
domReferenceElement = null (or trigger-1's element, depending on timing)
Focus returns to trigger-1 (if domReferenceElement is still trigger-1's element) or to previously focused element
Popup opened programmatically:
activeTriggerElement = null
domReferenceElement = null (with my fix)
Focus returns to previously focused element (the "Open programmatically" button)
Popup opened by clicking trigger-2 after being opened by trigger-1:
activeTriggerElement = trigger-2's element
domReferenceElement = trigger-2's element (updated when popup opens)
Focus returns to trigger-2
This all seems correct. Let me also check the case where the popup is closed and re-opened by the same trigger:
Popup opened by clicking trigger-1, closed, reopened by clicking trigger-1:
First open: domReferenceElement = trigger-1's element
Close: domReferenceElement might become null (depending on when activeTriggerElement is reset)
Re-open: domReferenceElement = trigger-1's element (updated when popup opens)
Focus returns to trigger-1
This also seems correct.
But there's a subtle issue. When the popup is closed, activeTriggerElement might not be reset to null immediately. It might be reset after the exit animation completes (to preserve focus management during the animation). So domReferenceElement might still point to the previous trigger when the popup is closed.
So activeTriggerElement is only non-null when mounted is true. When the popup is closed but still mounted (during exit animation), activeTriggerElement might still be the trigger's element. When the popup unmounts, activeTriggerElement becomes null.
So activeTriggerElement is reset to null only when forceUnmount is called (i.e., when the popup fully closes).
During the exit animation, activeTriggerElement is still the trigger's element. So domReferenceElement is also still the trigger's element. This means focus would return to the correct trigger.
And when the popup is opened programmatically, activeTriggerElement is null (because setOpenTriggerState was called with undefined trigger). So domReferenceElement would be updated to null (with my fix).
OK, I'm convinced that the fix should be in useSyncedFloatingRootContext to always update domReferenceElement, including setting it to null when referenceElement is not an element.
But wait, I need to reconsider. Let me trace through the flow more carefully.
When the popup is opened programmatically:
setOpen(true) is called from React state
onOpenChange callback is called
Dialog.Store.setOpen updates the state
setOpenTriggerState is called with trigger undefined
activeTriggerId=null and activeTriggerElement=null
Dialog opens
useSyncedFloatingRootContext syncs activeTriggerElement to domReferenceElement
At step 7, activeTriggerElement is null, so referenceElement is null. With my fix, domReferenceElement would be set to null.
Then, FloatingFocusManager's cleanup runs when the popup closes:
This is correct! Focus returns to the previously focused element (the "Open programmatically" button).
But I also need to make sure my first fix (in store.ts) doesn't break anything. Let me think about it...
With my first fix, isMountedByTrigger uses state.activeTriggerId instead of activeTriggerIdSelector(state). This means isMountedByTrigger only returns true when the popup was actually opened by a registered trigger.
This is used in useTriggerDataForwarding to determine isMountedByThisTrigger, which is used to update activeTriggerElement when the trigger mounts.
If isMountedByTrigger is false for all triggers (because the popup was opened programmatically), then isMountedByThisTrigger is false for all triggers. The effect in useTriggerDataForwarding won't run for any trigger. So activeTriggerElement is not updated.
This is correct behavior!
But I also need to consider the registerTrigger callback in useTriggerDataForwarding:
typescript
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) {
// Claim the first registered trigger
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
});
This callback uses store.select('activeTriggerId') which includes triggerIdProp. So when the popup is opened programmatically with triggerIdProp='trigger-2', store.select('activeTriggerId') returns 'trigger-2'.
When trigger-2's callback runs:
activeTriggerId = 'trigger-2' (from selector, which includes triggerIdProp)
activeTriggerElement is set to trigger-2's element
This is still wrong! The callback sets activeTriggerElement to trigger-2's element, even though the popup was opened programmatically.
So I also need to fix the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId').
But wait, the callback is called when the trigger mounts, which happens during the initial render (before the popup opens). At this point, store.select('activeTriggerId') might return undefined (since triggerIdProp hasn't been synced yet).
Let me trace through the timing again:
Component mounts
All three trigger components mount
Each trigger's ref is set, which calls registerTrigger
At this point, store.select('activeTriggerId') returns undefined (since triggerIdProp is not synced yet and popup is closed)
User clicks "Open programmatically" button
setTriggerId('trigger-2') and setOpen(true) are called
Dialog.Store opens with triggerIdProp='trigger-2'
activeTriggerElement=null
At step 7, the triggers are already registered (from step 3). The registerTrigger callback was already called, and it didn't set activeTriggerElement (because activeTriggerId was undefined).
So the callback doesn't run again when the popup opens. The issue is not in the callback.
Hmm, but then how does activeTriggerElement get set to trigger-2's element in the original bug? Let me re-read the code...
Actually, I think I was wrong. Let me look at the useSyncedFloatingRootContext again:
This selector returns null when mounted is false. So when the popup is closed and unmounted, activeTriggerElement (from the selector) is null.
But when the popup is closed but still mounted (during exit animation), activeTriggerElement is still the trigger's element. So domReferenceElement is still the trigger's element during the exit animation.
And when the popup is closed and fully unmounted, activeTriggerElement is null (from the selector). But domReferenceElement might still be the trigger's element (if it wasn't updated when activeTriggerElement became null).
So the fix is to update domReferenceElement to null when referenceElement (which is activeTriggerElement from the selector) is not an element. This includes:
When activeTriggerElement is null (because no trigger was involved)
When activeTriggerElement is null (because the popup is unmounted)
When activeTriggerElement is not an element (edge case)
Actually, I just realized something. Looking at the selector:
This returns null when mounted is false. So when the popup is unmounted, activeTriggerElement is null.
But when the popup is open, mounted is true, so activeTriggerElement returns state.activeTriggerElement.
So the sync effect runs when referenceElement changes. When the popup opens with activeTriggerElement=null, referenceElement changes to null. And the sync effect updates domReferenceElement to null (with my fix).
Then when the popup closes (but is still mounted during exit animation), activeTriggerElement is still the trigger's element (from the previous open). So referenceElement doesn't change, and domReferenceElement stays at the trigger's element.
When the popup fully closes and unmounts, mounted becomes false, so activeTriggerElement becomes null. The sync effect runs, and domReferenceElement is updated to null.
Hmm, but this means that during the exit animation, domReferenceElement is still the trigger's element. And FloatingFocusManager returns focus to domReference (which is the trigger's element). This is correct!
And when the popup is opened programmatically, domReferenceElement is updated to null (with my fix). So FloatingFocusManager falls back to getPreviouslyFocusedElement().
Wait, but I'm concerned about the timing. Let me think about what happens when the popup opens:
User clicks "Open programmatically" button
setOpen(true) is called
React renders Dialog.Root
Dialog.Store detects openProp=true and opens
onOpenChange callback is called
The callback sets setTriggerId(null) (since no trigger was involved)
React renders Dialog.Root again with triggerIdProp=null
At step 4, Dialog.Store opens. The popup's mounted state changes from false to true. This triggers a re-render.
At step 4-7, the useSyncedFloatingRootContext syncs activeTriggerElement (which is null) to domReferenceElement. With my fix, domReferenceElement is updated to null.
So the fix should work. Let me also check if my first fix (in store.ts) is needed.
Actually, thinking about it more, my first fix (changing isMountedByTrigger) might not be necessary if the second fix (in useSyncedFloatingRootContext) is in place. The reason is:
When the popup is opened programmatically, activeTriggerElement is null (from setOpenTriggerState)
The sync effect updates domReferenceElement to null
FloatingFocusManager falls back to getPreviouslyFocusedElement()
So even if isMountedByTrigger is false for all triggers, the focus is still returned correctly (to getPreviouslyFocusedElement()).
But there's still the issue with the registerTrigger callback. If the callback runs when the trigger mounts and the popup is already open, it might set activeTriggerElement to the trigger's element.
But wait, when does the callback run? The callback is called when the trigger's ref is set. If the trigger is already mounted when the popup opens, the callback has already run. If the trigger mounts after the popup opens, the callback runs when the trigger mounts.
If the trigger mounts after the popup opens, and the popup was opened programmatically, the callback might set activeTriggerElement to the trigger's element. Let me trace through:
Popup is opened programmatically
activeTriggerElement=null
Trigger-2 mounts
Trigger-2's registerTrigger callback is called
The callback checks store.select('activeTriggerId') which returns 'trigger-2' (from triggerIdProp)
activeTriggerElement is set to trigger-2's element
But wait, at step 2, triggerIdProp is synced to 'trigger-2' (from the parent component). So store.select('activeTriggerId') returns 'trigger-2'.
Hmm, but triggerIdProp is synced from props. When the popup opens, the parent component might have set triggerIdProp to 'trigger-2'. So store.select('activeTriggerId') would return 'trigger-2'.
But with my first fix, isMountedByTrigger uses state.activeTriggerId instead of activeTriggerIdSelector(state). So isMountedByTrigger returns false for all triggers.
But the registerTrigger callback still uses store.select('activeTriggerId'), which returns 'trigger-2' (from triggerIdProp). So the callback might set activeTriggerElement to trigger-2's element.
This is a problem! I need to also fix the callback to use store.state.activeTriggerId instead of store.select('activeTriggerId').
But wait, let me re-check the timing. When the popup opens programmatically:
setOpen(true) is called from React state
Dialog.Store.setOpen is called
setOpenTriggerState sets activeTriggerId=null and activeTriggerElement=null
triggerIdProp is synced to 'trigger-2' (from props)
At step 4, activeTriggerId is null and triggerIdProp is 'trigger-2'.
activeTriggerElement is set to trigger-2's element
So even with my second fix (in useSyncedFloatingRootContext), the registerTrigger callback might set activeTriggerElement to trigger-2's element.
And in the sync effect, activeTriggerElement (from selector) is now trigger-2's element. So domReferenceElement is updated to trigger-2's element.
So my second fix alone is not sufficient. I also need to fix the registerTrigger callback.
But wait, let me reconsider the timing. When does trigger-2's callback run?
If trigger-2 is already mounted when the popup opens, the callback has already run. At that point, activeTriggerId is null (from the initial state), so the callback didn't set activeTriggerElement.
If trigger-2 mounts after the popup opens, the callback runs when the trigger mounts. At this point, activeTriggerId might be null or 'trigger-2' (depending on whether triggerIdProp was synced).
Hmm, this is getting complicated. Let me just implement both fixes and see if it works.
Actually, I just realized that my first fix might already prevent this issue. Let me trace through again with my first fix:
The effect in useTriggerDataForwarding doesn't run for trigger-2
activeTriggerElement is not updated by the effect
So with my first fix, activeTriggerElement is not updated by the effect. Good.
But the registerTrigger callback is still called when trigger-2 mounts. And the callback uses store.select('activeTriggerId'), which returns 'trigger-2'.
So the callback still sets activeTriggerElement to trigger-2's element. This is wrong!
OK, I need to fix the callback as well. Let me change store.select('activeTriggerId') to store.state.activeTriggerId in the callback.
But I also need to be careful about the second condition:
typescript
if (activeTriggerId == null && open) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
If I change activeTriggerId to store.state.activeTriggerId, then for programmatic opens, activeTriggerId is null, and the condition would trigger for the first registered trigger.
To prevent this, I need to add a check for triggerIdProp:
typescript
if (activeTriggerId == null && open && store.state.triggerIdProp == null) {
store.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates,
} as Partial<State>);
}
This way, the first registered trigger only claims itself if:
activeTriggerId is null (no active trigger has been established)
The popup is open
triggerIdProp is not set (uncontrolled mode)
For programmatic opens with triggerIdProp='trigger-2', triggerIdProp is set, so no trigger claims itself.
For uncontrolled opens, triggerIdProp is not set, so the first registered trigger claims itself. This is the existing behavior.
OK, let me implement the fix for the callback as well.
<tool_call>
<function=bash_terminal>
<parameter=command>
sed -n '158,185p' /base-ui/packages/react/src/utils/popups/popupStoreUtils.ts
</tool_call>
Changed domReferenceElement to always be synced, setting it to null when referenceElement is not an element. This ensures that when a popup is opened programmatically, domReferenceElement is cleared, allowing FloatingFocusManager to fall back to getPreviouslyFocusedElement().
Changed registerTrigger to use store.state.activeTriggerId instead of store.select('activeTriggerId') (which includes triggerIdProp).
Added a check for triggerIdProp == null in the "first registered trigger" condition to prevent incorrect trigger claiming in controlled mode.
packages/react/src/utils/popups/store.ts:
Changed isMountedByTrigger to use state.activeTriggerId instead of activeTriggerIdSelector(state), ensuring it only returns true when the popup was actually opened by a registered trigger.