Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export default function AnchorPositioning() {
floatingElement: null,
triggerElements: new PopupTriggerMap(),
floatingId: '',
syncOnly: false,
nested: false,
onOpenChange: undefined,
});
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/combobox/root/ComboboxRootContext.tsx
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -15,7 +15,7 @@ export interface ComboboxDerivedItemsContext {
}

export const ComboboxRootContext = React.createContext<ComboboxStore | undefined>(undefined);
export const ComboboxFloatingContext = React.createContext<FloatingRootContext | undefined>(
export const ComboboxFloatingContext = React.createContext<FloatingRootStore | undefined>(
undefined,
);
export const ComboboxDerivedItemsContext = React.createContext<
Expand Down
5 changes: 2 additions & 3 deletions packages/react/src/dialog/popup/DialogPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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();

Expand Down Expand Up @@ -99,7 +98,7 @@ export const DialogPopup = React.forwardRef(function DialogPopup(

return (
<FloatingFocusManager
context={floatingRootContext}
context={store}
openInteractionType={openMethod}
disabled={!mounted}
closeOnFocusOut={!disablePointerDismissal}
Expand Down
52 changes: 46 additions & 6 deletions packages/react/src/dialog/root/DialogRoot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,8 @@ describe('<Dialog.Root />', () => {
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;
Expand Down Expand Up @@ -2135,6 +2134,48 @@ describe('<Dialog.Root />', () => {
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(
<div>
<style>
{`
@keyframes dialog-await-exit { to { opacity: 0; } }
.dialog-await-popup[data-ending-style] { animation: dialog-await-exit 200ms; }
`}
</style>
<Dialog.Root
defaultOpen
onOpenChange={async (open, eventDetails) => {
if (!open) {
await Promise.resolve();
eventDetails.preventUnmountOnClose();
}
}}
>
<Dialog.Portal>
<Dialog.Popup data-testid="popup" className="dialog-await-popup">
Content
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
</div>,
);
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 <html>, falling back to <body> when <html> doesn't
Expand All @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/dialog/root/DialogRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down
3 changes: 1 addition & 2 deletions packages/react/src/dialog/root/useDialogRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
81 changes: 20 additions & 61 deletions packages/react/src/dialog/root/useRenderDialogRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,21 @@ 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<Payload>(
mode: DialogRootMode,
props: DialogRootProps<Payload>,
) {
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';
Expand All @@ -42,49 +31,15 @@ export function useRenderDialogRoot<Payload>(
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<Payload>(
{
open: defaultOpen,
openProp,
activeTriggerId: defaultTriggerIdProp,
triggerIdProp,
...rootState,
},
floatingId,
floatingNested,
),
true,
const { store, open, mounted, payload } = usePopupRoot(
props,
(initialState, floatingId) =>
new DialogStore<Payload>({ ...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
Expand All @@ -93,15 +48,19 @@ export function useRenderDialogRoot<Payload>(

return (
<DialogRootContext.Provider value={store as DialogStore<unknown>}>
{handle && <PopupHandleAttachment handle={handle} store={store} />}
{shouldRenderInteractions && (
<DialogInteractions
store={store}
parentContext={parentStore?.context}
isDrawer={isDrawer}
/>
)}
{typeof children === 'function' ? children({ payload }) : children}
{renderPopupRootChildren({
store,
handle,
interactions: shouldRenderInteractions && (
<DialogInteractions
store={store}
parentContext={parentStore?.context}
isDrawer={isDrawer}
/>
),
children,
payload,
})}
</DialogRootContext.Provider>
);
}
Expand Down
Loading
Loading