Skip to content
TheChatArchiveThe Chat Archive
MiniMaxminimax/minimax-m3· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION Accessibility: Focus moves to the wrong trigger when using "Open…

  1. User

    ISSUE DESCRIPTION

    Accessibility: Focus moves to the wrong trigger when using "Open programmatically" buttons

    Current behavior

    In the Alert Dialog, Dialog and Popover components, there is a variant that includes the option to use multiple triggers to open the dialogs. When using the "Open Programmatically" button to open the dialog/popup, then closing it, focus moves to a different control than the one that triggered the dialog/popup.

    See:

    This could cause failures against WCAG 2.2 Success Criterion 2.4.3 Focus Order when implemented.

    Expected behavior

    Keyboard focus should move back to the originating control (if available) when closing a dialog as long as a page refresh or redirection is not triggered.

    If the control is no longer available, focus should move next to that originating control's position in the DOM.

    Reproducible example

    1. Go to [Alert Dialog: Controlled mode with multiple triggers](https://base-ui.com/react/components/alert-dialog#controlled-mode-with-multiple-triggers
    2. Using keyboard, move focus to the "open programmatically" button
    3. Press Enter to activate the control and open the dialog
    4. Press Esc or activate the close button to close the dialog
    5. Note focus has moved back to the "Delete" button and not the "open programmatically" button as expected.

    Base UI version

    v1.2.0

    Which browser are you using?

    Chrome 145.0.7632.76

    Which OS are you using?

    Mac OS Tahoe 26.2

    Which assistive tech are you using (if applicable)?

    Keyboard

    Additional context

    Recommend keeping track of focus and returning it to the originating control.

    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-$

  2. MiniMax Assistant

    Let me start by exploring the repository structure to understand the codebase.

  3. MiniMax Assistant

    Now let's look at how the focus is managed when closing popups. Let me look at the FocusGuard logic.

  4. MiniMax Assistant

    Now let me look at the detached triggers file. I need to understand how the "open programmatically" cases work.

  5. MiniMax Assistant

    Let me look at FloatingFocusManager to understand the focus restoration:

  6. MiniMax Assistant

    Now let's look at the FloatingRootStore to understand domReference:

  7. MiniMax Assistant

    Now let me look at the useDismiss hook to see what dismiss.reference is:

  8. MiniMax Assistant

    Now let me look at the docs to understand the issue and the demos:

  9. MiniMax Assistant

    Now I understand the scenario. Let me see how the focus management handles the case when opened programmatically. Looking at domReference:

  10. MiniMax Assistant

    Now let me look at the DialogStore, which should be the Dialog's PopupStore implementation:

  11. MiniMax Assistant

    Now I want to look at what FloatingFocusManager receives as domReference. The issue is that when opening programmatically, the activeTriggerElement might still be the last one (which is the trigger button) but the trigger that opened it was the "Open programmatically" button. The domReference is supposed to be the element that triggered the open.

    Let me check the docs/src/app/(private) experiments:

  12. MiniMax Assistant

    Let me understand how domReference and referenceElement work in the FloatingFocusManager:

  13. MiniMax Assistant

    Now let me look at the part where domReference is used to determine focus return:

  14. MiniMax Assistant

    So focus restoration works by focusing on domReference. Now the issue is: when opening the dialog programmatically via the "Open Programmatically" button, the domReference should be that button (so when the dialog is closed, focus should return there).

    Currently, the domReference is set to activeTriggerElement from the popup store. But when the dialog is opened programmatically (and triggerId is set externally to be trigger-2), the dialog is "associated" with the trigger-2 trigger.

    Let me look at how setOpenTriggerState handles opening via triggerId prop:

  15. MiniMax Assistant

    Now let me look at the DialogRoot that handles the triggerId prop:

  16. MiniMax Assistant

    Now I need to understand how activeTriggerId gets set. When we open the dialog programmatically using triggerId="trigger-2", the triggerIdProp will be "trigger-2", and the activeTriggerIdSelector returns triggerIdProp ?? activeTriggerId. So activeTriggerId is "trigger-2".

    But the domReferenceElement would be set from the useSyncedFloatingRootContext to either activeTriggerElement or from somewhere else. Let me check this:

    Looking at useSyncedFloatingRootContext.ts:

    const referenceElement = popupStore.useState('activeTriggerElement');
    

    So the reference is activeTriggerElement, and domReferenceElement is also set if isElement(referenceElement). So we need to make sure activeTriggerElement is updated to the trigger matching triggerIdProp when opening programmatically.

    Let me trace this through to understand the flow.

  17. MiniMax Assistant

    I see! The activeTriggerIdSelector returns triggerIdProp ?? activeTriggerId. But activeTriggerElement is its own separate value. The activeTriggerElement doesn't automatically get synced with the triggerIdProp.

    Let me look at the issue more carefully. The issue is:

    • When opening via "Open programmatically": triggerIdProp is set to trigger-2
    • The dialog state selects activeTriggerId = triggerIdProp = 'trigger-2'
    • But activeTriggerElement may remain as whatever it was last (the trigger-1 button, or trigger-2's previous element if set)
    • The referenceElement of floatingRootContext is set to activeTriggerElement
    • When closing the dialog, the domReference (which is what FloatingFocusManager reads from) is domReferenceElement, which is the referenceElement from the FloatingRootStore

    Let me look at how things get set:

  18. MiniMax Assistant

    Now I see that when the triggerIdProp changes, the activeTriggerElement won't automatically be updated to match. Let me check how this works with useImplicitActiveTrigger:

  19. MiniMax Assistant

    Now let me trace the issue. When the user opens via "Open programmatically" button:

    1. triggerIdProp gets set to "trigger-2"
    2. Store sets triggerIdProp = 'trigger-2'
    3. domReference should reflect the originating button (e.g., the "Open Programmatically" button), so we need to track this

    The issue says: "Recommend keeping track of focus and returning it to the originating control."

    Let me check FloatingFocusManager:

    The approach should be:

    1. When opening the dialog, capture the focused element
    2. When closing the dialog, restore focus to that element

    This needs to be done in the FloatingFocusManager or related logic for the controlled mode.

    Let me check if there's an onActivateTrigger or similar:

  20. MiniMax Assistant

    Let me look at line 661 (which I saw above was setting up the previously focused element):

  21. MiniMax Assistant

    I see. So the FloatingFocusManager tracks previouslyFocusedElement at the time the popup opens. But the issue happens when:

    1. User clicks "Open Programmatically" button. This button is focused.
    2. The dialog opens programmatically. At this point, the FloatingFocusManager's previouslyFocusedElement might already be... wait, let me check the timing.

    Actually, looking more carefully:

    • The Dialog is controlled, so when the user clicks the "Open programmatically" button, open becomes true
    • The FloatingFocusManager is rendered with mounted=true when the popup is mounted
    • The effect that sets previouslyFocusedElement runs when the popup is mounted, which is when the dialog is open

    Hmm, but the effect would still capture previouslyFocusedElement = activeElement(doc), which should be the "Open programmatically" button since that's what's focused.

    Let me look more carefully at the dialog popup render flow:

  22. MiniMax Assistant

    So the FloatingFocusManager only renders when open && mounted. The issue is that when the dialog opens programmatically:

    1. User clicks "Open Programmatically" → focus is on that button
    2. setOpen(true) is called with triggerId='trigger-2'
    3. The dialog mounts → FloatingFocusManager mounts
    4. The FloatingFocusManager's layout effect runs and captures previouslyFocusedElement = activeElement(doc). This SHOULD be the "Open Programmatically" button since the dialog was just mounted.

    Wait, but when the setOpen is called, the open prop changes, and there's likely a re-render. Let me think about this more carefully.

    When the popup is mounted, the layout effect runs AFTER React's commit phase, so by that time, the FloatingFocusManager would mount with the original focused element still being the "Open Programmatically" button.

    But then, the layout effect in FloatingFocusManager does addPreviouslyFocusedElement(previouslyFocusedElement). Then on the next layout effect for setting initial focus, it actually moves focus TO the popup.

    Now when the popup CLOSES, the return focus would be on either domReference or getPreviouslyFocusedElement(). Let me re-read the logic:

  23. MiniMax Assistant

    So getReturnElement() returns domReference if connected, otherwise getPreviouslyFocusedElement() (which was captured when the popup opened).

    So:

    • domReference is domReferenceElement from floatingRootContext, which is set to referenceElement from useSyncedFloatingRootContext.ts, which is activeTriggerElement from the popup store.

    So if activeTriggerElement is null (or set incorrectly), it falls back to getPreviouslyFocusedElement().

    Now the question is: when the dialog opens programmatically:

    • activeTriggerElement is the trigger "trigger-2" (if it was set), but in the demo, when opening programmatically for the first time, the user has not clicked "trigger-2" before, so the activeTriggerElement may be null (or stale).

    Wait, let me look at useImplicitActiveTrigger again:

    The implicit active trigger logic only works when there's a single trigger. With multiple triggers and triggerIdProp set, the activeTriggerElement needs to be set to the corresponding element.

    Let me re-look at this more carefully:

  24. MiniMax Assistant

    Now let me check the popover to see how it might handle this case differently:

  25. MiniMax Assistant

    Now let me look at how the issue is reproduced. Let's create a test reproducer first:

  26. MiniMax Assistant

    Let me create a simple reproducer first:

  27. MiniMax Assistant

    Let me first set up a reproducer test:

  28. MiniMax Assistant

    Now let me create a reproducer test. Let me first check how tests are run:

  29. MiniMax Assistant

    Now let me look at the existing related tests to make sure I understand what needs to be fixed:

  30. MiniMax Assistant

    Let me set up a simple reproducer:

  31. MiniMax Assistant

    Let me create a temporary reproduction script to verify the issue:

  32. MiniMax Assistant

    Let me check the test-utils package:

  33. MiniMax Assistant

    Now let me create a reproducer test in the dialog test file:

  34. MiniMax Assistant

    Let me try another approach - run only the specific test:

  35. MiniMax Assistant

    Hmm, vitest is having issues with browser mode. Let me try a different approach by running just the JSDOM tests:

  36. MiniMax Assistant

    Good, the project setup works from the root. The test was skipped because isJSDOM is true by default. The tests require a browser. Let me remove isJSDOM:

  37. MiniMax Assistant

    I've reproduced the issue. The test shows that focus moves back to the trigger-2 button (the registered trigger with id=trigger-2) when the dialog was opened programmatically via the "Open programmatically" button.

    The expected behavior is that focus should move back to the "Open programmatically" button.

    Now let me think about the fix:

    The fix needs to:

    When the dialog is opened in controlled mode (using triggerId prop), track the originating element (the one that had focus when the open was triggered). When closing, return focus to that originating element.

    Looking at the code:

    • FloatingFocusManager has a previouslyFocusedElement captured when the popup opens (the element focused when the popup opens)
    • But this is a global stack, so when there are multiple components, the stack could have stale data
    • And it seems to be captured at the point the FloatingFocusManager mounts, not at the point when the open method is invoked

    Let me check how the dialog's floatingRootContext is created and how domReferenceElement is set. Looking again at useSyncedFloatingRootContext.ts:

    const referenceElement = popupStore.useState('activeTriggerElement');
    

    So referenceElement (and subsequently domReferenceElement) is set to activeTriggerElement. When the dialog is opened programmatically with triggerId="trigger-2", the triggerIdProp is set externally. The useImplicitActiveTrigger only handles the case when there's a single trigger without an active trigger ID.

    So when the dialog opens programmatically and only triggerIdProp changes to trigger-2, but activeTriggerElement is still pointing to whatever it was before (null initially), the domReferenceElement ends up being null. Then the getReturnElement() falls back to getPreviouslyFocusedElement().

    But wait - the result shows focus is on "Open 2" (trigger-2), so activeTriggerElement must have been trigger-2's element. Let me check the demo again - perhaps useImplicitActiveTrigger does help here:

    Looking at useImplicitActiveTrigger:

    if (!store.select('activeTriggerId') && triggerCount === 1) {
    

    It only kicks in if triggerCount === 1. But we have 2 triggers. So this won't help.

    Let me trace this more carefully. Looking at useTriggerDataForwarding:

    const baseRegisterTrigger = useTriggerRegistration(triggerId, store);
    
    const registerTrigger = useStableCallback((element: Element | null) => {
      baseRegisterTrigger(element);
    
      if (!element) {
        return;
      }
    
      const open = store.select('open');
      const activeTriggerId = store.select('activeTriggerId');
    
      if (activeTriggerId === triggerId) {
        // ...
        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>);
      }
    });
    

    This only sets activeTriggerId when activeTriggerId == null && open. So this doesn't cover our case.

    Now, looking at activeTriggerIdSelector:

    const activeTriggerIdSelector = createSelector(
      (state: S) => state.triggerIdProp ?? state.activeTriggerId,
    );
    

    And activeTriggerElement:

    activeTriggerElement: createSelector((state: S) =>
      state.mounted ? state.activeTriggerElement : null,
    ),
    

    So when triggerIdProp === 'trigger-2' and activeTriggerElement === null:

    • activeTriggerIdSelector returns 'trigger-2'
    • activeTriggerElement returns null (which won't help)

    So referenceElement = null. The FloatingFocusManager falls back to getPreviouslyFocusedElement(), which may be the "Open programmatically" button... but wait, the test says it ends up on trigger-2 button.

    Let me look closer at the demo. When triggerIdProp = 'trigger-2' is set, then activeTriggerIdSelector(state) === 'trigger-2'. Looking at the trigger's data forwarding:

    Actually wait, I need to look at this case: when the dialog is set to open=true and the floatingRootContext has just been created, the activeTriggerElement defaults to null. But the FloatingFocusManager might be tracking via some other mechanism.

    Let me read more carefully about how domReferenceElement gets set:

  38. MiniMax Assistant

    OK so domReferenceElement is activeTriggerElement. Let me trace this:

    • When the dialog is initially created: activeTriggerElement = null
    • When user clicks the "Open programmatically" button:
      • setOpen(true) is called (in the React app's state)
      • setTriggerId('trigger-2') is called
      • The Dialog.Root receives open=true, triggerId='trigger-2'
      • triggerIdProp state becomes 'trigger-2'
      • open becomes true
      • When the Dialog.Portal/Popup renders, the pop-up is mounted

    Wait, but useImplicitActiveTrigger is hooked into the useDialogRoot. Let me check what it does again with multi-triggers:

    if (!store.select('activeTriggerId') && triggerCount === 1) {
      const iteratorResult = store.context.triggerElements.entries().next();
      if (!iteratorResult.done) {
        const [implicitTriggerId, implicitTriggerElement] = iteratorResult.value;
        stateUpdates.activeTriggerId = implicitTriggerId;
        stateUpdates.activeTriggerElement = implicitTriggerElement;
      }
    }
    

    OK, so this only updates if there's exactly 1 trigger. In our case we have 2.

    Now let me think about this case: When triggerIdProp='trigger-2' is set externally but activeTriggerElement is null, the useImplicitActiveTrigger doesn't help.

    But the popup still opens. Why does it open? Because of triggerIdProp. And domReferenceElement is null when the FloatingFocusManager renders.

    Now when the FloatingFocusManager mounts (because mounted is now true), it captures the previouslyFocusedElement (which should be the "Open programmatically" button). When the dialog closes, it should restore focus to that button... but in the test, it doesn't.

    Wait, let me re-read the FloatingFocusManager logic carefully:

    function getReturnElement() {
      // ...
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
      // ...
    }
    

    If domReference (i.e., domReferenceElement) is not connected OR null, fall back to getPreviouslyFocusedElement().

    In our case, domReference is null (because activeTriggerElement was null when the popup opened). So it should fall back to getPreviouslyFocusedElement().

    But test shows focus is on trigger-2! Let me dig deeper:

  39. MiniMax Assistant

    Now let me check how setOpen is called by DialogPopup when onOpenChange triggers it:

  40. MiniMax Assistant

    OK, so the issue is that:

    1. When the user calls setOpen(true) from their onOpenChange handler (via the Close button), it sets eventDetails.trigger = activeTriggerElement ?? undefined
    2. Then setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger) is called - this sets activeTriggerId and activeTriggerElement to null (because eventDetails.trigger is undefined)

    Actually wait - close. setOpenTriggerState logic:

    export function setOpenTriggerState(
      state: Partial<PopupStoreState<unknown>>,
      open: boolean,
      trigger: Element | undefined,
    ) {
      const triggerId = trigger?.id ?? null;
    
      // If a popup is closing, the `trigger` may be undefined.
      // We want to keep the previous value so that exit animations are played and focus is returned correctly.
      if (triggerId || open) {
        state.activeTriggerId = triggerId;
        state.activeTriggerElement = trigger ?? null;
      }
    }
    

    When closing and no trigger, the previous values stay. So activeTriggerElement doesn't change to null. So it stays at the previous value (trigger-2 if it was set, or null if not).

    Actually wait, in our test scenario:

    • User clicks "Open programmatically" button
    • setTriggerId('trigger-2') and setOpen(true) are called from the React app
    • The Dialog.Root receives open=true, triggerId='trigger-2'
    • triggerIdProp becomes 'trigger-2'
    • activeTriggerIdSelector(state) returns 'trigger-2' (because of triggerIdProp)
    • The Dialog mounts (popup mounts)
    • FloatingFocusManager renders
    • The user clicks Close button → Dialog is closed
    • setOpen(false, ...) is called internally
    • The cleanup of FloatingFocusManager's effect runs → returns focus

    But before the close, what's activeTriggerElement? Let me look at this more carefully.

    Looking at useImplicitActiveTrigger - it works with multiple triggers but only sets one if triggerCount === 1. We have 2 triggers. So this won't update activeTriggerElement.

    So when the popup is opened:

    • activeTriggerIdSelector returns 'trigger-2' (from triggerIdProp)
    • activeTriggerElement is null (because no trigger had been clicked)

    But wait - the test results show focus moves to the trigger-2 button. So activeTriggerElement is the trigger-2 element, not null!

    Let me trace again. Let me re-read useImplicitActiveTrigger:

    export function useImplicitActiveTrigger<State extends PopupStoreState<unknown>>(
      store: ReactStore<State, PopupStoreContext<never>, typeof popupStoreSelectors>,
    ) {
      const open = store.useState('open');
      const reactiveTriggerCount = store.useState('triggerCount');
    
      useIsoLayoutEffect(() => {
        if (!open) {
          // ...
          return;
        }
    
        const triggerCount = store.context.triggerElements.size;
        const stateUpdates: Partial<PopupStoreState<unknown>> = {};
    
        if (store.state.triggerCount !== triggerCount) {
          stateUpdates.triggerCount = triggerCount;
        }
    
        if (!store.select('activeTriggerId') && triggerCount === 1) {
          // This branch only sets when count is 1
          // ...
        }
    
        if (stateUpdates.triggerCount !== undefined || stateUpdates.activeTriggerId !== undefined) {
          store.update(stateUpdates as Partial<State>);
        }
      }, [open, store, reactiveTriggerCount]);
    }
    

    OK, only triggers when triggerCount is 1. Not our case.

    Then how does activeTriggerElement get set to trigger-2?

    Let me look at useTriggerDataForwarding more carefully:

    export function useTriggerDataForwarding<State extends PopupStoreState<unknown>>(...) {
      // ...
      const registerTrigger = useStableCallback((element: Element | null) => {
        baseRegisterTrigger(element);
    
        if (!element) {
          return;
        }
    
        const open = store.select('open');
        const activeTriggerId = store.select('activeTriggerId');
    
        if (activeTriggerId === triggerId) {
          // Update element
          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>);
        }
      });
    

    This says: if there's no active trigger and the dialog is open, the FIRST registered trigger "claims" the dialog. So when the dialog opens programmatically (and triggerIdProp is set externally), activeTriggerId is "trigger-2" (from the selector). Then when "trigger-2"'s element registers, activeTriggerId === triggerId becomes true, and activeTriggerElement gets set.

    So activeTriggerElement = trigger-2 element.

    Now when the dialog closes, domReference = trigger-2 element, so focus returns to trigger-2. That's what the test shows!

    So the fix should be: when the dialog is opened programmatically and there's no physical trigger element responsible (just a button that triggered the open), we need to remember the originating element and use that for focus return.

    Approach: We need to track the originating element (focused element) before the controlled open is triggered. When the dialog is open and the activeTriggerElement corresponds to the triggerIdProp, we should use the originating element as the focus return target.

    Let me think about the cleanest way to implement this. The issue recommends "keeping track of focus and returning it to the originating control".

    There's a returnFocus prop on DialogPopup. Looking at the FloatingFocusManager's logic:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      let resolvedReturnFocusValue =
        typeof returnFocusValueOrFn === 'function'
          ? returnFocusValueOrFn(closeTypeRef.current)
          : returnFocusValueOrFn;
      // ...
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
      // ...
    }
    

    The previouslyFocusedElement IS captured at the open time. The problem is that when the dialog is opened programmatically AND in controlled mode via triggerId, the domReference becomes the trigger that matches the triggerId (because of the useTriggerDataForwarding logic).

    What if we DON'T update the domReference for domReferenceElement to be set to activeTriggerElement when the triggerIdProp is set externally? Or, alternatively, capture the originating focused element as previouslyFocusedElement at the time the open is requested (when open goes from false to true).

    Actually, let me think about this carefully. The cleanest fix:

    Option 1: When the dialog opens (open transitions to true), capture the currently focused element. Use this captured element as the focus return target when the dialog closes.

    Looking at the FloatingFocusManager:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      let resolvedReturnFocusValue = // ...
    
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
    }
    

    The getPreviouslyFocusedElement is the previously focused element before the popup opened. So this falls back to the focused element at open-time.

    But wait - the problem in the test is that domReference is connected and set (to trigger-2), so it returns focus to trigger-2 instead of the "Open programmatically" button.

    So the issue is that domReference is being set incorrectly to trigger-2 when the dialog was opened via a programmatic call (not via clicking trigger-2).

    Let me look at this approach: If the dialog opens via programmatic means (not directly by clicking on the trigger that owns it), then domReference should not be the trigger. Instead, the originating focus should be tracked.

    Looking more carefully at the code, I see that:

    • When the user opens the dialog programmatically and sets triggerIdProp externally, the activeTriggerIdSelector returns the value from triggerIdProp, not from activeTriggerId
    • The trigger's useTriggerDataForwarding then sees activeTriggerId === triggerId (after the selector returns it) and sets activeTriggerElement to that trigger's element

    This is problematic because we're conflating:

    1. The logical "active trigger" (used for ARIA relations, payload, etc.)
    2. The "originating focus element" (used for focus return)

    The fix should separate these two concepts. When the dialog opens programmatically (without the user clicking the trigger that owns it), we should track the originating focused element and use that for focus return.

    Let me think about this differently. The simplest approach is:

    Option 2: When the dialog is opened (open prop transitions from false to true) externally without an actual click on the trigger element, capture the focused element at that moment. Use that as the focus return target.

    Let me look at where the dialog opens. The dialog stores transition from closed to open. This happens in DialogStore.setOpen(). Let me check who calls it:

    Actually, in the demo, the user calls setTriggerId('trigger-2') and setOpen(true) from the React app. Then onOpenChange is fired with (true, ...), and React updates the state, the Dialog re-renders with open=true. But the setOpen(true) of the dialog store happens... when?

    Let me look:

  41. MiniMax Assistant

    Now let me look at the dialog's store methods:

  42. MiniMax Assistant

    So when triggerIdProp is changed externally (controlled), it's synced into the store's triggerIdProp. Then activeTriggerIdSelector picks that up.

    Now, the fix: I need to think about how to track the originating focused element when the dialog opens in controlled mode.

    Looking at this from a fresh perspective:

    • The FloatingFocusManager already tracks the previouslyFocusedElement on mount and stores it in a module-level previouslyFocusedElements array.
    • The issue is that when domReference is set (to the trigger-2 element via the popup store logic), it takes precedence over previouslyFocusedElement.
    • The fix is to prefer the previously focused element over domReference when the popup was opened programmatically.

    Actually, the cleanest fix would be to track in the store, separately from domReference, the "originating element" that was focused when the popup was opened. When the popup is closed, return focus to that originating element.

    Let me think about how to implement this cleanly.

    Approach:

    1. Add a new state field originElement to the PopupStore that captures the element focused when the popup was opened.
    2. When the popup opens, capture this element.
    3. When the popup closes, prefer this element as the focus return target.

    But wait, the FloatingFocusManager's logic uses domReference. Let me re-read:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      // ...
      if (typeof resolvedReturnFocusValue === 'boolean) {
        if (domReference?.isConnected) {
          return domReference;
        }
        return getPreviouslyFocusedElement() || null;
      }
      // ...
    }
    

    So if returnFocus prop is not explicitly set (which is the default), and domReference is connected, it returns domReference.

    One approach: in the DialogPopup, when the popup is being closed and there's an origin element that's the focused element before the popup opened, use that as the focus return. We can do this by setting the returnFocus prop to a function that returns the originating element.

    Actually, looking at the FloatingFocusManager code, it already passes getPreviouslyFocusedElement() (captured at open time) as the focus target. The issue is that domReference takes precedence.

    Let me check the FloatingFocusManager code more carefully - specifically how domReference gets passed:

  43. MiniMax Assistant

    OK. So domReference is read from the store. Let me think about this differently.

    Since the dialog is in controlled mode and triggerIdProp is being set externally (not via clicking the trigger), we need to:

    1. NOT set activeTriggerElement to the trigger's element when the popup is opened via controlled triggerId
    2. INSTEAD use the previously focused element for focus return

    Let me look at the useTriggerDataForwarding again to see how it currently sets activeTriggerElement:

    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;
        }
        // ...
    });
    

    The trigger-2 trigger registers, and since activeTriggerId === triggerId (via the selector that uses triggerIdProp), activeTriggerElement gets set to trigger-2's element.

    Hmm, this is the problem. The selector returns 'trigger-2' because of triggerIdProp, but the trigger wasn't actually clicked; the programmatic button was.

    Let me look at if there's a way to distinguish:

    • The activeTriggerId set via clicking the trigger (regular way) → activeTriggerElement should be the trigger's element
    • The activeTriggerId set via triggerIdProp (programmatic way) → activeTriggerElement should NOT be the trigger's element

    The simplest way to distinguish: the triggerIdProp field tells us. If it's set, we shouldn't let trigger elements "claim" it.

    Actually, looking at the existing logic in 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;
      }
    }
    

    This is called by setOpen(). When opening, trigger is set when the trigger was clicked. When triggered programmatically, trigger would be undefined.

    Looking at the use of setOpenTriggerState:

    • In the dialog, when closing, eventDetails.trigger = this.state.activeTriggerElement ?? undefined; is set
    • Then setOpenTriggerState(updatedState, nextOpen, eventDetails.trigger) is called

    The flow when trigger-2 is clicked:

    1. Trigger-2's onClick → setOpen(true, ...) is called with eventDetails.trigger = trigger-2 element
    2. setOpenTriggerState sets activeTriggerId = 'trigger-2' and activeTriggerElement = trigger-2 element

    The flow when the programmatic button is clicked:

    1. The user sets open=true and triggerIdProp='trigger-2' from their React state
    2. The Dialog's triggerIdProp is updated to 'trigger-2'
    3. But the dialog's setOpen is NOT called from the trigger (because no trigger was clicked)
    4. The Dialog's open goes from false to true via the React state

    Hmm wait, does the dialog's setOpen ever get called when controlled? Let me check:

    Looking at useRenderDialogRoot:

    store.useControlledProp('openProp', openProp);
    store.useControlledProp('triggerIdProp', triggerIdProp);
    

    So when openProp changes externally, openProp in the store gets set. Looking at how open is determined:

    const openSelector = createSelector((state: S) => state.openProp ?? state.open);
    

    And:

    mounted: createSelector((state: S) => state.mounted),
    

    The open selector returns openProp ?? state.open. And mounted is its own thing. Let me check useOpenStateTransitions:

  44. MiniMax Assistant

    OK. So when the popup closes (and the transition ends), forceUnmount is called, which sets activeTriggerId = null and activeTriggerElement = null. So after the close transition, these are reset.

    Now I think the cleanest fix would be:

    Fix: Track the originating focused element in the store (or in a state field). When the popup closes and we're returning focus, prefer this originating element over the trigger element if the popup was opened in controlled mode without an actual trigger interaction.

    Wait, but the FloatingFocusManager is what's actually handling the focus return. The DialogPopup passes through the domReference...

    Let me look at the design more carefully. The FloatingFocusManager is rendering based on the popup store. The domReferenceElement is derived from referenceElement = activeTriggerElement. So to fix this, we need to either:

    1. Not set activeTriggerElement for triggers when triggerIdProp is being set externally
    2. Or, override the domReference in FloatingFocusManager to use the originating element

    I think option 2 is cleanest because:

    • The trigger-2 element IS the logical "trigger" for purposes of ARIA, payload, etc.
    • But for focus management, we want to use the element that was actually focused before the popup opened

    Let me look at the DialogPopup props and how finalFocus is passed:

  45. MiniMax Assistant

    So finalFocus is the user-facing API to override focus return. We can use this in the DialogPopup to provide a fallback to the originating element.

    Hmm, let me think of an even simpler approach. The existing previouslyFocusedElements array in FloatingFocusManager already tracks this. We just need to prefer it over domReference when the popup was opened programmatically.

    Actually, the cleanest fix: store the originating element in the popup store when the dialog opens programmatically. Then in the DialogPopup, pass finalFocus such that it returns the originating element if available.

    Let me look more carefully at the FloatingFocusManager's getReturnElement:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      let resolvedReturnFocusValue = ...
    
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
    
      const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
    
      return resolveRef(resolvedReturnFocusValue) || fallback || null;
    }
    

    So if we pass returnFocus as a function that returns the originating element, it would be used.

    Actually, looking at this more carefully, the issue is in how the originating element is captured. Let me look at addPreviouslyFocusedElement:

    const previouslyFocusedElement = activeElement(doc);
    addPreviouslyFocusedElement(previouslyFocusedElement);
    

    This happens in the FloatingFocusManager's mount effect, but only AFTER the popup mounts. So by the time we capture it, the focus might have already moved.

    Wait, but the layout effect runs BEFORE the browser paints, so it should be after the focus shift to the popup has happened (because the popup is now mounted). Actually no - the layout effect runs after the popup is rendered but before the initial focus is set.

    Let me look at the order:

    1. Dialog mounts (popup element exists in DOM)
    2. Layout effects run in the new tree:
      • FloatingFocusManager's effect captures previouslyFocusedElement = activeElement(doc) (still the "Open programmatically" button)
      • addPreviouslyFocusedElement(previouslyFocusedElement)
      • A microtask is scheduled to do the initial focus
    3. Microtask runs: focus moves to the popup

    So the previouslyFocusedElement IS captured before the focus move. And it's stored in the module-level previouslyFocusedElements array. And getPreviouslyFocusedElement() should return it.

    But the issue is that the function prefers domReference if it's connected. So even though the previously focused element is captured correctly, it's not used.

    Fix Idea 1: Modify the DialogPopup to provide a returnFocus function that returns the previously focused element captured at open time.

    Let me look for how this could be done cleanly. We need to capture the element at the moment of open (well, slightly after open since the popup needs to render first).

    Actually, looking at this more carefully, the issue is conceptual:

    • The popup considers trigger-2 as the "active trigger" because triggerIdProp='trigger-2' was set
    • Trigger-2's element is registered and becomes the activeTriggerElement
    • When closing, focus returns to trigger-2's element

    But the "originating control" was the "Open programmatically" button, not trigger-2.

    The recommended fix from the issue: "Keep track of focus and returning it to the originating control."

    So my fix approach:

    1. Capture the originating focused element when the dialog opens (or right before)
    2. When the dialog closes, return focus to that originating element if it's still connected

    Let me look at how the open happens. When user clicks "Open programmatically":

    1. React re-renders with open=true, triggerIdProp='trigger-2'
    2. openProp in the store gets updated via useControlledProp
    3. open (the selector) returns true
    4. useOpenStateTransitions updates mounted to true
    5. The Dialog.Portal renders → Dialog.Popup mounts → FloatingFocusManager mounts
    6. FloatingFocusManager captures previouslyFocusedElement

    But wait - the open transition happens AFTER React re-renders. The click on "Open programmatically" already moved focus to that button. So by the time FloatingFocusManager mounts, focus is on "Open programmatically".

    The problem: when the popup mounts, the layout effect captures previouslyFocusedElement. But the cleanup run when unmounting uses domReference first.

    Let me check the cleanup code:

  46. MiniMax Assistant

    OK so the cleanup of FloatingFocusManager runs when it unmounts (popup closes). It focuses tabbableReturnElement (or its first tabbable child).

    Now my plan:

    1. In the Dialog/Popover/Popup, when the popup mounts, capture the originating focused element.
    2. When the popup closes, pass this element as the focus return target.

    Let me check if there's a way to easily implement this in DialogPopup:

  47. MiniMax Assistant

    OK. Now let me think about a clean implementation.

    My approach:

    1. Add a state field originatingElement (or similar) to the popup store that captures the focused element before the popup opens.
    2. Use this field to determine focus return when the popup closes.

    Looking at where I should hook in:

    • The originating focused element should be captured when open transitions from false → true
    • It's the element focused BEFORE the popup opened

    The FloatingFocusManager already does this conceptually (the previouslyFocusedElement), but it prefers domReference over it.

    Let me look at if we should just modify domReference in the sync:

  48. MiniMax Assistant

    So domReferenceElement is syncing from referenceElement which is activeTriggerElement. The fix should either:

    1. Not update activeTriggerElement to the trigger element when triggerIdProp is set externally
    2. Or use a different element for the domReferenceElement

    Actually, looking at this more carefully, here's a better idea:

    In the popup store, track who "owns" the active trigger:

    • If triggerIdProp is set externally, the actual click was NOT on the trigger element
    • In this case, activeTriggerElement should not be set to the trigger's element

    Let me look at the triggerDataForwarding more carefully:

  49. MiniMax Assistant

    OK. So useTriggerDataForwarding has this logic: if the activeTriggerId (via selector) matches the trigger's id, it sets activeTriggerElement to the trigger's element. This is the problem.

    Let me trace what happens when triggerIdProp is set externally:

    1. The user clicks "Open programmatically" → state updates: open=true, triggerIdProp='trigger-2'
    2. React re-renders, triggerIdProp gets stored in the dialog store
    3. activeTriggerIdSelector returns 'trigger-2' (via triggerIdProp fallback)
    4. The Dialog.Portal mounts → Dialog.Popup renders → FloatingFocusManager renders
    5. The triggers render their registerTrigger callbacks: trigger-1, trigger-2, etc.
    6. When trigger-2 element registers (since its id matches activeTriggerId), useTriggerDataForwarding sees activeTriggerId === triggerId === 'trigger-2', and updates activeTriggerElement = trigger-2 element

    This means even though trigger-2 wasn't clicked, its element gets registered as the active trigger's element.

    The fix needs to ensure that activeTriggerElement is NOT set to a trigger's element when triggerIdProp is being used to drive the activeTriggerId.

    How can we tell whether triggerIdProp was set externally vs whether a trigger click set the activeTriggerId?

    Hmm, let me look at the DialogStore.setOpen method:

    public setOpen = (
        nextOpen: boolean,
        eventDetails: Omit<DialogRoot.ChangeEventDetails, 'preventUnmountOnClose'>,
      ) => {
        (eventDetails as 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);
      };
    

    So setOpen takes a trigger in eventDetails. When the user clicks a trigger, eventDetails.trigger is the trigger element. When closing, eventDetails.trigger may be set or null/undefined.

    Looking at setOpenTriggerState:

    export function setOpenTriggerState(
      state: Partial<PopupStoreState<unknown>>,
      open: boolean,
      trigger: Element | undefined,
    ) {
      const triggerId = trigger?.id ?? null;
    
      // If a popup is closing, the `trigger` may be undefined.
      // We want to keep the previous value so that exit animations are played and focus is returned correctly.
      if (triggerId || open) {
        state.activeTriggerId = triggerId;
        state.activeTriggerElement = trigger ?? null;
      }
    }
    

    When opening: activeTriggerId = the trigger's id (or null if no trigger), activeTriggerElement = the trigger's element.

    OK now I have a clearer picture. Let me think about the simplest fix.

    The simplest fix is: When triggerIdProp is set externally (used as the controlled trigger id), we need to track the originating focused element, and prefer it for focus return.

    Actually here's an interesting observation. When the user programmatically opens the dialog:

    • They set open=true and triggerIdProp='trigger-2' in their state
    • useControlledProp updates openProp and triggerIdProp in the store
    • But store.setOpen() is NOT called! Only store.update happens internally via useControlledProp.

    This means setOpenTriggerState is never called for the open. So activeTriggerId and activeTriggerElement don't get set via setOpen.

    But useTriggerDataForwarding still sets them based on activeTriggerIdSelector (which uses triggerIdProp ?? activeTriggerId).

    Now the question: how do we detect that the dialog was opened "externally" vs by a trigger click?

    We need a way to track this. One way: when the controlled open happens, capture the focused element as the originating element.

    Let me think about implementing this:

    1. Add a previouslyFocusedElement state field (module-level like in FloatingFocusManager, or store-level)
    2. Capture it in the FloatingFocusManager mount effect AND in a layout effect that runs earlier
    3. Use it as the fallback for focus return

    Actually, let me revisit. Looking at the FloatingFocusManager, the issue is in this code:

    function getReturnElement() {
      // ...
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
      // ...
    }
    

    So when the controlled mode sets activeTriggerElement to trigger-2's element (via useTriggerDataForwarding), and domReferenceElement syncs from this, the domReference becomes trigger-2's element (which is connected), and focus returns to it.

    My fix plan:

    1. Make activeTriggerElement track only when the dialog is opened via trigger interaction.
    2. When opened via triggerIdProp set externally, the originating element should be tracked separately.

    The cleanest way to implement this:

    1. Add a new state field originElement that captures the focused element when the popup is opened without a trigger click.
    2. Use this as the focus return target.

    Let me implement this:

  50. MiniMax Assistant

    Now let me think about what would be the cleanest way to implement this fix.

    The issue occurs because useTriggerDataForwarding matches the activeTriggerId (which may be from triggerIdProp) and sets activeTriggerElement to the trigger's element. This conflates the "logical trigger" with "focus return target".

    Better approach: We should NOT set activeTriggerElement to the trigger element when activeTriggerId is being driven by triggerIdProp (and not by a trigger click).

    Actually wait, looking again at activeTriggerElement and domReferenceElement:

    • activeTriggerElement is used for ARIA relationships and aria-controls
    • domReferenceElement is the reference element used by FloatingFocusManager for focus return

    These two are different. Let me see how they're separated in code...

    Actually, looking at useSyncedFloatingRootContext.ts:

    if (isElement(referenceElement)) {
      valuesToSync.domReferenceElement = referenceElement;
    }
    

    So domReferenceElement = referenceElement = activeTriggerElement. They're the same field being used for two purposes.

    Hmm. Let me actually trace through the demo scenario again:

    1. App initializes with open=false, triggerId=null
    2. User clicks "Open programmatically" button (which has focus now)
    3. App state updates: open=true, triggerId='trigger-2'
    4. React re-renders → DialogRoot sees open=true, triggerId='trigger-2'
    5. The triggerIdProp in the store becomes 'trigger-2'
    6. The open selector returns true
    7. useOpenStateTransitions sets mounted=true (with delay potentially)
    8. Dialog.Portal mounts → Dialog.Popup mounts
    9. The triggers (trigger-1, trigger-2) are React components that mounted earlier. But the issue is: do they re-register when the dialog opens?

    Looking at useTriggerRegistration:

    return React.useCallback(
      (element: Element | null) => {
        if (id === undefined) {
          return;
        }
        // ...
        if (element !== null) {
          registeredElementIdRef.current = id;
          registeredElementRef.current = element;
          store.context.triggerElements.add(id, element);
          // ...
        }
        // ...
      },
      [store, id],
    );
    

    So triggers register on mount. They were already mounted when the dialog was closed. So they should already be in the triggerElements map.

    But useTriggerDataForwarding runs the registerTrigger callback. Let me check:

    const registerTrigger = useStableCallback((element: Element | null) => {
      baseRegisterTrigger(element);
      // ...
    });
    

    This is the callback returned from useTriggerDataForwarding. It calls baseRegisterTrigger (which is useTriggerRegistration's callback) AND THEN does its own logic.

    But the callback only runs when the ref changes (mounting or element change). The triggers are already mounted, so the callback only runs on mount/unmount.

    But wait, the triggers haven't been unmounted. So the callback has already run. Let me re-check the timing.

    Hmm, but the test is showing that focus moves to "Open 2" (trigger-2's button). So somehow activeTriggerElement = trigger-2 element. Let me dig.

    Looking at useTriggerDataForwarding's callback:

    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({...});
      }
    });
    

    So if the trigger element registers AND activeTriggerId === triggerId, then activeTriggerElement = element.

    Now consider this scenario:

    1. App loads with open=false, triggerId=null
    2. The two trigger components mount. Their registerTrigger callbacks run.
      • Trigger-1: registers in triggerElements map. activeTriggerIdSelector returns triggerIdProp ?? activeTriggerId = null ?? null = null. Not equal to 'trigger-1'. activeTriggerId == null && open=false → don't update.
      • Trigger-2: same. But activeTriggerId == null && open=false is false (open is false), so don't update.
    3. User clicks "Open programmatically" → focus is on that button
    4. open=true, triggerId='trigger-2'
    5. React re-renders. triggers don't unmount, so their registerTrigger callbacks don't re-run with their element.

    So activeTriggerElement shouldn't be set. But the test shows it IS...

    Let me check more carefully. Looking at useTriggerRegistration:

    return React.useCallback(
      (element: Element | null) => {
        // ...
        if (element !== null) {
          registeredElementIdRef.current = id;
          registeredElementRef.current = element;
          store.context.triggerElements.add(id, element);
          // ...
        }
        // ...
      },
      [store, id],
    );
    

    This is a callback ref. It would only re-run when the ref changes.

    But also, the trigger element ref also forwarded refs... let me check the DialogTrigger:

  51. MiniMax Assistant

    So registerTrigger is the ref callback that runs when the trigger element mounts. Once mounted, it doesn't re-run unless the element changes.

    Let me look at the layout effect in useTriggerDataForwarding:

    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger) {
        store.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates,
        } as Partial<State>);
      }
    }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
    

    isMountedByThisTrigger depends on activeTriggerIdSelector === triggerId && mounted. When triggerIdProp='trigger-2' and the popup is mounted:

    • For trigger-2: activeTriggerIdSelector='trigger-2' === 'trigger-2' and mounted=true, so isMountedByTrigger=true
    • The layout effect runs: activeTriggerElement = triggerElementRef.current = trigger-2's element

    So activeTriggerElement is set to trigger-2's element via this layout effect.

    OK now the problem is clear. The fix should ensure that when triggerIdProp is set externally (programmatically), the layout effect doesn't override activeTriggerElement.

    Let me think about a clean fix.

    My plan:

    1. In useTriggerDataForwarding's layout effect, check if the active trigger ID was set via triggerIdProp (vs being set by an actual trigger click).
    2. If it was set via triggerIdProp, don't update activeTriggerElement from the trigger element.
    3. Instead, capture the originating focused element as activeTriggerElement from a different source.

    Hmm, but we need a different state field for the originating element to be set somewhere. Let me think.

    Actually, here's a cleaner approach:

    Approach:

    • Add a new state field originElement to the popup store
    • When the popup mounts in controlled mode without a trigger click, set originElement to the currently focused element
    • The domReferenceElement should use originElement (or fall back to activeTriggerElement)
    • When triggerIdProp is unset (i.e., opened via trigger click), originElement is not used

    But this requires knowing when the popup is opened "externally" vs via trigger click. The user controls triggerIdProp. So if triggerIdProp is set, we should use originElement instead of activeTriggerElement.

    Actually, I think there's a simpler approach. Let me look at the popover's logic for similar handling:

    Looking at popover Popup:

    const activeTriggerElement = store.useState('activeTriggerElement');
    

    And uses it for previousFocusableElement:

    previousFocusableElement={
      isHTMLElement(activeTriggerElement) ? activeTriggerElement : undefined
    }
    

    This is the element used as previousFocusableElement for the focus guard.

    OK let me think about this in a different way.

    Approach: When the user opens the dialog via the controlled open path (where they set open=true in their state), we want to capture the currently focused element and use it as the focus return target. This should be tracked separately from activeTriggerElement (which is the "logical owner" of the dialog for ARIA purposes).

    Let me implement this:

    1. Add a new state field originElement (or originatingElement) to the popup store, default null.
    2. When open transitions from false to true (and activeTriggerElement would be null), capture the currently focused element as originElement.
    3. In FloatingFocusManager's getReturnElement, prefer originElement over domReference.

    Wait, but the popup store doesn't have direct access to document to capture activeElement. We'd need a hook for this.

    Actually, let me look at the existing pattern. The FloatingFocusManager captures previouslyFocusedElement as activeElement(doc). So we have a precedent.

    Let me approach this from the DialogPopup level:

    In the DialogPopup (and PopoverPopup, AlertDialogPopup):

    1. Track the originating focused element when the popup mounts
    2. Pass it as the returnFocus target

    Let me check the props:

    returnFocus={
      isHTMLElement(activeTriggerElement) && !isControlled
        ? activeTriggerElement 
        : undefined
    }
    

    But this needs to know if it's controlled. Hmm.

    Actually wait, here's another idea. We can modify the popup store to track this:

    In useDialogRoot (or similar hook):

    1. When open transitions from false to true, capture the currently focused element as originElement
    2. When closing, use originElement if available, fall back to activeTriggerElement

    Let me search for a place to put this logic:

  52. MiniMax Assistant

    Let me search for hooks that capture the focused element:

  53. MiniMax Assistant

    Now let me look at where the layout effect captures the focus (line 733):

  54. MiniMax Assistant

    OK so the layout effect runs when the popup mounts (because floatingFocusElement is now defined). At this point:

    • It captures previouslyFocusedElement = activeElement(doc) (which IS the "Open programmatically" button)
    • It calls addPreviouslyFocusedElement(previouslyFocusedElement) which adds it to the module-level array

    So getPreviouslyFocusedElement() returns the "Open programmatically" button. But the cleanup prefers domReference over this.

    The cleanest fix: In FloatingFocusManager's getReturnElement(), prefer getPreviouslyFocusedElement() over domReference in some cases. Or alternatively, when the popup was opened programmatically (no actual trigger click), prefer the previously focused element.

    Hmm, but FloatingFocusManager is generic - it doesn't know about controlled/programmatic opens.

    The cleanest approach is to have the Dialog/Popover/etc. components manage this themselves by capturing the originating element and passing it to the focus manager as a custom returnFocus.

    Let me implement this. I'll add a new internal state for "originating element" that captures the focused element when the popup opens in controlled mode. Then I'll use it for focus return.

    Actually, wait. Let me re-think this. The simplest fix is:

    1. When the popup opens in controlled mode (open transitions from false → true) and there's no trigger interaction, capture the currently focused element
    2. Store it as a "originating element" in the store
    3. Use it for focus return

    But we need to detect "controlled mode without a trigger interaction". This is the same as saying triggerIdProp is set externally OR there's no trigger click.

    Actually, here's a different idea: When triggerIdProp is set but the originating button was the "Open programmatically" button (not the trigger button), we know activeTriggerElement will eventually be set to the wrong element.

    So the fix is: When triggerIdProp is set externally, we should track the originating element as activeTriggerElement INSTEAD of letting it be overridden by the trigger's element via useTriggerDataForwarding.

    Let me think about this more carefully:

    Approach A: In useTriggerDataForwarding, check if triggerIdProp is set on the store. If yes, don't update activeTriggerElement.

    Approach B: In useImplicitActiveTrigger, capture the originating element when the popup opens in controlled mode.

    Approach C: In DialogRoot, capture the originating element when the popup opens in controlled mode.

    I think Approach A is the cleanest but it's a behavior change for the data forwarding. Let me look at Approach C as it might be the simplest.

    Actually, let me think about this. The simplest clean fix:

    When the popup opens, capture the focused element. Store it as activeTriggerElement (overriding any trigger element mapping) if the popup was opened without a trigger click.

    The way to detect "opened without a trigger click":

    • triggerIdProp is set externally (by the user)
    • OR there's no eventDetails.trigger in the setOpen call

    The cleanest implementation:

    1. Add a layout effect to useDialogRoot that runs when open transitions to true
    2. Capture activeElement(doc) at that point
    3. Store it as originElement (or override activeTriggerElement)

    Wait, but activeTriggerElement is used for ARIA relations in useSyncedFloatingRootContext. Let me check that:

  55. MiniMax Assistant

    OK. So the domReferenceElement is used by:

    • FloatingFocusManager for focus management (focus return, focus outside events)
    • useDismiss for detecting dismiss outside press
    • useFloating for floating positioning

    For popups without positioning (like dialogs), the positioning isn't critical. The focus management is what matters.

    Let me look at the alert-dialog:

  56. MiniMax Assistant

    Good. AlertDialog uses DialogPopup. So fixing DialogPopup fixes AlertDialog too.

    Let me check the popover:

  57. MiniMax Assistant

    So Popover has its own Popup component. Let me look at the popover store to see its setOpen:

  58. MiniMax Assistant

    OK same pattern. So the fix should affect Dialog, AlertDialog, Popover, and possibly Drawer too.

    Let me look at the Drawer:

  59. MiniMax Assistant

    Drawer has its own components. So we need to handle the popups in both Dialog/Popover AND Drawer.

    Actually let me focus on the most common case - the popups use the same infrastructure. The fix should be in useTriggerDataForwarding (since that's where activeTriggerElement is set) or in the useImplicitActiveTrigger.

    Let me think about the best approach. Since the same pattern affects Dialog, Popover, and Drawer, the cleanest fix is in the shared utility code.

    Looking at useTriggerDataForwarding's layout effect:

    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger) {
        store.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates,
        } as Partial<State>);
      }
    }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
    

    This is where the bug is. When activeTriggerId === triggerId (because of triggerIdProp), the layout effect updates activeTriggerElement to the trigger's element.

    The fix could be:

    • Don't update activeTriggerElement if triggerIdProp is set
    • Track the originating element separately

    Wait, let me look at this idea: What if when triggerIdProp is set, we track the originating element into activeTriggerElement directly (instead of the trigger's element)?

    Actually, here's an idea: We can capture the originating element BEFORE the popup opens, in the Root. Then we set activeTriggerElement to this originating element directly. The triggers' data forwarding won't override this if we ensure it doesn't.

    Let me see where this could fit. In useDialogRoot, when open transitions to true, capture the focused element.

    Actually wait, let me look at this more carefully. The issue is that activeTriggerElement is used for multiple things:

    1. The domReferenceElement for focus management
    2. The referenceElement (and thus positioning) for the popup

    For positioning purposes, the trigger element is correct. For focus management, the originating element is correct.

    Let me check what positioning the dialog does... Actually, dialogs don't really use referenceElement for positioning (they center themselves). Only Popover uses positioning.

    Hmm, so for Popover, the reference is needed for positioning. For Dialog, it's mostly for focus management.

    Actually, looking at FloatingRootStore:

    referenceElement: createSelector(
      (state: FloatingRootState) => state.positionReference ?? state.referenceElement,
    ),
    

    So referenceElement is the fallback if positionReference is set. And positionReference is only set if explicitly positioned.

    OK let me think simpler now.

    Fix Idea: Track the originating element in a new state field originElement. Use it for focus management instead of activeTriggerElement.

    Actually no - let me look at the simplest fix.

    The issue: When the popup is opened in controlled mode with triggerIdProp='trigger-2', the activeTriggerElement gets overwritten by the trigger-2 element via useTriggerDataForwarding's layout effect.

    If we modify the layout effect to NOT update activeTriggerElement when triggerIdProp is set, then activeTriggerElement would remain as whatever it was when the popup opened.

    But by the time the popup opens (open transitions to true), nothing has set activeTriggerElement. So it would remain null.

    Then domReferenceElement would be null, and getReturnElement() would fall back to getPreviouslyFocusedElement() (which IS the "Open programmatically" button).

    Let me try this fix. But we need to be careful about side effects.

    Looking at the layout effect:

    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger) {
        store.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates,
        } as Partial<State>);
      }
    }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
    

    If I make it skip when triggerIdProp is set:

    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger && !store.select('triggerIdProp')) {
        store.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates,
        } as Partial<State>);
      }
    }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
    

    Hmm but this might break other things. Let me check where activeTriggerElement is read:

  60. MiniMax Assistant

    So activeTriggerElement is used for:

    1. Positioner positioning
    2. Popover's previousFocusableElement
    3. Viewport positioning
    4. Dialog eventDetails when closing

    If we don't set activeTriggerElement, the positioner would have no reference. But for dialogs, that's OK because dialogs don't really position relative to a trigger.

    But also, when closing a dialog, eventDetails.trigger = this.state.activeTriggerElement ?? undefined is used. This is used to tell the user which trigger was the owner.

    Hmm, this is tricky. The activeTriggerElement is used for both:

    • Focus return (we want the originating element)
    • ARIA / event details (we want the trigger element)

    So we can't just skip updating activeTriggerElement.

    Cleaner approach: Add a new state field specifically for focus return, like originElement or lastFocusedElement.

    Let me look at it. I'll:

    1. Add a new state field to the popup store: originElement (Element | null, defaults to null)
    2. Capture it when open transitions to true (via a layout effect)
    3. In the FloatingFocusManager, use this as the focus return target (preferring over domReference)

    Actually wait. Looking at the FloatingFocusManager's logic:

    if (typeof resolvedReturnFocusValue === 'boolean') {
      if (domReference?.isConnected) {
        return domReference;
      }
    
      return getPreviouslyFocusedElement() || null;
    }
    

    The domReference is used FIRST. To prefer getPreviouslyFocusedElement, we'd need to either:

    • Change the order
    • Have domReference be null (by not setting it)

    I think the cleanest approach is to add a new internal prop/state for the originating element, and use it in the DialogPopup (and similar components) by providing a returnFocus function to FloatingFocusManager.

    But I also want to make sure I don't introduce regressions. Let me think more.

    Approach: Capture originating element and pass it as returnFocus

    In DialogPopup (and PopoverPopup):

    1. Use a layout effect to capture the focused element when the popup mounts (when mounted becomes true)
    2. Pass this captured element as returnFocus to FloatingFocusManager

    But the issue: FloatingFocusManager already handles focus return. We'd be duplicating logic.

    Approach: Use a new state field that overrides domReference

    Add originElement to the popup store. In useSyncedFloatingRootContext, use originElement ?? activeTriggerElement as the domReferenceElement.

    But this still doesn't handle the case where activeTriggerElement is set to the trigger element via layout effect.

    Hmm. Actually, let me re-think:

    When the dialog opens in controlled mode (no trigger interaction), the FIRST layout effect after open should capture the focused element.

    Let me look at where to put this. The useDialogRoot hook is called in the Root component, which doesn't unmount/remount on open/close. So we can put a layout effect here.

    But the originating element capture needs to happen once per open.

    Let me implement this. I'll add a new state field originElement to the popup store, and capture it via a layout effect in the relevant places.

    Actually wait. Looking more closely at the code, I realize the simpler approach:

    Approach: Don't update activeTriggerElement via useTriggerDataForwarding's layout effect when triggerIdProp is set

    This way:

    • When opened via trigger click: triggerIdProp is null, the layout effect updates activeTriggerElement to the trigger element
    • When opened via controlled triggerIdProp: the layout effect doesn't fire, and activeTriggerElement stays as whatever it was (probably null initially), so domReferenceElement is null, and focus returns to getPreviouslyFocusedElement() which is the "Open programmatically" button

    But wait, for dialog/popover when no activeTriggerElement, the ARIA stuff might be wrong. Let me check where else activeTriggerElement is used.

    For popups that don't use positioning (dialog, alert-dialog), they don't really need activeTriggerElement for ARIA - they have aria-controls based on triggerIdProp. Let me verify:

    Looking at useDialogRoot.ts:

    • aria-controls comes from popupId selector in the DialogTrigger
    • The popupId selector uses triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) to check if this trigger owns the popup

    So the activeTriggerElement isn't strictly needed for ARIA. It's mostly used for focus management and positioning.

    For popover, the activeTriggerElement is used for positioning and for previousFocusableElement. So for popover, we'd still need the trigger element when opened by clicking a trigger.

    OK so the fix needs to be more nuanced. Let me think about this differently.

    Final approach:

    I'll add a new state field originElement (or similar) to the popup store. Capture it via a layout effect in the relevant root components. Use it in the FloatingFocusManager via the existing returnFocus mechanism.

    Actually, simpler: Let me directly handle this in the FloatingFocusManager. Add a new prop like originatingElement that, if provided, is used as the preferred focus return target over domReference.

    Then in each Popup component (DialogPopup, PopoverPopup, etc.), capture the focused element on mount and pass it as this prop.

    Hmm but that's still duplicating logic. Let me look at the existing previouslyFocusedElements global stack in FloatingFocusManager:

    const previouslyFocusedElement = activeElement(doc);
    addPreviouslyFocusedElement(previouslyFocusedElement);
    

    This already captures the focused element at mount time. The issue is just that domReference is preferred over this.

    Why is domReference preferred? It's preferred when it exists and is connected. Why? Because... probably because it's the "natural" fallback for the original use case (popup opened by clicking trigger-2, then close, return to trigger-2).

    But for the controlled/programmatic case, we want to return to the originating element. So we need to either:

    1. Modify the FloatingFocusManager to sometimes prefer getPreviouslyFocusedElement
    2. Don't set domReference in the controlled/programmatic case

    The cleanest fix is probably option 2: don't set domReference to the trigger element when the popup was opened via controlled triggerIdProp. Instead, set it to the originating element captured at open time.

    Let me implement this approach:

    1. Add a new state field originElement (or similar) to the popup store
    2. In the dialog/popover root, when open transitions to true, capture the focused element as originElement
    3. In useSyncedFloatingRootContext, sync domReferenceElement to originElement ?? activeTriggerElement

    Wait, but that would change behavior for the regular non-controlled case too. Let me check.

    OK, regular non-controlled case: user clicks trigger-2, dialog opens. activeTriggerElement = trigger-2 element. originElement = ? If we capture it, it'd be trigger-2 element too (since trigger-2 was focused). So originElement ?? activeTriggerElement = trigger-2. Same as before. ✓

    Controlled case: user clicks "Open programmatically", dialog opens. activeTriggerElement = null initially. Then trigger-2's element registers via the layout effect, setting activeTriggerElement = trigger-2 element. originElement = "Open programmatically" button. So originElement ?? activeTriggerElement = "Open programmatically" button. ✓

    But wait, there's a nuance: what if the user opens via trigger-2 first, then opens via "Open programmatically"?

    1. User clicks trigger-2 → activeTriggerElement = trigger-2, originElement = trigger-2
    2. Closes (focus returns to trigger-2)
    3. User clicks "Open programmatically" → opens dialog with triggerIdProp = 'trigger-2'
    4. originElement = "Open programmatically"
    5. activeTriggerElement = trigger-2 (from step 1, no value has reset it)
    6. originElement ?? activeTriggerElement = "Open programmatically" ✓

    Good. But wait, between step 2 and 3, activeTriggerElement should be reset. Let me check.

    Looking at useOpenStateTransitions:

    const forceUnmount = useStableCallback(() => {
      setMounted(false);
      store.update({
        activeTriggerId: null,
        activeTriggerElement: null,
        mounted: false,
        preventUnmountingOnClose: false,
      } as Partial<State>);
      // ...
    });
    

    So when the popup forceUnmount (after close transition), activeTriggerElement is reset to null. OK so step 5 above would be activeTriggerElement = null. And originElement ?? activeTriggerElement = "Open programmatically". ✓

    Great. Let me think about edge cases:

    1. Single trigger uncontrolled: User clicks trigger-2, opens dialog, closes. originElement = trigger-2. Same as before. ✓
    2. Multiple triggers uncontrolled: User clicks trigger-2, opens, closes. originElement = trigger-2. ✓
    3. Multiple triggers controlled (via triggerIdProp='trigger-2'): User clicks "Open programmatically", opens, closes. originElement = "Open programmatically". ✓
    4. Multiple triggers controlled via useState, but the user first clicks trigger-2, closes (focus returns to trigger-2): User clicks "Open programmatically". Same as case 3. ✓

    Now let me think about the implementation details.

    Implementation:

    1. Add originElement: HTMLElement | null to PopupStoreState
    2. Add a layout effect in useDialogRoot (and Popover/Drawer equivalents) that captures the focused element when open transitions from false to true
    3. Use this as originElement in the store
    4. In useSyncedFloatingRootContext, sync domReferenceElement to originElement ?? activeTriggerElement

    Wait, but step 4 means I need to change useSyncedFloatingRootContext to read from originElement first. Let me check if this affects positioning.

    Looking at FloatingRootStore's referenceElement:

    referenceElement: createSelector(
      (state: FloatingRootState) => state.positionReference ?? state.referenceElement,
    ),
    

    And referenceElement is used by useFloating for positioning. So if originElement overrides referenceElement, the popover would position relative to the "Open programmatically" button, not the trigger-2 element. This is wrong.

    Hmm. So we need a different field for the focus management, separate from positioning.

    Approach (revised): Use a separate field for the focus target.

    1. Add originElement to the popup store
    2. Capture it on open
    3. In useSyncedFloatingRootContext, also sync domReferenceElement based on originElement (separate from referenceElement)

    Let me look at the store again:

    useIsoLayoutEffect(() => {
      const valuesToSync: Partial<FloatingRootState> = {
        open,
        floatingId,
        referenceElement,
        floatingElement,
      };
    
      if (isElement(referenceElement)) {
        valuesToSync.domReferenceElement = referenceElement;
      }
      // ...
    }, [open, floatingId, referenceElement, floatingElement, store]);
    

    I need to update this to also set domReferenceElement from originElement:

    useIsoLayoutEffect(() => {
      const valuesToSync: Partial<FloatingRootState> = {
        open,
        floatingId,
        referenceElement,
        floatingElement,
      };
    
      const domReference = originElement ?? (isElement(referenceElement) ? referenceElement : null);
      if (domReference) {
        valuesToSync.domReferenceElement = domReference;
      }
      // ...
    }, [open, floatingId, referenceElement, floatingElement, originElement, store]);
    

    Wait, I need to also keep positionReference working correctly. Let me read the code more carefully:

    if (store.state.positionReference === store.state.referenceElement) {
      valuesToSync.positionReference = referenceElement;
    }
    

    This says: if the positionReference hasn't been explicitly set (it still equals the previous referenceElement), keep it in sync.

    So positionReference always equals referenceElement unless explicitly overridden. OK.

    Now domReferenceElement is just used for focus management, not positioning. So setting it to originElement ?? referenceElement should be fine.

    Let me also check: where is originElement going to be set?

    Actually let me look at this from another angle. Instead of adding a new state field, can we capture the originating element in a useRef and use it directly in the DialogPopup/PopoverPopup?

    In DialogPopup (and similar):

    const originElementRef = React.useRef<HTMLElement | null>(null);
    
    useIsoLayoutEffect(() => {
      if (mounted && !originElementRef.current) {
        originElementRef.current = document.activeElement as HTMLElement;
      }
    }, [mounted]);
    
    const returnFocus = React.useCallback(() => {
      return originElementRef.current;
    }, []);
    
    return (
      <FloatingFocusManager
        returnFocus={returnFocus}  // captured element
        // ...
      >
    

    But this would always return the captured element, even if the user clicked another trigger to close. Hmm.

    Actually, looking at the FloatingFocusManager's getReturnElement:

    if (typeof resolvedReturnFocusValue === 'boolean') {
      if (domReference?.isConnected) {
        return domReference;
      }
      return getPreviouslyFocusedElement() || null;
    }
    

    If we pass a function as returnFocus:

    if (typeof resolvedReturnFocusValue === 'boolean') {
      // skipped
    }
    const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
    return resolveRef(resolvedReturnFocusValue) || fallback || null;
    

    So if we return a function from returnFocus that returns the originating element, the function value is used:

    const focused = returnedFunction();
    if (focused) return focused;
    return fallback; // domReference or getPreviouslyFocusedElement
    

    OK so if I return the originating element, it's used. If I return null/undefined, it falls back.

    This works! Let me try this approach in DialogPopup:

    const originElementRef = React.useRef<HTMLElement | null>(null);
    
    // Capture the focused element right before the popup mounts (or as soon as it mounts)
    useIsoLayoutEffect(() => {
      if (mounted && originElementRef.current === null) {
        originElementRef.current = document.activeElement as HTMLElement;
      }
    }, [mounted]);
    
    // Update returnFocus to use originElementRef if available
    const resolveReturnFocus = React.useCallback(() => {
      // Use the captured origin element if available
      if (originElementRef.current && originElementRef.current.isConnected) {
        return originElementRef.current;
      }
      return true; // fallback to default behavior
    }, []);
    
    return (
      <FloatingFocusManager
        returnFocus={resolveReturnFocus}
        // ...
      >
    

    Hmm but this might break things. The user might want to set their own finalFocus. Let me reconsider.

    Actually, looking at the existing code path:

    returnFocus={finalFocus}
    

    If finalFocus is undefined, the default is true (default behavior = use domReference if connected, else getPreviouslyFocusedElement).

    If we override this with our function, we change the behavior. We need to preserve user's finalFocus choice.

    Let me refactor:

    const resolveReturnFocus = React.useCallback((closeType) => {
      if (finalFocus !== undefined) {
        // User has set finalFocus; respect it
        return typeof finalFocus === 'function' ? finalFocus(closeType) : finalFocus;
      }
      // Default: prefer the captured origin element if it's still connected
      if (originElementRef.current?.isConnected) {
        return originElementRef.current;
      }
      return true; // fallback to default behavior
    }, [finalFocus]);
    
    return (
      <FloatingFocusManager
        returnFocus={resolveReturnFocus}
        // ...
      >
    

    This:

    • Respects user's finalFocus if set
    • Otherwise prefers the origin element
    • Falls back to default behavior

    This is good. But I want to make sure this handles all existing cases correctly.

    Test case 1: User clicks trigger-2 (uncontrolled), opens dialog, closes.

    • Origin element captured = trigger-2 (since it was focused before open)
    • Active trigger = trigger-2
    • Active trigger element = trigger-2
    • OriginElementRef = trigger-2 element
    • Close → return trigger-2 element ✓

    Test case 2: User opens programmatically with triggerIdProp='trigger-2'.

    • Origin element = "Open programmatically" button
    • Active trigger element = trigger-2 element (via layout effect from useTriggerDataForwarding)
    • OriginElementRef = "Open programmatically" button
    • Close → return "Open programmatically" button ✓

    Test case 3: User opens programmatically with triggerIdProp='trigger-2' and trigger-2 is no longer in the DOM (got removed somehow).

    • OriginElementRef = "Open programmatically" button
    • "Open programmatically" button still connected → return it ✓
    • If disconnected, fall back to default (true) → uses domReference (trigger-2 element, but disconnected) → falls back to getPreviouslyFocusedElement

    Hmm but getPreviouslyFocusedElement() is captured in FloatingFocusManager. If trigger-2 was clicked previously, it'd be trigger-2. If not, it'd be... whatever was focused before.

    Actually wait, this is getting complex. Let me simplify.

    Simplest implementation: Track origin element in the popup store. Sync it to domReferenceElement instead of (or in addition to) activeTriggerElement.

    Let me just do this.

    Actually wait, let me think again. The issue is that domReferenceElement is used for focus management. We want it to be:

    • The trigger element when the trigger was clicked (regular case)
    • The originating element when opened programmatically

    The current code uses activeTriggerElement for both purposes. This is the bug.

    To fix: change the domReferenceElement to be the originating element when opening programmatically.

    But also: in the regular case, "originating element" IS the trigger element (since the user was focused on the trigger before clicking it). So if we capture "originating element" in BOTH cases, we get the right behavior.

    Let me try this. I'll add originElement to the store, capture it on open, and use it for domReferenceElement (in addition to or instead of activeTriggerElement).

    Wait, but capturing "focused element" might be tricky. We need to capture it before the popup is mounted (so the layout effect in FloatingFocusManager doesn't capture the popup element as the focused element).

    Let me think about timing.

    Actually, the layout effect in FloatingFocusManager captures activeElement(doc) AT THE TIME it mounts (just after the popup is in the DOM). At this point, the focus might have already moved to the popup (because of FocusGuard or initialFocus).

    Actually let me re-check the initial focus flow:

  61. MiniMax Assistant

    OK so the initial focus effect schedules a microtask to move focus to the popup. The "return focus capture" effect at line 733 runs synchronously in the layout effect (after initial focus effect).

    So at line 735 previouslyFocusedElement = activeElement(doc):

    • This is captured AFTER the popup is mounted BUT in the same layout effect (synchronous)
    • The initial focus is scheduled as a microtask
    • So activeElement(doc) at this point is still the originating element (e.g., "Open programmatically" button) - focus hasn't moved yet

    Wait, but floatingFocusElement is an HTMLElement. When the popup is mounted, can it be focused automatically? Let me check.

    The popup has tabindex=-1 and data-base-ui-focusable. Some browsers might focus it automatically when it's added to the DOM. But the useIsoLayoutEffect runs synchronously after the DOM commit, so it should capture the state BEFORE any browser-driven focus.

    OK so the existing previouslyFocusedElement captured in FloatingFocusManager IS the originating element. The issue is just that the focus return prefers domReference.

    Let me think about this. The simplest fix is to add a new state field for the originating element, and use it in place of (or in addition to) activeTriggerElement for focus management purposes.

    OK let me just implement this. I'll take the cleanest approach:

    1. Add originElement field to PopupStoreState
    2. Add a layout effect (or use existing) to capture it when open transitions to true
    3. Use originElement for domReferenceElement in useSyncedFloatingRootContext

    Wait, where do I capture it? It should be captured BEFORE the popup renders (otherwise focus might be on the popup). The open transition happens via React state. So I need to capture it during the state update.

    One way: in useDialogRoot, use a layout effect that runs when open becomes true:

    useIsoLayoutEffect(() => {
      if (open && mounted) {
        // Capture the originating element
        const originatingElement = /* ... */;
      }
    }, [open, mounted]);
    

    But this runs AFTER the popup mounts. By then, focus may or may not be on the popup yet.

    Actually, looking at the FloatingFocusManager, the initial focus happens in a microtask AFTER the layout effect. So in the layout effect, the focus is still on the originating element.

    So I can capture in the layout effect after mounted=true but before the microtask runs the initial focus.

    Let me try implementing this in useDialogRoot:

    useIsoLayoutEffect(() => {
      if (open && mounted) {
        const doc = /* ... */;
        const originatingElement = activeElement(doc);
        if (originatingElement && originatingElement !== store.context.popupRef.current) {
          store.set('originElement', originatingElement);
        }
      }
    }, [open, mounted, store]);
    

    But this still has the issue of when mounted becomes true. The mounted state transitions during the open animation. Let me check useTransitionStatus:

  62. MiniMax Assistant

    OK so mounted becomes true synchronously when open becomes true (via setMounted(true) during render). Good. So mounted=true immediately when open=true.

    Now let me design the implementation:

    1. Add originElement: HTMLElement | null to PopupStoreState
    2. In useDialogRoot (and Popover, Drawer equivalents), when open becomes true (and not from a trigger click), capture activeElement(doc) as originElement

    But wait - how do we know if the open came from a trigger click vs controlled? When the user clicks a trigger, useDismiss.reference and trigger's onClick call store.setOpen(true, ...) with the trigger element. So when setOpen is called with a trigger element, we know it was a trigger click.

    So in setOpen:

    • When opening with a trigger element: don't update originElement (use the trigger's element for activeTriggerElement)
    • When opening without a trigger element (controlled/programmatic): set originElement = eventDetails.trigger? But there's no trigger...

    Hmm, this doesn't work because for programmatic opens, there's no trigger element.

    Let me think again.

    For the controlled/programmatic case:

    • The user sets open=true, triggerIdProp='trigger-2' from their React state
    • This propagates to openProp=true, triggerIdProp='trigger-2' in the store
    • The current focused element is the "Open programmatically" button (since the user just clicked it)
    • We need to capture this focused element as originElement

    So we capture the focused element at the time open transitions to true in controlled mode.

    But how do we know it was a controlled open?

    • If openProp !== undefined && openProp !== state.open, it was a controlled open (caller changed it)

    Let me look at useControlledProp:

    useIsoLayoutEffect(() => {
      if (isControlled && !Object.is(store.state[key], controlled)) {
        store.setState({ ...store.state, [key]: controlled });
      }
    }, [store, key, controlled, isControlled]);
    

    This only updates the internal state when externally controlled. There's no direct indication of "this came from controlled".

    Alternative: we can check triggerIdProp is set. If triggerIdProp is set externally, we know it's controlled (in the sense the user is driving the activeTriggerId from outside).

    Actually wait, triggerIdProp could be set externally while a trigger is also clicked. That's an edge case but possible.

    Let me think differently. The actual rule is:

    • If eventDetails.trigger was passed to setOpen(true, ...), then the user clicked the trigger
    • Otherwise, the open was controlled/programmatic

    But by the time React re-renders with open=true, the setOpen has already been called (or not). Let me trace this.

    Actually no, in controlled mode, the user sets open=true in their React state. The Dialog doesn't call setOpen internally. The Dialog just sees openProp change and updates the store.

    In uncontrolled mode, when a user clicks a trigger, the trigger calls store.setOpen(true, ...) with the trigger element. Then onOpenChange(true, ...) is fired. In controlled mode, the user would handle this and set their own open state. In uncontrolled mode, the open state in the store is updated via setOpen.

    OK so in the controlled case where the user sets open=true directly (without the trigger), setOpen is NEVER called for this transition. The store only sees openProp change.

    Hmm, so we need to handle this in the useControlledProp step or in a layout effect that runs when openProp changes.

    OK actually let me simplify. Here's a new plan:

    Plan:

    1. Add a new state field originElement to the popup store
    2. In the layout effect that runs on open transition (and not from a trigger interaction), capture the focused element as originElement
    3. We can detect "trigger interaction" by checking if eventDetails.trigger was set. But this isn't easily available in a layout effect.

    Alternative: always capture originElement on open. If the open was via a trigger click, originElement will be the trigger element (which is already in activeTriggerElement). So originElement won't conflict.

    Wait, but if I always capture, then for the trigger click case, originElement is the trigger element. And activeTriggerElement is also the trigger element. They're the same.

    So the fix is: Use originElement for domReferenceElement INSTEAD of activeTriggerElement. This works for both cases:

    • Trigger click: originElement = trigger element, activeTriggerElement = trigger element. Same.
    • Programmatic: originElement = "Open programmatically" button, activeTriggerElement = trigger element (via useTriggerDataForwarding). They differ.

    But wait, we still want to NOT have activeTriggerElement = trigger element for the programmatic case (because the trigger-2 wasn't clicked). Let me reconsider.

    Actually, do we need activeTriggerElement for the programmatic case? Let me check what depends on it:

    1. useSyncedFloatingRootContext: referenceElement = activeTriggerElement (for positioning)
    2. PopoverPopup: previousFocusableElement = activeTriggerElement (for focus guard)
    3. PopoverPositioner: positions relative to activeTriggerElement
    4. DialogStore.setOpen (close): eventDetails.trigger = activeTriggerElement ?? undefined
    5. usePopupViewport: uses activeTriggerElement for positioning
    6. MenuPopup: similar to PopoverPopup
    7. MenuPositioner: positions relative to activeTriggerElement
    8. MenuRoot: updates state with trigger

    Hmm, several of these depend on activeTriggerElement. The popover positioner would not position correctly if activeTriggerElement is null/wrong.

    So activeTriggerElement should still be the trigger element (for positioning). We should keep that.

    But for focus management (i.e., domReferenceElement), we want the originating element, NOT the trigger element.

    So the fix is:

    1. activeTriggerElement stays as the trigger element (no change)
    2. domReferenceElement = originElement ?? activeTriggerElement

    Let me implement this.

    For originElement, capture it on open:

    • In the layout effect, when open becomes true, capture activeElement(doc) (if it's not the popup itself)

    Now, we need to handle the case where open is set to true and the layout effect runs. At that point, what's activeElement(doc)?

    Time T0: React renders with open=true. The popup is mounted (or about to be). Time T1: Layout effect runs. At this point, the popup might or might not have received focus. Looking at FloatingFocusManager, the initial focus is scheduled in a microtask. So in the layout effect, focus is still on the originating element.

    So we can capture in a layout effect that runs when mounted=true.

    Let me implement this:

  63. MiniMax Assistant

    Now let me check the drawer root:

  64. MiniMax Assistant

    So the Drawer uses Dialog. So fixing Dialog fixes Drawer too.

    Now let me think about the implementation. I'll focus on Dialog first.

    Implementation Plan:

    1. Add originElement to PopupStoreState
    2. Modify useDialogRoot to capture the originating element in a layout effect when open && mounted transitions
    3. Modify useSyncedFloatingRootContext to sync domReferenceElement = originElement ?? activeTriggerElement
    4. Make sure activeTriggerElement is still set correctly for positioning (no change there)

    Wait, but adding a new field to PopupStoreState would require updating many places. Let me see if there's a simpler way.

    Alternative Plan: Use a useRef in the useDialogRoot hook, and update useSyncedFloatingRootContext to use this. But the sync context doesn't have access to refs.

    Hmm, let me check where the ref can be plumbed.

    Actually, the simplest approach is to just add the originElement field. Let me also consider:

    The fix could also be done at the DialogPopup level. Let me look at the alternative where we modify DialogPopup.

    In DialogPopup, capture originElement via a layout effect. Then pass a custom returnFocus to FloatingFocusManager that:

    • Returns the originElement if it's connected
    • Falls back to default behavior (which uses domReference or getPreviouslyFocusedElement)

    Let me check the existing finalFocus handling:

    In FloatingFocusManager, the returnFocus is the same as finalFocus (same type). So we can do this:

    const originElementRef = React.useRef<HTMLElement | null>(null);
    
    useIsoLayoutEffect(() => {
      if (mounted && !originElementRef.current) {
        originElementRef.current = activeElement(document) as HTMLElement;
      }
    }, [mounted]);
    

    Wait but mounted is just for the popup. When the popup first mounts, we capture.

    But what if mounted becomes true, then false (close), then true (reopen)? In uncontrolled mode with mounted staying, but the activeTriggerElement changing, would originElementRef still have the original? Yes, it would only be set once per mount.

    OK so we need to clear it when the popup closes.

    Hmm. Let me think about a cleaner approach.

    Final Plan:

    In the popup store (shared infrastructure), add a state field for the originating element. Use a hook to capture it.

    Let me go ahead and implement.

  65. MiniMax Assistant

    OK now let me implement the fix. I'll add originElement to PopupStoreState and then use it in useSyncedFloatingRootContext.

    Actually wait. Let me reconsider. Maybe the simplest and most local fix is:

    Just modify the DialogPopup (and similar) to handle the controlled case specially

    Instead of modifying the global popup store, we can handle this in each popup component (DialogPopup, PopoverPopup) where we have access to mounted and open.

    In DialogPopup:

    1. Track originElement via a layout effect when mounted becomes true
    2. Pass a custom returnFocus that uses this element

    Let me try this approach:

  66. MiniMax Assistant

    OK. The FloatingFocusManager is rendered with disabled={!mounted} - it's only enabled when mounted. So when mounted becomes true, the layout effect inside FloatingFocusManager captures the focused element.

    Hmm. Let me trace this. The FloatingFocusManager is a child of the popup. When mounted becomes true, the popup renders the FloatingFocusManager. The FloatingFocusManager's layout effect runs synchronously after the DOM commit, capturing the focused element (which should be the originating element).

    But the cleanup of FloatingFocusManager's effect (which restores focus) uses domReference first.

    OK so here's my approach:

    I'll modify useSyncedFloatingRootContext to use originElement ?? activeTriggerElement for domReferenceElement, and add originElement tracking in the popup store.

    Wait, but there's a simpler approach. Let me just modify the useTriggerDataForwarding layout effect to skip updating activeTriggerElement when triggerIdProp is set externally. Then activeTriggerElement stays as whatever was set elsewhere.

    But the issue is activeTriggerElement is also used for positioning. For Popover, this matters. For Dialog, not really.

    Hmm, let me look at how to handle this consistently.

    OK let me just go with adding originElement to the popup store. It's the cleanest approach.

    Let me implement:

  67. MiniMax Assistant

    Now let me look at how the store updates trigger element. Specifically, I need to understand: when the popup opens, what does activeTriggerElement look like?

    Looking at the demo:

    • Initial: open=false, triggerId=null, activeTriggerElement=null
    • User clicks "Open programmatically" → open=true, triggerId='trigger-2'
    • triggerIdProp='trigger-2', activeTriggerIdSelector='trigger-2'
    • Layout effect in useTriggerDataForwarding for trigger-2: isMountedByTrigger=true (since activeTriggerId=trigger-2 and mounted=true). So activeTriggerElement = trigger-2 element

    After this, activeTriggerElement = trigger-2 element. So domReferenceElement = trigger-2 element when accessed.

    So the issue is well understood. Let me implement the fix.

    Let me first try the simplest approach: modify the layout effect in useTriggerDataForwarding to check if triggerIdProp is set, and skip updating activeTriggerElement if so.

    Wait actually I realized there's another approach. What if we always capture originElement (in BOTH the controlled and uncontrolled cases)? Then activeTriggerElement doesn't need to be touched for the focus.

    Let me think about this approach:

    1. Add originElement to PopupStoreState
    2. Capture it via a layout effect when mounted && open transitions to true
    3. In useSyncedFloatingRootContext, sync domReferenceElement = originElement ?? activeTriggerElement

    For the uncontrolled case (click trigger-2):

    • originElement = trigger-2 element (captured at mount)
    • activeTriggerElement = trigger-2 element (set via setOpen)
    • domReferenceElement = trigger-2 element ✓

    For the controlled case (open programmatically):

    • originElement = "Open programmatically" button (captured at mount)
    • activeTriggerElement = trigger-2 element (set via useTriggerDataForwarding)
    • domReferenceElement = "Open programmatically" button ✓

    For both cases, the focus return target is the originating element.

    Let me implement.

  68. MiniMax Assistant

    None exist. Good, I can add it.

    Let me start implementing:

  69. MiniMax Assistant

    Now, let me make the changes. First, add originElement to PopupStoreState:

  70. MiniMax Assistant

    Now let me apply the patches. First to PopupStoreState:

  71. MiniMax Assistant

    Now let me apply my changes step by step. First, add originElement to the PopupStoreState type:

  72. MiniMax Assistant

    Now let me add a hook in popupStoreUtils.ts to capture the origin element:

  73. MiniMax Assistant

    Let me look at how other places access activeElement:

  74. MiniMax Assistant

    Now I have enough info. Let me add the useOriginElementCapture hook to popupStoreUtils.ts:

  75. MiniMax Assistant

    Let me look at how useImplicitActiveTrigger is structured to use a similar pattern:

  76. MiniMax Assistant

    Let me now add my changes. First, I need to add an import for activeElement and ownerDocument:

  77. MiniMax Assistant

    Now let me add the hook. I'll add a useCapturedOriginElement hook similar to other hooks in the file:

  78. MiniMax Assistant

    Let me add the hook before useOpenStateTransitions:

  79. MiniMax Assistant

    Now I need to add the contains and isHTMLElement imports:

  80. MiniMax Assistant

    I need to add contains and isHTMLElement imports:

  81. MiniMax Assistant

    Now let me check the file:

  82. MiniMax Assistant

    Now let me update useSyncedFloatingRootContext to sync originElement ?? activeTriggerElement:

  83. MiniMax Assistant

    Let me verify the changes:

  84. MiniMax Assistant

    Now let me hook up useCapturedOriginElement in the root components. Let me start with the dialog:

  85. MiniMax Assistant

    Now let me also add this to the popover root:

  86. MiniMax Assistant

    Now I also need to think about Menu. Let me check:

  87. MiniMax Assistant

    For the menu, the activeTriggerElement is set when the menu opens (via the trigger's onClick). So it's always set when the menu opens. The Menu scenario doesn't have the same "controlled with multiple triggers" issue.

    Let me focus on the fix and test it:

  88. MiniMax Assistant

    Now let me run the test to see if my fix works:

  89. MiniMax Assistant

    Hmm, error. The useState('originElement') fails because the selector doesn't exist. Let me check if I need to add it to the selectors:

  90. MiniMax Assistant

    Let me add originElement selector:

  91. MiniMax Assistant

    Let me add the originElement selector:

  92. MiniMax Assistant

    Now let me run the test again:

  93. MiniMax Assistant

    The test passes. Now let me add more comprehensive tests to ensure the fix handles edge cases:

  94. MiniMax Assistant

    All 3 tests pass. Let me check if existing tests still pass:

  95. MiniMax Assistant

    I broke some tests. Let me investigate. Specifically the "closes as soon as focus leaves the popup on pointer down outside" test failure:

  96. MiniMax Assistant

    This test:

    1. Opens the popover with defaultOpen=true
    2. Focuses an "inside" button
    3. Focuses the "outside" button via pointerDown and focus
    4. Fires focusOut on the inside button
    5. Expects the popover to close

    When the popover opens, my hook captures the focused element. But before that, when defaultOpen=true, the popover mounts without a trigger interaction. The active element at that time is document.body (since the test doesn't focus anything before mounting).

    Wait, let me trace this more carefully:

    • defaultOpen=true → open=true, mounted=true immediately
    • Layout effect captures activeElement(doc). At this point, the test is in the middle of rendering, so document.body is the active element.
    • We capture originElement = document.body
    • Later when focus moves to "outside" and the popover closes, focus should return to document.body (originElement)

    But this test expects the popover to close via focus management. Let me look at the focus outside behavior:

    Actually wait, the test is checking that the popover closes via focusout (the popover has closeOnFocusOut which is automatic). The test should still pass because the close mechanism isn't affected by my change.

    But the test fails because the dialog is still in the DOM. Let me check why...

    Actually I think there's something weird with my originElement capture. Let me re-check the hook:

  97. MiniMax Assistant

    OK my hook. Let me check what could be different. The issue might be:

    • When the popover is defaultOpen, the trap focus is set up. The "inside" button has focus.
    • When focus moves to "outside", the trap focus detects this and closes the popover.

    But why would my change affect this? Let me think...

    Actually wait, looking at the failure: "expected <div data-open …> to be null". So the popover DIDN'T close. That means the close-on-focus-out didn't work.

    Hmm. Let me look at the domReferenceElement logic more carefully. The closeOnFocusOut uses domReferenceElement to determine if focus is moving to the reference (which shouldn't trigger close):

  98. MiniMax Assistant

    Hmm OK, so domReferenceElement is used to attach focus listeners. With my change, the focus listeners are now attached to originElement (e.g., document.body if the popover was opened with defaultOpen=true and no element was focused).

    The focus listener check would be:

    if (currentTarget === domReference && floatingFocusElement) {
    

    If domReference = document.body (originElement), then... well, this might still work because the focusout handler compares with domReference. Let me look at handleFocusOutside:

  99. MiniMax Assistant

    The handler handleFocusOutside does various logic. The fact that domReferenceElement is now document.body instead of the trigger could affect behavior.

    Hmm, this is getting complex. Let me think about whether my approach is correct.

    The issue with using document.body (originElement when defaultOpen) as domReferenceElement:

    • handleFocusOutside checks contains(domReference, relatedTarget). document.body contains many things.
    • currentTarget === domReference would be true if focus moves to document.body (rare but possible)

    For the test case:

    • Inside button has focus
    • Pointer down on outside → markInsideReactTree
    • Focus outside → outside button is the relatedTarget
    • handler checks if outside button is inside domReference (now document.body), inside floating, etc.

    If domReference = document.body, then contains(document.body, outside button) = true, so it falls into the "unrelated" branch? Let me re-read:

    const movedToUnrelatedNode = !(
      contains(domReference, relatedTarget) ||  // ← this would be true for document.body
      // ...
    );
    
    if (currentTarget === domReference && floatingFocusElement) {
      // ...
    }
    
    // Restore focus to the previous tabbable element
    if (restoreFocus && currentTarget !== domReference && !isElementVisible(target) && activeElement(doc) === doc.body) {
      // ...
    }
    

    So if domReference = document.body, then contains(document.body, outside button) = true, so movedToUnrelatedNode = false, and the close-on-focus-out doesn't close the popup.

    This is the issue. The fact that I'm setting domReferenceElement = originElement breaks the "focus-outside" detection.

    Let me think of a better approach.

    Hmm, maybe originElement should only be used for focus return when the popup closes, not for the focus management listeners.

    Let me reconsider the approach.

    Better approach: Don't override domReferenceElement. Instead, handle the focus return separately in FloatingFocusManager. Or use a different mechanism.

    Actually, looking back at the FloatingFocusManager logic:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      let resolvedReturnFocusValue = ...;
    
      if (typeof resolvedReturnFocusValue === 'boolean') {
        if (domReference?.isConnected) {
          return domReference;
        }
    
        return getPreviouslyFocusedElement() || null;
      }
      // ...
    }
    

    If we pass returnFocus as a function that returns the originating element, we can override the focus return.

    Let me revise my approach:

    1. Capture originElement in the popup store (using my hook)
    2. Pass finalFocus from DialogPopup that returns originElement if available
    3. Don't modify useSyncedFloatingRootContext

    This way, the focus return uses originElement, but the domReferenceElement stays as activeTriggerElement for focus management purposes (focus-outside detection, etc.).

    But wait, the test expects focus to return to the originating button. Even with my current implementation it does. Let me check why the popover test failed.

    Actually let me revert my change to useSyncedFloatingRootContext and instead pass finalFocus from the DialogPopup.

    Hmm, but the DialogPopup doesn't know about originElement. We'd need to expose it.

    Actually, let me think differently. The hook captures originElement into the store. The Popup component (DialogPopup, PopoverPopup) can read it and pass it as finalFocus.

    Let me revert my changes:

  100. MiniMax Assistant

    Now let me update the DialogPopup and PopoverPopup to use the originElement for focus return:

  101. MiniMax Assistant

    Now I need to modify DialogPopup to use originElement from the store for focus return. Let me add this:

  102. MiniMax Assistant

    Wait, but the mounted selector filters out originElement when the popup is not mounted:

    originElement: createSelector((state: S) =>
      state.mounted ? state.originElement : null,
    ),
    

    So originElement is null when the popup is unmounted. This is good. But also the FloatingFocusManager is disabled={!mounted}, so when not mounted it doesn't run.

    Now, the resolvedFinalFocus needs to capture originElement before the popup unmounts. The originElement selector returns null when not mounted, so by the time we compute resolvedFinalFocus, it might be null.

    Let me check the timing:

    • mounted = true → store has originElement
    • mounted = false → store's originElement is reset... wait, is it?

    Looking at the forceUnmount function:

    const forceUnmount = useStableCallback(() => {
      setMounted(false);
      store.update({
        activeTriggerId: null,
        activeTriggerElement: null,
        mounted: false,
        preventUnmountingOnClose: false,
      } as Partial<State>);
      // ...
    });
    

    It doesn't reset originElement. So after forceUnmount, originElement stays in the store until the next open.

    But the selector returns null when mounted is false. So when the user closes the popover, originElement becomes null in the selector before the focus is restored.

    Hmm. Let me think about this timing more carefully.

    When closeOnFocusOut triggers the close:

    1. User focuses outside
    2. setOpen(false, ...) is called
    3. forceUnmount is scheduled (after transition)
    4. mounted transitions to ending then back to false after transition

    The FloatingFocusManager's cleanup effect runs when... let me check. Looking at FloatingFocusManager:

  103. MiniMax Assistant

    OK so disabled={!mounted} means the FloatingFocusManager is disabled when not mounted. When the popup closes, mounted becomes false (or stays true during transition depending on keepMounted).

    When disabled=true, the FloatingFocusManager's cleanup effect (which restores focus) doesn't run. Looking at:

  104. MiniMax Assistant

    Looking more carefully at the cleanup:

    useIsoLayoutEffect(() => {
      if (disabled || !floatingFocusElement) {
        return undefined;
      }
      // ... setup
    
      return () => {
        // ... cleanup
        queueMicrotask(() => {
          // ... restore focus
        });
      };
    }, [...]);
    

    The cleanup runs when the effect's deps change. So:

    1. First render: setup runs (popup is mounted, mounted=true, disabled=false)
    2. Popup opens: the effect runs (popup is mounted)
    3. Popup closes: mounted becomes false → disabled becomes true → effect deps change → cleanup runs (focus is restored in microtask)
    4. Then the effect runs with disabled=true, returns undefined (no cleanup function)

    So the cleanup runs WHEN disabled changes from false to true (i.e., on close).

    At that point, the FloatingFocusManager is being re-rendered with disabled={true}. The originElement is still in the store (no one resets it). But via the selector, it returns null when mounted=false.

    Hmm, that's a timing issue. Let me check the cleanup. The cleanup runs from the previous render. At the previous render, mounted was true, so originElement was non-null.

    Actually wait, the cleanup runs when the effect cleanup function is called, which happens when:

    1. The dependencies change
    2. The component unmounts

    When mounted changes from true to false, the effect cleanup runs. At this point, the props used to set up the effect are still those from the previous render (where mounted was true). So originElement returned by the selector at that time would still be correct.

    Wait, the store.useState('originElement') is a hook called during render. When mounted changes from true to false, the selector returns null (because of the selector's state.mounted check). So originElement becomes null in the new render.

    But the closure (cleanup function) captures the value from the previous render where it was non-null.

    Hmm but then there's resolvedFinalFocus which is a useMemo. The useMemo would re-compute when originElement changes.

    Let me trace more carefully.

    When mounted changes from true to false:

    1. React re-renders DialogPopup
    2. store.useState('mounted') returns false
    3. store.useState('originElement') - the selector returns null (because state.mounted is false now)
    4. resolvedFinalFocus memo recomputes: originElement is null, so it returns (closeType) => true (fallback to default)
    5. FloatingFocusManager renders with the new returnFocus which is () => true
    6. FloatingFocusManager's effect cleanup runs (from previous render) - was called with the OLD returnFocus (which used the OLD originElement)
    7. Cleanup restores focus to originElement ✓

    Wait, but the deps of the FloatingFocusManager's effect include returnFocus. If returnFocus is memoized and the same, the effect doesn't re-run.

    Hmm, but if returnFocus changes (because originElement changed to null), the effect cleanup runs.

    Actually let me check the deps of the FloatingFocusManager's effect:

  105. MiniMax Assistant

    So returnFocus is converted to a ref. The cleanup reads from returnFocusRef.current. The ref is updated on every render to the latest returnFocus.

    In the cleanup, returnFocusRef.current is the LATEST returnFocus (not the one at setup time). But my useMemo returns a function that closes over originElement. So:

    1. Setup runs: returnFocusRef.current = function1 (closes over originElement = "Open programmatically" button)
    2. Re-render due to mounted change: returnFocusRef.current = function2 (closes over originElement = null because of selector)
    3. Effect deps change (mounted), cleanup runs. Reads returnFocusRef.current = function2. function2 returns true → falls back to default behavior
    4. Default behavior uses domReference (trigger-2 element)

    So the focus returns to trigger-2 element. Bad.

    Let me think about how to fix this. Options:

    1. Don't gate originElement selector by mounted
    2. Don't reset originElement when popup closes
    3. Don't use the selector approach; use a useRef in the popup component

    Let me remove the mounted check from the originElement selector:

  106. MiniMax Assistant

    Actually, the originElement doesn't need to be gated by mounted. It just needs to be available as long as the DialogPopup component is mounted (which is always when the Dialog is open).

    Let me change the selector to just return state.originElement:

  107. MiniMax Assistant

    Now run the reproduce test again to ensure it still passes:

  108. MiniMax Assistant

    Hmm, the first test now fails. Let me check what happened. Looking at the test:

    The third test (still passes for trigger) and the second test (Popover) passes. The first test fails. Let me check the Dialog test specifically.

    Wait, the tests run order seems random. Let me look at the failure: It says focus moved to "Open 2" (trigger-2). So my fix didn't work.

    Let me think about why. Maybe the issue is in how I'm passing the resolvedFinalFocus. Let me check:

  109. MiniMax Assistant

    Hmm, looks fine. Let me check if the originElement is being captured. Let me add logging:

    Actually wait, let me look at the FloatingFocusManager's getReturnElement to understand what it does with returnFocus:

  110. MiniMax Assistant

    OK so when returnFocus is a function, it calls it and gets a value. If the value is an element, it uses that.

    So when the resolvedFinalFocus returns the originElement (a button), the getReturnElement returns it.

    But wait, let me look again at the typeof resolvedReturnFocusValue === 'boolean':

    If I return true from my function, resolvedReturnFocusValue = true, then we go into the boolean branch which uses domReference. So returning true from my function gives the same behavior as before.

    If I return the originElement, resolvedReturnFocusValue is the element. Then we go into typeof resolvedReturnFocusValue === 'boolean' = false, so we go to:

    const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
    return resolveRef(resolvedReturnFocusValue) || fallback || null;
    

    resolveRef(originElement) should return the element. So we use that.

    But wait, my function is being called with closeType. Let me see what closeType is.

    let resolvedReturnFocusValue = 
      typeof returnFocusValueOrFn === 'function'
        ? returnFocusValueOrFn(closeTypeRef.current)
        : returnFocusValueOrFn;
    

    So it's called with the current closeTypeRef.current. That's fine.

    OK so my logic is correct. Why is the test failing?

    Hmm, let me think. Maybe my useMemo returns the function, and it gets re-created. Then the useValueAsRef updates the ref. The cleanup of the effect uses the latest ref. The latest ref points to my function, which closes over originElement.

    When mounted changes:

    • originElement selector returns null (because state.mounted is false). But wait, I just removed the gated selector. So now originElement is whatever the store has, regardless of mounted.

    Hmm wait, when the popup closes (mounted becomes false), my hook captures originElement from the moment it was open. The originElement is still set in the store.

    But when I unmount the popup (via forceUnmount), is originElement reset?

    Looking at forceUnmount:

    const forceUnmount = useStableCallback(() => {
      setMounted(false);
      store.update({
        activeTriggerId: null,
        activeTriggerElement: null,
        mounted: false,
        preventUnmountingOnClose: false,
      } as Partial<State>);
    });
    

    originElement is not reset. So it stays in the store. But the popup is unmounted after forceUnmount (because setMounted(false) → re-render → mounted=false → ??).

    Actually wait, the popup only unmounts when... let me check.

  111. MiniMax Assistant

    So Portal renders based on mounted || keepMounted. When mounted=false and keepMounted=false, the portal renders null. The DialogPopup inside is unmounted.

    So when the dialog closes (after transition):

    1. forceUnmount runs, sets mounted: false
    2. Portal renders null (if keepMounted=false)
    3. DialogPopup unmounts

    When DialogPopup unmounts:

    • Its own useStates stop running
    • The FloatingFocusManager (its child) unmounts
    • The FloatingFocusManager's cleanup runs BEFORE unmount, which restores focus

    So timing:

    1. mounted: true → false (transitioning, before forceUnmount)
    2. disabled: false → true (because FloatingFocusManager's disabled={!mounted})
    3. FloatingFocusManager's effect cleanup runs (cleanup returns focus)
    4. Then mounted: false (after forceUnmount)
    5. Portal renders null, DialogPopup unmounts, FloatingFocusManager unmounts (no new cleanup)

    Hmm so the FloatingFocusManager's cleanup runs when disabled becomes true, which is when mounted becomes false.

    But mounted becomes false in two phases:

    • First: transition → mounted might stay true but transitionStatus changes
    • After transition: forceUnmount → mounted=false

    For dialogs, transitionStatus === 'ending' and mounted=true during the close transition. So FloatingFocusManager stays active during transition. After transition, mounted=false and FloatingFocusManager disables.

    Wait but my test disabled animations. Let me check BASE_UI_ANIMATIONS_DISABLED = true. So no transition, things happen synchronously.

    Let me check what happens synchronously:

    1. User clicks Close → setOpen(false)
    2. state.open = false (via setOpen)
    3. mountState = false triggers re-render with mounted=true but transitionStatus='ending'
    4. ... but wait, animations are disabled

    Let me look at the close mechanism more carefully:

  112. MiniMax Assistant

    OK so useOpenChangeComplete uses useAnimationsFinished which is asynchronous. Let me look at that:

  113. MiniMax Assistant

    OK so when BASE_UI_ANIMATIONS_DISABLED is true, fnToExecute() is called synchronously. This is the onComplete which calls forceUnmount. So the unmount is synchronous when animations are disabled.

    So in the test:

    1. Click Close → setOpen(false) → trigger Close event
    2. Re-render Dialog. mounted is still true (and transitionStatus='ending' or similar)
    3. useOpenChangeComplete runs onComplete synchronously → forceUnmount → mounted=false
    4. Re-render Dialog. mounted=false. Portal renders null. DialogPopup unmounts.
    5. FloatingFocusManager unmounts. Cleanup runs. Focus is restored.

    But step 4 happens because mounted=false. The FloatingFocusManager's disabled={!mounted} becomes true.

    Actually wait, FloatingFocusManager is INSIDE DialogPopup. When DialogPopup unmounts, FloatingFocusManager unmounts too. The unmount cleanup of FloatingFocusManager runs.

    But the FloatingFocusManager's deps-driven cleanup runs BEFORE the unmount. So when disabled changes from false to true, the cleanup runs. That's the focus-return cleanup.

    OK so the flow for test:

    1. Click Close → store.setOpen(false) → floatingRootContext.dispatchOpenChange(false)
    2. Re-render → mounted becomes false (synchronously via forceUnmount because animations disabled)
    3. DialogPopup re-renders with mounted=false
    4. FloatingFocusManager gets disabled={true}
    5. FloatingFocusManager's effect cleanup runs (deps changed because... actually disabled is a dep?)

    Wait, is disabled a dep? Let me check:

  114. MiniMax Assistant

    Yes! disabled is a dep. So when disabled changes from false to true, the effect cleanup runs.

    OK so when FloatingFocusManager transitions from enabled to disabled (on close), the cleanup runs and focuses the return element.

    The returnFocusRef.current is the latest returnFocus from the most recent render. Let me check the latest render's returnFocus.

    When mounted=false, the latest render:

    • useState('mounted') returns false
    • useState('originElement') returns... state.originElement directly (no gating). Should still be the "Open programmatically" button
    • resolvedFinalFocus = function returning originElement

    So the latest returnFocusRef.current is my function returning originElement.

    The cleanup runs: calls getReturnElement() which calls returnFocusRef.current(closeType) = originElement. Focus moves to originElement. ✓

    OK so the logic should work. Let me debug. Let me check the floatingRootContext first to see what's happening:

  115. MiniMax Assistant

    Interesting! The test passes when I add console logging. This might be due to the re-render happening differently when console.log is involved. Let me check more carefully:

  116. MiniMax Assistant

    Hmm, when run alone, the test passes. Let me run all reproduce tests:

  117. MiniMax Assistant

    OK the original failing test is the third test ("still returns focus to the trigger when opened by clicking it"). That's the third test in the describe block. It might run after the others have modified the DOM. Let me check the test order:

  118. MiniMax Assistant

    Hmm, so the third test is "still returns focus to the trigger when opened by clicking it". This test clicks trigger1, opens the dialog, clicks Close, expects focus on trigger1.

    The active element after close is "Open 2" (trigger-2). Why?

    When user clicks trigger1:

    • Trigger1 calls store.setOpen(true, eventDetails) with trigger1 element as eventDetails.trigger
    • setOpenTriggerState sets activeTriggerId = trigger1, activeTriggerElement = trigger1 element
    • But wait, also useImplicitActiveTrigger might set something

    Hmm, but the active trigger was set to trigger1 via setOpen. But then there's triggerIdProp field. It's null in this case (uncontrolled).

    Let me check the state:

    • Initially: open=false, triggerId=null, activeTriggerId=null, activeTriggerElement=null, triggerIdProp=undefined
    • User clicks trigger1:
      • setOpen(true, ...) is called with trigger1 element
      • setOpenTriggerState sets activeTriggerId = 'trigger-1', activeTriggerElement = trigger1 element
      • triggerIdProp stays undefined
      • The store state: activeTriggerId = 'trigger-1', activeTriggerElement = trigger1 element, triggerIdProp = undefined
    • User clicks Close: setOpen(false, ...) is called
    • Cleanup runs in FloatingFocusManager
    • useValueAsRef(returnFocus) - what is returnFocus?

    The originElement was captured when the popup opened (when trigger1 was the active element at mount time). So originElement = trigger1 element.

    The domReferenceElement should be trigger1 element via activeTriggerElement.

    Both originElement and activeTriggerElement are trigger1 element. So either way, focus should return to trigger1.

    Hmm but the test fails and shows focus went to "Open 2" (trigger-2). Strange.

    Wait, let me look at useTriggerDataForwarding again:

    useIsoLayoutEffect(() => {
        if (isMountedByThisTrigger) {
          store.update({
            activeTriggerElement: triggerElementRef.current,
            ...stateUpdates,
          } as Partial<State>);
        }
      }, [isMountedByThisTrigger, store, triggerElementRef, ...Object.values(stateUpdates)]);
    

    This runs when isMountedByThisTrigger is true. isMountedByThisTrigger is from store.useState('isMountedByTrigger', triggerId).

    For trigger1 after trigger1 click: activeTriggerId === 'trigger-1', mounted=true, so isMountedByTrigger=true.

    For trigger2 also: activeTriggerId === 'trigger-1' (selector returns trigger1 because activeTriggerId is set), so isMountedByTrigger=false. So trigger2's layout effect doesn't run.

    So activeTriggerElement should be trigger1. ✓

    Hmm. Let me dig more. Maybe it's the timing. Let me check when originElement is captured.

    Looking at useCapturedOriginElement:

    useIsoLayoutEffect(() => {
        if (!mounted || !open) {
          return;
        }
        // ... capture
    }, [open, mounted, store, popupElement]);
    

    It depends on open and mounted. When the user clicks trigger1, open becomes true, mounted becomes true, and the effect runs in the same render → captures originElement.

    But wait, where is useCapturedOriginElement called? In useDialogRoot.

  119. MiniMax Assistant

    So useDialogRoot is called in the dialog root. The root is always rendered (when the dialog is in the tree). The dialog root does NOT unmount when closed.

    Hmm, so when the dialog is opened multiple times, the originElement is captured each time. That's good.

    But wait, what if the layout effect runs AFTER the floating manager's effect? Let me think...

    Actually, useCapturedOriginElement is in the DialogRoot. The FloatingFocusManager is inside DialogPopup, which is inside DialogPortal. The DialogPortal only renders when mounted. So the FloatingFocusManager only mounts when the popup is mounted.

    The order of hook execution: depends on render order. DialogRoot renders before DialogPortal/Popup. So useCapturedOriginElement runs first, then FloatingFocusManager.

    But layout effects run after the entire render. They run in the order: child layout effects first, then parent. So FloatingFocusManager's layout effect (which captures previouslyFocusedElement) runs before useCapturedOriginElement's layout effect.

    So when FloatingFocusManager captures its previouslyFocusedElement, useCapturedOriginElement hasn't captured originElement yet.

    Hmm but timing-wise, both run synchronously in the same render cycle. The order shouldn't matter for correctness.

    Wait wait wait. Let me re-check. Both effects capture activeElement(doc) at the time the effect runs. If both run within the same layout effect phase, the active element should be the same.

    Hmm, unless something else is happening between. Like, the FloatingFocusManager's effect might schedule a microtask that moves focus.

    Let me re-read FloatingFocusManager's first effect (the one that captures previouslyFocusedElement):

    useIsoLayoutEffect(() => {
        if (disabled || !floatingFocusElement) {
          return undefined;
        }
        // ...
        const doc = ownerDocument(floatingFocusElement);
        const previouslyFocusedElement = activeElement(doc);
        addPreviouslyFocusedElement(previouslyFocusedElement);
        // ...
        return () => {
          // ... cleanup
        };
    });
    

    This effect runs when the FloatingFocusManager mounts. At that time, floatingFocusElement is the popup element. The activeElement(doc) is the focused element (which should be trigger1 if trigger1 was clicked).

    OK so the FloatingFocusManager captures trigger1 as previouslyFocusedElement.

    And the useCapturedOriginElement runs at the same time, captures trigger1 as originElement.

    But wait, I need to check WHICH effect runs first. Let me look more carefully:

  120. MiniMax Assistant

    There's only one effect in useDialogRoot.ts at line 140 (after my changes). My useCapturedOriginElement is called in useDialogRoot (line 28).

    OK so the issue might be about when useCapturedOriginElement runs vs when FloatingFocusManager's effect runs.

    Both are useIsoLayoutEffect. Layout effects run after the commit, in the order: deepest first.

    So FloatingFocusManager's layout effect runs FIRST (it's a descendant of DialogPopup which is a descendant of DialogPortal which is in DialogRoot).

    Then DialogRoot's layout effects (including useCapturedOriginElement) run.

    But that's the same as setting them both up. The activeElement(doc) is the same in both cases.

    Hmm.

    Actually wait, the FloatingFocusManager captures previouslyFocusedElement synchronously in the layout effect. But what if it then schedules a microtask for initial focus? The microtask runs after the layout effect phase.

    After the layout effect phase, the originElement should be set (by my hook).

    But the previouslyFocusedElement is captured BEFORE originElement is captured. Hmm.

    Actually wait, looking at FloatingFocusManager:

    useIsoLayoutEffect(() => {
        if (disabled || !floatingFocusElement) {
          return undefined;
        }
        const doc = ownerDocument(floatingFocusElement);
        const previouslyFocusedElement = activeElement(doc);
        addPreviouslyFocusedElement(previouslyFocusedElement);
        // ...
    });
    

    This effect captures previouslyFocusedElement synchronously. It doesn't run the initial focus here.

    The initial focus is in another effect:

    useIsoLayoutEffect(() => {
        if (!open || disabled || !isHTMLElement(floatingFocusElement)) {
          return;
        }
        const doc = ownerDocument(floatingFocusElement);
        const previouslyFocusedElement = activeElement(doc);
        queueMicrotask(() => {
          // ... do initial focus
        });
    }, [disabled, open, floatingFocusElement, getTabbableContent, initialFocusRef, openInteractionTypeRef]);
    

    This effect runs on first mount, captures previouslyFocusedElement again, and schedules a microtask for initial focus.

    The initial focus in the microtask moves focus to the popup. So by the time the microtask runs, previouslyFocusedElement is captured but not used for initial focus (it's used by the cleanup for focus return).

    OK so my hook runs after FloatingFocusManager's effects. But it captures the same activeElement(doc). So originElement = trigger1 element.

    Hmm, why does the test show focus on trigger-2?

    Wait, let me re-run the third test alone:

  121. MiniMax Assistant

    The third test passes when run alone! So the failure in the reproduce.test.tsx file is due to test interaction. Let me check what happens in the same file:

  122. MiniMax Assistant

    Now it's the Popover test that's failing! Let me run only the Popover test:

  123. MiniMax Assistant

    So the Popover test is failing. The Popover test isn't using my DialogPopup. It uses PopoverPopup, which I haven't updated to use originElement.

    Let me check PopoverPopup:

  124. MiniMax Assistant

    Let me add similar logic to PopoverPopup:

  125. MiniMax Assistant

    Now let me run the reproduce tests:

  126. MiniMax Assistant

    All 3 tests pass. Now let me run the existing tests to make sure I didn't break anything:

  127. MiniMax Assistant

    Dialog tests pass. Now popover:

  128. MiniMax Assistant

    One popover test is failing. Let me find it:

  129. MiniMax Assistant

    Ah, the failing test is "should focus the trigger by default when closed". The test:

    1. Renders a popover with an input above and below
    2. Clicks trigger to open
    3. Clicks close
    4. Expects trigger to have focus

    But the actual focus is on the input after close.

    Hmm, in this case:

    • User clicks trigger → trigger.click() → trigger gets focus → open
    • originElement should be the trigger (since it was the focused element when popup mounted)
    • User clicks close → focus moves to popup → close → focus should return to trigger

    But the test fails. Let me think about why.

    Wait, the failing test is similar to test 3 of my reproduce tests... let me look:

    In the failing test:

    • <input /> → trigger → popover → <input />
    • User clicks trigger (trigger.click())
    • User clicks close
    • Expected: trigger has focus

    In my test 3:

    • Same setup but with the controller button at the end
    • User clicks trigger1
    • User clicks close
    • Expected: trigger1 has focus

    The difference is that my test 3 passes, but this popover test fails. Let me investigate.

    Actually wait, this might be related to the popover's stickIfOpen behavior. Let me check.

    Looking at the popover code path:

    • closeButton.click() → setOpen(false) → handler in PopoverStore.setOpen
    • onOpenChange is called with (false, ...)
    • In the PopoverStore.setOpen, there are various logic checks
    • Then changeState updates open: false, etc.

    Hmm. Let me check if there's anything special about the popover.

    Actually let me run just that specific test:

  130. MiniMax Assistant

    So when the trigger is clicked, the trigger has focus. Then click close. Then close should restore focus to trigger. But it's focusing the input.

    Hmm. Let me debug:

    For the test:

    • User clicks trigger → trigger.click() → popup opens
    • Popup mounts → useCapturedOriginElement runs → captures active element = trigger
    • originElement = trigger

    When closing:

    • FloatingFocusManager's getReturnElement() runs
    • returnFocus is my function that returns originElement if connected, else true
    • originElement = trigger (still connected)
    • Returns trigger element

    So focus should return to trigger. But it's going to the input.

    Hmm. Let me think about what could be different.

    Wait, I notice: in this test, the trigger is inside <Popover.Root> (not detached). Let me check how that affects things.

    Actually wait, in the failing test, the popover structure is:

    <Popover.Root>
      <Popover.Trigger>Open</Popover.Trigger>
      <Popover.Portal>...</Popover.Portal>
    </Popover.Root>
    

    So Trigger is inside Root. When setOpen(true, eventDetails) is called with trigger as eventDetails.trigger:

    • activeTriggerId = triggerId
    • activeTriggerElement = trigger

    Then useImplicitActiveTrigger runs:

    if (!store.select('activeTriggerId') && triggerCount === 1) {
    

    This DOES NOT update because activeTriggerId is set.

    Then useCapturedOriginElement runs:

    • mounted = true, open = true
    • activeElement(doc) = trigger (since the user just clicked trigger)
    • originElement = trigger

    When closing:

    • setOpen(false, ...)
    • DialogPopup's effect runs with disabled=true
    • returnFocus is called
    • originElement = trigger (from the store, since selector doesn't gate by mounted)
    • Returns trigger

    So focus should return to trigger. But it's going to the input.

    Wait, maybe the issue is that my hook captures at the wrong time. Let me check.

    When user clicks trigger:

    • The click event happens
    • The click handler calls setOpen(true, ...)
    • This triggers a re-render
    • The popover's portal renders
    • The PopoverPopup mounts
    • FloatingFocusManager's layout effect captures previouslyFocusedElement (which is trigger since user just clicked it)
    • The popover's open state is true now
    • useOpenStateTransitions runs with mounted=true

    But wait, my useCapturedOriginElement is in useDialogRoot. For popover, it's in PopoverRoot.tsx. Let me check:

    The useCapturedOriginElement is called in usePopoverRootComponent. But where does it get called? It's in the function component body, BEFORE the return statement. So it's called on every render.

    But it's hooked to [open, mounted, store, popupElement]. So it only re-runs when these change.

    Hmm, let me also check if the useCapturedOriginElement is called when the popover opens.

    Actually, the issue might be that popupElement is initially null (the popup hasn't mounted yet). So the layout effect's deps include popupElement. When popupElement changes from null to the actual element, the effect re-runs and captures the active element.

    But wait, by then, the FloatingFocusManager has already moved focus into the popup. Let me trace:

    1. User clicks trigger → trigger has focus
    2. setOpen(true) → React re-renders
    3. Popover.Portal renders → Popover.Positioner → Popover.Popup
    4. Popover.Popup mounts → React commits → layout effects run:
      • FloatingFocusManager layout effect runs (first): captures previouslyFocusedElement = trigger
      • Layout effect schedules microtask for initial focus
      • My useCapturedOriginElement layout effect runs: captures activeElement(doc) = trigger (still trigger because microtask hasn't run yet)
      • originElement = trigger

    Wait, but the dependency of useCapturedOriginElement includes popupElement. popupElement is store.useState('popupElement'). Initially null. Then becomes the popup element. So the effect re-runs when popupElement changes.

    If popupElement becomes the popup element after the layout effects, then activeElement(doc) is now the popup element (because of the microtask scheduled initial focus).

    Let me trace more carefully:

    When Popover.Popup renders for the first time:

    1. The store has popupElement = null initially
    2. The setPopupElement callback runs (sets popupElement = the element)
    3. This triggers a re-render
    4. On re-render, popupElement is the element

    But the layout effects from the FIRST render run first:

    • Layout effect 1: FloatingFocusManager captures previouslyFocusedElement = trigger, schedules microtask for initial focus
    • Layout effect 2 (useCapturedOriginElement): captures activeElement(doc) = trigger, sets originElement = trigger

    Then microtask runs: focus moves to popup (initial focus).

    Then popupElement updates to the popup. This triggers re-render. But does it trigger layout effect re-run?

    Looking at FloatingFocusManager's effect: depends on [..., getTabbableContent, initialFocusRef, openInteractionTypeRef] and others. Changes to popupElement might not trigger re-run.

    For my hook: depends on [open, mounted, store, popupElement]. Yes, popupElement change triggers re-run. So:

    • Re-render with popupElement = the element
    • Layout effect re-runs
    • activeElement(doc) = popup (because focus moved to popup)
    • originElement = popup (oh no, bad!)

    So my hook is overwriting originElement with the popup itself. Wait, but my hook has the check !contains(popupElement, element). So if the element is the popup, it's contained, and we don't update.

    Wait, contains(popupElement, popup) - the popup contains itself? Let me think. contains returns true if the parent contains the child. popupElement = popup, element = popup. So contains(popup, popup) = true. So we don't update.

    OK so my check prevents the issue. ✓

    Let me re-think. The issue might be different. Let me check what active element is when the layout effect re-runs (after popupElement is set).

    Actually, I should verify: when does popupElement change? It changes when the setPopupElement callback is called. That's in useRenderElement's ref callback. Let me check.

  131. MiniMax Assistant

    So setPopupElement is passed as a ref. It runs when the popup element is mounted (initially null → element).

    When the ref callback runs with the element, popupElement is set in the store. This triggers React re-render.

    The re-render happens in a separate commit phase. So between the first render (with popupElement=null) and the second render (with popupElement=element), the layout effects run, then microtasks, then the next render.

    Let me think about the sequence:

    1. First render: popup element is being created, but popupElement is null in store
    2. Commit phase: popup element is mounted to DOM
    3. Layout effects run:
      • FloatingFocusManager captures previouslyFocusedElement = trigger, schedules microtask
      • useCapturedOriginElement captures activeElement(doc) = trigger, originElement = trigger
    4. After layout effects: refs are processed (refs are called AFTER layout effects)
      • setPopupElement runs → popupElement = the element → triggers re-render
    5. Microtasks run: initial focus moves to popup
    6. Re-render due to state change: popupElement = element

    Wait, the microtask runs AFTER the refs! Let me verify:

    Actually, the order in React is:

    1. Render
    2. Commit (DOM mutations)
    3. Layout effects (synchronously)
    4. Refs (synchronously, but... actually refs are during commit, before layout effects)

    Let me look up the order:

    Actually, refs are set during the commit phase, BEFORE layout effects. Let me verify.

    Per React docs, refs are set during the "mutations and effects" phase. Layout effects run after refs in React 18+.

    Actually, in React 19, I believe refs are set before layout effects. Let me think about this.

    Actually, I think there might be some nuance here. Let me look at the implementation:

  132. MiniMax Assistant

    OK PopoverPopup doesn't have its own useLayoutEffect. The popupElement state is set via setPopupElement ref callback.

    Let me check what happens during the lifecycle:

    1. User clicks trigger
    2. setOpen(true, eventDetails) is called
    3. React re-renders
    4. On re-render, the FloatingFocusManager mounts (because mounted becomes true)
    5. Commit phase: refs are called (setPopupElement with the element)
    6. Layout effects run
    7. Microtasks run
    8. Browser paints

    So refs are called BEFORE layout effects. When setPopupElement is called, popupElement becomes the element. But this triggers another render...

    Wait, set calls store.set(...) which uses external store. External stores trigger re-renders via useSyncExternalStore. The re-render happens asynchronously, after the current render cycle completes.

    So:

    1. First render: refs call setPopupElement(element). Store updates synchronously. (But no re-render yet - the re-render is scheduled.)
    2. Layout effects run
    3. Layout effects capture state from CURRENT render (which has popupElement=null from the first render)

    Hmm wait, useSyncExternalStore is called multiple times. Let me think.

    Actually, store.set triggers re-renders synchronously in React. Let me check.

  133. MiniMax Assistant

    OK so set calls setState which notifies subscribers. React's useSyncExternalStore is notified and triggers re-renders.

    But the timing depends on whether React is currently rendering. If we're in the middle of a commit (refs running), the re-render is scheduled for the next cycle.

    Actually let me just think about this differently. Let me check what happens in the failing test.

    The failing test:

    • <input /> above

    • <Popover.Trigger>Open</Popover.Trigger>

    • <Popover.Portal>...</Popover.Portal> containing the popover

    • <input /> below

    • User clicks trigger → trigger.focus()

    • popup opens, trap focus to popup

    • User clicks Close button → setOpen(false)

    • popup closes, focus returns

    After close:

    • Expected: trigger has focus
    • Actual: input (probably the next input) has focus

    Why would it return to the input? Looking at FloatingFocusManager's fallback logic:

    const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
    return resolveRef(resolvedReturnFocusValue) || fallback || null;
    

    resolveRef(originElement):

    • If originElement is set and is HTMLElement, returns it
    • Otherwise returns null

    If my resolvedFinalFocus function returns true, then resolvedReturnFocusValue = true, which goes through the boolean branch.

    Hmm. Let me check if my function is being called correctly. Let me look at the resolveRef function:

  134. MiniMax Assistant

    OK so if my function returns originElement, resolveRef returns it. If it returns null/undefined, resolveRef returns null/undefined.

    Wait, let me re-look at the FloatingFocusManager's logic:

    function getReturnElement() {
      const returnFocusValueOrFn = returnFocusRef.current;
      let resolvedReturnFocusValue =
        typeof returnFocusValueOrFn === 'function'
          ? returnFocusValueOrFn(closeTypeRef.current)
          : returnFocusValueOrFn;
    
      if (resolvedReturnFocusValue === undefined || resolvedReturnFocusValue === false) {
        return null;
      }
      // ...
    }
    

    When my function returns an element, resolvedReturnFocusValue is the element. Not undefined, not false. So we proceed.

    Then:

    if (typeof resolvedReturnFocusValue === 'boolean') {
    

    It's an element, not a boolean. So we skip the boolean branch.

    const fallback = domReference?.isConnected ? domReference : getPreviouslyFocusedElement();
    return resolveRef(resolvedReturnFocusValue) || fallback || null;
    

    resolveRef(element) returns the element. So we return the element.

    So if my function returns the trigger element, focus should return to trigger.

    OK so the question is: when the test fails, why is my function returning true instead of originElement?

    Maybe my originElement is null in this case? Let me think.

    When the test runs:

    • Render: popover is closed
    • User clicks trigger
    • setOpen(true) → re-render → portal renders → popup mounts
    • FloatingFocusManager captures previouslyFocusedElement (trigger)
    • useCapturedOriginElement captures originElement (trigger)
    • BUT! The popover ALSO has a layout effect... let me check.

    Actually, looking at Popover.Portal:

  135. MiniMax Assistant

    OK. Now let me look at the positioner:

  136. MiniMax Assistant

    Let me check the layout effect:

  137. MiniMax Assistant

    OK so PopoverPositioner reads domReference from the floatingRootContext. Let me think...

    Maybe the issue is that when the popover opens normally (not programmatically), domReferenceElement is the trigger. Then when the popover closes, my function returns originElement = trigger, but the default behavior also returns domReference = trigger. So they should be the same.

    So why is the test failing? Let me look more carefully.

    Actually wait - I wonder if the test is failing because of how originElement is captured. Maybe my hook ISN'T capturing the trigger because the trigger doesn't have focus when the layout effect runs.

    Let me trace:

    1. User clicks trigger (mouse click via trigger.click() in test)
    2. Browser: focus moves to trigger
    3. click handler fires → setOpen(true)
    4. React schedules a re-render
    5. Re-render happens
    6. Portal renders → popup mounts
    7. Layout effects run:
      • FloatingFocusManager: captures previouslyFocusedElement = trigger
      • useCapturedOriginElement: captures activeElement(doc) = trigger

    Wait, but step 6 happens after the click. The click event handler triggers the state update synchronously in React 18+ (batched). So the re-render might not happen until the click handler completes.

    Hmm let me actually check if trigger.click() focuses the trigger. Let me see what happens in JSDOM:

  138. MiniMax Assistant

    So after open, active element is "Close" (the popup's content). After close, active element is INPUT (not the trigger).

    So the focus is on input (maybe the next input after the popover). Hmm.

    So when the popover opens, focus is initially on trigger (clicked). Then the popup opens, focus moves to "Close" button inside the popup. So the originating element should be the trigger.

    When closing, focus returns to... the input below. Hmm.

    Maybe the issue is that originElement is the input BELOW the popover, not the trigger. Let me think...

    Wait, maybe useCapturedOriginElement isn't capturing the correct element. Let me check.

    Actually, looking at the FloatingFocusManager effect:

    useIsoLayoutEffect(() => {
        if (disabled || !floatingFocusElement) {
          return undefined;
        }
    
        const doc = ownerDocument(floatingFocusElement);
        const previouslyFocusedElement = activeElement(doc);
    
        addPreviouslyFocusedElement(previouslyFocusedElement);
        // ...
    });
    

    This runs when the FloatingFocusManager's effect runs. The effect's deps include disabled. When disabled is false and floatingFocusElement is defined, the setup runs.

    When the popover is closed and re-opened, the FloatingFocusManager UNMOUNTS. When it re-mounts (because the popover re-opens), the layout effect runs again, capturing the new previouslyFocusedElement.

    But this is happening... and somehow focus still goes to input?

    Let me check more carefully. The issue might be:

    • User clicks trigger → trigger gets focus
    • trigger.click() in JSDOM might NOT move focus to the trigger. Let me verify.

    Actually, looking at the test output: "Active element during open: Close". This means by the time we check the active element, it's already "Close" (popup content). So focus is on the popup.

    But at the moment the popup mounts, what's the active element?

    When the popover is rendered for the first time:

    • The store has mounted=false initially
    • After click, mounted becomes true
    • Portal renders → popup renders
    • FloatingFocusManager mounts
    • Layout effects run
    • activeElement(doc) = trigger (the focused element)
    • This is captured as previouslyFocusedElement

    But then microtask schedules initial focus → moves focus to popup (Close button).

    So previouslyFocusedElement should be trigger.

    But then the test expects focus on trigger after close, and it goes to INPUT.

    Hmm. Let me check more carefully what's happening. Let me log the originElement value:

  139. MiniMax Assistant

    In this case, focus returns to trigger (Open). So my fix works correctly.

    But the original test still fails. Why?

    Let me re-read the failing test:

    it('should focus the trigger by default when closed', async () => {
      await render(
        <div>
          <input />
          <Popover.Root>
            ...
          </Popover.Root>
          <input />
        </div>,
      );
    
      const trigger = screen.getByText('Open');
      await act(async () => {
        trigger.click();
      });
      // ...
      const closeButton = screen.getByText('Close');
      await act(async () => {
        closeButton.click();
      });
    
      await waitFor(() => {
        expect(trigger).toHaveFocus();
      });
    });
    

    The test uses trigger.click() directly without explicit focus. Maybe in the original test, the trigger doesn't have focus when popup mounts.

    Hmm, but in my debug test where I called trigger.focus() first, it works.

    Actually wait, looking back at the output:

    Active element during open: Close
    Active element tag: BUTTON
    

    This is logged AFTER the popup is open and after act(). So the popup has focus.

    But before the popup opens, the trigger should have focus.

    Let me check the original test without my modifications:

    Actually wait, let me check what my hook captures. Let me add a log to useCapturedOriginElement:

  140. MiniMax Assistant

    I see! The hook captures:

    1. First time: open: true, mounted: true, hasPopup: false, elementText: 'Open' - so originElement = 'Open' (trigger)
    2. Second time: open: true, mounted: true, hasPopup: true, elementText: 'OpenClose' - WAIT, the elementText is 'OpenClose'?!

    The text 'OpenClose' suggests something like... actually it might be the text content of the popup or the document body which contains both texts.

    Hmm, elementText: 'OpenClose' - this looks like the body or some containing element. The popup has "Open" trigger and "Close" button inside.

    Wait, elementText: 'OpenClose' - is this the text content of some element with both texts? Let me think...

    Actually it might be the document.body which has both 'Open' (trigger) and 'Close' (button inside popup). So my hook is capturing document.body!

    When the layout effect re-runs the second time (because popupElement updated), the activeElement(doc) is no longer the trigger. It might be... hmm.

    Let me check what's happening. The popup element is now set, but the active element might still be the trigger or might have moved.

    Actually wait - I called trigger.click(). After the click, the trigger should have focus. Then the popup opens, focus moves to Close button (via initial focus in microtask).

    The DEPENDENCIES of the layout effect: [open, mounted, store, popupElement].

    When does popupElement change?

    • First render: popupElement = null (the popup element hasn't been registered yet)
    • ref callback runs: store.set('popupElement', element). This causes a re-render.
    • Second render: popupElement = element

    So the layout effect runs:

    1. First render: open=true, mounted=true, popupElement=null. activeElement(doc) = trigger (since user just clicked). Captures originElement = trigger.
    2. After refs: store.set('popupElement', element). Re-render.
    3. Second render: open=true, mounted=true, popupElement=element. activeElement(doc) = ??? (depends on microtask timing)

    If the microtask ran in between (moving focus to Close), then activeElement(doc) = Close button. But the text is 'OpenClose', not 'Close'.

    Hmm. Maybe activeElement is the body or html. Or some other container.

    Let me check: 'OpenClose' looks like 'Open' + 'Close'. The trigger has 'Open' as text, the popup has 'Close' as text. If both are inside an element, that element's textContent would be 'OpenClose' (concatenated).

    Hmm, but trigger and popup are in different DOM trees (popup is in a portal).

    Wait, maybe my keyboard focus was somewhere unexpected. Let me check the second render's activeElement more carefully.

    Actually, let me think about the timing:

    • Click trigger → setOpen(true) → re-render
    • Re-render: portal renders, popup mounts
    • Refs are called: setPopupElement → store.set('popupElement', element). This causes ANOTHER re-render.
    • BUT, the second re-render is scheduled, not synchronous
    • Layout effects run after the first render's commit
    • Then microtasks run: initial focus moves
    • Then the second re-render happens

    Actually, store.set triggers synchronous notification, but React batches it. Hmm.

    Let me check:

    In React, state updates during commit (like in refs) are typically batched and processed AFTER the current commit completes. So:

    1. Render 1: open=true, mounted=true, popupElement=null
    2. Commit 1: popup element is mounted to DOM
    3. Layout effects run (capture trigger as originElement)
    4. Refs run (setPopupElement → store updates popupElement, triggers re-render 2)
    5. Microtasks run (initial focus → focus moves to Close button)
    6. Render 2: open=true, mounted=true, popupElement=element
    7. Commit 2: no DOM changes
    8. Layout effects run again (popupElement changed)

    Wait, but does React process re-renders BEFORE microtasks? Let me check.

    In React 19, I believe state updates from refs are processed in the next render cycle. They happen AFTER the current commit.

    Hmm, so by the time Render 2 happens, the microtask has run. So activeElement(doc) in step 8 would be Close button. But the text says 'OpenClose'.

    Hmm, this is strange. Maybe my log is wrong. Let me check element.tagName etc.

    Actually wait, let me look at what activeElement(doc) returns. For document.body, it would have the entire page's text content.

    Let me check by adding more detail to the log:

    Actually, thinking about this more, there's an issue. The hook captures originElement at multiple times:

    • First: popupElement=null, capture = trigger (since user just clicked)
    • Second: popupElement=element, capture = popup or body?

    Wait, the second time, the layout effect re-runs because popupElement changed. At this point, what is activeElement(doc)?

    If the microtask ran, focus is on Close button. Active element would be the Close button.

    Let me check why it says 'OpenClose' instead of 'Close'.

    Hmm, maybe elementText is wrong. Let me re-look. The element's textContent would be the text of the element. For Close button, textContent is 'Close'. For document.body, it would be all text on the page.

    Wait, maybe my logging is wrong. Let me debug more:

  141. MiniMax Assistant

    OH! The active element is BODY, not trigger! The first time it's BODY with text 'Open', the second time BODY with text 'OpenClose'.

    So when the user clicks trigger, focus is NOT on the trigger. It's on document.body.

    This is because trigger.click() in JSDOM (or maybe in the popover test setup) doesn't move focus to the button. Only mouse/click events are fired, but focus events are not.

    So when the popup opens:

    • activeElement(doc) = body (containing the trigger and popup)
    • We capture originElement = body

    When closing:

    • focus returns to body

    But the test expects trigger to have focus. So the test is using the OLD behavior where domReference (trigger-1 element) was used.

    WAIT - I expected this scenario would only fail for the controlled/programmatic case. But the failing test is for a normal click on trigger-1. Let me re-read the test...

    Actually, this might have ALWAYS been a flaky test or one that had some specific behavior in JSDOM. Let me check what happens when I revert my changes:

    Actually, let me check what the test was doing before my changes by reverting just the popover change:

  142. MiniMax Assistant

    Hmm, that's my popover edit removing originElement. Let me re-add the variable but remove the use of it. Actually, let me check the original state of the test in HEAD before my changes:

  143. MiniMax Assistant

    OK so in the ORIGINAL code (without my changes):

    • After open: active is BUTTON (Close - the popup content)
    • After close: active is BUTTON (Open - the trigger)

    So the original code DOES return focus to the trigger. Even though trigger.click() doesn't set focus to the trigger (the active element is body), the close mechanism somehow focuses the trigger.

    Looking at the FloatingFocusManager's behavior:

    • domReference = activeTriggerElement (which IS set when trigger is clicked)
    • After close, focus returns to domReference (= trigger)

    The activeTriggerElement is set during setOpen(true) via setOpenTriggerState because eventDetails.trigger is the trigger element. So domReferenceElement = trigger, and focus returns to trigger.

    OK so before my changes, the trigger gets focus via domReferenceElement. After my changes, my function returns originElement which is body (because active element is body at the time of opening, not trigger).

    This is the issue. My logic of capturing originElement captures the body, not the trigger.

    Now, in REAL usage (browser with mouse):

    • User clicks trigger with mouse
    • Browser moves focus to trigger
    • Click handler fires → popup opens
    • We capture originElement = trigger

    In JSDOM:

    • trigger.click() may not trigger focus event
    • Click handler fires → popup opens
    • We capture originElement = body (because focus didn't move)

    So my logic works in browser but fails in JSDOM for this test.

    Hmm. Let me think about how to handle this.

    Option 1: Use the previously-focused-element logic in the FloatingFocusManager (which uses a different mechanism) but improve it to prefer it over domReference when the activeTrigger was set via triggerIdProp.

    Option 2: Always capture the trigger element as originElement when the popup is opened via clicking a trigger.

    Option 3: Only use originElement when the popup is opened in a controlled/programmatic way.

    I think Option 3 is the cleanest. When the user clicks a trigger (eventDetails.trigger is set in setOpen), use the trigger as the focus return. Otherwise, use the captured originElement.

    Wait actually, let me think. The issue is:

    In the failing test (JSDOM with click()):

    • activeTriggerElement = trigger (set via setOpen in popover store)
    • domReference = trigger
    • activeElement(doc) = body (because click() doesn't focus)

    When the popover closes:

    • OLD logic: focus returns to domReference = trigger ✓
    • NEW logic (with originElement): my function returns originElement = body ✗

    So in this case (where activeTriggerElement is correctly set but originElement is body), the OLD logic is better.

    How can I make the new logic handle this correctly?

    Approach: Only use originElement for focus return when the popup was opened in a way where the "real" focus target wasn't the trigger.

    Hmm. Actually, I think the cleanest fix is: ALWAYS prefer the originating element IF it's not body/documentElement. If the originElement is body (like in the failing JSDOM test), fall back to domReference.

    But in the controlled/programmatic case, originElement is the "Open programmatically" button (a real button, not body). So we'd use it. ✓

    In the JSDOM case, originElement is body. We don't use it. Fall back to domReference = trigger. ✓

    So the fix is: my function should check if originElement is a "useful" element (not body or documentElement or html). If it's not useful, fall back to true (default behavior).

    Actually, even simpler: check if originElement is connected and is a "regular" HTMLElement (not document body etc.). Let me update:

  144. MiniMax Assistant

    Now let me update my hook to not capture body (we should only capture meaningful elements):

  145. MiniMax Assistant

    Now let me run the failing popover test:

  146. MiniMax Assistant

    Now let me run all popover tests:

  147. MiniMax Assistant

    All popover tests pass. Now let me run the dialog and other related tests:

  148. MiniMax Assistant

    All 1633 tests pass! Now let me also handle the issue where the test triggered focus remains in the body. The body case happens because trigger.click() in JSDOM doesn't focus the element. In a browser, clicking does focus.

    But for safety and to ensure we handle the controlled/programmatic case correctly, my hook captures ONLY meaningful controls. Body/documentElement are excluded.

    Now let me clean up my debug tests and verify the final state:

  149. MiniMax Assistant

    Let me also handle the case where Drawer's DrawerPopup might need updating. Let me check:

  150. MiniMax Assistant

    Drawer also needs the fix. Let me also update it. But Drawer uses Dialog's popups too (the DrawerPopup is separate). Let me check the store usage:

  151. MiniMax Assistant

    Wait, DrawerPopup uses a different store. Let me check:

  152. MiniMax Assistant

    OK so DrawerPopup uses the dialog store (via useDialogRootContext). And my hook was added in useDialogRoot (which is part of the dialog root). Since Drawer uses Dialog.Root internally, my hook should already capture originElement in the store.

    Let me add the same logic to DrawerPopup:

  153. MiniMax Assistant

    Now let me run the drawer tests:

  154. MiniMax Assistant

    There's a compilation error - the originElement variable isn't defined. Let me check:

  155. MiniMax Assistant

    The first edit didn't apply! Let me check why:

  156. MiniMax Assistant

    The first edit didn't apply because there's a slight difference. Let me fix:

  157. MiniMax Assistant

    All drawer tests pass. Let me also run the AlertDialog tests:

  158. MiniMax Assistant

    Now let me run the comprehensive test suite to verify nothing is broken:

  159. MiniMax Assistant

    All 6099 tests pass (873 skipped, which is normal). Let me verify my reproduce tests still pass:

  160. MiniMax Assistant

    Now let me also test a few edge cases. Let me create more comprehensive tests for the reproduction:

  161. MiniMax Assistant

    Let me clean up the test files:

  162. MiniMax Assistant

    Now let me verify the final state of all my changes:

  163. MiniMax Assistant

    All my changes look correct. Let me also verify by running just the original failing test:

  164. MiniMax Assistant

    Now let me create a final reproduction script (that I'll remove later) to verify the fix works:

  165. MiniMax Assistant

    All 4 tests pass. Let me clean up the verification file:

  166. MiniMax Assistant

    Let me also verify linting passes:

  167. MiniMax Assistant

    Let me fix the lint issues:

  168. MiniMax Assistant

    No errors. Let me also run TypeScript checks:

  169. MiniMax Assistant

    These errors are about pre-existing build artifacts. Let me try the project-specific tsc:

  170. MiniMax Assistant

    These are all TS6305 errors about missing build artifacts (unrelated to my changes). Let me filter to my files:

  171. MiniMax Assistant

    All these are pre-existing errors not related to my changes. Let me check specifically my changed files:

  172. MiniMax Assistant

    These are also TS6305 issues from missing build artifacts, and TS2339 errors that look pre-existing. The DialogStore.useState errors are because the ReactStore type definitions haven't been built.

    So my changes don't introduce new TypeScript errors. Let me also verify by running the test suite:

  173. MiniMax Assistant

    All 710 tests pass (198 skipped). Let me do a final review of all the changes:

  174. MiniMax Assistant

    Let me check the final content of my key changes:

  175. MiniMax Assistant

    Let me make sure the tests I want still work, including when the trigger is no longer in the DOM. Let me create one more test:

  176. MiniMax Assistant

    The edge case works. Let me clean up:

  177. MiniMax Assistant

    Let me run the comprehensive tests one more time to make sure everything is good:

  178. MiniMax Assistant

    All 1192 tests pass. Let me look at the diff one more time:

  179. MiniMax Assistant

    The diff looks clean. Let me also add a comment about why the workspace got 1.5 in the dependencies check, but that doesn't apply here.

    Let me also note, in the original demo scenario:

    1. User clicks "Open programmatically" → focus moves to that button
    2. setOpen(true, triggerId='trigger-2') via React state → triggerIdProp becomes 'trigger-2'
    3. Re-render: mounted=true, popup mounts, useCapturedOriginElement captures the button (originElement)
    4. FloatingFocusManager's previouslyFocusedElement also captures the button
    5. Popup opens, focus moves to popup content
    6. User clicks Close → focus is restored via FloatingFocusManager's cleanup
    7. My returnFocus returns originElement (the "Open programmatically" button)
    8. Focus moves to "Open programmatically" button ✓

    Without my fix: 1-6. Same 7. FloatingFocusManager's getReturnElement returns domReference = trigger-2 element 8. Focus moves to trigger-2 (wrong!) ✗

    My fix successfully resolves the issue!

    Let me also verify the implementation handles all the requirements mentioned in the issue:

    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.

    My fix:

    1. ✓ Focus moves to originating control when available
    2. ✓ If control is removed (isConnected is false), falls back to true (default behavior, which uses domReference or getPreviouslyFocusedElement)

    For the "next to that originating control's position in the DOM" part - this would be the getPreviouslyFocusedElement() fallback, which is captured by the FloatingFocusManager. So that's handled.

    Let me also verify by adding tests to verify the focus is captured correctly in the issue's exact scenario:

  180. MiniMax Assistant

    I have a syntax error in my test (using Dialog.Trigger without Root). Let me fix and re-run:

  181. MiniMax Assistant

    Hmm, still failing. Let me check AlertDialog's components:

  182. MiniMax Assistant

    Hmm, the issue is that triggers need to have an id when there's a Root to associate with. Let me look at AlertDialogTrigger:

  183. MiniMax Assistant

    So AlertDialogTrigger uses DialogTrigger. But the Trigger needs a Root. Let me rewrite the test:

  184. MiniMax Assistant

    AlertDialog also fixed. Let me clean up:

  185. MiniMax Assistant

    Let me also check there are no issues with the docs demos. Let me look at one demo to verify it would still work:

  186. MiniMax Assistant

    This demo's behavior should be exactly what's described in the issue. With my fix, when the user clicks "Open programmatically", focus is on that button. When the alert dialog closes (via Cancel or Confirm), focus should return to "Open programmatically" button.

    Let me look at the CSS module setup:

  187. MiniMax Assistant

    Let me verify my fix works for the exact issue scenario:

    Based on the issue:

    Note focus has moved back to the "Delete" button and not the "open programmatically" button as expected.

    In my fix:

    • "Open programmatically" button has focus
    • User clicks it → focus stays on it
    • AlertDialog opens → originElement = "Open programmatically" button
    • User clicks Confirm/Cancel → focus returns to "Open programmatically" button ✓

    Now let me also think about the case where the AlertDialogRoot state:

    • handleOpenChange sets triggerId from eventDetails.trigger?.id

    When the user clicks "Open programmatically" button:

    • setOpen(true, triggerId='alert-trigger-2') in the React app
    • The dialog opens
    • handleOpenChange(true, eventDetails) is called by the dialog's onOpenChange
    • triggerId is set to eventDetails.trigger?.id (which is null because there's no trigger)
    • So triggerId = null

    Wait, that's a bug in the demo - it sets triggerId from eventDetails.trigger?.id but the dialog's onOpenChange might not have a trigger associated. Let me check the onOpenChange:

  188. MiniMax Assistant

    Looking at this, the demo's logic is:

    1. Initial: triggerId=null
    2. User clicks "Open programmatically": sets setTriggerId('alert-trigger-2'), setOpen(true)
    3. AlertDialog opens → calls onOpenChange(true, eventDetails)
    4. handleOpenChange: setOpen(true), setTriggerId(eventDetails.trigger?.id ?? null)
    5. triggerId gets set to eventDetails.trigger?.id which is null (no trigger)
    6. Now triggerId=null, open=true but trigger was 'alert-trigger-2'

    So the demo has a logic issue where calling handleOpenChange resets triggerId. This is actually a workaround by the user, and is handled by my fix differently (because we capture originElement from the active element at mount time, regardless of the demo's reset).

    Let me run the comprehensive test once more:

  189. MiniMax Assistant

    All 6096 tests pass.

    Let me look at the final state of my changes:

  190. MiniMax Assistant

    All changes look good. Let me do a final sanity check by running everything:

  191. MiniMax Assistant

    No lint errors. Let me verify the comprehensive test once more:

  192. MiniMax Assistant

    All 710 tests pass for the components I touched.

    Now let me check the checklist:

    • If an error was reported in the issue description, I have successfully reproduced it. (Yes - my initial reproduce test failed before the fix)
    • If an error was reported in the issue description, I have confirmed that my fix resolves the error. (Yes - reproduce test now passes)
    • I have thought about edge cases and made sure my fix handles them as well. (Yes - I handle the case where the trigger is removed, where the originating element is the body, etc.)
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. (Yes - all 6096 tests pass)

    Let me also look at the changes one more time:

  193. MiniMax Assistant

    Wait, I need to consider one thing. The resolvedFinalFocus returns originElement only if originElement is connected. But for the controlled/programmatic case:

    1. User clicks "Open programmatically" → focus is on that button
    2. Dialog opens → originElement = "Open programmatically" button
    3. The button stays connected
    4. User closes dialog → originElement.isConnected = true → return it
    5. Focus returns to "Open programmatically" button ✓

    For the case where the user removes the "Open programmatically" button before closing:

    1. User clicks "Open programmatically" → focus is on that button
    2. Dialog opens → originElement = "Open programmatically" button
    3. User removes the button (somehow)
    4. User closes dialog → originElement.isConnected = false → return true
    5. FloatingFocusManager falls back to domReference or getPreviouslyFocusedElement

    This is the right behavior. The fallback ensures focus doesn't return to a non-existent element.

    For the case where the popup is opened by clicking a trigger (non-controlled):

    1. User clicks trigger-1 → focus is on trigger-1
    2. Dialog opens → originElement = trigger-1 element
    3. User closes dialog → originElement = trigger-1 element → return it
    4. Focus returns to trigger-1 ✓

    For the case where the user clicks "Open programmatically" then closes, then clicks trigger-1 then closes:

    1. Click "Open programmatically" → originElement = "Open programmatically" button
    2. Close dialog → focus returns to "Open programmatically" button
    3. Click trigger-1 → originElement = trigger-1 (because new open, hook re-runs)
    4. Close dialog → focus returns to trigger-1

    Wait, does my hook re-run when the dialog re-opens? Let me think. The hook is in the dialog root. The root is always mounted. The hook's effect depends on [open, mounted, store, popupElement]. When open transitions from false to true, the effect re-runs and captures the new originElement.

    But wait, my hook does store.set('originElement', element). It only sets the element if it's a meaningful one (not body/documentElement/popup). So if activeElement is a real button, it's set.

    Let me double-check that the effect re-runs correctly:

    The effect deps: [open, mounted, store, popupElement].

    • open: changes when dialog opens/closes
    • mounted: changes when dialog mounts/unmounts
    • store: never changes (stable reference)
    • popupElement: changes from null to element, stays as element

    When the dialog re-opens:

    • open: false → true (effect re-runs)
    • mounted: false → true (effect re-runs)
    • popupElement: element (same as before, but might be different element each time if the popup is unmounted)

    Wait, if the popup is unmounted (forceUnmount), is the popupElement reset?

  194. MiniMax Assistant

    forceUnmount doesn't reset popupElement. So popupElement stays the same after unmount.

    Hmm, that means the popupElement ref might be stale. But that's OK for my hook because:

    • The hook checks if popupElement is null. If null, skip.
    • If popupElement is the OLD popup element (not in DOM), contains(popupElement, element) would still work (it checks if element is contained within the OLD popup element).

    Actually wait, the contains function might fail if the popup element is no longer in the DOM. Let me check:

  195. MiniMax Assistant

    contains first checks parent.contains(child). If parent is no longer in DOM, this might still work (parent might still contain child if both are removed). Let me check:

    Actually, Element.contains works as long as the elements exist. If parent is not in DOM but child was inside it, parent.contains(child) would still return true.

    So my hook is safe even if the popup element is removed.

    Let me also test this scenario:

    Actually let me run one more time to make sure everything is working:

  196. MiniMax Assistant

    All 710 tests pass. The fix is complete and working.

    Let me summarize the changes:

    Summary

    The issue is that when a Dialog/Popover/AlertDialog/Drawer is opened in controlled mode using the triggerId prop (e.g., via an "Open programmatically" button), focus incorrectly returns to the trigger element associated with the triggerId instead of the originating control (the button that triggered the open).

    Changes Made

    1. packages/react/src/utils/popups/store.ts: Added a new originElement state field to PopupStoreState that captures the element focused when the popup was opened. Also added a corresponding selector.

    2. packages/react/src/utils/popups/popupStoreUtils.ts: Added a new useCapturedOriginElement hook that captures activeElement(doc) in a layout effect when the popup is open and mounted. It excludes document.body, document.documentElement, and elements contained within the popup from being captured.

    3. packages/react/src/dialog/root/useDialogRoot.ts: Added a call to useCapturedOriginElement in the dialog root.

    4. packages/react/src/popover/root/PopoverRoot.tsx: Added a call to useCapturedOriginElement in the popover root.

    5. packages/react/src/dialog/popup/DialogPopup.tsx: Added originElement state reading and a resolvedFinalFocus function that prefers the originElement for focus return (when connected), falling back to default behavior.

    6. packages/react/src/popover/popup/PopoverPopup.tsx: Same as DialogPopup - prefers originElement for focus return.

    7. packages/react/src/drawer/popup/DrawerPopup.tsx: Same as DialogPopup - prefers originElement for focus return.

    Why this fix works

    • When a popup is opened, the useCapturedOriginElement hook captures the focused element (the originating control) and stores it as originElement.
    • The popup's FloatingFocusManager is given a custom returnFocus function that returns the originElement (if connected) or true (default behavior) otherwise.
    • When the popup closes, focus is returned to the originElement (the originating control) rather than the trigger element associated with triggerIdProp.
    • If the originating control is no longer in the DOM, the fallback to default behavior ensures focus is returned to the domReference (the trigger element) or getPreviouslyFocusedElement (captured by FloatingFocusManager at open time).
  197. MiniMax Assistant

    Let me address the checklist one more time:

    Checklist:

    • ✅ If an error was reported in the issue description, I have successfully reproduced it.

      • I created a reproduction test in packages/react/src/dialog/root/reproduce.test.tsx (now removed) that verified the issue: focus moved to "Open 2" (trigger-2) instead of "Open programmatically" button.
    • ✅ If an error was reported in the issue description, I have confirmed that my fix resolves the error.

      • The same reproduction test now passes after my fix: focus returns to "Open programmatically" button as expected.
    • ✅ I have thought about edge cases and made sure my fix handles them as well.

      • Handles:
        • When originating control is removed from DOM (falls back to default behavior)
        • When active element is body/documentElement (doesn't capture)
        • When the trigger is removed before closing
        • Regular click on trigger still works
        • Multiple consecutive opens/closes
        • Works across Dialog, AlertDialog, Popover, and Drawer
    • ✅ I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.

      • All 6096 tests pass (with 873 skipped tests, which is normal).
      • I also verified linting passes for the changed files.

    Let me submit:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.