Built on <dialog>, showModal() and Invoker Commands. The platform supplies the top layer, the backdrop, the inert page, Escape, initial focus and focus return. The library adds the asynchronous half: opening a dialog whose content loads is a transition, so the trigger shows data-pending and the dialog opens once its content is ready, and closing it with one of its parts waits for your action and can animate with a view transition.
// No "use client": this file is a Server Component. The Dialog.Root has no `open`, `defaultOpen`
// or `openChangeAction`, so it runs in JS-free mode: the Trigger is a native
// `command="show-modal"` invoker, Cancel is a `command="request-close"` button and Delete submits
// a `<form method="dialog">`. The browser opens, focuses, closes on Escape and returns focus,
// before hydration and with JavaScript off.
import { Dialog } from "@funstack/ui/dialog";
export function DialogConfirm() {
return (
<Dialog.Root>
<Dialog.Trigger className="demo-button">Delete draft…</Dialog.Trigger>
<Dialog.Popup className="demo-dialog" role="alertdialog">
<Dialog.Title>Delete this draft?</Dialog.Title>
<Dialog.Description>This cannot be undone.</Dialog.Description>
<Dialog.Form className="demo-dialog-actions">
<Dialog.Close className="demo-button" value="cancel">
Cancel
</Dialog.Close>
<button type="submit" className="demo-button demo-danger" value="delete">
Delete
</button>
</Dialog.Form>
</Dialog.Popup>
</Dialog.Root>
);
}/* Dialog: the Popup is the <dialog> itself. Open state is `:open` / `:modal` on it (exact in
both modes); the Trigger carries `data-open` / `data-pending` in library mode only. */
/* CSS-only scroll lock, keyed on :modal: covers dialogs opened before hydration and nested ones. */
html:has(.demo-dialog:modal) {
overflow: hidden;
}
.demo-dialog {
inline-size: min(28rem, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--color-border);
border-radius: 10px;
background: var(--color-bg);
color: var(--color-text);
box-shadow: 0 12px 40px rgb(0 0 0 / 0.3);
overscroll-behavior: contain;
}
.demo-dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
.demo-dialog h2 {
margin: 0 0 8px;
padding: 0;
border: 0;
font-size: 1.2rem;
}
.demo-dialog p {
margin: 0 0 12px;
color: var(--color-text-secondary);
}
/* Enter and exit with CSS, both modes. Enter works everywhere; the exit animates in Chromium
(with `overlay`) and Safari and is instant in Firefox. */
.demo-dialog,
.demo-dialog::backdrop {
opacity: 0;
transition:
opacity 150ms,
translate 150ms,
display 150ms allow-discrete,
overlay 150ms allow-discrete;
}
.demo-dialog {
translate: 0 8px;
}
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 1;
translate: 0 0;
}
@starting-style {
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 0;
}
.demo-dialog:open {
translate: 0 8px;
}
}
/* With `transition`, a view transition animates the library-driven opens and closes (a Close
part, a Form, a controlled close), Firefox included; dismissals (Escape, a click on the
backdrop) are the browser's and keep the CSS exit above.
The library keeps the two apart; no extra rule is needed. */
::view-transition-new(.demo-dialog-pop) {
animation: 180ms ease-out both demo-dialog-pop-in;
}
::view-transition-old(.demo-dialog-pop) {
animation: 140ms ease-in both demo-dialog-pop-out;
}
@keyframes demo-dialog-pop-in {
from {
opacity: 0;
scale: 0.96;
}
}
@keyframes demo-dialog-pop-out {
to {
opacity: 0;
scale: 0.96;
}
}
@media (prefers-reduced-motion: reduce) {
.demo-dialog,
.demo-dialog::backdrop {
transition: none;
}
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
.demo-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.demo-dialog-form label {
display: grid;
gap: 4px;
}
.demo-dialog-form input {
padding: 0.35em 0.6em;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font: inherit;
}
.demo-dialog-details {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0;
}
.demo-dialog-details dd {
margin: 0;
}
/* The Trigger in library mode: optimistic open and pending. */
.demo-button[data-open] {
border-color: var(--color-primary);
color: var(--color-primary);
}
.demo-button[data-pending] {
cursor: progress;
}
/* A Cancel clicked while the confirm runs: pending until its close commits (the close waits for
the confirm). The delay keeps a close that commits at once from flashing. */
.demo-cancel[data-pending] {
opacity: 0.6;
transition: opacity 0s 150ms;
}
ul.demo-list {
margin: 0 0 12px;
padding: 0;
list-style: none;
}
ul.demo-list .demo-row {
justify-content: space-between;
max-inline-size: 20rem;
padding-block: 4px;
}For confirmations, AlertDialog is this pattern with the defaults built in: role="alertdialog", no light dismiss, focus on Cancel, and a confirm button that runs an async action.
This confirmation is a Server Component in JS-free mode. Every button is a native invoker or a method="dialog" submit, so it works before hydration and with JavaScript disabled.
import { Dialog } from "@funstack/ui/dialog";
<Dialog.Root> {/* no DOM: ids, mode, state */}
<Dialog.Trigger>Edit profile</Dialog.Trigger> {/* button[commandfor][command=show-modal] */}
<Dialog.Popup> {/* dialog */}
<Dialog.Title>Edit profile</Dialog.Title> {/* h2, wired to aria-labelledby */}
<Dialog.Description>…</Dialog.Description> {/* p, wired to aria-describedby */}
<Dialog.Form action={saveProfile}> {/* form: closes after the action settles */}
<input name="name" />
<Dialog.Close>Cancel</Dialog.Close> {/* button[commandfor][command=request-close] */}
<button type="submit">Save</button>
</Dialog.Form>
</Dialog.Popup>
</Dialog.Root>commandfor links them by id. A Popup without a Trigger is fine (controlled open); a Trigger without a Popup is a development warning. A <button commandfor command> of your own that targets the dialog is a foreign invoker; in library mode it goes through the library too.<dialog> itself, so it carries ::backdrop. There is no Portal, Backdrop or Positioner part: the top layer makes them unnecessary. Nothing inside the dialog portals out of it.render: Popup must render a <dialog>, Form a <form>. Trigger and Close must render a <button> for the command path; another element works only through a click handler (Trigger in library mode, Close with action). Wrong elements are development warnings.| JS-free mode | Library mode | |
|---|---|---|
| Selected when | Root has none of open, defaultOpen, openChangeAction, onOpenChange | Root has any of them |
| Open | the browser runs command="show-modal" | the click is intercepted and dispatched in the Root's transition; showModal() runs in the commit that mounts the content |
Close by a part (Close, Form, a foreign close command, controlled open={false}) | the browser | the click, submit or command is cancelled and dispatched in the Root's transition; close(returnValue) runs in the commit that ends it |
| Dismissal (Escape, Android back, a click outside) | the browser | the browser, at once; a fact: onOpenChange(false) is called synchronously, nothing is pending, no view transition |
| Popup content | always mounted (in the server HTML) | rendered from committed open; unmounted while closed unless keepMounted |
Trigger data-open, data-pending | not emitted; style :open on the dialog | emitted (optimistic) |
| Before hydration | everything works | the native open happens; the content arrives on hydration (see below) |
transition on Popup | no effect (development warning) | animates its own opens and library-driven closes (a string: this instance only) |
In library mode, opening and a part's close are the library's; a dismissal (Escape, Android back, a click outside) is the browser's: a fact, reported to onOpenChange (Requests and facts). The mode is decided on the first render; switching later is not supported (development warning).
Dialog.Root| Prop | Type | Default | Description |
|---|---|---|---|
open | boolean | – | Controlled open state. undefined means uncontrolled. Selects library mode. Pass onOpenChange too: the browser closes the dialog without asking (development warns). |
defaultOpen | boolean | – | Initial open state in uncontrolled library mode. A dialog that starts open is shown after hydration, never by the server HTML; its content and the Trigger's open state are already in that HTML. defaultOpen={false} is the usual way to select library mode without an action. |
openChangeAction | ChangeAction<boolean, DialogOpenChangeDetails> | – | Requests only. Awaited for true: the dialog opens when it resolves and the content has rendered. Awaited for a false the user asked a part for (a Dialog.Close, a Dialog.Form submit or settled action, a foreign close command): the dialog closes with details.returnValue when it resolves, with a view transition if the Popup has transition; a controlled parent that keeps open vetoes it. Never called for a dismissal (onOpenChange). Runs in the Root's transition; may be a Server Function; rejections reach the nearest Error Boundary above the Root. details: reason ("activate" or "platform") and returnValue (the closing button's or submitter's value, undefined on open). Selects library mode. |
onOpenChange | UrgentChangeHandler<boolean, DialogOpenChangeDetails> | – | Facts only: the dialog was closed without the library closing it (Escape, Android back, an assistive-technology dismiss, a click outside with lightDismiss, a script close() / requestClose()). Always false, with reason: "dismiss" and returnValue as the browser left it ("" for Escape). Called synchronously in the browser's close event, outside any transition, and not awaited: nothing is pending and no view transition runs. A dismissal while a part's close is still running is reported at once and supersedes that close. In controlled mode set state directly here (onOpenChange={setOpen}), never in startTransition or after an await; a parent that keeps open gets the dialog shown again at once. May return a promise (a Server Function); a rejection or a throw goes to reportError. Selects library mode. On a controlled Root with no openChangeAction, also a part's close (a Close part, a Dialog.Form submission): the library performs it at once and calls this with "activate" (nothing waits). |
modal | boolean | true | showModal() (top layer, backdrop, inert page, Escape) or show(). A non-modal dialog has no command to open it, so its Trigger always uses a click handler: in JS-free mode too, it needs JavaScript to open. |
children | ReactNode | ((state: DialogRootState) => ReactNode) | – | The parts. The function form receives the optimistic state and must not suspend. |
DialogRootState is { open, pending, modal }; open is optimistic, and open and pending are false in JS-free mode.ref, className or style).Dialog.TriggerOne per Root: focus returns to the Trigger that mounted last, and a non-modal dialog treats a press on any other one as outside. A second Dialog.Trigger in the same Root is not supported (development warns); use a Root per trigger.
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | false | Native disabled: a disabled button is not an invoker and never opens. With a link or component render where the Trigger handles the click (library mode, or a non-modal dialog), aria-disabled="true" instead (the element stays focusable). A host link is aria-disabled in every mode (it cannot be natively disabled), and its click is cancelled. Inside a `Toolbar.Root`, in every mode, a disabled Trigger is aria-disabled="true" instead: it stays focusable and in the arrow-key sequence, renders no invoker attribute, and its click is cancelled. A click runs no onClick, a render element's included, and is cancelled; a render element's disabled disables the part too (unavailable parts). |
className | string | ((state: DialogTriggerState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: DialogTriggerState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: DialogTriggerState) => ReactNode) | – | Rendered from optimistic state; must not suspend. |
render | ReactElement | ((props, state: DialogTriggerState) => ReactNode) | – | Replace the default <button> (element form) or take over rendering (function form). |
DialogTriggerState is { open, pending, disabled }; pending is true while the Root is pending: an open in flight, or a part's close waiting for openChangeAction(false). A dismissal never pends, but a request still running when a dismissal superseded it keeps pending until that request settles. In JS-free mode state.open is false (React holds no value) while data-open follows the dialog, written from its toggle event.type (on a <button> only), disabled, aria-disabled (a host link, a component render with the click handler installed, or inside a Toolbar), commandfor, command (not on a link or other non-button host element), onClick (when it installs one), onPointerDown (non-modal JS-free mode), data-open, data-pending, data-disabled. Owned and never written: popoverTarget, popoverTargetAction.Dialog.Popup| Prop | Type | Default | Description |
|---|---|---|---|
keepMounted | boolean | false | Library mode. false: children are not rendered while closed, so content that suspends holds the open until it is ready. true: children stay in <Activity mode="hidden"> (state kept, effects stopped, pre-rendered at low priority; not in the server HTML). Either way, unmounting waits for the dialog's CSS exit animation, or happens inside the close's view transition when transition is set. Ignored in JS-free mode (always mounted). An action of a part inside that rejects while it is hidden goes to reportError, not to an Error Boundary (see Action props). |
initialFocus | RefObject<HTMLElement | null> | string | – | The element to focus on open: a ref, or a selector resolved inside the dialog. The library writes autofocus on it right before showModal() and lets the platform focus it; it never calls .focus(). Default: the platform's choice (the first focusable element). In JS-free mode the attribute is written after mount; prefer it to autoFocus, which React writes only into server-rendered HTML (not when the Popup renders on the client, for example after a client navigation to a Server Component page). |
lightDismiss | boolean | false | Close on a click outside the dialog (the ::backdrop for a modal). JS pointerdown and click listeners: both the press and the click must land outside, so a drag that starts inside (selecting text) never closes. With experimental_closedBy, native closedby="any", which behaves the same. A click on the Trigger of an open non-modal dialog counts as outside, as native closedby="any" treats it: the dialog ends closed and the click does not re-open it, in JS-free and library mode. |
experimental_closedBy | boolean | false | Renders closedby ("any" with lightDismiss, else "closerequest") and skips the JS dismiss listeners where the browser implements it (Chromium, Firefox). Elsewhere the JS stays. See Experimental features. |
transition | ViewTransitionClass | – | Library mode only. The class of the <ViewTransition> around the dialog; without it no boundary is rendered. A string animates this dialog's own opens and closes that the library dispatched (the Trigger, a Close part, a Form submit or settled action, a foreign close command) and its own mount and unmount (only as the top of what is inserted or removed), in all engines; nothing else (not another dialog, not an unrelated transition, not content that changes inside). A controlled open you change in your own transition needs a map keyed on fsui-dialog-open / fsui-dialog-close plus addTransitionType (recipe). A type map is React's: it names every dialog that has it and that a commit with its types reaches, and each plays the class; end it with default: "none" (Type maps). Dismissals animate with CSS only. Keep it static: changing it remounts the popup. Any value, "none" included, makes a mount of the Popup while it is open, or a second reveal of a mounted Popup by <Suspense> or <Activity>, inside a transition run the page cross-fade; a plain open does not, and neither does the mount of a closed Popup: it renders its element one commit after its mount, before paint, so its ref is still empty in the mount effects of the component that renders it (two-step mount). While a view transition runs, the popup's CSS transitions are cut for the library's own show or hide (a @keyframes animation is not, and a dismissal keeps its CSS exit). |
className | string | ((state: DialogPopupState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: DialogPopupState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: DialogPopupState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: DialogPopupState) => ReactNode) | – | Replace the default <dialog> (element form) or take over rendering (function form). |
DialogPopupState is { open, modal }; open is committed (false in JS-free mode; :open is the DOM truth).id, open (never rendered: opening goes through showModal() only), closedby, data-modal, suppressHydrationWarning; aria-labelledby and aria-describedby name the Title and the Description only while each is mounted (none while the content is not rendered), merged with yours. onToggle and onBeforeToggle are not accepted: use a ref for the platform events. popover is not accepted either: a <dialog popover> cannot be opened with showModal().Other props, such as role or onCancel, pass through. For a confirmation, use AlertDialog: role="alertdialog", no light dismiss and focus on Cancel are its defaults.
Dialog.Close| Prop | Type | Default | Description |
|---|---|---|---|
action | Action<[details: DialogCloseActionDetails & Rejectable]> | – | Runs in this button's own transition (data-pending on it), then closes the dialog with value as returnValue: in library mode through the Root (openChangeAction(false) awaited, view transition if set; the button stays pending until the dialog closes), in JS-free mode with close(value). A rejection reaches the nearest Error Boundary above the button and leaves the dialog open. If the dialog was closed and opened again while the action ran, the close is dropped: it belonged to the previous opening. A second click while it is pending is ignored, and the button is aria-disabled="true" meanwhile, unless whilePending is "run". With action the button renders no commandfor / command, so a click before hydration does nothing (rather than closing the dialog without running the action). Without action the button is a native command="request-close" invoker in JS-free mode and goes straight through the Root in library mode, pending until that close has committed. details.returnValue is the value. |
whilePending | "run" | "ignore" | "ignore" | What a click, Enter or Space does while this part's action is pending. "ignore": nothing (the click is cancelled, aria-disabled="true" meanwhile). "run": the action runs again (data-pending until every run has settled, no aria-disabled); the dialog closes once the last run has settled, and only if the latest run resolved: a rejection leaves it open in both modes. No effect without action: the part then shows data-pending while the Root's close waits, never aria-disabled. See A second click while pending. |
value | string | – | Becomes dialog.returnValue, and details.returnValue of openChangeAction(false). |
disabled | boolean | false | Native disabled; owned, so a render element cannot re-enable it. With a link or component render where the Close handles the click (library mode, or with action), aria-disabled="true" instead (the element stays focusable). A host link is aria-disabled in every mode (it cannot be natively disabled), and its click is cancelled. A click runs no onClick, a render element's included, and is cancelled; a render element's disabled disables the part too (unavailable parts). |
className | string | ((state: DialogCloseState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: DialogCloseState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: DialogCloseState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: DialogCloseState) => ReactNode) | – | Replace the default <button> (element form) or take over rendering (function form). |
DialogCloseState is { pending, disabled }; pending runs from the click until the close this part asked for has committed, with or without action (library mode).type (on a <button> only), disabled, aria-disabled, commandfor, command (not with action, and not on a link or other non-button host element), value, onClick (library mode, or with action), data-pending, data-disabled; a render element cannot re-enable a disabled Close. Owned and never written: popoverTarget, popoverTargetAction.By default (whilePending="ignore") a second click, Enter or Space while the action is pending is ignored (and cancelled), and the button is aria-disabled="true" for as long as it shows data-pending, which spans the action and the close; it is never natively disabled, so it keeps focus. To close at once and finish the work in the background, do not return the promise: action={() => { void save(); }}.
Dialog.Form| Prop | Type | Default | Description |
|---|---|---|---|
action | string | ((formData: FormData) => unknown) | – | Without action the form renders method="dialog": a submit closes the dialog with the submitter's value, natively in JS-free mode and through the Root in library mode (openChangeAction(false) awaited, view transition if set). A preventDefault() in your onSubmit keeps it open in both modes. A function (may be a Server Function) is React's form action, passed through unwrapped; the dialog closes, in the same way, once the action's transition has settled, including any Suspense wait it causes (see closeOnSettle). A rejection leaves the dialog open. A string is a plain navigating form. |
closeOnSettle | boolean | true | With a function action: close the dialog once the action settles without throwing and, when the form is rendered as a Form.Root (render={<Form.Root errors={state.errors} error={state.error} />}), with no error: a settle whose errors has a non-empty entry (hidden stale ones included) or whose form-level error is not empty (the autoReset rule) keeps the dialog open; the Form focuses the first errored field or announces the form-level error (Form-level errors). Without a Form.Root the library never sees a result, so any settle that does not throw counts, including a useActionState result that reports errors: render the form as a Form.Root to route them, throw to keep the dialog open, or set false and close it yourself (a Dialog.Close, a submit button in a separate method="dialog" form, or a controlled open; a formMethod="dialog" submitter inside this form runs the action again instead). The dialog is never closed when it was closed while the action ran, even if the user re-opened it meanwhile. |
method | string | – | Only with a string action (for example "post"). Otherwise owned: "dialog" without action, React's own with a function. |
className | string | ((state: DialogFormState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: DialogFormState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: DialogFormState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: DialogFormState) => ReactNode) | – | Replace the default <form> (element form) or take over rendering (function form). |
DialogFormState is { pending }, this form's useFormStatus().pending; it is not emitted as data-pending and not folded into any other part's state.action, and method unless action is a string.With field errors from useActionState, render it as a Form.Root: <Dialog.Form action={dispatch} render={<Form.Root errors={state.errors} />}>. The Form then runs the action, routes the errors to its fields and resets the form only on success (React's own path resets it after every successful action), and the dialog closes only on a result with no field error: errors keep it open with the first errored field focused. The composition needs a function action (without one the form would navigate; a development warning says so). The reset runs before the close, so pass autoReset={false} on the Form.Root element if your exit animation is visible. See Field and Form: in a Dialog.
Dialog.Title, Dialog.Description| Prop | Type | Default | Description |
|---|---|---|---|
className | string | ((state: DialogTitleState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: DialogTitleState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: DialogTitleState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: DialogTitleState) => ReactNode) | – | Replace the default <h2> (Title) or <p> (Description) (element form), or take over rendering (function form). render={<h3 />} changes the heading level. |
DialogTitleState and DialogDescriptionState are DialogPopupState).id.| Attribute | On | Meaning |
|---|---|---|
:open | Popup | The dialog is open (DOM truth, both modes). |
:modal | Popup | Opened with showModal(). |
::backdrop | Popup | The modal backdrop. |
data-modal | Popup | The modal prop (also before the dialog opens). |
data-open | Trigger | Library mode: optimistic open state. JS-free mode: whether the dialog is open, written from its toggle event. |
data-pending | Trigger | Library mode: an open or a part's close is in flight. A dismissal never pends, but a request still running when a dismissal superseded it keeps it until that request settles. |
data-pending | Close | From the click until the close it asked for has committed: its action, then the Root's close (library mode, also without action). |
aria-disabled | Close | "true" with action, while data-pending with whilePending="ignore" (the default): a second click is ignored meanwhile. |
data-disabled | Trigger, Close | The disabled prop (both modes). |
The <dialog> emits no data-open: :open and :modal are exact. Enter and exit animate in CSS, in both modes:
.dialog, .dialog::backdrop {
opacity: 0;
transition: opacity 150ms, display 150ms allow-discrete, overlay 150ms allow-discrete;
}
.dialog:open, .dialog:open::backdrop { opacity: 1; }
@starting-style { .dialog:open, .dialog:open::backdrop { opacity: 0; } }
/* Scroll lock, CSS only: keyed on :modal, so it covers pre-hydration opens and nested dialogs. */
html { scrollbar-gutter: stable; }
html:has(dialog:modal) { overflow: hidden; }The CSS exit animates in Chromium and Safari; Firefox closes a dialog instantly. The library keeps the content mounted until the exit animation ends, so a fading dialog is never empty, and a controlled close keeps it through the fade as well.
| Key | Where | Behaviour | Who |
|---|---|---|---|
| Enter / Space | Trigger | Opens. | the browser (JS-free) or the Trigger |
| Tab / Shift+Tab | Popup, modal | Cycles through the dialog and the browser UI; the page is inert. | the browser |
| Escape | Popup, modal | Closes and returns focus; onOpenChange(false, { reason: "dismiss" }). | the browser |
| Escape | Popup, non-modal | Closes with requestClose(). | the Popup (or closedby with the flag) |
| Escape | a nested dialog | Closes the innermost one only. | the browser |
| Escape | a Popover, Menu, HoverCard or Tooltip open inside | Closes that layer only; the next Escape closes the dialog (modal and non-modal). A handler that calls preventDefault() on the Escape keeps the dialog open; stopPropagation() does not, as for the browser's own Escape. | the browser, the inner component, or the Popup (non-modal) |
| Enter | a form field in the Form | Submits the Form: closes (through the Root in library mode), or runs the action and then closes. | the browser / Form |
dialog; aria-modal is exposed by the browser after showModal(), never set by hand. role="alertdialog" passes through; for a confirmation that needs an answer, AlertDialog renders it for you, with no light dismiss and focus on Cancel. aria-labelledby and aria-describedby point at Title and Description while they are mounted (never at a missing element). A Popup with neither a Title nor an aria-label is a development warning.showModal() makes the rest of the page inert. Focus return is the platform's; the library only steps in when the opener has been removed (focus goes to the Trigger if it is still there, else to the body), and when a library-driven close of a non-modal dialog unmounted the focused button before the dialog closed (focus goes to the Trigger).initialFocus pointing at a <Dialog.Title tabIndex={-1}>.aria-expanded, no aria-haspopup. Give an icon-only Close an aria-label.Concept: Transitions & ViewTransition
Library mode: fsui-dialog plus fsui-dialog-open or fsui-dialog-close; a dismissal and a controlled change carry none unless you add them. JS-free mode starts no transitions. These types are public API: key a transition map on them, and add them with addTransitionType for a controlled change (Transitions). A string transition is keyed on an internal per-instance type instead, which this component's own dispatch adds.
With transition, the Popup renders <ViewTransition> around the <dialog>. A library-driven open calls showModal() in the layout effect of its commit and a library-driven close calls close(returnValue) in the layout effect of its commit, so the view transition captures the dialog's box as ::view-transition-new on open and ::view-transition-old (with its content) on close. That is the only way a dialog's exit can animate in Firefox. The order example below uses it.
<Dialog.Popup transition="pop">The string animates this dialog's own opens and closes only. A dialog you open or close yourself in a transition (a keyboard shortcut) needs the map { "fsui-dialog-open": "pop", "fsui-dialog-close": "pop", default: "none" } and addTransitionType("fsui-dialog-open") in that transition (recipe).
::view-transition-new(.pop) { animation: 180ms ease-out both pop-in; }
::view-transition-old(.pop) { animation: 140ms ease-in both pop-out; }
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }
}Dialog.Close, a Dialog.Form submit or settled action, a foreign request-close / close command; a controlled open={false} with the map and the type above. Transition types: fsui-dialog plus fsui-dialog-open or fsui-dialog-close; a controlled close carries none unless you add it.transition. The library turns the dialog's CSS transitions off for the moment of its own show and hide while a view transition runs, so you need no extra rule (A popup with a CSS exit and a view transition).::backdrop is not captured on its own: it is part of the page snapshot and leaves with the root cross-fade. A backdrop that should animate with the dialog is an element rendered as the Popup's first child (position: fixed; inset: 0; clicks on it are not light dismiss).transition="none" starts no document view transition (the content mounts under the already-mounted <dialog>). A closed Popup that mounts in a transition (a Root inserted by one, a nested Popup mounting with the outer content, a table a Suspense boundary reveals) starts none either: it renders its <dialog> one commit after its mount, before paint (two-step mount). A Popup that is open when it mounts, or a mounted one that <Suspense> or <Activity> reveals again, runs the page cross-fade (issue #35).Concept: Pending & optimistic state
Library mode: the Trigger shows the optimistic open state (data-open) and data-pending while an open or a part's close is in flight; a dismissal is a fact and pends nothing. The Popup's content renders from the committed open. A Close with an action is a pure trigger (data-pending; aria-disabled while it ignores a second click, the default). Every Close shows data-pending from the click until the close it asked for has committed, so a close that waits for openChangeAction(false) shows on the button the user pressed; without action it is never aria-disabled.
"use client";
import { use, useState } from "react";
import { Dialog } from "@funstack/ui/dialog";
import type { DialogOpenChangeDetails } from "@funstack/ui/dialog";
import { sleep } from "./fake-api.js";
interface Order {
readonly items: string;
readonly total: string;
}
// Cache the promises so `use()` sees the same one on every render.
const cache = new Map<string, Promise<Order>>();
function loadOrder(id: string): Promise<Order> {
let promise = cache.get(id);
if (promise === undefined) {
promise = sleep(1200).then(() => ({
items: id === "1042" ? "Keyboard, USB-C cable" : "Notebook",
total: id === "1042" ? "$129.00" : "$18.50",
}));
cache.set(id, promise);
}
return promise;
}
function OrderDetails({ id }: { id: string }) {
const order = use(loadOrder(id));
return (
<dl className="demo-dialog-details">
<dt>Items</dt>
<dd>{order.items}</dd>
<dt>Total</dt>
<dd>{order.total}</dd>
</dl>
);
}
// Library mode: `defaultOpen={false}` (or any action prop) hands the open to the library. The
// Popup's children render from committed state, so <OrderDetails> mounts inside the opening
// transition and suspends: the dialog stays closed and the Trigger carries data-pending until the
// data is ready, then the dialog opens once, complete. The Close button's close is library-owned
// too: openChangeAction(false) runs first, then the dialog closes in a view transition
// (`transition`), so the exit animates in every engine, Firefox included. Escape and a click on
// the backdrop are dismissals: the browser closes the dialog (with the CSS exit), a fact reported
// to `onOpenChange` synchronously. The readout shows what the Root received.
export function DialogOrders() {
const [last, setLast] = useState("(none yet)");
const record = (open: boolean, { reason, returnValue }: DialogOpenChangeDetails) => {
// The synchronous part of an action: this setState is a transition update.
setLast(`openChangeAction(${open}, "${reason}") returnValue=${JSON.stringify(returnValue)}`);
};
const recordFact = (open: boolean, { reason, returnValue }: DialogOpenChangeDetails) => {
// A fact handler: this setState is urgent.
setLast(`onOpenChange(${open}, "${reason}") returnValue=${JSON.stringify(returnValue)}`);
};
return (
<>
<ul className="demo-list">
{["1042", "1043"].map((id) => (
<li key={id} className="demo-row">
Order #{id}
<Dialog.Root defaultOpen={false} openChangeAction={record} onOpenChange={recordFact}>
<Dialog.Trigger className="demo-button">
{({ pending }) => (
<>
Details
{pending && <span className="demo-spinner" aria-hidden />}
</>
)}
</Dialog.Trigger>
<Dialog.Popup
className="demo-dialog"
lightDismiss
initialFocus="[data-autofocus]"
transition={{
"fsui-dialog-open": "demo-dialog-pop",
"fsui-dialog-close": "demo-dialog-pop",
default: "none",
}}
>
<Dialog.Title>Order #{id}</Dialog.Title>
<OrderDetails id={id} />
<div className="demo-dialog-actions">
<Dialog.Close className="demo-button" value="done" data-autofocus="">
Close
</Dialog.Close>
</div>
</Dialog.Popup>
</Dialog.Root>
</li>
))}
</ul>
<div className="demo-row">
<button type="button" className="demo-button" onClick={() => cache.clear()}>
Clear the cache
</button>
</div>
<output className="demo-readout">
last call: <code>{last}</code>
</output>
</>
);
}/* Dialog: the Popup is the <dialog> itself. Open state is `:open` / `:modal` on it (exact in
both modes); the Trigger carries `data-open` / `data-pending` in library mode only. */
/* CSS-only scroll lock, keyed on :modal: covers dialogs opened before hydration and nested ones. */
html:has(.demo-dialog:modal) {
overflow: hidden;
}
.demo-dialog {
inline-size: min(28rem, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--color-border);
border-radius: 10px;
background: var(--color-bg);
color: var(--color-text);
box-shadow: 0 12px 40px rgb(0 0 0 / 0.3);
overscroll-behavior: contain;
}
.demo-dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
.demo-dialog h2 {
margin: 0 0 8px;
padding: 0;
border: 0;
font-size: 1.2rem;
}
.demo-dialog p {
margin: 0 0 12px;
color: var(--color-text-secondary);
}
/* Enter and exit with CSS, both modes. Enter works everywhere; the exit animates in Chromium
(with `overlay`) and Safari and is instant in Firefox. */
.demo-dialog,
.demo-dialog::backdrop {
opacity: 0;
transition:
opacity 150ms,
translate 150ms,
display 150ms allow-discrete,
overlay 150ms allow-discrete;
}
.demo-dialog {
translate: 0 8px;
}
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 1;
translate: 0 0;
}
@starting-style {
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 0;
}
.demo-dialog:open {
translate: 0 8px;
}
}
/* With `transition`, a view transition animates the library-driven opens and closes (a Close
part, a Form, a controlled close), Firefox included; dismissals (Escape, a click on the
backdrop) are the browser's and keep the CSS exit above.
The library keeps the two apart; no extra rule is needed. */
::view-transition-new(.demo-dialog-pop) {
animation: 180ms ease-out both demo-dialog-pop-in;
}
::view-transition-old(.demo-dialog-pop) {
animation: 140ms ease-in both demo-dialog-pop-out;
}
@keyframes demo-dialog-pop-in {
from {
opacity: 0;
scale: 0.96;
}
}
@keyframes demo-dialog-pop-out {
to {
opacity: 0;
scale: 0.96;
}
}
@media (prefers-reduced-motion: reduce) {
.demo-dialog,
.demo-dialog::backdrop {
transition: none;
}
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
.demo-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.demo-dialog-form label {
display: grid;
gap: 4px;
}
.demo-dialog-form input {
padding: 0.35em 0.6em;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font: inherit;
}
.demo-dialog-details {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0;
}
.demo-dialog-details dd {
margin: 0;
}
/* The Trigger in library mode: optimistic open and pending. */
.demo-button[data-open] {
border-color: var(--color-primary);
color: var(--color-primary);
}
.demo-button[data-pending] {
cursor: progress;
}
/* A Cancel clicked while the confirm runs: pending until its close commits (the close waits for
the confirm). The delay keeps a close that commits at once from flashing. */
.demo-cancel[data-pending] {
opacity: 0.6;
transition: opacity 0s 150ms;
}
ul.demo-list {
margin: 0 0 12px;
padding: 0;
list-style: none;
}
ul.demo-list .demo-row {
justify-content: space-between;
max-inline-size: 20rem;
padding-block: 4px;
}data-open and data-pending, and openChangeAction(true, { reason: "activate", returnValue: undefined }) runs.open renders the Popup's children; OrderDetails suspends, so React holds the commit. The dialog stays closed; the Trigger keeps spinning.showModal() runs in the same commit's layout effect, so the platform focuses fully rendered content (here the Close button, through initialFocus).data-pending while openChangeAction(false, { reason: "activate", returnValue: "done" }) runs, then the dialog closes in a view transition (the transition prop), in Firefox too. Escape or a click on the backdrop (lightDismiss) are dismissals: the browser closes the dialog at once and the Root calls onOpenChange(false, { reason: "dismiss" }) in the same event, with nothing pending. The second open is instant (the data is cached).To open now and show a skeleton instead, put a <Suspense> boundary inside the Popup: a newly mounted boundary shows its fallback immediately.
Library mode, with open or an openChangeAction: an open also waits for any other action pending in the app. An uncontrolled Root with no openChangeAction does not wait, and neither does a JS-free dialog. To open a controlled dialog from your own code while a save runs, a keyboard shortcut for example, set open with an urgent update. See Open your own controlled overlay urgently.
Concept: Suspense
Content that suspends holds the open: the dialog stays closed with the Trigger pending, then opens once, complete. A <Suspense> inside the Popup opens at once with a skeleton instead.
Concept: Browser-owned state
JS-free mode: the browser owns everything through Invoker Commands. Library mode: opening and a close asked for by a part are requests (openChangeAction); a dismissal (Escape, Android back, a click outside) is the browser's, a fact: the dialog closes at once, onOpenChange(false) is called with reason: "dismiss", and a controlled parent that keeps open gets it re-opened at once. Dismissals animate with CSS only.
Concept: Server Components
JS-free mode: everything for a modal dialog: open (command="show-modal"), Escape, Close buttons without action (command="request-close"; one with action does nothing until hydration), <form method="dialog">, focus and focus return, autoFocus in server-rendered markup, CSS animation; a Dialog.Form with a Server Function action submits with React's progressive enhancement. Hydration adds initialFocus, lightDismiss and closing after a form action. A non-modal dialog needs JavaScript to open. Library mode: the Trigger opens the dialog natively, but its content is not in the HTML; on hydration it is reconciled with one openChangeAction(true) call (reason: "platform") and the content mounts.
autoFocus in server-rendered markup and Dialog.Form with a Server Function action (React's progressive enhancement). After hydration, and for content React renders on the client, use initialFocus: React does not write autofocus on client-rendered elements.openChangeAction(true, { reason: "platform" }) with no event; the content mounts into the open dialog. If the action rejects or a controlled parent refuses, the dialog closes again. A dialog whose pre-hydration experience matters belongs in JS-free mode.<button commandfor command="show-modal"> (or "request-close" / "close") pointing at the dialog goes through the library too, as the Trigger and Close parts do; a close command's value becomes the returnValue."use client";
import { startTransition, useState } from "react";
import { useFormStatus } from "react-dom";
import { Dialog } from "@funstack/ui/dialog";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { sleep } from "./fake-api.js";
function SaveButton() {
// React's form channel. The Form part only observes it; nothing in the library reports it as
// its own pending state.
const { pending } = useFormStatus();
return (
<button type="submit" className="demo-button demo-primary" value="save">
{pending && <span className="demo-spinner" aria-hidden />}
Save
</button>
);
}
// Dialog.Form with a function `action` renders <form action> (React's form action, passed
// through unwrapped, so a Server Function keeps progressive enhancement) and closes the dialog
// once the action's transition has settled, with the submitter's value as returnValue. A name
// containing "fail" makes the save reject: the Error Boundary inside the dialog shows the error
// and the dialog stays open.
export function DialogProfile() {
const [name, setName] = useState("Ada Lovelace");
return (
<>
<Dialog.Root defaultOpen={false}>
<Dialog.Trigger className="demo-button">Edit profile</Dialog.Trigger>
<Dialog.Popup className="demo-dialog" initialFocus="[name=name]">
<Dialog.Title>Edit profile</Dialog.Title>
<Dialog.Description>
Type a name containing "fail" to see a rejected save.
</Dialog.Description>
<DemoErrorBoundary>
<Dialog.Form
className="demo-dialog-form"
action={async (formData) => {
const next = String(formData.get("name") ?? "");
await sleep(900);
if (next.toLowerCase().includes("fail")) {
throw new Error(`The server rejected the name "${next}".`);
}
// After an await: wrap the update yourself (React limitation).
startTransition(() => setName(next));
}}
>
<label>
Name <input name="name" defaultValue={name} />
</label>
<div className="demo-dialog-actions">
<Dialog.Close className="demo-button" value="cancel">
Cancel
</Dialog.Close>
<SaveButton />
</div>
</Dialog.Form>
</DemoErrorBoundary>
</Dialog.Popup>
</Dialog.Root>
<output className="demo-readout">
saved name: <strong>{name}</strong>
</output>
</>
);
}/* Dialog: the Popup is the <dialog> itself. Open state is `:open` / `:modal` on it (exact in
both modes); the Trigger carries `data-open` / `data-pending` in library mode only. */
/* CSS-only scroll lock, keyed on :modal: covers dialogs opened before hydration and nested ones. */
html:has(.demo-dialog:modal) {
overflow: hidden;
}
.demo-dialog {
inline-size: min(28rem, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--color-border);
border-radius: 10px;
background: var(--color-bg);
color: var(--color-text);
box-shadow: 0 12px 40px rgb(0 0 0 / 0.3);
overscroll-behavior: contain;
}
.demo-dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
.demo-dialog h2 {
margin: 0 0 8px;
padding: 0;
border: 0;
font-size: 1.2rem;
}
.demo-dialog p {
margin: 0 0 12px;
color: var(--color-text-secondary);
}
/* Enter and exit with CSS, both modes. Enter works everywhere; the exit animates in Chromium
(with `overlay`) and Safari and is instant in Firefox. */
.demo-dialog,
.demo-dialog::backdrop {
opacity: 0;
transition:
opacity 150ms,
translate 150ms,
display 150ms allow-discrete,
overlay 150ms allow-discrete;
}
.demo-dialog {
translate: 0 8px;
}
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 1;
translate: 0 0;
}
@starting-style {
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 0;
}
.demo-dialog:open {
translate: 0 8px;
}
}
/* With `transition`, a view transition animates the library-driven opens and closes (a Close
part, a Form, a controlled close), Firefox included; dismissals (Escape, a click on the
backdrop) are the browser's and keep the CSS exit above.
The library keeps the two apart; no extra rule is needed. */
::view-transition-new(.demo-dialog-pop) {
animation: 180ms ease-out both demo-dialog-pop-in;
}
::view-transition-old(.demo-dialog-pop) {
animation: 140ms ease-in both demo-dialog-pop-out;
}
@keyframes demo-dialog-pop-in {
from {
opacity: 0;
scale: 0.96;
}
}
@keyframes demo-dialog-pop-out {
to {
opacity: 0;
scale: 0.96;
}
}
@media (prefers-reduced-motion: reduce) {
.demo-dialog,
.demo-dialog::backdrop {
transition: none;
}
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
.demo-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.demo-dialog-form label {
display: grid;
gap: 4px;
}
.demo-dialog-form input {
padding: 0.35em 0.6em;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font: inherit;
}
.demo-dialog-details {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0;
}
.demo-dialog-details dd {
margin: 0;
}
/* The Trigger in library mode: optimistic open and pending. */
.demo-button[data-open] {
border-color: var(--color-primary);
color: var(--color-primary);
}
.demo-button[data-pending] {
cursor: progress;
}
/* A Cancel clicked while the confirm runs: pending until its close commits (the close waits for
the confirm). The delay keeps a close that commits at once from flashing. */
.demo-cancel[data-pending] {
opacity: 0.6;
transition: opacity 0s 150ms;
}
ul.demo-list {
margin: 0 0 12px;
padding: 0;
list-style: none;
}
ul.demo-list .demo-row {
justify-content: space-between;
max-inline-size: 20rem;
padding-block: 4px;
}useFormStatus().pending is true in the Save button. The dialog stays open.value ("save"): openChangeAction(false) runs with reason: "activate", then the dialog closes.For a single "run this, then close" button without a form, such as Delete, use Dialog.Close action: it shows data-pending on the button and closes when the action resolves.
In library mode a method="dialog" submit is a library-owned close too, with the submitter's value, after your own onSubmit ran. To leave such a form to the browser, call event.stopPropagation() in its onSubmit: the dialog then closes natively and onOpenChange hears it as a reason: "dismiss" fact.
The dialog's action and the form channel are independent, and both usable from a Server Component:
// Persist "seen" when the user closes an announcement: a Close button is a request,
// Escape a fact, so pass the Server Function to both. It receives (open, details): with a
// Trigger inside, the action is also called with true when the dialog opens.
<Dialog.Root
defaultOpen={!user.seenAnnouncement}
openChangeAction={markAnnouncementSeen}
onOpenChange={markAnnouncementSeen}
>
...
</Dialog.Root>
// A form inside the dialog: progressive enhancement before hydration, close after success.
<Dialog.Form action={saveProfile}>...</Dialog.Form>openChangeAction is a per-dialog action with the Trigger's pending state; onOpenChange is called and not awaited, nothing pends for it, and its rejection goes to reportError; Dialog.Form action is React's form action with React's useFormStatus. The Form only observes the form channel to close the dialog afterwards; it never wraps your function and never reports form pending as the dialog's.
const [open, setOpen] = useState(false);
// The handler alone: Escape and the Close part both close at once.
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Popup>...</Dialog.Popup>
</Dialog.Root>For a dialog your app opens itself (a menu item, a shortcut, a route), pass open and onOpenChange and no openChangeAction. Open it with a plain setOpen(true) from your own event handler, not from another part's action: state set in an action waits for every action pending in the app (Open your own controlled overlay urgently; from a menu: Open a dialog or navigate from an item).
With no openChangeAction there is nobody to ask, so a Close part (and a Dialog.Form submission) closes the dialog in the click and tells onOpenChange(false, { reason: "activate", returnValue }), also while a save is pending elsewhere: nothing waits, nothing is pending. What this shape costs:
open at true sees the dialog close and open again, as after Escape.transition.Dialog.Trigger does nothing there (a development warning says so). For a dialog with a Trigger, or a close you want to be asked about, add openChangeAction={setOpen}: then a Close part is a request, runs in the Root's transition and waits for a save pending elsewhere (about 1.4 s with a 1.5 s save, Chromium and Firefox), while Escape still closes at once. An urgent setOpen(false) of your own closes it at once even while that request is held.<Dialog.Root
defaultOpen={false}
openChangeAction={(open, { reason, returnValue }) => {
if (!open && reason === "activate" && returnValue === "delete") deleteDraft();
}}
>A <ViewTransition> that mounts inside a transition runs the page cross-fade (the transition prop, issue #35). In a library-mode dialog that happens when the content mounts parts that render one, such as a control with transition set. A nested Dialog that is closed at that moment does not: a closed Popup mounts in two steps (two-step mount).