diff --git a/GLOSSARY.md b/GLOSSARY.md index eab80bacc41..bb55f545c36 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -11,6 +11,10 @@ Content that a component shows on top of the page while it is open, such as a po _Avoid_: floating element, floating, overlay _In code_: `floatingElement` is the popup in components without a positioner, such as Dialog. +**Root**: +The part that holds a popup's open state and groups its other parts. It renders no element of its own. +_Avoid_: provider, container + **Trigger**: An element the user interacts with to open or close a popup. A popup can have several triggers; the one that opened it is the **active trigger**. _Avoid_: reference, reference element, DOM reference diff --git a/docs/src/app/(private)/experiments/anchor-positioning.tsx b/docs/src/app/(private)/experiments/anchor-positioning.tsx index a057f4620ab..d78a8b10ae2 100644 --- a/docs/src/app/(private)/experiments/anchor-positioning.tsx +++ b/docs/src/app/(private)/experiments/anchor-positioning.tsx @@ -50,7 +50,6 @@ export default function AnchorPositioning() { floatingElement: null, triggerElements: new PopupTriggerMap(), floatingId: '', - syncOnly: false, nested: false, onOpenChange: undefined, }); diff --git a/packages/react/src/combobox/root/ComboboxRootContext.tsx b/packages/react/src/combobox/root/ComboboxRootContext.tsx index bc02ec0a75c..7a1d20fd187 100644 --- a/packages/react/src/combobox/root/ComboboxRootContext.tsx +++ b/packages/react/src/combobox/root/ComboboxRootContext.tsx @@ -1,7 +1,7 @@ 'use client'; import * as React from 'react'; import type { ComboboxStore } from '../store'; -import type { FloatingRootContext } from '../../utils/popups/types'; +import type { FloatingRootStore } from '../../utils/popups/floating-root/FloatingRootStore'; export interface ComboboxDerivedItemsContext { query: string; @@ -15,7 +15,7 @@ export interface ComboboxDerivedItemsContext { } export const ComboboxRootContext = React.createContext(undefined); -export const ComboboxFloatingContext = React.createContext( +export const ComboboxFloatingContext = React.createContext( undefined, ); export const ComboboxDerivedItemsContext = React.createContext< diff --git a/packages/react/src/dialog/popup/DialogPopup.tsx b/packages/react/src/dialog/popup/DialogPopup.tsx index 9cd446771f6..498c5851777 100644 --- a/packages/react/src/dialog/popup/DialogPopup.tsx +++ b/packages/react/src/dialog/popup/DialogPopup.tsx @@ -32,7 +32,6 @@ export const DialogPopup = React.forwardRef(function DialogPopup( const descriptionElementId = store.useState('descriptionElementId'); const disablePointerDismissal = store.useState('disablePointerDismissal'); - const floatingRootContext = store.useState('floatingRootContext'); const rootPopupProps = store.useState('popupProps'); const modal = store.useState('modal'); const mounted = store.useState('mounted'); @@ -43,7 +42,7 @@ export const DialogPopup = React.forwardRef(function DialogPopup( const titleElementId = store.useState('titleElementId'); const transitionStatus = store.useState('transitionStatus'); const role = store.useState('role'); - const floatingId = floatingRootContext.useState('floatingId'); + const floatingId = store.useState('floatingId'); useDialogPortalContext(); @@ -99,7 +98,7 @@ export const DialogPopup = React.forwardRef(function DialogPopup( return ( ', () => { disablePointerDismissal: false, }, undefined, - true, ); - const parentStore = new DialogStore(undefined, undefined, false); + const parentStore = new DialogStore(undefined, undefined); let mountPassiveEffectFlushed = false; let teardownPassiveEffectFlushed = false; let mountedBeforePassiveEffect: boolean | null = null; @@ -2135,6 +2134,48 @@ describe('', () => { expect(field).not.toHaveFocus(); }, ); + + describe.skipIf(isJSDOM)('close requests', () => { + afterEach(() => { + globalThis.BASE_UI_ANIMATIONS_DISABLED = true; + }); + + it('keeps the dialog mounted when onOpenChange prevents unmounting after an await', async () => { + globalThis.BASE_UI_ANIMATIONS_DISABLED = false; + const { user } = await render( +
+ + { + if (!open) { + await Promise.resolve(); + eventDetails.preventUnmountOnClose(); + } + }} + > + + + Content + + + +
, + ); + expect(screen.getByTestId('popup')).toHaveAttribute('data-open'); + + await user.keyboard('[Escape]'); + await wait(400); + + expect(screen.queryByTestId('popup')).not.toBe(null); + expect(screen.getByTestId('popup')).not.toHaveAttribute('data-open'); + }); + }); }); // The viewport takes its overflow from , falling back to when doesn't @@ -2158,18 +2199,17 @@ function DialogOpenChangeSpy(props: { }) { const { onOpenChange } = props; const store = useDialogRootContext(); - const floatingRootContext = store.useState('floatingRootContext'); React.useEffect(() => { function handleOpenChange(details: { open: boolean; reason: string | null | undefined }) { onOpenChange(details); } - floatingRootContext.context.events.on('openchange', handleOpenChange); + store.context.events.on('openchange', handleOpenChange); return () => { - floatingRootContext.context.events.off('openchange', handleOpenChange); + store.context.events.off('openchange', handleOpenChange); }; - }, [floatingRootContext, onOpenChange]); + }, [store, onOpenChange]); return null; } diff --git a/packages/react/src/dialog/root/DialogRoot.tsx b/packages/react/src/dialog/root/DialogRoot.tsx index d442fc3cfaa..baf94763463 100644 --- a/packages/react/src/dialog/root/DialogRoot.tsx +++ b/packages/react/src/dialog/root/DialogRoot.tsx @@ -4,7 +4,7 @@ import { fastComponent } from '@base-ui/utils/fastHooks'; import type { BaseUIChangeEventDetails } from '../../internals/createBaseUIEventDetails'; import type { REASONS } from '../../internals/reasons'; import type { DialogHandle } from '../store/DialogHandle'; -import type { PayloadChildRenderFunction } from '../../utils/popups/popupStoreUtils'; +import type { PayloadChildRenderFunction } from '../../utils/popups/popupRoot'; import { useRenderDialogRoot } from './useRenderDialogRoot'; /** diff --git a/packages/react/src/dialog/root/useDialogRoot.ts b/packages/react/src/dialog/root/useDialogRoot.ts index 6bd90bcb416..2fb03808fd9 100644 --- a/packages/react/src/dialog/root/useDialogRoot.ts +++ b/packages/react/src/dialog/root/useDialogRoot.ts @@ -21,13 +21,12 @@ export function DialogInteractions({ const disablePointerDismissal = store.useState('disablePointerDismissal'); const modal = store.useState('modal'); const popupElement = store.useState('popupElement'); - const floatingRootContext = store.useState('floatingRootContext'); const [ownNestedOpenDialogs, setOwnNestedOpenDialogs] = React.useState(0); const [ownNestedOpenDrawers, setOwnNestedOpenDrawers] = React.useState(0); const isTopmost = ownNestedOpenDialogs === 0; - const dismiss = useDismiss(floatingRootContext, { + const dismiss = useDismiss(store, { outsidePressEvent() { if (store.context.internalBackdropRef.current || store.context.backdropRef.current) { return 'intentional'; diff --git a/packages/react/src/dialog/root/useRenderDialogRoot.tsx b/packages/react/src/dialog/root/useRenderDialogRoot.tsx index cb5d615306b..8b666d12796 100644 --- a/packages/react/src/dialog/root/useRenderDialogRoot.tsx +++ b/packages/react/src/dialog/root/useRenderDialogRoot.tsx @@ -4,15 +4,11 @@ import { DialogInteractions } from './useDialogRoot'; import { DialogRootContext, useDialogRootContext } from './DialogRootContext'; import { DialogStore } from '../store/DialogStore'; import type { DialogRootProps } from './DialogRoot'; -import { createChangeEventDetails } from '../../internals/createBaseUIEventDetails'; -import { REASONS } from '../../internals/reasons'; import { - useImplicitActiveTrigger, - useOpenStateTransitions, - PopupHandleAttachment, - usePopupRootStore, + renderPopupRootChildren, + usePopupRoot, usePopupRootSync, -} from '../../utils/popups/popupStoreUtils'; +} from '../../utils/popups/popupRoot'; export function useRenderDialogRoot( mode: DialogRootMode, @@ -20,16 +16,9 @@ export function useRenderDialogRoot( ) { const { children, - open: openProp, - defaultOpen = false, - onOpenChange, - onOpenChangeComplete, disablePointerDismissal: disablePointerDismissalProp = false, modal: modalProp = true, - actionsRef, handle, - triggerId: triggerIdProp, - defaultTriggerId: defaultTriggerIdProp = null, } = props; const isDrawer = mode === 'drawer'; @@ -42,49 +31,15 @@ export function useRenderDialogRoot( const nested = parentStore != null; const rootState = { modal, disablePointerDismissal, nested, role }; - // The store is owned by this Root instance and created exactly once. It is not tied to the handle: - // the handle attaches to it, so swapping the handle re-attaches rather than recreating state. - // Default values are only initial values; controlled values and root state are synced after creation. - // Dialogs pass the popup element to Floating UI as the floating element (`treatPopupAsFloatingElement`). - const store = usePopupRootStore( - (floatingId, floatingNested) => - new DialogStore( - { - open: defaultOpen, - openProp, - activeTriggerId: defaultTriggerIdProp, - triggerIdProp, - ...rootState, - }, - floatingId, - floatingNested, - ), - true, + const { store, open, mounted, payload } = usePopupRoot( + props, + (initialState, floatingId) => + new DialogStore({ ...initialState, ...rootState }, floatingId), ); - store.useControlledProp('openProp', openProp); - store.useControlledProp('triggerIdProp', triggerIdProp); - store.useSyncedValues(rootState); - store.useContextCallback('onOpenChange', onOpenChange); - store.useContextCallback('onOpenChangeComplete', onOpenChangeComplete); - - const open = store.useState('open'); - const mounted = store.useState('mounted'); - const payload = store.useState('payload') as Payload | undefined; usePopupRootSync(store, open); - useImplicitActiveTrigger(store); - const { forceUnmount } = useOpenStateTransitions(open, store, openProp); - - React.useImperativeHandle( - actionsRef, - () => ({ - unmount: forceUnmount, - close: () => store.setOpen(false, createChangeEventDetails(REASONS.imperativeAction)), - }), - [forceUnmount, store], - ); // Detached triggers share this one Root, so mounting its interactions eagerly is cheap. The // trigger props they publish then stay stable, so opening and closing doesn't re-render inactive @@ -93,15 +48,19 @@ export function useRenderDialogRoot( return ( }> - {handle && } - {shouldRenderInteractions && ( - - )} - {typeof children === 'function' ? children({ payload }) : children} + {renderPopupRootChildren({ + store, + handle, + interactions: shouldRenderInteractions && ( + + ), + children, + payload, + })} ); } diff --git a/packages/react/src/dialog/store/DialogStore.ts b/packages/react/src/dialog/store/DialogStore.ts index c276550075b..51e6bddb131 100644 --- a/packages/react/src/dialog/store/DialogStore.ts +++ b/packages/react/src/dialog/store/DialogStore.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import { ReactStore } from '@base-ui/utils/store'; +import { NOOP } from '@base-ui/utils/empty'; import type { InteractionType } from '@base-ui/utils/useEnhancedClickHandler'; import type { DialogRoot } from '../root/DialogRoot'; import { NullStore } from '../../utils/NullStore'; @@ -8,9 +8,12 @@ import type { PopupTriggerDataStore, PopupStoreState, } from '../../utils/popups/store'; -import { createInitialPopupStoreState, popupStoreSelectors } from '../../utils/popups/store'; -import { PopupTriggerMap } from '../../utils/popups/popupTriggerMap'; -import { createPopupOpenState } from '../../utils/popups/popupStoreUtils'; +import { + BasePopupStore, + createInitialPopupStoreState, + createPopupStoreContext, + popupStoreSelectors, +} from '../../utils/popups/store'; export type State = PopupStoreState & { modal: boolean | 'trap-focus'; @@ -45,6 +48,8 @@ const selectors = { titleElementId: (state: State) => state.titleElementId, viewportElement: (state: State) => state.viewportElement, role: (state: State) => state.role, + // Dialogs have no positioner, so the interaction hooks treat the popup as the floating element. + floatingElement: (state: State) => state.popupElement, }; /** @@ -52,48 +57,36 @@ const selectors = { * `DialogStore` and the inert fallback store satisfy it, so a trigger can read from whichever * store the handle currently exposes. */ -export type DialogHandleStore = PopupTriggerDataStore>; +export type DialogHandleStore = PopupTriggerDataStore> & + Pick, 'setOpen'>; -export class DialogStore extends ReactStore< - Readonly>, +export class DialogStore extends BasePopupStore< + State, Context, - typeof selectors + typeof selectors, + DialogRoot.ChangeEventDetails > { - constructor( - initialState: Partial> | undefined, - floatingId: string | undefined, - nested: boolean, - ) { - const triggerElements = new PopupTriggerMap(); - const state = createInitialState(initialState, triggerElements, floatingId, nested); + constructor(initialState: Partial> | undefined, floatingId: string | undefined) { + const state = createInitialState(initialState, floatingId); + + super(state, createInitialContext(), selectors); + } - super(state, createInitialContext(triggerElements), selectors); + protected getCloseTrigger() { + // When closing the dialog, pass the old trigger to the onOpenChange event + // so it's not reset too early (potentially causing focus issues in controlled scenarios). + return this.state.activeTriggerId != null + ? (this.state.activeTriggerElement ?? undefined) + : undefined; } - public setOpen = ( - nextOpen: boolean, - eventDetails: Omit, - ) => { - (eventDetails as DialogRoot.ChangeEventDetails).preventUnmountOnClose = () => { + // The request is recorded as soon as it's made, so `onOpenChange` can make it after an `await`. + protected attachPreventUnmountOnClose(eventDetails: DialogRoot.ChangeEventDetails) { + eventDetails.preventUnmountOnClose = () => { this.set('preventUnmountingOnClose', true); }; - - if (!nextOpen && eventDetails.trigger == null && this.state.activeTriggerId != null) { - // When closing the dialog, pass the old trigger to the onOpenChange event - // so it's not reset too early (potentially causing focus issues in controlled scenarios). - eventDetails.trigger = this.state.activeTriggerElement ?? undefined; - } - - this.context.onOpenChange?.(nextOpen, eventDetails as DialogRoot.ChangeEventDetails); - - if (eventDetails.isCanceled) { - return; - } - - this.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails); - - this.update(createPopupOpenState(this.state, nextOpen, eventDetails.trigger)); - }; + return () => false; + } } /** @@ -102,23 +95,20 @@ export class DialogStore extends ReactStore< * detached triggers can register before migrating to the live root store. */ export function createNullDialogStore(): DialogHandleStore { - const triggerElements = new PopupTriggerMap(); - - return new NullStore>, Context, typeof selectors>( - Object.freeze(createInitialState(undefined, triggerElements)), - Object.freeze(createInitialContext(triggerElements)), + const store = new NullStore>, Context, typeof selectors>( + Object.freeze(createInitialState(undefined)), + Object.freeze(createInitialContext()), selectors, ); + return Object.assign(store, { setOpen: NOOP }); } function createInitialState( initialState: Partial> | undefined, - triggerElements: PopupTriggerMap, floatingId?: string | undefined, - nested = false, ): State { const state: State = { - ...createInitialPopupStoreState(triggerElements, floatingId, nested), + ...createInitialPopupStoreState(floatingId), modal: true, disablePointerDismissal: false, viewportElement: null, @@ -135,14 +125,11 @@ function createInitialState( return state; } -function createInitialContext(triggerElements: PopupTriggerMap): Context { +function createInitialContext(): Context { return { - popupRef: React.createRef(), + ...createPopupStoreContext(), backdropRef: React.createRef(), internalBackdropRef: React.createRef(), outsidePressEnabledRef: { current: true }, - triggerElements, - onOpenChange: undefined, - onOpenChangeComplete: undefined, }; } diff --git a/packages/react/src/dialog/trigger/DialogTrigger.tsx b/packages/react/src/dialog/trigger/DialogTrigger.tsx index 76424d8b9d4..f528853c7be 100644 --- a/packages/react/src/dialog/trigger/DialogTrigger.tsx +++ b/packages/react/src/dialog/trigger/DialogTrigger.tsx @@ -46,7 +46,6 @@ export const DialogTrigger = fastComponentRef(function DialogTrigger( } const thisTriggerId = useBaseUiId(idProp); - const floatingContext = store.useState('floatingRootContext'); const isOpenedByThisTrigger = store.useState('isOpenedByTrigger', thisTriggerId); const popupId = store.useState('triggerPopupId', thisTriggerId); @@ -66,7 +65,7 @@ export const DialogTrigger = fastComponentRef(function DialogTrigger( native: nativeButton, }); - const click = useClick(floatingContext); + const click = useClick(store); const interactionTypeProps = useOpenMethodTriggerProps( () => store.select('open'), (interactionType) => { diff --git a/packages/react/src/drawer/popup/DrawerPopup.tsx b/packages/react/src/drawer/popup/DrawerPopup.tsx index 4c33c6d1361..14f9ac52969 100644 --- a/packages/react/src/drawer/popup/DrawerPopup.tsx +++ b/packages/react/src/drawer/popup/DrawerPopup.tsx @@ -135,7 +135,6 @@ export const DrawerPopup = React.forwardRef(function DrawerPopup( const descriptionElementId = store.useState('descriptionElementId'); const disablePointerDismissal = store.useState('disablePointerDismissal'); - const floatingRootContext = store.useState('floatingRootContext'); const rootPopupProps = store.useState('popupProps'); const modal = store.useState('modal'); const mounted = store.useState('mounted'); @@ -146,7 +145,7 @@ export const DrawerPopup = React.forwardRef(function DrawerPopup( const openMethod = store.useState('openMethod'); const titleElementId = store.useState('titleElementId'); const role = store.useState('role'); - const floatingId = floatingRootContext.useState('floatingId'); + const floatingId = store.useState('floatingId'); const popupId = elementProps.id ?? floatingId; @@ -395,7 +394,7 @@ export const DrawerPopup = React.forwardRef(function DrawerPopup( return ( UseFloatingReturn; * `useFloating` hook. */ export function useAnchorPositioning( - params: UseAnchorPositioningParameters & { floatingRootContext: FloatingRootContext }, + params: UseAnchorPositioningParameters & { floatingRootContext: PositioningRootContext }, ): UseAnchorPositioningReturnValue { return useAnchorPositioningWithHook(params, useBaseUIFloating as UseFloatingHook); } @@ -462,12 +462,7 @@ export function useAnchorPositioningWithHook( // Ensure positioning doesn't run initially for `keepMounted` elements that // aren't initially open. if (!mounted && floatingRootContext) { - floatingRootContext.update({ - referenceElement: null, - floatingElement: null, - domReferenceElement: null, - positionReference: null, - }); + floatingRootContext.clearPositioning(); } }, [mounted, floatingRootContext]); @@ -814,7 +809,7 @@ export interface UseAnchorPositioningSharedParameters { export interface UseAnchorPositioningParameters extends UseAnchorPositioningSharedParameters { keepMounted?: boolean | undefined; - floatingRootContext?: FloatingRootContext | undefined; + floatingRootContext?: PositioningRootContext | undefined; mounted: boolean; disableAnchorTracking: boolean; nodeId?: string | undefined; diff --git a/packages/react/src/menu/popup/MenuPopup.tsx b/packages/react/src/menu/popup/MenuPopup.tsx index bf47e57c123..3fded64fd90 100644 --- a/packages/react/src/menu/popup/MenuPopup.tsx +++ b/packages/react/src/menu/popup/MenuPopup.tsx @@ -61,7 +61,6 @@ export const MenuPopupPlain = React.forwardRef(function MenuPopupPlain( const parent = store.useState('parent'); const lastOpenChangeReason = store.useState('lastOpenChangeReason'); const rootId = store.useState('rootId'); - const floatingContext = store.useState('floatingRootContext'); const floatingTreeRoot = store.useState('floatingTreeRoot'); const closeDelay = store.useState('closeDelay'); const hoverEnabled = store.useState('hoverEnabled'); @@ -121,7 +120,7 @@ export const MenuPopupPlain = React.forwardRef(function MenuPopupPlain( }; }, [floatingTreeRoot.events, store]); - useHoverFloatingInteraction(floatingContext, { + useHoverFloatingInteraction(store, { enabled: hoverEnabled && !disabled && !isContextMenu && parent.type !== 'menubar', closeDelay, }); @@ -193,7 +192,7 @@ export const MenuPopupPlain = React.forwardRef(function MenuPopupPlain( return ( ', () => { @@ -597,4 +598,109 @@ describe('', () => { }, ); }); + + describe('controlled open and triggerId fed from the change details, while StoreInspector serializes the store', () => { + const handle = Menu.createHandle(); + + function App() { + const [open, setOpen] = React.useState(false); + const [triggerId, setTriggerId] = React.useState(null); + + return ( + + + { + setOpen(nextOpen); + setTriggerId(eventDetails.trigger?.id ?? null); + }} + > + {({ payload }) => ( + + + + {payload} + + + + )} + + + Library + + + Playback + + + Sharing + + + + + ); + } + + async function expectOpenWith(item: string) { + await waitFor(() => { + expect(screen.queryByTestId('popup')).not.toBe(null); + }); + await waitFor(() => { + expect(screen.getByRole('menuitem')).toHaveTextContent(item); + }); + } + + async function expectClosed() { + await waitFor(() => { + expect(screen.queryByTestId('popup')).toBe(null); + }); + } + + it('opens from each trigger, an item, and both external buttons', async () => { + const { user } = await render(); + + for (const name of ['Library', 'Playback', 'Sharing']) { + const trigger = screen.getByRole('button', { name }); + // eslint-disable-next-line no-await-in-loop + await user.click(trigger); + // eslint-disable-next-line no-await-in-loop + await expectOpenWith(name); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + + // eslint-disable-next-line no-await-in-loop + await user.click(screen.getByRole('menuitem')); + // eslint-disable-next-line no-await-in-loop + await expectClosed(); + } + + await user.click(screen.getByRole('button', { name: 'Library' })); + await expectOpenWith('Library'); + await user.click(screen.getByRole('button', { name: 'Sharing' })); + await expectOpenWith('Sharing'); + await user.click(screen.getByRole('button', { name: 'Sharing' })); + await expectClosed(); + + await user.click(screen.getByRole('button', { name: 'Open externally' })); + await expectOpenWith('Playback'); + await user.keyboard('[Escape]'); + await expectClosed(); + + await user.click(screen.getByRole('button', { name: 'Open via handle' })); + await expectOpenWith('Playback'); + await user.click(screen.getByRole('menuitem')); + await expectClosed(); + }); + }); }); diff --git a/packages/react/src/menu/root/MenuRoot.test.tsx b/packages/react/src/menu/root/MenuRoot.test.tsx index ab798adb117..8432f8782ae 100644 --- a/packages/react/src/menu/root/MenuRoot.test.tsx +++ b/packages/react/src/menu/root/MenuRoot.test.tsx @@ -30,6 +30,7 @@ import { waitSingleFrame, } from '#test-utils'; import { REASONS } from '../../internals/reasons'; +import { createChangeEventDetails } from '../../internals/createBaseUIEventDetails'; import { PATIENT_CLICK_THRESHOLD } from '../../internals/constants'; import type { MenuStore } from '../store/MenuStore'; import { useMenuRootContext } from './MenuRootContext'; @@ -3802,6 +3803,482 @@ describe('', () => { expect(submenuListener).toHaveBeenCalled(); }); }); + + describe('open change requests', () => { + it('reports two identical requests made in one tick twice', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + const { user } = await render( + + + + + + Item + + + + + + Trigger A + + + Trigger B + + , + ); + + await user.click(screen.getByRole('button', { name: 'Trigger A' })); + await waitFor(() => { + expect(screen.queryByRole('menu')).not.toBe(null); + }); + onOpenChange.mockClear(); + + await act(async () => { + handle.open('trigger-b'); + handle.open('trigger-b'); + }); + + expect(onOpenChange).toHaveBeenCalledTimes(2); + expect(screen.getByRole('button', { name: 'Trigger B' })).toHaveAttribute( + 'aria-expanded', + 'true', + ); + }); + + it('ignores a request made before the root has mounted', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + + function OpenOnMount() { + React.useLayoutEffect(() => { + handle.open('trigger'); + }, []); + return null; + } + + await render( + + + Trigger + + + + + + + Item + + + + + , + ); + + expect(onOpenChange).not.toHaveBeenCalled(); + expect(screen.queryByRole('menu')).toBe(null); + }); + + it('accepts a request made after the root has mounted in the same commit', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + + function OpenOnMount() { + React.useLayoutEffect(() => { + handle.open('trigger'); + }, []); + return null; + } + + await render( + + + Trigger + + + + + + Item + + + + + + , + ); + + expect(onOpenChange.mock.calls[0][0]).toBe(true); + expect(screen.queryByRole('menu')).not.toBe(null); + }); + + it('ignores a request identical to the open state the root committed', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + await render( + + + + + + Item + + + + + + Trigger + + , + ); + + await act(async () => { + handle.open('trigger'); + }); + expect(screen.queryByRole('menu')).not.toBe(null); + expect(onOpenChange).toHaveBeenCalledTimes(1); + + await act(async () => { + handle.open('trigger'); + }); + + expect(onOpenChange).toHaveBeenCalledTimes(1); + }); + + it('ignores a close request while the menu is already closed', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + await render( + + + + + + Item + + + + + + Trigger + + , + ); + expect(screen.queryByRole('menu')).toBe(null); + + await act(async () => { + handle.close(); + }); + + expect(onOpenChange).not.toHaveBeenCalled(); + }); + + it('drops a request made after the root unmounts', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + + function Fixture({ showRoot }: { showRoot: boolean }) { + return ( + + {showRoot && ( + + + + + Item + + + + + )} + + Trigger + + + ); + } + + const { setProps } = await render(); + const store = handle.store; + await setProps({ showRoot: false }); + + await act(async () => { + store.setOpen(true, createChangeEventDetails(REASONS.imperativeAction)); + }); + + expect(onOpenChange).not.toHaveBeenCalled(); + }); + + it('reports the committed active trigger for a close that carries no trigger', async () => { + const handle = Menu.createHandle(); + const onOpenChange = vi.fn(); + const { user } = await render( + + + + + + Item + + + + + + Trigger A + + + Trigger B + + , + ); + + await user.click(screen.getByRole('button', { name: 'Trigger B' })); + await waitFor(() => { + expect(screen.queryByRole('menu')).not.toBe(null); + }); + onOpenChange.mockClear(); + + await act(async () => { + handle.close(); + }); + + expect(onOpenChange).toHaveBeenCalledTimes(1); + expect(onOpenChange.mock.calls[0][1].trigger).toBe( + screen.getByRole('button', { name: 'Trigger B' }), + ); + }); + + it('resets allowMouseEnter once the menu unmounts after closing', async () => { + const handle = Menu.createHandle(); + await render( + + + + + + Item + + + + + + Trigger + + , + ); + + await act(async () => { + handle.open('trigger'); + }); + await act(async () => { + handle.store.set('allowMouseEnter', true); + }); + expect(handle.store.state.allowMouseEnter).toBe(true); + + await act(async () => { + handle.close(); + }); + await waitFor(() => { + expect(screen.queryByRole('menu')).toBe(null); + }); + + expect(handle.store.state.allowMouseEnter).toBe(false); + }); + + it('marks a close without a reason as a dismissal', async () => { + const handle = Menu.createHandle(); + await render( + + + + + + Item + + + + + + Trigger + + , + ); + + await act(async () => { + handle.open('trigger'); + }); + expect(screen.getByTestId('popup')).toHaveAttribute('data-open'); + + await act(async () => { + handle.store.setOpen( + false, + createChangeEventDetails(undefined as unknown as typeof REASONS.none), + ); + }); + + expect(screen.getByTestId('popup')).not.toHaveAttribute('data-open'); + expect(screen.getByTestId('popup')).toHaveAttribute('data-instant', 'dismiss'); + }); + + it('commits a hover open after the hover event has been dispatched', async () => { + const menuPresentDuringEvent: boolean[] = []; + await render( + + + Trigger + + + + + Item + + + + , + ); + const trigger = screen.getByRole('button', { name: 'Trigger' }); + + function recordMenu() { + menuPresentDuringEvent.push(screen.queryByRole('menu') !== null); + } + + // The trigger opens from a native `mouseenter` listener. One added after it runs once the + // menu has handled the event. The event is dispatched outside `act()`, so React commits the + // open on its own schedule. + ignoreActWarnings(); + trigger.addEventListener('mouseenter', recordMenu); + try { + trigger.dispatchEvent(new MouseEvent('mouseenter')); + } finally { + trigger.removeEventListener('mouseenter', recordMenu); + } + + await waitFor(() => { + expect(screen.queryByRole('menu')).not.toBe(null); + }); + expect(menuPresentDuringEvent).toEqual([false]); + }); + + it.skipIf(isJSDOM)( + 'reopens immediately when re-hovering the trigger during its close transition', + async () => { + globalThis.BASE_UI_ANIMATIONS_DISABLED = false; + + // Long enough that a slow run can't finish the close before the re-enter. + const closeTransitionMs = 10_000; + const style = ` + @keyframes menu-reopen-during-close { + from { + opacity: 1; + } + to { + opacity: 0.01; + } + } + + [data-testid="popup"][data-ending-style] { + animation: menu-reopen-during-close ${closeTransitionMs}ms linear forwards; + } + `; + + const { user } = await render( + + {/* eslint-disable-next-line react/no-danger */} +