Skip to content

[popups] Fix detached trigger remounting - #3724

Merged
atomiks merged 4 commits into
mui:masterfrom
atomiks:fix/popover-anchor-remount
Jan 14, 2026
Merged

atomiks merged 4 commits into
mui:masterfrom
atomiks:fix/popover-anchor-remount

Conversation

@atomiks

@atomiks atomiks commented Jan 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3681

https://stackblitz.com/edit/tzqusig4-qsqweuem?file=src%2FApp.tsx

  1. Fixed detached trigger remount positioning by keeping FloatingRootStore.positionReference synced with the latest referenceElement (when it hasn't been overridden), so Floating UI doesn't remain anchored to a stale trigger
  2. Hardened trigger registration against keyed remount ordering (avoid unregistering a newer element under the same id) and refresh activeTriggerElement when the active trigger re-registers
  3. Fixed hot reloading and general behavior when the trigger gets reparented. Popover.createHandle() is recreated: previously useRefWithInit(() => externalStore ?? ...) would keep the old store forever, so the Root kept syncing listeners/floatingRootContext into the old store while the Trigger was using the new one. Additionally, the store needs to be reactive to the store handle itself, not just its values

Review: @greptileai

@atomiks atomiks added type: bug It doesn't behave as expected. component: popover Changes related to the popover component. labels Jan 12, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jan 12, 2026 •

Copy link
Copy Markdown
  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@3724
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@3724
    

commit: f285947

@mui-bot

mui-bot commented Jan 12, 2026 •

Copy link
Copy Markdown

Bundle size report

Bundle Parsed size Gzip size
@base-ui/react 🔺+314B(+0.08%) 🔺+110B(+0.08%)

Details of bundle changes


Check out the code infra dashboard for more information about this PR.

@netlify

netlify Bot commented Jan 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit f285947
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/69676daff5f0ec0008dee4a6
😎 Deploy Preview https://deploy-preview-3724--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@atomiks
atomiks marked this pull request as ready for review January 12, 2026 09:13
@greptile-apps

greptile-apps Bot commented Jan 12, 2026

Copy link
Copy Markdown
Contributor

Greptile Overview

Greptile Summary

Overview

This PR fixes a critical bug where detached popover triggers would lose correct positioning after remounting, particularly in scenarios involving React key-based remounts and conditional trigger rendering.

Root Cause

When triggers remount (especially with React key changes), the cleanup function from the old component instance could run after the new instance had already registered, causing the new element to be incorrectly removed from the trigger map. Additionally, stale element references weren't being updated in the floating root store.

Solution

The fix implements three coordinated changes:

1. Registration Race Condition Guard (popupStoreUtils.ts)

Added element identity checking before deletion to prevent newer elements from being unregistered by stale cleanup callbacks:

if (registeredElement && currentElement === registeredElement) {
  store.context.triggerElements.delete(registeredId);
}

2. Active Trigger Element Refresh (popupStoreUtils.ts)

When an active trigger re-registers (due to remounting), the activeTriggerElement is immediately refreshed to point to the new element:

if (activeTriggerId === triggerId) {
  store.update({ activeTriggerElement: element, ...stateUpdates });
  return;
}

3. Position Reference Synchronization (useSyncedFloatingRootContext.ts)

Keeps positionReference in sync with referenceElement when they're equal (i.e., when not overridden by custom positioning like virtual elements):

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

Test Coverage

Added a comprehensive test case that validates the fix by:

  • Using React key-based remounting to simulate the problematic scenario
  • Conditionally rendering triggers to test cleanup ordering
  • Verifying positioning accuracy before and after remount

Architecture Notes

The solution correctly handles edge cases:

  • Custom positionReference (e.g., virtual elements from useClientPoint) are not overridden
  • Closed popups that reopen after trigger remount
  • Multiple triggers with different mount/unmount timings
  • No memory leaks (old elements properly removed from the map)

Confidence Score: 5/5

  • This PR is safe to merge with high confidence - it fixes a specific bug with well-targeted changes and comprehensive test coverage
  • Score of 5 reflects: (1) thoroughly analyzed implementation that correctly addresses the root cause, (2) no logic errors, race conditions, or security issues found, (3) proper handling of all edge cases including custom position references and closed popups, (4) comprehensive test coverage that validates the fix, (5) no memory leaks or breaking changes, (6) clean code following repository patterns and conventions
  • No files require special attention - all changes are clean and well-implemented

Important Files Changed

File Analysis

Filename Score Overview
packages/react/src/floating-ui-react/hooks/useSyncedFloatingRootContext.ts 5/5 Added positionReference sync when it equals referenceElement, ensuring Floating UI stays anchored to current trigger during remounts
packages/react/src/utils/popups/popupStoreUtils.ts 5/5 Hardened trigger registration against race conditions during keyed remounts and added logic to refresh activeTriggerElement when active trigger re-registers
packages/react/src/popover/root/PopoverRoot.detached-triggers.test.tsx 5/5 Added comprehensive test case validating correct positioning when conditional triggers unmount and the tree remounts with a new key

Sequence Diagram

sequenceDiagram
    participant React
    participant TriggerOld as Trigger 0 (old)
    participant TriggerMap
    participant PopupStore
    participant FloatingStore
    participant TriggerNew as Trigger 0 (new)

    Note over React,FloatingStore: Initial state with old element

    React->>TriggerNew: Mount new element with same ID
    TriggerNew->>TriggerMap: register(newElement)
    TriggerMap->>TriggerMap: add id, newElement
    Note over TriggerNew,PopupStore: Fix 2: Refresh active element
    TriggerNew->>PopupStore: update activeTriggerElement
    Note over PopupStore,FloatingStore: Fix 3: Sync position reference
    PopupStore->>FloatingStore: sync referenceElement
    PopupStore->>FloatingStore: sync positionReference

    React->>TriggerOld: Cleanup old element
    Note over TriggerOld,TriggerMap: Fix 1: Guard deletion
    TriggerOld->>TriggerMap: check if currentElement == oldElement
    TriggerMap-->>TriggerOld: No match, skip deletion

    Note over FloatingStore: Positioning stays correct
Loading

@atomiks atomiks mentioned this pull request Jan 13, 2026
1 task done

@michaldudak michaldudak left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: popover Changes related to the popover component. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[popover] Incorrect positioning with multiple detached triggers

3 participants