Now I understand the issue. The problem is:
- There are multiple triggers: "Discard", "Delete", "Sign out" buttons that use
AlertDialog.Trigger components
- There's also a "Open programmatically" button that uses a regular
<button> element and programmatically opens the dialog
- When you click "Open programmatically", focus is not being tracked properly - the
domReferenceElement is not being set to the "Open programmatically" button
Let me trace the issue:
When using handle.open('alert-trigger-2') to open the dialog:
- The
DialogHandle.open method is called with the triggerId
- It gets the trigger element from
store.context.triggerElements.getById(triggerId)
- It calls
store.setOpen(true, eventDetails) with the triggerElement
But in the demo, when opening programmatically:
- The user clicks a regular
<button> element
- They set
setOpen(true) but don't pass a trigger element
- The
activeTriggerElement stays as the last trigger that was used
The issue is in setOpenTriggerState in popupStoreUtils.ts:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
This only sets the trigger state when there's a triggerId or when opening. But the problem is when opening via a plain button click, there's no trigger element passed.
Looking at useSyncedFloatingRootContext, it syncs the referenceElement (which is activeTriggerElement) to domReferenceElement in the FloatingRootStore.
The fix needs to:
- When opening the dialog via a non-trigger element (like "Open programmatically" button), track that element as the active trigger
- When closing, return focus to that element instead of the previous trigger
Let me look at where the trigger element comes from when opening the dialog programmatically. The issue is that the "Open programmatically" button is a regular <button>, not an AlertDialog.Trigger, so it doesn't register with the trigger elements map.
In DialogStore.setOpen, when nextOpen is true and no trigger is passed:
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;
}
The problem is clear: when opening, if no trigger is passed, the old trigger state is preserved. When closing, the code uses activeTriggerElement to return focus.
The solution should be to track the element that actually caused the open event, even if it wasn't a registered trigger. Let me think about how to implement this.
Looking at the DialogStore.setOpen method:
- When opening (
nextOpen is true), if eventDetails.trigger is undefined/null, we need to set it to the currently focused element if there is one
- When closing, we return focus to this stored element
Wait, let me re-read the issue. The problem is specifically with the "Open programmatically" button scenario. When:
- User clicks "Open programmatically" button (focus moves there)
- The button's onClick handler calls
setOpen(true)
- The dialog opens
- User presses Esc to close
- Focus returns to "Delete" button instead of "Open programmatically" button
The root cause is that the dialog doesn't know which element opened it when opened programmatically. The solution is to track the currently focused element when the dialog is opened programmatically.
Let me look at how the event details are created and passed.
In DialogHandle.open:
this.store.setOpen(
true,
createChangeEventDetails(REASONS.imperativeAction, undefined, triggerElement),
);
The triggerElement is passed from the handle. If handle.open('trigger-id') is called, it looks up the element. But if a plain button click triggers an open (like in the controlled demo), the open state is just set via setOpen(true), and no trigger element is passed.
Looking at the demo again, the "Open programmatically" button does:
onClick={() => {
setTriggerId('alert-trigger-2');
setOpen(true);
}}
So it's setting the triggerId to 'alert-trigger-2' (which corresponds to the "Delete" button), not to the "Open programmatically" button itself. This means the dialog thinks it was opened by the "Delete" button.
Wait, that's actually the intended behavior in this demo! The demo is using triggerId to specify which trigger "owns" the popup. Let me re-read the issue more carefully.
Actually, looking at the issue again:
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.
And the expected behavior:
Keyboard focus should move back to the originating control (if available) when closing a dialog as long as a page refresh or redirection is not triggered.
So the issue is about the focus management, not about which trigger "owns" the popup. The problem is that when opening via a non-trigger element, the domReferenceElement is not updated to that element.
Let me trace through the code again:
- "Open programmatically" button is clicked
setOpen(true) is called
- In
DialogStore.setOpen, since nextOpen is true and eventDetails.trigger is undefined:
- The
setOpenTriggerState function is called with trigger = undefined
- Since
open is true, the state is updated: activeTriggerId = null, activeTriggerElement = null
Wait, let me re-read setOpenTriggerState:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
When opening with no trigger:
open is true
- So the condition
triggerId || open is true
activeTriggerId is set to null (because trigger is undefined, so trigger?.id ?? null is null)
activeTriggerElement is set to null (because trigger ?? null is null)
So after opening programmatically without a trigger, activeTriggerElement becomes null, and domReferenceElement in the FloatingRootStore becomes null.
Then when closing:
getReturnElement() in FloatingFocusManager checks if domReference is connected
- If not, it falls back to
getPreviouslyFocusedElement()
getPreviouslyFocusedElement() returns the last element that was focused before opening the dialog
But wait, what was the last element focused before opening the dialog? When clicking "Open programmatically", the click focuses that button first (via the click event), then the onClick handler fires. So the previously focused element might be the "Open programmatically" button.
Actually, let me think about this differently. The issue says:
Note focus has moved back to the "Delete" button and not the "open programmatically" button as expected.
This suggests that when pressing Esc to close, focus goes to the "Delete" button instead of "Open programmatically". Why?
Let me look at getPreviouslyFocusedElement():
let previouslyFocusedElements: WeakRef<Element>[] = [];
function addPreviouslyFocusedElement(element: Element | null | undefined) {
clearDisconnectedPreviouslyFocusedElements();
if (element && getNodeName(element) !== 'body') {
previouslyFocusedElements.push(new WeakRef(element));
if (previouslyFocusedElements.length > LIST_LIMIT) {
previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);
}
}
}
function getPreviouslyFocusedElement() {
clearDisconnectedPreviouslyFocusedElements();
return previouslyFocusedElements[previouslyFocusedElements.length - 1]?.deref();
}
And it's called in the FloatingFocusManager:
useIsoLayoutEffect(() => {
if (disabled || !floatingFocusElement) {
return undefined;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
addPreviouslyFocusedElement(previouslyFocusedElement);
...
});
So when the dialog opens, the currently focused element (which might be the popup itself or the backdrop) is added to the previously focused elements list. This isn't helpful.
Actually, wait. Let me look at when the dialog opens. The user presses Enter on "Open programmatically" button. At this point:
- The button is focused
- The onClick handler fires
setOpen(true) is called
- The dialog opens
When does addPreviouslyFocusedElement get called? It's in an effect in FloatingFocusManager. Let me see when that effect runs.
Looking at the FloatingFocusManager code, the effect that tracks previously focused elements runs when the floating element is mounted and focused. At that point, the focus might have already moved inside the dialog, so the "previously focused" element is whatever is inside the dialog, not the button that opened it.
The key insight is that when opening the dialog programmatically via a non-trigger element, we need to capture the currently focused element (the button that was clicked/activated) and use it as the return focus target.
Let me think about where to make this fix:
Option 1: In DialogStore.setOpen, when opening and no trigger is provided, set the trigger to the currently focused element.
Option 2: In the FloatingFocusManager, when the return focus target is null, use the currently focused element at the time of opening.
Option 3: In the useSyncedFloatingRootContext, sync the currently focused element when opening.
I think Option 1 is the cleanest approach. When opening and no trigger is provided, we should use the currently focused element as the trigger.
Let me look at the DialogStore.setOpen code again:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
// When closing the dialog, pass the old trigger to the onOpenChange event
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
this.context.onOpenChange?.(nextOpen, eventDetails as DialogRoot.ChangeEventDetails);
if (eventDetails.isCanceled) {
return;
}
this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const updatedState: Partial<State<Payload>> = {
open: nextOpen,
};
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
};
When opening (nextOpen is true):
- The first
if block is skipped (because it's for closing)
onOpenChange is called
- If not canceled,
dispatchOpenChange is called
setOpenTriggerState is called with eventDetails.trigger
The issue is that eventDetails.trigger might be undefined when opening programmatically without a trigger. We should set it to the currently focused element in that case.
Let me also check if there's a PopoverStore or similar for the Popover component. The issue mentions Alert Dialog, Dialog, and Popover.
Actually, let me re-read the setOpenTriggerState function:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
Wait, when opening with no trigger:
trigger is undefined
triggerId is null (because undefined?.id ?? null is null)
open is true
- Condition:
null || true = true, so we enter the block
state.activeTriggerId = null
state.activeTriggerElement = null
So after opening programmatically without a trigger, the active trigger is null. Then when closing:
getReturnElement() in FloatingFocusManager checks domReference
domReference is the domReferenceElement from FloatingRootStore
- Which is synced from
referenceElement from popup store
- Which is
activeTriggerElement
- Which is
null
So the return element falls back to getPreviouslyFocusedElement(), which returns... whatever was focused when the dialog opened.
The fix should be: when opening and no trigger is provided, set the trigger to the currently focused element.
Let me implement this in setOpenTriggerState:
export function setOpenTriggerState(
state: Partial<PopupStoreState<unknown>>,
open: boolean,
trigger: Element | undefined,
) {
const triggerId = trigger?.id ?? null;
// If a popup is opening without a trigger, use the currently focused element
if (open && trigger == null) {
const currentlyFocused = activeElement(ownerDocument(getTarget(event)));
// ...
}
// If a popup is closing, the `trigger` may be undefined.
// We want to keep the previous value so that exit animations are played and focus is returned correctly.
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
Hmm, but this function doesn't have access to the document. Let me think about where the fix should go.
Actually, the fix should probably be in the DialogStore.setOpen method, where we have access to the document:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
// When closing the dialog, pass the old trigger to the onOpenChange event
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
// When opening without a trigger, use the currently focused element
if (nextOpen && eventDetails.trigger == null) {
const focusedElement = activeElement(ownerDocument(this.context.popupRef.current ?? document.body));
eventDetails.trigger = focusedElement ?? undefined;
}
this.context.onOpenChange?.(nextOpen, eventDetails as DialogRoot.ChangeEventDetails);
// ...
};
Wait, but the issue also affects Popover. Let me check how Popover handles this.
Let me also consider: the fix needs to handle edge cases:
- What if the dialog is opened by a touch interaction (no element is focused)?
- What if the dialog is opened by a script that doesn't focus anything?
For case 1, if there's no focused element, we should probably use body or not set any trigger.
Actually, wait. Let me look at the existing code more carefully. The setOpenTriggerState function already handles the case when opening without a trigger - it sets activeTriggerElement to null. The issue is that FloatingFocusManager falls back to getPreviouslyFocusedElement(), which returns the wrong element.
Let me look at how getPreviouslyFocusedElement works. When does it get populated?
In FloatingFocusManager:
useIsoLayoutEffect(() => {
if (disabled || !floatingFocusElement) {
return undefined;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
addPreviouslyFocusedElement(previouslyFocusedElement);
// ...
});
This effect runs when the FloatingFocusManager component mounts. At this point, focus has already been moved inside the dialog (by the initial focus logic), so previouslyFocusedElement is the element inside the dialog, not the element that opened it.
The fix should be to capture the currently focused element at the time of opening and use it as the return focus target.
Actually, I realize now that the issue might be more subtle. Let me look at the full flow again.
When the user presses Enter on "Open programmatically":
- Focus is on the "Open programmatically" button
- Enter key fires
- The onClick handler calls
setOpen(true)
- The dialog opens
- Focus moves inside the dialog (probably to the close button or first focusable element)
At step 4, the FloatingFocusManager effect that adds to previously focused elements runs. At this point, the focus has already moved inside the dialog, so the previously focused element is whatever is inside the dialog.
Actually, wait. The FloatingFocusManager renders inside the DialogPopup, which is conditionally rendered based on mounted. Let me look at how this works.
Looking at DialogPopup:
return (
<FloatingFocusManager
context={floatingRootContext}
openInteractionType={openMethod}
disabled={!mounted}
closeOnFocusOut={!disablePointerDismissal}
initialFocus={resolvedInitialFocus}
returnFocus={finalFocus}
modal={modal !== false}
restoreFocus="popup"
>
{element}
</FloatingFocusManager>
);
And the element is:
{
...
hidden: !mounted,
...
}
So when the dialog is first opened, mounted is true and the popup is rendered with hidden: false. The FloatingFocusManager is also rendered.
The FloatingFocusManager has an initial focus logic that focuses the first tabbable element or the popup itself. This happens during the initial render.
Then the effect that adds to previously focused elements runs (as an effect cleanup). This cleanup runs when the FloatingFocusManager unmounts (when the dialog closes).
Wait, let me re-read:
useIsoLayoutEffect(() => {
if (disabled || !floatingFocusElement) {
return undefined;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
addPreviouslyFocusedElement(previouslyFocusedElement);
// ...
return () => {
// Return focus logic
};
}, [disabled, floating, floatingFocusElement, returnFocusRef, events, tree, domReference, getNodeId, getResolvedInsideElements]);
So the effect:
- Adds the currently focused element to
previouslyFocusedElements (when the dialog opens)
- Returns a cleanup function that handles returning focus (when the dialog closes)
The issue is that when the dialog opens, activeElement(doc) might be the element that was focused before the dialog opened (the "Open programmatically" button), OR it might be the popup/focusable element inside the dialog (after initial focus has been applied).
Actually, I think the initial focus is applied synchronously (in the same render cycle), so by the time the effect runs, focus might have already moved inside the dialog.
Hmm, but the effect is an useIsoLayoutEffect, which runs synchronously after render but before paint. The initial focus is probably also applied in the render cycle or via an effect.
Let me think about this differently. The key question is: what is activeElement(doc) when the FloatingFocusManager's effect runs for the first time?
If focus was moved inside the dialog during the render (before the effect runs), then activeElement(doc) would be the element inside the dialog, not the button.
If focus hasn't moved yet, then activeElement(doc) would be the "Open programmatically" button.
Let me look at the initial focus logic. The FloatingFocusManager's initialFocus logic runs during render (via useIsoLayoutEffect or similar). Let me check.
Looking at FloatingFocusManager:
// Manage focus when tabbing within the floating element.
useIsoLayoutEffect(() => {
// ...
if (open && floatingFocusElement) {
if (initialFocusRef.current !== false) {
// ...
enqueueFocus(targetElement);
}
}
// ...
}, [...]);
And enqueueFocus:
function enqueueFocus(element: FocusableElement | null | undefined) {
if (element) {
focusQueue.push(element);
}
}
So focus is enqueued, not applied immediately. This means the effect that adds to previously focused elements runs while the "Open programmatically" button is still focused.
So previouslyFocusedElement should be the "Open programmatically" button.
But wait, the issue says focus goes to "Delete" button, not the "Open programmatically" button. Let me think about what else could cause this.
Oh wait, I think I understand now. The issue is not about the previously focused element. It's about the domReference (active trigger element).
When the dialog is opened programmatically (without using a trigger), the activeTriggerElement is set to null (because setOpenTriggerState sets it to null when no trigger is provided).
When the dialog is closed:
getReturnElement() in FloatingFocusManager checks if domReference is connected
domReference is the domReferenceElement from FloatingRootStore
domReferenceElement is synced from referenceElement from popup store
referenceElement is activeTriggerElement
activeTriggerElement is null (because the dialog was opened programmatically without a trigger)
So the return focus logic falls through to getPreviouslyFocusedElement().
Wait, but getPreviouslyFocusedElement() should return the "Open programmatically" button, which is what we want. Unless...
Oh, I think I see the issue now. Let me trace through again:
- User clicks "Open programmatically" button
- Focus moves to "Open programmatically" button (via pointerdown/focus event)
- onClick handler fires
setOpen(true) is called
setOpenTriggerState sets activeTriggerElement = null
- FloatingFocusManager effect runs and adds
activeElement(doc) to previously focused elements
- At this point, what is
activeElement(doc)? It could be:
a. The "Open programmatically" button (if focus hasn't moved inside the dialog yet)
b. The popup or first focusable element inside the dialog (if initial focus has been applied)
If it's (a), then getPreviouslyFocusedElement() returns "Open programmatically" button.
If it's (b), then getPreviouslyFocusedElement() returns the element inside the dialog.
Let me check if initial focus is applied before or after the effect that tracks previously focused elements.
Looking at FloatingFocusManager, both the initial focus logic and the "track previously focused" logic are in useIsoLayoutEffect hooks. Since they're separate effects, they might run in order of declaration.
The initial focus effect runs before the "track previously focused" effect (based on the code structure). So by the time the "track previously focused" effect runs, focus has already moved inside the dialog.
This means previouslyFocusedElement is the element inside the dialog (probably the popup or close button), not the "Open programmatically" button.
Then when the dialog closes, getPreviouslyFocusedElement() returns the element inside the dialog. But that element might no longer be valid (the dialog is closing), so it falls back to... wait, what does it fall back to?
Actually, let me re-read getReturnElement():
function getReturnElement() {
const returnFocusValueOrFn = returnFocusRef.current;
let resolvedReturnFocusValue =
typeof returnFocusValueOrFn === 'function'
? returnFocusValueOrFn(closeTypeRef.current)
: returnFocusValueOrFn;
// `null` should fallback to default behavior in case of an empty ref.
if (resolvedReturnFocusValue === undefined || resolvedReturnFocusValue === false) {
return null;
}
if (resolvedReturnFocusValue === null) {
resolvedReturnFocusValue = true;
}
if (typeof resolvedReturnFocusValue === 'boolean') {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
return resolveRef(resolvedReturnFocusValue) || fallback || null;
}
So it checks:
- If
returnFocus is a boolean:
- If
domReference is connected, return it
- Otherwise, return
getPreviouslyFocusedElement() or null
- If
returnFocus is a ref or function:
- Resolve the ref
- Otherwise, fallback to
domReference or getPreviouslyFocusedElement()
In the demo, returnFocus is set via finalFocus prop on DialogPopup:
returnFocus={finalFocus}
If finalFocus is not specified, it defaults to undefined. So returnFocus is undefined, which means resolvedReturnFocusValue is undefined, which means the function returns null.
Wait, that's not right. Let me re-read the getReturnElement() function:
function getReturnElement() {
const returnFocusValueOrFn = returnFocusRef.current;
// ...
if (resolvedReturnFocusValue === undefined || resolvedReturnFocusValue === false) {
return null;
}
// ...
}
So if returnFocus is undefined, the function returns null, and the cleanup function doesn't move focus at all!
But the issue says focus moves to "Delete" button. So something else is happening.
Wait, let me re-read the FloatingFocusManager code. The cleanup function is:
queueMicrotask(() => {
const tabbableReturnElement = getFirstTabbableElement(returnElement);
const hasExplicitReturnFocus = typeof returnFocusValueOrFn !== 'boolean';
if (
returnFocusValueOrFn &&
!preventReturnFocusRef.current &&
isHTMLElement(tabbableReturnElement) &&
// ...
) {
tabbableReturnElement.focus({ preventScroll: true });
}
preventReturnFocusRef.current = false;
});
So if returnFocusValueOrFn is undefined (falsy), the focus is not moved. But the issue says focus moves to "Delete" button.
Hmm, maybe I'm missing something. Let me check the Popover component to see if it has a different returnFocus default.
Actually, wait. The issue mentions Alert Dialog, Dialog, AND Popover. Let me check Popover.
Let me re-read the FloatingFocusManager's returnFocus prop:
/**
* Determines the element to focus when the floating element is closed.
*
* - `false`: Do not move focus.
* - `true`: Move focus based on the default behavior (reference or previously focused element).
* - `RefObject`: Move focus to the ref element.
* ...
* @default true
*/
returnFocus?:
| boolean
| React.RefObject<HTMLElement | null>
| ((closeType: InteractionType) => boolean | HTMLElement | null | void)
| undefined;
The default is true! So returnFocus is true by default, not undefined.
Looking at DialogPopup:
returnFocus={finalFocus}
If finalFocus is not provided, it defaults to undefined. But the FloatingFocusManager default is true. So the prop is undefined, which means FloatingFocusManager's default of true is used.
Wait, no. The prop is undefined, which means returnFocusRef.current is undefined, not the default. Let me check FloatingFocusManager:
const {
context,
openInteractionType,
disabled = false,
initialFocus = true,
returnFocus = true, // <-- default is true
restoreFocus = false,
modal = true,
closeOnFocusOut = true,
// ...
}: FloatingFocusManagerProps = props;
Ah, the default is applied in the destructuring. So returnFocusRef.current is true if the prop is not provided.
But DialogPopup passes finalFocus which might be undefined:
returnFocus={finalFocus}
If finalFocus is undefined, then returnFocus is undefined (the destructuring default only applies if the prop is not passed at all).
Hmm, let me check how DialogPopup uses finalFocus:
const { render, className, style, finalFocus, initialFocus, ...elementProps } = componentProps;
// ...
const resolvedInitialFocus = initialFocus === undefined ? defaultInitialFocus : initialFocus;
// ...
return (
<FloatingFocusManager
// ...
returnFocus={finalFocus}
// ...
>
{element}
</FloatingFocusManager>
);
So returnFocus is the value of finalFocus, which is undefined if not provided by the user.
But wait, I need to check if the DialogPopup is being rendered at all. Let me look at the demo again.
In the demo:
<AlertDialog.Popup className={styles.Popup}>
// ...
</AlertDialog.Popup>
No finalFocus prop is passed, so finalFocus is undefined. This means returnFocus is undefined in FloatingFocusManager.
But the destructuring default is true. So if the prop is not passed at all, returnFocus is true. But if the prop is passed as undefined, it's still undefined.
Wait, this is important. In React, if you pass undefined as a prop value, it's the same as not passing the prop. So returnFocus={undefined} is equivalent to not passing returnFocus at all, which means the default of true is used.
So returnFocus is true by default.
Then in getReturnElement():
if (typeof resolvedReturnFocusValue === 'boolean') {
if (domReference?.isConnected) {
return domReference;
}
return getPreviouslyFocusedElement() || null;
}
Since domReference is null (because activeTriggerElement is null), it returns getPreviouslyFocusedElement() or null.
And getPreviouslyFocusedElement() returns... what? Let me trace through again.
When the dialog opens:
- The user activates "Open programmatically" button (focus moves there)
setOpen(true) is called
activeTriggerElement is set to null
- FloatingFocusManager mounts
- Initial focus logic runs (focus moves inside dialog)
- Effect that tracks previously focused elements runs
addPreviouslyFocusedElement(activeElement(doc)) is called
At step 7, activeElement(doc) is the element inside the dialog (after step 5).
But wait, is that true? Let me check when initial focus is applied.
Looking at FloatingFocusManager, the initial focus logic is in a useIsoLayoutEffect:
// Manage focus when tabbing within the floating element.
useIsoLayoutEffect(() => {
// ...
if (open && floatingFocusElement) {
if (initialFocusRef.current !== false) {
// ...
enqueueFocus(targetElement);
}
}
// ...
}, [...]);
And enqueueFocus just adds to a queue, which is then drained by useAnimationFrame:
useAnimationFrame(() => {
// ...
while (focusQueue.length > 0) {
const element = focusQueue.shift();
enqueueFocus(element);
}
// ...
});
Hmm, this is getting complicated. Let me step back and think about what the issue actually is.
The issue says:
When using the "Open Programmatically" button to open the dialog/popup, then closing it, focus moves to a different control than the one that triggered the dialog/popup.
The "Open Programmatically" button is not a AlertDialog.Trigger, so it doesn't register with the popup store. When opened programmatically, the activeTriggerElement is null or the last trigger that was used.
When closed, focus should return to the "Open Programmatically" button, but it doesn't.
The fix should be: when opening a dialog/popover/alert dialog programmatically (without a registered trigger), capture the currently focused element and use it as the return focus target.
Now, where should this fix go?
Option 1: In DialogStore.setOpen (and similar stores), when opening without a trigger, set the trigger to the currently focused element.
Option 2: In FloatingFocusManager, when returning focus, use the currently focused element at the time of opening (not the currently focused element when the effect runs).
Option 3: In setOpenTriggerState, if opening without a trigger and there's a focused element, use it as the trigger.
I think Option 1 is the cleanest approach because it addresses the issue at the source: when opening without a trigger, we should use the currently focused element.
Let me look at where setOpen is defined and what it has access to.
Looking at DialogStore.setOpen:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
this.context.onOpenChange?.(nextOpen, eventDetails as DialogRoot.ChangeEventDetails);
if (eventDetails.isCanceled) {
return;
}
this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const updatedState: Partial<State<Payload>> = {
open: nextOpen,
};
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
};
The store has access to:
this.context.popupRef - the popup element ref
this.state.floatingRootContext - the floating root context
But it doesn't have direct access to document. We need to get the document from one of the refs.
Actually, we can use ownerDocument utility to get the document from an element. If the popupRef.current is null (which it likely is when opening), we can use document directly.
Wait, but document might not be available on the server. Let me check if there's a utility for this.
Looking at the imports in DialogStore.ts, I don't see ownerDocument or document imported. But I see * as React from 'react'.
Actually, I think we can use the activeElement utility to get the currently focused element. Let me check if it's available.
Looking at floating-ui-react/utils/element.ts:
export function activeElement(doc: Document): Element | null {
if (typeof document !== 'undefined') {
return doc.activeElement;
}
return null;
}
So activeElement takes a document and returns doc.activeElement.
Now, to get the document, we can use ownerDocument from @base-ui/utils/owner:
export function ownerDocument(node: Node | null | undefined): Document {
if (typeof document !== 'undefined' && node instanceof document.constructor) {
return document;
}
const ownerDocument = node?.ownerDocument ?? document;
if (ownerDocument == null || ownerDocument.document == null) {
return document;
}
return ownerDocument;
}
So the fix would be:
- In
DialogStore.setOpen, when opening without a trigger, set the trigger to the currently focused element.
- This way, when closing, focus returns to the element that was focused when the dialog opened.
But wait, there's a subtlety. When opening programmatically:
- The user presses Enter on the "Open programmatically" button
- Focus is on the button
- The onClick handler fires
- At this point,
document.activeElement should be the "Open programmatically" button
So we can capture document.activeElement when opening without a trigger.
Let me implement this fix:
public setOpen = (
nextOpen: boolean,
eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
) => {
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
// When opening without a trigger, use the currently focused element as the trigger
if (nextOpen && eventDetails.trigger == null) {
eventDetails.trigger = ownerDocument(this.context.popupRef.current ?? document.body).activeElement;
}
this.context.onOpenChange?.(nextOpen, eventDetails as DialogRoot.ChangeEventDetails);
if (eventDetails.isCanceled) {
return;
}
this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const updatedState: Partial<State<Payload>> = {
open: nextOpen,
};
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
this.update(updatedState);
};
Wait, but this has a problem. If the dialog is opened by a script (e.g., handle.open() without clicking anything), there might not be any focused element. In that case, we should fall back to null.
Actually, the current code already handles this case:
setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger);
Where setOpenTriggerState does:
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
If eventDetails.trigger is null (because there was no focused element), then activeTriggerElement is null, which is fine.
But there's another issue. When closing, the code passes the activeTriggerElement to onOpenChange:
if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) {
eventDetails.trigger = this.state.activeTriggerElement ?? undefined;
}
This is for controlled scenarios where the onOpenChange handler needs to know which trigger was used. If we always set activeTriggerElement when opening, this should work correctly.
OK, I think the fix is correct. Let me also check if there are similar issues in Popover.
Actually, wait. I need to think about this more carefully. The issue says:
If the control is no longer available, focus should move next to that originating control's position in the DOM.
This suggests that the fix should also consider returning focus to the neighboring element if the original control is no longer available. But for now, let me focus on the main issue: returning focus to the originating control.
Let me also check if the fix needs to be applied to Popover and AlertDialog separately, or if they all use the same DialogStore.
Looking at AlertDialog, it extends DialogHandle and uses DialogStore. So fixing DialogStore should fix AlertDialog too.
For Popover, let me check if it uses the same store mechanism.
<tool_call>
<function=bash_terminal>
<parameter=command>
cat /base-ui/packages/react/src/popover/store/PopoverStore.ts
</tool_call>