Dialog unstable
A popup that opens on top of the page and asks for the user's attention, such as a form, a confirmation or a detail view.
Dialog is headless: it owns the ids, the ARIA, the data attributes, focus,
dismissal and the popup's place in the top layer, and the consumer draws
the markup. The consumer owns whether the dialog is open, passes it as
open, and stores what the RequestedOpen and RequestedClose events
ask for. The dialog stays as it is until open changes, so a consumer can
refuse a close, such as an editor with unsaved changes asking first.
Anatomy
| Part | Element |
|---|---|
trigger |
<button> that opens the dialog |
portal |
<div> in the top layer, around the parts below |
backdrop |
<div> that covers the page |
viewport |
<div> that positions the popup |
popup |
<div> with the dialog role and the dialog's content |
title |
a heading, <h1> to <h6>, that labels the dialog |
description |
<p> that describes the dialog |
close |
<button> that closes the dialog |
initialFocus |
any element, focused when the dialog opens |
finalFocus |
any element, focused when the dialog closes |
Each part takes the consumer's builder and returns it with the part
applied, and the consumer adds the children:
dialog.portal(h.div)?.children(dialog.popup(h.div).children(dialog.title(h.h2).children("Settings"))).
The portal returns undefined while the dialog is closed, unless
keepMounted, and the backdrop returns undefined in a nested dialog, unless
forceRenderBackdrop. backdrop and viewport are optional. A part's result
is a builder, so it can also be another kit call's element, such as a
ui-kit Button's.
The portal is a presentational <div> shown as a manual popover, in every
mode, so it sits in the top layer and needs no portal to another place in
the document. The popup is the element with role="dialog", so the dialog's
accessible bounds are the popup's.
With topLayer: false it stays in place instead, as In place below
describes.
The kit resets its box inline to a strip along the viewport's top edge,
with no height and nothing visible of its own, so it takes no presses: an
unstyled popup shows there, as wide as the viewport. Style the backdrop,
viewport and popup as fixed-position layers:
.viewport { position: fixed; inset: 0; display: grid; place-items: center }.
With modal: true, the kit draws a transparent layer over the whole
viewport as the portal's last child, with z-index: -2.
It intercepts presses on the page behind. Adding or removing the layer
when modal changes preserves the popup's elements.
Data attributes
Each present with an empty value or absent:
trigger:data-popup-openbackdrop:data-open/data-closed,data-starting-style,data-ending-styleviewportandpopup: the backdrop's, anddata-nestedanddata-nested-dialog-open
The popup also sets the CSS variable --nested-dialogs, the number of
dialogs open inside this one. data-starting-style is present for the first
frame after the dialog opens and data-ending-style while it closes, so a
transition can start from and end in a hidden style. The dialog stays shown
until the popup's own transitions and animations finish, then closes and
emits Settled. One that loops, such as a spinner's, doesn't count. For an
exit the kit can't see, such as one run by an animation library, set
holdExit while it runs: the dialog stays in its ending state until it is
cleared.
Keyboard
The trigger and the close button are native buttons, so Enter and Space
press them. Escape asks the topmost open dialog to close, wherever focus is,
unless an input method is composing, focus is in a popover drawn above
the dialog, such as a toast, or something already cancelled it with
preventDefault. A refused close keeps the dialog open as often as Escape
is pressed.
When the dialog opens, focus moves to the initialFocus element, or else
to the first element in the popup that Tab reaches, or else to the popup.
Focus already inside the popup stays. Opened by touch, it focuses the popup
instead of the first field, so the on-screen keyboard doesn't open, but
still focuses an initialFocus element. initialFocus: false leaves focus
where it is unless modal: true, which focuses the popup because the
background is inert. When the focused element inside is removed or hidden,
focus moves to the popup.
As soon as the close starts, focus moves to the finalFocus element,
unless the dialog closed because focus left it, or because a press outside
gave focus to an element of the page. Otherwise, if focus was inside the
dialog, it moves to the trigger that opened it, or else to what had focus
before it opened. Focus that a press outside gave to the page or to
another dialog stays there. A dialog removed while focus is inside gives
focus back the same way. A touch that closes the dialog moves focus
once the finger lifts, so a tap on a field of the page keeps the field
focused. The popup is inert while the dialog closes, so during the exit
transition Tab skips it and screen readers don't reach it. Tab stays
inside a dialog with modal: true or modal: "trap-focus". With modal: true,
the dialog also takes focus back when an outside press or script focuses
an ancestor of its portal. These ancestors can't be inert without
disabling the dialog too. It also takes back focus a script moves from
the page or a popup iframe into an iframe behind it. Focus returns
to the last focused element in the dialog's own document, or to the popup.
It does not return to a field inside a popup iframe. When focus leaves a
cross-origin popup iframe, the dialog takes it back on the next animation
frame. Keys pressed before then reach the background iframe.
The dialog can follow focus through open shadow roots and its own closed shadow root. It cannot follow focus leaving an iframe inside a child component's closed shadow root for a background iframe.
Modes
modal: true, the default: the page behind isinert, so it takes no presses or focus and is hidden from screen readers and find-in-page, and it doesn't scroll. Focus stays inside.modal: "trap-focus": focus stays inside and the page is hidden from screen readers witharia-hidden, but the page behind still scrolls and takes clicks.modal: false: the page stays usable, and the dialog asks to close when focus leaves it.
The popup has aria-modal="true" in the first two modes. Live regions, such
as the toasts, are never hidden, and what the page adds while the dialog is
open is hidden too. So is a popover shown above it, except the DevTools
inspector. A dialog opened later with modal: false stays usable above a
modal one. The scroll lock keeps the space of the scrollbar, so the page
doesn't shift, and leaves a lock the page already has alone. It also stops
one-finger drags outside the popup, which scroll the page on iOS Safari
otherwise. Give a scrolling popup overscroll-behavior: contain so its
scroll doesn't carry on to the page there. Background hiding and scroll
locking end as soon as the close starts, so the page takes presses and
scrolls during the exit transition.
A press outside the popup asks the topmost dialog to close: a click with
the main mouse button that starts and ends outside, or one finger. A press
on a scrollbar doesn't count. With modal: true, only a press on the
kit's layer, the backdrop or the portal around the popup counts, so a press
on a toast above it doesn't close it. In the other modes, any press outside
counts, a toast's too, even in a toast viewport drawn after the dialog
opened, except one on an element added to the page since the dialog
opened, in a new root or inside one already there. An element the renderer
reuses for new content counts as already there. Focus that such a press
moves out of the dialog doesn't close it either, but moving focus there
with the keyboard does. disablePointerDismissal turns that off, and the
close on focus leaving with it.
In the modes other than modal: true, a press directly on the page that
closes the dialog still reaches what it landed on, as in Base UI: a tap or
a click on a button of the page closes the dialog and presses the button.
With modal: true, or when a tap lands on the dialog's own backdrop or
viewport, a finger closes the dialog as it touches and the tap's click is
dropped, so it doesn't land on the page behind it.
On Android, in a browser with CloseWatcher such as Chrome, the back
gesture asks the topmost open dialog to close, with close-watcher, and a
refused close keeps it open as often as back is used. Firefox on Android
has no CloseWatcher, so back doesn't reach the dialog there. On desktop
and iOS, close requests other than Escape don't reach it.
In place
With topLayer: false, the portal is a <div> where the view draws it,
hidden while the dialog doesn't show, like Base UI's portal given a
container, so an ancestor's overflow, position and stacking context
apply to it. Its box is reset
to none of its own, so the backdrop, viewport and popup are positioned
against the nearest positioned ancestor:
.card { position: relative; overflow: hidden } with
.viewport { position: absolute; inset: 0 } keeps the dialog inside the
card. Popups in the top layer, such as the toasts, stay above it.
A dialog in place is never modal, whatever modal says: no scroll lock,
nothing hidden or inert and no layer over the viewport. It still asks to
close on Escape, a press outside and focus leaving it.
Nesting
A dialog drawn inside another one's popup is nested. It finds the dialog
above it by itself: the outer popup gets data-nested-dialog-open and
--nested-dialogs, the inner one data-nested, and only the inner one hears
Escape, outside presses and Android's back gesture. Two dialogs under one
parent each take a key. Of two dialogs open side by side, the one opened
later is on top, as in the browser's top layer, and only it hears them. Focus
a dialog moves by itself, into it as it opens or back to its trigger as it
closes, doesn't close another one with modal: false. Focus the user
moves out of it still does.
A widget of the consumer's own joins the same stack with
Dismissal.TrackDismissal. Drawn in the popup, such as an inline editor,
it is above the dialog and hears them instead, while Tab still stays inside
a modal dialog.
Triggers drawn elsewhere
A DialogTrigger opens a dialog from another part of the page. Give the
dialog an id and the trigger the same popupId: the dialog then counts a
press on the trigger as the trigger's, not a press outside, and gives focus
back to it when it closes. Store the press's method and pass it as the
dialog's openMethod, so an open by touch is treated as one.
Example A settings dialog whose open state lives in the consumer's Model
import { UiSchema } from "effect/ui"import { Html, HtmlServer } from "effect/ui/html"import { Dialog } from "effect/ui/kit"import { Effect, Schema } from "effect"
const ToolbarMessage = UiSchema.TaggedEnum({ RequestedOpenSettings: {}, RequestedCloseSettings: {} })
const Toolbar = Html.component({ name: "Toolbar", model: Schema.Struct({ settings: Schema.Boolean }), message: ToolbarMessage}).make({ init: () => ({ settings: true }), update: { RequestedOpenSettings: ($) => $.evolve({ settings: true }), RequestedCloseSettings: ($) => $.evolve({ settings: false }) }, view: (h, model) => Dialog(h, { props: { open: model.settings }, onEmit: { RequestedOpen: () => ToolbarMessage.RequestedOpenSettings(), RequestedClose: () => ToolbarMessage.RequestedCloseSettings(), Settled: () => undefined }, view: (dialog) => h.div( dialog.trigger(h.button.class("button")).children("Settings"), dialog.portal(h.div)?.children( dialog.viewport(h.div.class("viewport")).children( dialog.popup(h.div.class("popup")).children( dialog.title(h.h2).children("Settings"), dialog.close(h.button.class("button")).children("Close") ) ) ) ) })})
// The popup keeps the consumer's class, and the dialog is labelled by its title.const { html } = await Effect.runPromise(HtmlServer.renderToHtml(Toolbar, {}))const title = /<h2 id="([^"]+)"/.exec(html)?.[1]if (title === undefined || !html.includes(`aria-labelledby="${title}"`) || !html.includes(`class="popup"`)) { throw new Error("the dialog isn't labelled by its title")}Components
A headless dialog. Call it with the consumer's h and a view closure that
draws the trigger with dialog.trigger and the dialog with dialog.portal and the
parts inside it.
Details
The parts also return plain values for markup that depends on them:
open, mounted (the dialog shows, through its exit transition),
transitionStatus, nested, nestedDialogs, triggerId, the id of the
trigger the dialog is open for or last was, and openMethod and
closeMethod, how the user opened the open dialog and last closed it.
Draw initialFocus on a field only for some ways of opening by branching
on dialog.openMethod, which is null once the dialog closes.
A trigger reports the id the consumer gave it in RequestedOpen: set it
on the builder before the part,
dialog.trigger(h.button.attr("id", "edit-" + row.id)). A trigger without
one gets a generated id. The dialog remembers the trigger that opened
it: only that one reports it open, and focus goes back to it. Pressing it
asks the dialog to close, and pressing another one while it is open asks
it to open for that one, which it then remembers.
Each part's attributes win over the ones the consumer set on the builder
it passes in, including the ones a state leaves absent: on the trigger
type, aria-haspopup, aria-expanded, aria-controls, data-popup-open,
and data-dialog-trigger, which the dialog tells its triggers by; on the
portal popover (hidden with topLayer: false) and
data-dialog-portal, which the dialog tells its portal by; role on the
backdrop and the viewport; the data attributes on the backdrop (including
data-dialog-backdrop), viewport and popup; id, role, aria-modal,
tabindex and inert on the popup; type on the close part;
autofocus on initialFocus; and data-final-focus, which the dialog
finds the element by, on finalFocus.
The title and description keep an id the consumer gives them, and get a
generated one otherwise. The popup's aria-labelledby and aria-describedby
point at the title and description that are drawn, after the consumer's
own. Consumer inline styles override the portal's box defaults. The
backdrop's user-select, the closing backdrop's and viewport's
pointer-events, and the popup's --nested-dialogs are added after
consumer styles. A handler the consumer adds to a part runs after the
dialog's own.
On a host that doesn't run mounts, such as TestHost, an open dialog
shows, so HtmlPlay finds it. Backdrop clicks request closure with reason
outside-press unless disablePointerDismissal is set. Escape and other
outside presses are not handled on these hosts. On the server, an open
dialog in place renders without hidden, and one in the top layer stays
hidden until the client's first commit. On both, the dialog stays at
data-starting-style and
closes without waiting for a transition.
History restore saves nothing of it: after Back, forward or a reload it
starts from init.
Signature
declare const Dialog: Headless<{ readonly disablePointerDismissal?: boolean; readonly finalFocus?: boolean; readonly forceRenderBackdrop?: boolean; readonly holdExit?: boolean; readonly id?: string; readonly initialFocus?: boolean; readonly keepMounted?: boolean; readonly modal?: boolean | "trap-focus"; readonly nested?: boolean; readonly open: boolean; readonly openMethod?: "mouse" | "touch" | "pen" | "keyboard" | null; readonly topLayer?: boolean; readonly triggerId?: string | null;}, { readonly _tag: "Settled"; readonly open: boolean;} | { readonly _tag: "RequestedOpen"; readonly triggerId: string | null;} | { readonly _tag: "RequestedClose"; readonly reason: "trigger-press" | "outside-press" | "escape-key" | "close-press" | "focus-out" | "close-watcher";}, { backdrop: <B extends PartTarget<"div">>(element: B) => ReturnType<B["attr"]> | undefined & Pick<Part<"div", [], never>, "~R">; close: Part<"button", [], never>; closeMethod: "mouse" | "touch" | "pen" | "keyboard" | null; description: <B extends PartTarget<"p">>(element: B) => ReturnType<B["attr"]> & Pick<Part<"p", [id: string], never>, "~R">; finalFocus: Part<string, [], never>; initialFocus: Part<string, [], never>; mounted: boolean; nested: boolean; nestedDialogs: number; open: boolean; openMethod: "mouse" | "touch" | "pen" | "keyboard" | null; popup: Part<"div", [], never>; portal: <B extends PartTarget<"div">>(element: B) => ReturnType<B["attr"]> | undefined & Pick<Part<"div", [], never>, "~R">; title: <B extends PartTarget<"h1" | "h2" | "h3" | "h4" | "h5" | "h6">>(element: B) => ReturnType<B["attr"]> & Pick<Part<"h1" | "h2" | "h3" | "h4" | "h5" | "h6", [id: string], never>, "~R">; transitionStatus: DialogTransitionStatus; trigger: <B extends PartTarget<"button">>(element: B) => ReturnType<B["attr"]> & Pick<Part<"button", [triggerId: string | null, key: string, disabled: boolean], never>, "~R">; triggerId: string | null; viewport: Part<"div", [], never>;}, never, never, Shared<"Dialog">, { open: boolean;}, number, never, { readonly closeMethod: "mouse" | "touch" | "pen" | "keyboard" | null; readonly mounted: boolean; readonly nestedOpen: number; readonly openMethod: "mouse" | "touch" | "pen" | "keyboard" | null; readonly reason: "trigger-press" | "outside-press" | "escape-key" | "close-press" | "focus-out" | "close-watcher" | null; readonly started: boolean; readonly trigger: string | null;}, { readonly _tag: "RenderedFirstFrame";} | { readonly _tag: "ClickedTrigger"; readonly key: string; readonly pointerType: string; readonly triggerId: string | null;} | { readonly _tag: "FinishedTransition"; readonly open: boolean;} | { readonly _tag: "ClickedClose"; readonly pointerType: string;} | { readonly _tag: "PressedEscape";} | { readonly _tag: "PressedOutside"; readonly pointerType: string;} | { readonly _tag: "FocusedOutside";} | { readonly _tag: "CancelledCloseWatcher";} | { readonly _tag: "ShowedPortal";} | { readonly _tag: "BlurredTrigger";} | { readonly _tag: "ChangedNested"; readonly count: number;}, QueryEntries<{}, {}>>DialogTrigger
unstableA button that opens a dialog drawn somewhere else, such as in another
component. Call it with the caller's h, whether the dialog is open for
this trigger, the dialog's id as popupId, and what a press sends as
onPress, then chain the label.
Details
It sets the trigger's aria-haspopup="dialog", aria-expanded,
data-popup-open, and aria-controls while the dialog is open, in
forward, so they win over the caller's. Give the dialog the same id
prop: the dialog then finds the trigger by its aria-controls, so a press
on it isn't a press outside, and focus goes back to it when the dialog
closes.
onPress is a message, or a function of the press, which carries the
trigger's id and how the user pressed it. Store the method and pass it
as the dialog's openMethod, so an open by touch focuses the popup.
Given onPress, a click handler of the caller's own, set on element or
chained after the call, throws at render: pass the message as onPress.
Signature
declare function DialogTrigger<Msg, R = never>(h: { readonly button: DialogTriggerElement<Msg>;}, options: { readonly element?: DialogTriggerElement<Msg, R>; readonly onPress?: NoInfer<Msg> | (press: DialogTriggerPress) => NoInfer<Msg>; readonly props: DialogTriggerProps;}): DialogTriggerElement<Msg, R>Models
Why a dialog asks to close.
Signature
type DialogDismissReason = typeof DialogDismissReason.TypeWhat a Dialog emits.
Signature
type DialogEvents = typeof DialogEvents.TypeHow the user opened or closed a dialog.
Signature
type DialogInteraction = typeof DialogInteraction.TypeHow a dialog limits the page behind it.
Signature
type DialogModal = typeof DialogModal.TypeThe props of a Dialog.
Signature
type DialogProps = typeof DialogProps.TypeWhere a dialog is in its open or close transition: starting for the first
frame after it opens, ending while it closes, and null otherwise.
Signature
type DialogTransitionStatus = "starting" | "ending" | nullA <button> builder: what DialogTrigger accepts as element, from the
caller's h.button, and what it returns.
Signature
type DialogTriggerElement<Msg, R = never> = Html.Element<Msg, R, Html.EventsOf<"button">, HTMLButtonElement, "button">A press on a DialogTrigger: the trigger's id, if it has one, and how
the user pressed it.
Signature
interface DialogTriggerPress { readonly method: "mouse" | "touch" | "pen" | "keyboard"; readonly triggerId: string | null;}The props of a DialogTrigger.
Signature
interface DialogTriggerProps { readonly open: boolean; readonly popupId?: string;}Schemas
DialogDismissReason
unstableWhy a dialog asks to close: a press on its open trigger, a press outside
the popup, Escape, a press on the close part, focus leaving a dialog with
modal: false, or a close request from the browser, such as Android's back
gesture.
Signature
declare const DialogDismissReason: Literals<readonly ["trigger-press", "outside-press", "escape-key", "close-press", "focus-out", "close-watcher"]>DialogEvents
unstableRequestedOpen asks for the dialog to open, from a press on a trigger, with
the trigger's id if it has one. RequestedClose asks for it to close,
with the reason. The consumer decides whether to change open. Settled
reports that the transitions and animations of an open or a close finished.
Signature
declare const DialogEvents: TaggedEnum<{ RequestedClose: TaggedStruct<"RequestedClose", { readonly reason: Literals<readonly ["trigger-press", "outside-press", "escape-key", "close-press", "focus-out", "close-watcher"]>; }>; RequestedOpen: TaggedStruct<"RequestedOpen", { readonly triggerId: NullOr<String>; }>; Settled: TaggedStruct<"Settled", { readonly open: Boolean; }>;}>DialogInteraction
unstableHow the user opened or closed a dialog. keyboard covers Enter and Space
on a button and Escape.
Signature
declare const DialogInteraction: Literals<readonly ["mouse", "touch", "pen", "keyboard"]>DialogModal
unstableHow a dialog limits the page behind it: true for a modal, "trap-focus"
to keep focus inside but leave the page usable, false for neither.
Signature
declare const DialogModal: Union<readonly [Boolean, Literal<"trap-focus">]>DialogProps
unstableControls whether the dialog is open, how it treats the page behind it, and where focus goes.
Details
open: whether the dialog shows. Required: the consumer owns it.modal:trueby default,"trap-focus"orfalse, as the module describes.disablePointerDismissal: a press outside the popup doesn't ask to close, and neither does focus leaving a dialog withmodal: false.triggerId: theidof the trigger the dialog is open for, when it has several. Only that trigger getsaria-expandedanddata-popup-open, and focus goes back to it. With none, every trigger reports the dialog open.keepMounted: the portal stays in the page while the dialog is closed, hidden.forceRenderBackdrop: a nested dialog draws its backdrop too.nested:falsekeeps a dialog drawn inside another one out of the nesting: the outer popup doesn't count it, neither gets the nesting attributes, and its backdrop draws. It is still on top, so only it hears Escape and outside presses. For a popup that isn't a second dialog to the user, such as a date picker in a form.initialFocus:falseleaves focus where it is when the dialog opens, or withmodal: truefocuses the popup. Clearing it while the dialog is open moves focus in as an open does.finalFocus:falseleaves focus where it is when the dialog closes.id: the popup'sid, generated when left out. Set it to pair the dialog with aDialogTriggerdrawn somewhere else, as itspopupId.openMethod: how the user opened the dialog, for a dialog opened from aDialogTrigger, whose press reports it. It wins over the one the dialog's own trigger records, and decides the focus of a touch open.holdExit: a closed dialog stays shown, in its ending state, while this istrue, for an exit animation that the consumer runs itself. Set it back tofalseonce that animation ends, and the dialog closes and emitsSettled.topLayer:falsedraws the dialog in place instead of in the top layer, and makes it non-modal, as the module's In place describes.truewhen left out.
Signature
declare const DialogProps: Struct<{ readonly disablePointerDismissal: optional<Boolean>; readonly finalFocus: optional<Boolean>; readonly forceRenderBackdrop: optional<Boolean>; readonly holdExit: optional<Boolean>; readonly id: optional<String>; readonly initialFocus: optional<Boolean>; readonly keepMounted: optional<Boolean>; readonly modal: optional<Union<readonly [Boolean, Literal<"trap-focus">]>>; readonly nested: optional<Boolean>; readonly open: Boolean; readonly openMethod: optional<NullOr<Literals<readonly ["mouse", "touch", "pen", "keyboard"]>>>; readonly topLayer: optional<Boolean>; readonly triggerId: optional<NullOr<String>>;}>