Skip to content

[popover][menu] Fix hover-out animations when switching between detached triggers - #4261

Merged
michaldudak merged 9 commits into
mui:masterfrom
michaldudak:instant-hoverout
Oct 2, 2026
Merged

michaldudak merged 9 commits into
mui:masterfrom
michaldudak:instant-hoverout

Conversation

@michaldudak

@michaldudak michaldudak commented Mar 4, 2026 •

Copy link
Copy Markdown
Member

When openOnHover is enabled, moving between detached triggers clears instantType so the positioner can animate to the new trigger, then sets it to trigger-change once that move finishes. That value could outlive the open cycle that set it. When it leaked into a close, the popup rendered data-instant and skipped its exit transition, so it disappeared instead of fading out. When it leaked into a later open, the entrance transition was skipped instead.

Root cause

Nothing tied trigger-change to the open cycle that set it, and several paths let it reach a render it didn't belong to:

  1. The first closing frame. PopoverStore.setOpen flushSynces a hover close before it resets instantType, so the closing render inherited trigger-change. Menu doesn't flushSync here, so its state update and reset batch into a single render.
  2. A late restoration. The runOnceAnimationsFinish callback that restores trigger-change could fire after a close had already started.
  3. Closes that skip setOpen. A controlled consumer committing open={false}, whether directly or after deferring a hover close, goes straight through the prop, so nothing reset the value.
  4. Reopening. A popup that closed and reopened on the same trigger mid-exit kept its positioner mounted and its trigger unchanged, so nothing cancelled the pending restoration. A controlled reopen changes only openProp, so a value stored during the previous cycle came back.

Fix

Instead of guarding each path separately, the fix enforces three invariants:

  • The instantType selector hides trigger-change while the popup is closed (PopoverStore and MenuStore). It is derived at render time, so no closing render can show it, whichever path closed the popup.
  • Closing cancels any pending restoration and clears the stored value, so the next open cycle starts clean.
  • A trigger switch is only scheduled while the popup is open.

The trigger-switch effect was copy-pasted between PopoverPositioner and MenuPositioner. Both now use a shared useTriggerSwitchTransition hook.

There is no API change. Bundle size: +239B parsed, +38B gzip.

Tests

The regression tests record instant on every closing render rather than asserting on the DOM, because a later render clears the stale value before waitFor can observe it. They run in Chromium only, since they need real CSS transitions.

Component Test Fails on master
Popover does not apply the trigger-change instant to a hover close after switching triggers Yes
Popover does not apply the trigger-change instant to a non-hover close after switching triggers No (regression guard: a non-hover close isn't flushed, so the reset lands in the same render)
Popover does not apply the trigger-change instant after switching back to the original trigger Yes
Popover does not restore the trigger-change instant after a reopen on the same trigger Yes
Popover does not apply the trigger-change instant to a prop-driven close after a switch Yes
Popover does not restore the trigger-change instant when a controlled close commits late Yes
Popover does not restore the trigger-change instant after a hover close has started Yes
Menu does not apply the trigger-change instant to a hover close after switching triggers No (regression guard: Menu doesn't flushSync the close)
Menu does not restore the trigger-change instant when a controlled close commits late Yes
Menu does not restore the trigger-change instant after a hover close has started Yes

Removing the stored-value clear on its own makes the prop-driven test fail on its reopen assertion.

The two "controlled close commits late" tests also assert that trigger 2 took over the popup and that trigger-change was restored before the late open={false} landed, so they can't pass without exercising the race.

Two guards have no test:

  • Scheduling a switch only while open. It covers a trigger element being replaced mid-exit while a position animation is still running, and I couldn't drive that sequence reliably. It is kept because there is no move to animate while the popup is closed.
  • The open check inside the restoration callback. Removing it leaves every test passing. A committed close normally aborts the callback first, but under a React 18 legacy root, flushSync can flush pending passive effects before running the callback. A controlled close committed there would let the restoration write trigger-change after the close had cleared it. That ordering is inferred from React's source and hasn't been reproduced, so the check is kept as a cheap safeguard.

Scope

Earlier revisions of this PR also carried a hover-close grace window that let a popup reopen without waiting for delay right after a hover close. It has been split out: it's a separate behavior change with its own bundle cost and open design questions, and this fix doesn't need it. As a result, the handoff issue it targeted (moving from the popup to a different trigger sometimes doesn't open it) is not fixed here.

Reproduction

  1. Check "Open on hover".
  2. Hover a trigger in the detached/multiple examples so a popover appears.
  3. Hover an adjacent trigger. The popover repositions.
  4. Hover out. The popover should fade out instead of disappearing instantly.

Originally reported on Edge on Mac, but it reproduces in Chromium as well.

@pkg-pr-new

pkg-pr-new Bot commented Mar 4, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

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

commit: 8a9ba2d

@michaldudak michaldudak added type: bug It doesn't behave as expected. component: popover Changes related to the popover component. labels Mar 4, 2026
@netlify

netlify Bot commented Mar 4, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 8a9ba2d
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6abf55e263ccee0007934ccd
😎 Deploy Preview https://deploy-preview-4261--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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

@michaldudak

michaldudak commented Mar 4, 2026 •

Copy link
Copy Markdown
Member Author

Codex Review

Overview

This branch fixes the detached-trigger hover animation races and adds a Popover-only hover handoff grace window so quick re-entry or trigger-to-trigger moves can reopen without waiting through the full hover delay. The latest changes also scope that grace behavior away from Tooltip and add regression coverage for controlled, canceled, and delayed-close paths.

Findings (None)

No blocking issues found in this patch.

Confidence: 4/5

High confidence based on a full pass over the master...head diff, targeted JSDOM/Chromium verification of the changed hover paths, and a focused micro-check of the new delay-bypass guard. Residual risk is limited to browser-specific pointer timing variants outside the detached-trigger scenarios covered here.

Notes

  • The previous shared-hook concern looks addressed: hoverCloseGracePeriod is now only wired through Popover, while TooltipRoot.test.tsx adds coverage that Tooltip.Provider timeout still governs Tooltip reopen timing after the provider window expires.
  • Verified with pnpm test:jsdom useHoverReferenceInteraction --no-watch, pnpm test:jsdom PopoverRoot --no-watch, pnpm test:jsdom TooltipRoot --no-watch, and pnpm test:chromium PopoverRoot.detached-triggers --no-watch; all passed.
  • Focused micro-check for the added hover-delay-bypass branch (10 samples, 5,000,000 iterations per sample):
Ref Mean (ms) p50 (ms) p95 (ms) Sample size
upstream/master baseline 2.09 1.72 3.18 10
PR head 101.10 100.80 104.27 10

The absolute delta is roughly 0.02µs per call in a tight loop, which does not look material for the user-facing hover path.

@atomiks

atomiks commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

In some cases, traversing from the popup to a different trigger fails to open it. Similar issue when there are gaps between. Tooltip handles this but it uses the delay provider logic iirc.

Screen.Recording.2026-03-05.at.7.46.16.pm.mov

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Mar 5, 2026
@michaldudak

Copy link
Copy Markdown
Member Author

I added a period (400ms, matching TooltipProvider) during which delay is ignored when one popup is closed, and another is open.
I also set the default closeDelay to 100ms to avoid popups trying to close immediately when the user might hover over another trigger. An alternative would be to apply safe polygon logic for all inactive triggers, but it would be too expensive computationally.

@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Mar 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c00eb9198b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 03b32a4f4d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@atomiks

atomiks commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

After hovering and switching to a new trigger, the exit animation is incorrectly instant

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 92d5ef810f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions github-actions Bot added PR: out-of-date The pull request has merge conflicts and can't be merged. and removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Mar 9, 2026
@atomiks

atomiks commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review

Overview

This branch fixes the detached-trigger exit-animation race and adds a short hover handoff window so Popover and Menu can reopen immediately after a recent hover close. The later revisions also narrowed that behavior away from Tooltip and cleaned up the shared hover helpers, but there is still one controlled-mode gap in the new committed-close bookkeeping.

Findings

1. 🔴 [Blocking] Controlled no-op closes are still counted as committed closes

Impact: In controlled Popover/Menu/NavigationMenu usage, a consumer can keep the popup open by leaving the controlled open prop unchanged. In that case this patch still records a recent hover close and emits floating.closed even though the popup never actually closed, which can incorrectly bypass the next hover delay and can advance tree-based parent-close coordination while the child popup is still visible.

Evidence: closeHoverPopup() now treats every non-canceled setOpen(false, ...) as a committed close and returns { closed: true } without checking whether the popup actually ended up closed (packages/react/src/floating-ui-react/hooks/useHoverInteractionSharedState.ts:139). Popup stores read open from openProp ?? state.open, so controlled components can remain open even after an internal close request (packages/react/src/utils/popups/store.ts:123). Both hover hooks immediately translate that closed flag into a floating.closed tree event (packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:102, packages/react/src/floating-ui-react/hooks/useHoverFloatingInteraction.ts:72). The new regression coverage exercises canceled closes and controlled programmatic open/close cycles, but not the controlled “ignore the close request without calling cancel() path (packages/react/src/popover/root/PopoverRoot.test.tsx:383, packages/react/src/popover/root/PopoverRoot.test.tsx:428`).

Recommendation: After setOpen(false, ...), re-read the effective controlled selector (or otherwise confirm that the popup actually became closed) before recording lastHoverCloseTime or emitting floating.closed. I would also add a regression where onOpenChange ignores a hover-close request without calling cancel() and assert that no grace window or tree-close signal is produced.

2. 🟡 [Non-blocking] Committed-close signaling is still duplicated in both hover hooks

Impact: The reference and floating hover hooks still each wrap closeHoverPopupShared() with the same “if it closed, emit floating.closed” logic. That duplication makes future fixes to committed-close semantics easy to land in one place and miss in the other.

Evidence: packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:102 and packages/react/src/floating-ui-react/hooks/useHoverFloatingInteraction.ts:72 both recreate the same wrapper around the shared helper, differing only by the surrounding hook context.

Recommendation: Once the controlled-close bug is fixed, consider pulling the close-and-emit behavior behind one shared helper so the tree signal and committed-close criteria live in a single place.

3. ℹ️ [Informational] The added delay-bypass branch looks cheap in isolation

Impact: I did not see evidence that the new wasHoverClosedRecently() check is large enough on its own to make hover movement measurably slower.

Evidence: Focused micro-check of the new delay-bypass branch versus master (10 samples, 5,000,000 iterations per sample):

Ref Mean (ms) p50 (ms) p95 (ms) Sample size
master baseline 2.57 2.12 4.38 10
PR head branch 19.25 18.76 21.24 10

That synthetic delta is roughly 3.3ns per call, so the extra branch itself does not look user-visible.

Recommendation: No perf change needed from this measurement alone; I would just keep the benchmark in mind if more logic gets added to the hover-move path.

Confidence: 3/5

Moderate confidence based on a full master...head pass, a second sweep over rendering/accessibility/API/maintainability/perf concerns, and a focused micro-check of the new hot-path branch. The blocking issue above is inferred directly from the controlled selector and shared close bookkeeping rather than from a dedicated regression repro.

Notes

  • Since the previous review, the branch improved Tooltip scoping, reduced stable-callback churn, and added Menu coverage. I did not find a new a11y or API-surface blocker beyond the controlled committed-close accounting above.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Mar 11, 2026
@michaldudak

Copy link
Copy Markdown
Member Author

[Blocking] closeDelay now changes Popover's published default behavior

This was done intentionally to improve UX by reducing flickering. The default delay is short enough so it's not obvious and still enough to prevent the tooltip from closing when moving the mouse from one trigger to another.

[Blocking] The new fixed 400ms handoff window overrides Tooltip's existing timeout contract

Fixed by explicitly enabling this feature on the Popover only.

@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Mar 11, 2026
@michaldudak michaldudak added the component: menu Changes related to the menu component. label Mar 12, 2026
@michaldudak michaldudak changed the title [popover] Fix hover-out animations when switching between detached triggers [popover][menu] Fix hover-out animations when switching between detached triggers Mar 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 167a5173ec

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions github-actions Bot added PR: out-of-date The pull request has merge conflicts and can't be merged. and removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Mar 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cec53f14a3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@michaldudak

Copy link
Copy Markdown
Member Author

Codex Review

Overview

This branch hardens the shared hover-close bookkeeping used by floating interactions and wires the grace-period behavior into popover and menu handoffs, including detached-trigger animation cleanup. It also changes the popover hover close default to 100ms and adds targeted coverage for controlled and detached-trigger cases.

Findings (None)

No blocking issues found in this patch.

Confidence: 4/5

High confidence based on a full-branch pass over the touched hover/popover/menu code paths plus targeted validation of the updated JSDOM and Chromium suites covering PopoverRoot, PopoverRoot.detached-triggers, MenuRoot, MenuRoot.detached-triggers, TooltipRoot, and useHoverReferenceInteraction. Residual risk is low and mainly limited to broader interaction patterns not exercised by those suites.

@atomiks

atomiks commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Codex Review

Overview

This branch fixes the detached-trigger exit-animation race and adds a hover-close grace window so popovers and menus can reopen immediately during quick handoffs. It also moves the shared hover-close bookkeeping into the reference and popup hooks and adds targeted regression coverage around those paths.

Findings

1. 🔴 [Blocking] External controlled closes can still finalize a stale hover close

Impact: In controlled Popover/Menu usage, a parent that ignores a hover-close request and later flips open to false directly will still inherit the hover grace window and floating.closed tree signal from that earlier rejected close. The next hover can therefore reopen immediately even though the committed close did not come from hover, and tree-based coordination can advance as if a hover close really happened.

Evidence: closeHoverPopup() now stores pendingHoverClose before the effective controlled state is known (packages/react/src/floating-ui-react/hooks/useHoverInteractionSharedState.ts:208-255). That pending close is later finalized whenever open becomes false in the reference/floating effects (packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:141-153, packages/react/src/floating-ui-react/hooks/useHoverFloatingInteraction.ts:108-121). Direct openProp changes are only synced into the floating store via store.update(...) and do not emit a non-hover openchange cleanup (packages/react/src/floating-ui-react/hooks/useSyncedFloatingRootContext.ts:58-75, packages/react/src/utils/popups/store.ts:123-125). I reproduced this with a focused JSDOM repro: hover-open, ignore the hover close without calling cancel(), then flip open to false directly; the next hover opens immediately instead of waiting through delay.

Recommendation: Only keep pendingHoverClose alive while the close can still be attributed to that hover request. For direct controlled openProp transitions, clear the pending hover close before emitCommittedHoverClose() runs, or tag pending closes with the originating request and ignore them when open changes for unrelated reasons.

2. 🟡 [Non-blocking] The grace window now overrides delay even for same-trigger re-entry

Impact: delay is no longer authoritative for Popover/Menu after any recent hover close. Briefly leaving and re-entering the same trigger within 400ms now reopens immediately, even when consumers configured delay specifically to prevent accidental reopen.

Evidence: shouldIgnoreOpenDelayAfterHoverClose() only checks !isOpen plus wasHoverClosedRecently(...); it does not require a different trigger or popup-to-trigger transfer (packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:229-248, packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:366-445). Popover and Menu both hard-wire this grace window on both the trigger and popup sides (packages/react/src/popover/trigger/PopoverTrigger.tsx:92-106, packages/react/src/popover/popup/PopoverPopup.tsx:73-77, packages/react/src/menu/trigger/MenuTrigger.tsx:182-196, packages/react/src/menu/popup/MenuPopup.tsx:88-92), and the new regression explicitly locks in same-trigger re-entry bypassing delay (packages/react/src/popover/root/PopoverRoot.test.tsx:296-317).

Recommendation: If the goal is only handoff UX, scope the grace window to real handoffs (different trigger or popup-to-trigger transfer). Otherwise document that delay is intentionally bypassed during this window so consumers do not treat it as a strict reopen delay.

3. 🟡 [Non-blocking] Menu coverage does not exercise the new popup/cross-trigger handoff paths

Impact: The Menu part of the patch now relies on both the trigger hook and the floating hook, but the added regression only covers the simplest “leave trigger, re-enter same trigger” case. A bug in popup-to-trigger handoff or detached trigger switching can therefore slip through even though those are the more complex paths this change is enabling.

Evidence: Menu now opts into the grace window in both MenuTrigger and MenuPopup (packages/react/src/menu/trigger/MenuTrigger.tsx:182-196, packages/react/src/menu/popup/MenuPopup.tsx:88-92), and the close/finalize path runs through useHoverFloatingInteraction (packages/react/src/floating-ui-react/hooks/useHoverFloatingInteraction.ts:73-121). The only new Menu regression is packages/react/src/menu/root/MenuRoot.test.tsx:1382-1409, which never leaves the popup, never switches triggers, and never exercises the newly hardened floating-hook path.

Recommendation: Add at least one Menu regression that mirrors the Popover detached-trigger coverage: trigger A -> popup or trigger B handoff, plus a popup mouseleave case that proves the useHoverFloatingInteraction path really preserves the intended no-delay reopen behavior.

4. ℹ️ [Informational] The delayed-close commit logic is still duplicated across the two hover hooks

Impact: closeHoverPopup() centralizes the commit semantics, but each hook still wraps it with nearly identical handleHoverClose / closeWithDelay glue. That duplication leaves future fixes to timeout gating, tree signaling, or commit criteria with multiple places to keep in sync.

Evidence: Compare packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:103-129 with packages/react/src/floating-ui-react/hooks/useHoverFloatingInteraction.ts:68-102. The same pattern also exists for the shared grace-period default being repeated in packages/react/src/popover/utils/constants.ts:1-3 and packages/react/src/menu/utils/constants.ts:1-3.

Recommendation: Consider one shared “close with optional delay” helper and one shared default grace-period constant so the individual hooks/components only provide wiring, not parallel control flow.

Confidence: 2/5

Low-to-moderate confidence. I covered the full upstream/master...HEAD diff, ran targeted JSDOM/Chromium suites for the touched hover paths, and reproduced the controlled stale-close bug with a focused one-off test, but I did not do a full browser matrix or add permanent regression coverage myself.

Notes

  • Verified passing: pnpm test:jsdom useHoverReferenceInteraction --no-watch, pnpm test:jsdom PopoverRoot --no-watch, pnpm test:jsdom MenuRoot --no-watch, pnpm test:jsdom TooltipRoot --no-watch, pnpm test:chromium PopoverRoot.detached-triggers --no-watch, pnpm test:chromium MenuRoot.detached-triggers --no-watch.
  • Focused synthetic micro-check of the added grace-window guard (10 samples, 5,000,000 iterations per sample):
Ref Mean (ms) p50 (ms) p95 (ms) Sample size
upstream/master equivalent (no guard) 2.13 1.98 3.52 10
PR head equivalent guard 20.39 20.11 22.87 10

The absolute delta is roughly 3.7ns per call in a tight loop, so the added guard itself does not look materially expensive in isolation.

@michaldudak
michaldudak marked this pull request as ready for review May 12, 2026 09:36

@flaviendelangle flaviendelangle 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.

PR #4261 Review Summary

[popover][menu] Fix hover-out animations when switching between detached triggers — 24 files, +1531/-97

Critical Issues (0)

None found.

Important Issues (5)

  1. Stale trigger-change clear ordering is untested — PopoverStore.ts:170-174. Tests only observe DOM after flushSync; a regression that moves the clear after flushSync would still pass. Add an ordering-sensitive assertion (e.g. captured store state) or a unit test exercising the synchronous order. (pr-test-analyzer)

  2. Verify Menu has the symmetric store-layer fix — MenuPositioner.tsx gets the positioner guard but I see no equivalent of PopoverStore.setOpen's instantType pre-clear in the Menu store. The Menu regression tests may currently pass by timing luck. Confirm/add the symmetric clear. (pr-test-analyzer)

  3. Consumer-cancel path silently kills hover handoff — useHoverInteractionSharedState.ts:206-211. When onOpenChange calls preventDefault(), the function returns with no pendingHoverClose, no grace, no event, no log. Add a logForDebugging so a developer canceling close in dev can see why the handoff was suppressed. (silent-failure-hunter)

  4. pendingHoverClose cleared before the open check — useHoverInteractionSharedState.ts:200-204. A reentrant call while open === false silently discards a still-pending close, so emitCommittedHoverClose no-ops and floating.closed is never emitted. Either clear after confirming open, or call emitCommittedHoverClose first. (silent-failure-hunter)

  5. New useHoverInteractionSharedState.test.ts lacks describe.skipIf(!isJSDOM) — useHoverInteractionSharedState.test.ts:5. Every other unit test in floating-ui-react/hooks/ (e.g. useHoverReferenceInteraction.test.tsx:11) wraps with this guard. (code-reviewer)

Suggestions

Code / silent failures

  • Add logForDebugging when the three-part positioner guard rejects in PopoverPositioner.tsx:120-131 / MenuPositioner.tsx:250-258 — especially the domReferenceElement !== triggerOnSwitch branch.
  • The queueMicrotask deferred-drop fallback at useHoverInteractionSharedState.ts:229-236 drops pendingHoverClose invisibly when consumers defer via startTransition. Consider routing through emitCommittedHoverClose or surfacing a debug log; also clear pendingHoverCloseGrace for robustness.
  • Wrap the instance.handler(event) call in useHoverFloatingInteraction.ts:241 in try/catch + finally { clearPointerEvents() } so a thrown safePolygon handler doesn't leave pointer-events: none stuck.
  • Use realm-safe ownerWindow(node).queueMicrotask rather than the global, matching CheckboxRoot.tsx:364.
  • Unify the deferred-commit fallback in useHoverReferenceInteraction.ts:196 on useIsoLayoutEffect instead of React.useEffect so reference/floating sides emit floating.closed in the same phase. (Per AGENTS.md: prefer useIsoLayoutEffect.)
  • Redundant && shouldOpen guard at useHoverReferenceInteraction.ts:313 — obscures intent; either drop it or move outside the merged branch.

Tests

  • Rewrite the flaky Menu "bypasses open delay" test at MenuRoot.detached-triggers.test.tsx:750-801 using clock.withFakeTimers() like its Popover analogue.
  • Replace hand-rolled createMockStore in useHoverInteractionSharedState.test.ts:91-137 with a real FloatingRootContext (or throw on unhandled select keys) so future additions don't silently bypass coverage.
  • Remove the .catch(() => undefined) on animation.finished in waitForAnimationsFinished — it swallows signal.
  • Add coverage for: controlled open={false} flip after a trigger switch (clean isolation of fix #2), and Portal keepMounted so data-instant doesn't stick across cycles.
  • Mirror regression tests for Tooltip/PreviewCard, which share the same trigger-change pattern.

Comments

  • // Layout phase so pointer-event mutations are cleaned up before paint. in useHoverFloatingInteraction.ts is now stale — the effect also calls emitCommittedHoverClose. Rewrite to cover both behaviors.
  • // Popover's internal 'flushSync' may have already synced… couples the generic hook to a specific consumer — generalize the wording.
  • // Keep positioner transition behavior aligned with Popover… in MenuPositioner.tsx will rot if Popover diverges; replace with the actual WHY (stale callback / wrong cycle).
  • Tighten // When the current trigger element changes, enable transitions on the positioner temporarily in PopoverPositioner.tsx — the effect now also gates instantType restoration.
  • All other added comments (closeHoverPopup, emitCommittedHoverClose, the performance.now realm choice, HOVER_CLOSE_GRACE_PERIOD, constants.ts close-delay rationale) are good and should stay.

Strengths

  • Clean decomposition into shared helpers (closeHoverPopup, emitCommittedHoverClose, clearRecentHoverClose, closeWithOptionalDelay) — matches AGENTS.md "avoid duplicating logic."
  • openCycleRef + domReferenceElement triple-guard in both positioners is the right shape and applied consistently across components.
  • Strongest test: PopoverRoot.detached-triggers.test.tsx:844 directly exercises race #2 by capturing animations before unhover.
  • Uses useStableCallback correctly for handlers, describe.skipIf(isJSDOM) is well-targeted (not overused), no flushMicrotasks after await render(...).
  • Comment hygiene overall is strong — non-obvious invariants (controlled-consumer race, realm-agnostic clock, flushSync vs startTransition tradeoff) are well documented.
  • Sync'd docs + JSDoc updates for the new delay-bypass behavior.
  • isHoverOpenEvent correctness tightening to === true.

Recommended Action

  1. Address importants #1–#5 (mostly small additions: ordering test, Menu store parity check, two logForDebugging calls, one describe.skipIf).
  2. Apply the comment tightening list — small text-only changes.
  3. Consider the test additions for keepMounted / controlled-flip / Tooltip-PreviewCard mirror as follow-up.
  4. Re-run pnpm test:chromium PopoverRoot --no-watch and pnpm test:chromium MenuRoot --no-watch after edits.

@atomiks

atomiks commented May 13, 2026

Copy link
Copy Markdown
Contributor

Code Review (GPT-5.5)

Request changes 🔴, because the +548B gzip increase appears to come from the new hover-close grace-window feature rather than the actual detached-trigger animation fix.

1. Bugs / Issues

1. 🔴 Drop the grace-window machinery from this bug fix (blocking)

The PR’s core bug is stale instantType="trigger-change" leaking into close renders. The low-size fix is the existing targeted work: clear instantType before close/hover updates, and guard the delayed trigger-switch restoration by open cycle + same trigger. The added hoverCloseGracePeriod path is a separate behavior change and brings most of the production code growth.

packages/react/src/floating-ui-react/hooks/useHoverInteractionSharedState.ts:

import * as ReactDOM from 'react-dom';

export const HOVER_CLOSE_GRACE_PERIOD = 400;

lastHoverCloseTime: number;
pendingHoverClose: MouseEvent | null;
pendingHoverCloseGrace: boolean;

export function closeHoverPopup(...) {
  ...
  ReactDOM.flushSync(() => {});
  ...
  queueMicrotask(() => {
    ...
  });
}

packages/react/src/floating-ui-react/hooks/useHoverReferenceInteraction.ts:

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

React.useEffect(() => {
  if (!hoverCloseGracePeriod || !open) {
    return;
  }

  clearRecentHoverClose(instance);
}, [hoverCloseGracePeriod, instance, open]);

function shouldIgnoreOpenDelayAfterHoverClose(...) {
  return (
    !isOpen &&
    (hoverCloseGracePeriod ?? 0) > 0 &&
    instance.lastHoverCloseTime !== 0 &&
    performance.now() - instance.lastHoverCloseTime <= hoverCloseGracePeriod!
  );
}

This adds shared state fields, flushSync, queueMicrotask, extra effects, an open subscription in the reference hook, duplicated trigger/popup wiring, and tests for a new “reopen instantly after close” behavior. It also changes the meaning of configured hover delay for quick same-trigger re-entry.

Fix: remove hoverCloseGracePeriod, HOVER_CLOSE_GRACE_PERIOD, lastHoverCloseTime, pendingHoverClose*, closeHoverPopup, emitCommittedHoverClose, clearRecentHoverClose, and shouldIgnoreOpenDelayAfterHoverClose from this PR. Keep only the instantType clearing plus the guarded positioner restoration. If the instant reopen behavior is wanted, ship it as a separate feature PR with its own bundle-size budget.

2. Bundle Assessment

CI reports @base-ui/react at +1.47KB parsed / +548B gzip. Based on the diff, the biggest recoverable chunk is not in the animation-race fix itself; it is the generalized committed-hover-close bookkeeping added to the shared hover hooks.

Expected small-shape patch:

  • PopoverStore.ts: keep clearing stale instantType before close/hover renders.
  • PopoverPositioner.tsx and MenuPositioner.tsx: keep the open-cycle / same-trigger guard before restoring trigger-change.
  • useHoverReferenceInteraction.ts and useHoverFloatingInteraction.ts: restore the previous lightweight close paths that call store.setOpen(false, ...) and emit floating.closed directly.
  • Remove the new grace-window tests, or move them to a follow-up PR that intentionally pays for that feature.

3. Test Coverage Assessment

The detached-trigger animation regressions are the right tests to keep. The delay-bypass/grace-window tests are evidence of a new behavior, not necessary coverage for the reported animation race, so removing that behavior should also remove the need for those tests.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 18, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 13, 2026
@michaldudak

Copy link
Copy Markdown
Member Author

I've force-pushed this down to just the animation fix, rebased on current master. Previous head was 043ffda if anyone needs it.

Why

@atomiks was right that the hover-close grace window is a separate behavior change riding along with a bug fix. It's now out of this PR. What's left is ~40 lines of production code with no API change, no new public behavior, and no meaningful bundle cost.

What's left

Two races that let instantType="trigger-change" leak into a close render and suppress the exit animation:

  1. PopoverStore.setOpen flushSynces the close render before it resets instantType, so that render inherits trigger-change. Cleared before the flush now.
  2. The positioner restores trigger-change from a runOnceAnimationsFinish callback that can fire after a close has started, or after the popup reopened on a different trigger. Now guarded on the open cycle, the open state, and the trigger still owning the popup.

Still reproducible on master, and not only in Edge — it reproduces in Chromium too.

On the review feedback

@flaviendelangle's point about the ordering being untested was correct, and worse than stated: the old test for the store fix passed on unfixed master. It asserted on the DOM through waitFor, by which time the follow-up render had already cleared the stale value. The new tests capture instant on every closing render instead. Each one is verified to fail without its corresponding fix:

Test Fails without
hover close after switching triggers store fix
after switching back to the original trigger store fix
does not restore after a hover close has started positioner guard
Menu: does not restore after a hover close has started positioner guard

On the question of Menu store parity: Menu only needs the positioner guard. MenuRoot.setOpen doesn't flushSync, so its state update and instantType reset batch into a single render and race 1 can't occur. The Menu render-capture test passes against an unguarded MenuPositioner, which is the evidence for that.

The grace window

Parked on a local branch rather than dropped. It'll come back as its own PR once these are settled:

  • The 400ms window is a hard-wired constant that overrides the documented delay prop, including for same-trigger re-entry, with no opt-out. Tooltip solves the equivalent problem through an explicit Tooltip.Provider, and a non-zero closeDelay covers much of the same UX with no new machinery.
  • Detecting whether a controlled consumer actually honored a close relies on an empty flushSync plus a queueMicrotask fallback, and still can't observe consumers that defer via startTransition. Every review round found a new hole in that bookkeeping, which suggests the approach rather than the details is the problem.
  • useHoverReferenceInteraction ends up subscribing to open unconditionally, so every trigger of all six consumers re-renders on every open/close.

Also worth re-checking whether the original handoff gap still reproduces on today's master before rebuilding it — a fair amount of hover-handoff work has landed since March (#4446, #4990, #5159).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c12eb8e531

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

michaldudak added a commit to michaldudak/base-ui that referenced this pull request Aug 13, 2026
A controlled consumer can accept a hover close but commit `open={false}`
later, for example from a transition or an async confirmation. Until it does,
the effective `open` selector (`openProp ?? open`) still reads `true`, so a
trigger-switch animation finishing inside that window restored
`trigger-change`. The eventual commit arrives through the prop rather than
`setOpen`, so nothing cleared it again and the whole exit transition was
skipped.

The store already distinguishes the requested open state (`state.open`, set
when the close is requested) from the effective one, so the restoration now
requires the requested state to be unchanged since the switch was scheduled.
This also leaves programmatically-opened controlled popups alone, where
`state.open` is `false` for the entire open cycle.

Reported by Codex on mui#4261. The race predates this branch — verified failing
on master — and is the same class as the two already fixed here.

Co-Authored-By: Claude Opus 5 <[email protected]>
@michaldudak

Copy link
Copy Markdown
Member Author

Confirmed and fixed in d709f72.

I reproduced it: controlled open, hover trigger 1 → hover trigger 2 → unhover while the switch is still animating, with the parent committing open={false} on a timer. Every closing render carried trigger-change, so the exit transition was collapsed entirely:

ENDING RENDERS: ["trigger-change", "trigger-change"]   // before
ENDING RENDERS: [null, null]                            // after

One correction to the report: this isn't caused by the new guard, and it isn't new. The same repro fails identically on master, so it's a third pre-existing race in the same family rather than something this branch introduced. The guard not covering it is fair — that part is accurate.

The fix

The store already distinguishes the two open states: state.open is the requested one, set as soon as the close is accepted, while the open selector returns openProp ?? state.open and stays true until the consumer commits. The restoration now requires the requested state to be unchanged since the switch was scheduled:

const requestedOpenOnSwitch = store.state.open;

runOnceAnimationsFinish(() => {
  if (
    store.select('open') &&
    store.state.open === requestedOpenOnSwitch &&
    floatingRootContext.select('domReferenceElement') === triggerOnSwitch
  ) {
    store.set('instantType', 'trigger-change');
  }
}, abortController.signal);

Comparing against the value captured at schedule time rather than testing state.open outright matters for programmatically-opened controlled popups, where state.open is false for the whole open cycle and an outright test would suppress the restoration permanently.

Regression tests added for both Popover and Menu, each verified to fail without the guard.

On openCycleRef

It's gone as of 1bad9e6, which predates this comment. I instrumented the callback and it never once fired with a mismatched cycle while open was true — a close either re-runs the effect and aborts the callback, or the callback fires when open is already false and the existing check discards it. It was a ref plus a layout effect running on every open change, in two components, guarding a state that can't occur.

Worth noting that the counter idea was directionally right but keyed on the wrong signal: committed open can't see a pending controlled close, which is exactly the gap this report identifies. The fix above is that same idea keyed on the requested state instead.

Every guard now has a test that fails without it:

Guard Covered by
PopoverStore pre-clear 2 Popover tests
store.select('open') 1 Popover + 1 Menu test
state.open === requestedOpenOnSwitch 1 Popover + 1 Menu test
same-trigger check none — kept as a cheap precondition, happy to drop it

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d709f72dab

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 323c1af14a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

michaldudak and others added 4 commits August 13, 2026 15:13
When `openOnHover` is enabled, moving between detached triggers sets
`instantType="trigger-change"` so the popup repositions without animating a
full close/open cycle. Two races let that state leak into the following
close, suppressing the exit animation.

1. `PopoverStore.setOpen` `flushSync`es the close render *before* it resets
   `instantType`, so the first closing frame inherits `trigger-change` and
   renders with `data-instant`. Clear it before the flush instead.

2. The positioner restores `trigger-change` from a `runOnceAnimationsFinish`
   callback that can fire after a close has already started, or after the
   popup reopened on a different trigger. Guard the restoration on the open
   cycle, the open state, and the trigger still owning the popup.

Menu shares race 2 and gets the same positioner guard. It does not share
race 1 because `MenuRoot.setOpen` does not `flushSync`, so its state update
and `instantType` reset batch into one render.

Regression tests capture `instant` on every closing render, since a later
render clears the stale value before the DOM can be asserted on.

Co-Authored-By: Claude Opus 5 <[email protected]>
Popover and Menu had the same trigger-switch effect copy-pasted, kept in
sync only by a "keep aligned with Popover" comment. They now share
`useTriggerSwitchTransition`.

Also drops the open-cycle counter the guard originally carried. It was meant
to catch a stale callback surviving into a later open, but instrumenting the
callback showed that never happens: a close either re-runs the effect and
aborts the callback, or the callback fires while `open` is already false and
the existing check discards it. Verified that every remaining guard has a
test that fails without it, and adds the close-and-reopen-on-the-same-trigger
case the counter was meant to cover.

Co-Authored-By: Claude Opus 5 <[email protected]>
A controlled consumer can accept a hover close but commit `open={false}`
later, for example from a transition or an async confirmation. Until it does,
the effective `open` selector (`openProp ?? open`) still reads `true`, so a
trigger-switch animation finishing inside that window restored
`trigger-change`. The eventual commit arrives through the prop rather than
`setOpen`, so nothing cleared it again and the whole exit transition was
skipped.

The store already distinguishes the requested open state (`state.open`, set
when the close is requested) from the effective one, so the restoration now
requires the requested state to be unchanged since the switch was scheduled.
This also leaves programmatically-opened controlled popups alone, where
`state.open` is `false` for the entire open cycle.

Reported by Codex on mui#4261. The race predates this branch — verified failing
on master — and is the same class as the two already fixed here.

Co-Authored-By: Claude Opus 5 <[email protected]>
…losed

Three more stale-instant reports on this PR, all reproduced:

- The popup closes and reopens on the same trigger mid-exit. The positioner
  stays mounted and the trigger is unchanged, so nothing re-runs the effect
  to cancel the pending restoration and the new open cycle inherits it.
- A controlled consumer switches triggers and then closes entirely through
  props. Neither transition passes through `setOpen`, so nothing clears the
  `trigger-change` the switch legitimately restored.
- A controlled root opened and switched purely by props, then hovered out
  with a deferred commit. The requested-open comparison added in the previous
  commit reads `false === false` and lets the restoration through.

Rather than adding a fourth condition to the restoration, the two underlying
invariants are now enforced directly:

- `trigger-change` describes a popup moving between triggers, which only has
  meaning while open. The stores' `instantType` selector drops it when the
  popup is closed, so no close path can inherit it, including those that
  never reach `setOpen`.
- Closing cancels any pending restoration, so a reopen starts clean.

This subsumes the earlier fixes. `PopoverStore.setOpen` no longer needs to
pre-clear `instantType` before its `flushSync`, and the restoration no longer
needs the open-cycle, requested-open, or same-trigger conditions. The
remaining `open` check prevents writing state that would outlive the close.

Co-Authored-By: Claude Opus 5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86cb0fa422

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Two follow-ups on the previous commit, both reproduced:

- Masking `trigger-change` while closed left the value stored. A controlled
  reopen on the same trigger changes only `openProp`, so neither the switch
  effect nor `setOpen` runs again to replace it, and the selector starts
  exposing the old value against the new cycle — suppressing its entrance
  transition instead of its exit.
- The trigger element can change while a closing popup is still mounted, when
  a trigger is replaced by a new element. There is no move to animate, and the
  cancellation effect has already run for that commit, so a restoration
  scheduled there would survive into whatever opens next.

Closing now clears the stored value as well as cancelling any pending
restoration, and a switch is only scheduled while the popup is open.

The clear has to read `store.state.instantType` rather than the selector: the
selector hides `trigger-change` precisely when the popup is closed, which is
when the clear needs to see it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 25, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Oct 1, 2026
The "controlled close commits late" tests only asserted that no closing
render carried `trigger-change`, so they would pass without testing anything
if the switch to trigger 2 stopped happening or the restoration stopped
landing before the deferred `open={false}`.

They now also assert that trigger 2 took over the popup and that
`trigger-change` was restored while the close was pending.
@michaldudak
michaldudak merged commit 564d5dd into mui:master Oct 2, 2026
24 checks passed
@michaldudak
michaldudak deleted the instant-hoverout branch October 2, 2026 07:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: menu Changes related to the menu component. 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.

3 participants