Dialog
A popup in the top layer that asks for the user's attention, with focus, dismissal and nesting handled.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogCloseIcon,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogBasicMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: {},
RequestedCloseDialog: {}
})
export const DialogBasic = Html.component({
name: "DialogBasic",
model: Schema.Struct({ open: Schema.Boolean }),
message: DialogBasicMessage
}).make({
init: () => ({ open: false }),
update: {
RequestedOpenDialog: ($) => $.evolve({ open: true }),
RequestedCloseDialog: ($) => $.evolve({ open: false })
},
view: (h, model) =>
Dialog(h, {
props: { open: model.open },
onEmit: {
RequestedOpen: () => DialogBasicMessage.RequestedOpenDialog(),
RequestedClose: () => DialogBasicMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Share project"),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children("Share this project"),
DialogDescription(h, dialog).children(
"Anyone with the link can view the project. Only members can edit it."
)
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Cancel"),
dialog.close(h.button.class(buttonVariants())).children("Copy link")
),
DialogCloseIcon(h, dialog)
)
)
)
)
})
})
Installation
Set up the project
Once per project: the packages, Tailwind CSS, the theme tokens and the
cnhelper. Follow Installation.Copy the component into your project
The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
src/ui/dialog.ts import type { Component } from "@effect/ui" import type { Html } from "@effect/ui/html" import type { Dialog } from "@effect/ui-kit" import { cn } from "#lib/cn" /** What a `Dialog`'s `view` closure receives. */ export type DialogParts = Component.Headless.Parts<typeof Dialog> interface ClassOption { readonly class?: string | undefined } const sizes = { sm: "w-full max-w-[340px]", default: "w-full max-w-[440px]", lg: "w-full max-w-[680px]", full: "h-full w-full rounded-none border-0 data-[ending-style]:translate-y-4 data-[starting-style]:translate-y-4 " + "data-[ending-style]:scale-100 data-[starting-style]:scale-100" } as const export type DialogSize = keyof typeof sizes /** The layer that dims the page. Leave it out of a non-modal dialog. */ export const DialogBackdrop = <Msg>(h: Html.H<Msg>, dialog: DialogParts, options: ClassOption = {}) => dialog.backdrop( h.div.class(cn( "fixed inset-0 bg-[color-mix(in_oklab,var(--shadow-color)_45%,transparent)] transition-opacity duration-200", "data-[ending-style]:opacity-0 data-[starting-style]:opacity-0", options.class )) ) /** Centres the popup in the screen. Presses pass through it to the backdrop or the page. */ export const DialogViewport = <Msg>( h: Html.H<Msg>, dialog: DialogParts, options: ClassOption & { readonly size?: DialogSize | undefined } = {} ) => dialog.viewport( h.div.class(cn( "pointer-events-none fixed inset-0 grid place-items-center", options.size === "full" ? "p-0" : "p-4", options.class )) ) /** The dialog's box. With another dialog open inside it, it steps back. */ export const DialogPopup = <Msg>( h: Html.H<Msg>, dialog: DialogParts, options: ClassOption & { readonly size?: DialogSize | undefined } = {} ) => dialog.popup( h.div.class(cn( "pointer-events-auto relative flex max-h-full flex-col gap-4 rounded-lg border bg-popover p-6 text-sm", "text-foreground shadow-float outline-none", "transition-[opacity,scale,translate,filter] duration-200 ease-out", "data-[ending-style]:scale-95 data-[ending-style]:opacity-0", "data-[starting-style]:scale-95 data-[starting-style]:opacity-0", "data-[nested-dialog-open]:-translate-y-[calc(14px*var(--nested-dialogs))]", "data-[nested-dialog-open]:scale-[calc(1-0.05*var(--nested-dialogs))]", "data-[nested-dialog-open]:brightness-95", sizes[options.size ?? "default"], options.class )) ) export const DialogHeader = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.div.class(cn("flex flex-col gap-1.5 pr-6", options.class)) export const DialogTitle = <Msg>(h: Html.H<Msg>, dialog: DialogParts, options: ClassOption = {}) => dialog.title(h.h2.class(cn("m-0 border-0 p-0 text-[16px] leading-snug font-semibold tracking-tight", options.class))) export const DialogDescription = <Msg>(h: Html.H<Msg>, dialog: DialogParts, options: ClassOption = {}) => dialog.description(h.p.class(cn("m-0 text-[13px] leading-normal text-muted-foreground", options.class))) /** The content between the header and the footer. `scrollable` lets it scroll when the dialog is taller than the screen. */ export const DialogBody = <Msg>( h: Html.H<Msg>, options: ClassOption & { readonly scrollable?: boolean | undefined } = {} ) => h.div.class(cn( "flex flex-col gap-3 text-[13px]", options.scrollable === true && "-mx-6 min-h-0 overflow-y-auto border-y px-6 py-4 text-muted-foreground", options.class )) export const DialogFooter = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.div.class(cn("flex flex-wrap items-center justify-end gap-2", options.class)) /** The small close button in the popup's corner. */ export const DialogCloseIcon = <Msg>( h: Html.H<Msg>, dialog: DialogParts, options: ClassOption & { readonly label?: string | undefined } = {} ) => dialog.close( h.button .class(cn( "absolute top-3.5 right-3.5 grid size-7 place-items-center rounded-sm text-muted-foreground", "transition-colors duration-150 hover:bg-accent hover:text-foreground", options.class )) .attr("aria-label", options.label ?? "Close") ).children( h.el("svg") .attrs({ class: "size-[15px]", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "aria-hidden": "true" }) .children(h.el("path").attr("d", "M6 6l12 12M18 6L6 18")) )Import it
import { DialogBackdrop, DialogViewport, DialogPopup, DialogHeader, DialogTitle, DialogDescription, DialogBody, DialogFooter, DialogCloseIcon } from "#ui/dialog"
Usage
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogCloseIcon,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogBasicMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: {},
RequestedCloseDialog: {}
})
export const DialogBasic = Html.component({
name: "DialogBasic",
model: Schema.Struct({ open: Schema.Boolean }),
message: DialogBasicMessage
}).make({
init: () => ({ open: false }),
update: {
RequestedOpenDialog: ($) => $.evolve({ open: true }),
RequestedCloseDialog: ($) => $.evolve({ open: false })
},
view: (h, model) =>
Dialog(h, {
props: { open: model.open },
onEmit: {
RequestedOpen: () => DialogBasicMessage.RequestedOpenDialog(),
RequestedClose: () => DialogBasicMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Share project"),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children("Share this project"),
DialogDescription(h, dialog).children(
"Anyone with the link can view the project. Only members can edit it."
)
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Cancel"),
dialog.close(h.button.class(buttonVariants())).children("Copy link")
),
DialogCloseIcon(h, dialog)
)
)
)
)
})
})
Examples
With a form
The draft lives in the Model. Enter submits, and initialFocus picks the first field.
Ada Lovelace · @ada
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const Profile = Schema.Struct({ name: Schema.String, username: Schema.String })
const DialogFormMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: {},
RequestedCloseDialog: {},
UpdatedName: { value: Schema.String },
UpdatedUsername: { value: Schema.String },
SubmittedProfile: {}
})
const labelClass = "flex flex-col gap-1.5 text-[13px] font-medium"
const inputClass =
"h-8.5 w-full rounded-md border border-input bg-background px-2.5 text-[13px] font-normal shadow-sm outline-none " +
"transition-[border-color,box-shadow] duration-150 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/20"
export const DialogForm = Html.component({
name: "DialogForm",
model: Schema.Struct({ open: Schema.Boolean, saved: Profile, draft: Profile }),
message: DialogFormMessage
}).make({
init: () => {
const profile = { name: "Ada Lovelace", username: "ada" }
return { open: false, saved: profile, draft: profile }
},
update: {
RequestedOpenDialog: ($) => $.evolve({ open: true, draft: $.model.saved }),
RequestedCloseDialog: ($) => $.evolve({ open: false }),
UpdatedName: ($, { value }) => $.evolve({ draft: { ...$.model.draft, name: value } }),
UpdatedUsername: ($, { value }) => $.evolve({ draft: { ...$.model.draft, username: value } }),
SubmittedProfile: ($) => $.evolve({ open: false, saved: $.model.draft })
},
view: (h, model) =>
Dialog(h, {
props: { open: model.open },
onEmit: {
RequestedOpen: () => DialogFormMessage.RequestedOpenDialog(),
RequestedClose: () => DialogFormMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div.class("flex flex-col items-center gap-3.5").children(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Edit profile"),
h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(`${model.saved.name} · @${model.saved.username}`),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog).children(
h.form.class("flex flex-col gap-4").on("submit", DialogFormMessage.SubmittedProfile()).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children("Edit profile"),
DialogDescription(h, dialog).children(
"Change how your name shows to the rest of the team."
)
),
h.label.class(labelClass).children(
"Name",
// Focus starts on the first field anyway; this picks the one to start on.
dialog.initialFocus(h.input.class(inputClass).attr("name", "name"))
.value(model.draft.name)
.on("input", ({ value }) => DialogFormMessage.UpdatedName({ value }))
),
h.label.class(labelClass).children(
"Username",
h.input.class(inputClass).attr("name", "username")
.value(model.draft.username)
.on("input", ({ value }) => DialogFormMessage.UpdatedUsername({ value }))
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Cancel"),
h.button.class(buttonVariants()).attr("type", "submit").children("Save changes")
)
)
)
)
)
)
})
})
Scrollable content
The popup never grows past the viewport: its body scrolls between a fixed header and footer.
Terms not accepted yet
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogBody,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogScrollableMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: {},
RequestedCloseDialog: {},
ClickedAccept: {}
})
const sections = [
["Using the service", "You may use the service only as these terms allow. You are responsible for what your account does and for keeping its password safe."],
["Your content", "What you upload stays yours. You give us the rights we need to store it, back it up and show it to the people you share it with."],
["Plans and billing", "Paid plans renew at the end of each period until you cancel. A cancelled plan stays active until the period it was paid for ends."],
["Acceptable use", "Don't use the service to break the law, to send spam, or to get at data or systems that aren't yours."],
["Availability", "We work to keep the service running, and we announce planned maintenance ahead of time on the status page."],
["Ending your account", "You can close your account at any time. We delete your content within thirty days of the account closing."],
["Changes to these terms", "When the terms change in a way that matters, we tell you by email at least two weeks before the change takes effect."]
] as const
export const DialogScrollable = Html.component({
name: "DialogScrollable",
model: Schema.Struct({ open: Schema.Boolean, accepted: Schema.Boolean }),
message: DialogScrollableMessage
}).make({
init: () => ({ open: false, accepted: false }),
update: {
RequestedOpenDialog: ($) => $.evolve({ open: true }),
RequestedCloseDialog: ($) => $.evolve({ open: false }),
ClickedAccept: ($) => $.evolve({ open: false, accepted: true })
},
view: (h, model) =>
Dialog(h, {
props: { open: model.open },
onEmit: {
RequestedOpen: () => DialogScrollableMessage.RequestedOpenDialog(),
RequestedClose: () => DialogScrollableMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div.class("flex flex-col items-center gap-3.5").children(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Read the terms"),
h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(model.accepted ? "Terms accepted" : "Terms not accepted yet"),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children("Terms of service"),
DialogDescription(h, dialog).children("Last updated 1 March 2026.")
),
DialogBody(h, { scrollable: true }).attr("tabindex", "0").children(
...sections.map(([heading, text]) => h.p.class("m-0 leading-relaxed").children(h.strong.class("text-foreground").children(heading), h.br, text))
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Decline"),
h.button.class(buttonVariants()).on("click", DialogScrollableMessage.ClickedAccept()).children("Accept")
)
)
)
)
)
})
})
Nested
A dialog drawn inside another's popup. The outer one steps back using --nested-dialogs.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogNestedMessage = UiSchema.TaggedEnum({
RequestedOpenSettings: {},
RequestedCloseSettings: {},
RequestedOpenConfirm: {},
RequestedCloseConfirm: {},
ClickedReset: {}
})
export const DialogNested = Html.component({
name: "DialogNested",
model: Schema.Struct({ settings: Schema.Boolean, confirm: Schema.Boolean, resets: Schema.Number }),
message: DialogNestedMessage
}).make({
init: () => ({ settings: false, confirm: false, resets: 0 }),
update: {
RequestedOpenSettings: ($) => $.evolve({ settings: true }),
RequestedCloseSettings: ($) => $.evolve({ settings: false, confirm: false }),
RequestedOpenConfirm: ($) => $.evolve({ confirm: true }),
RequestedCloseConfirm: ($) => $.evolve({ confirm: false }),
ClickedReset: ($) => $.evolve({ confirm: false, resets: (resets) => resets + 1 })
},
view: (h, model) =>
Dialog(h, {
key: "settings",
props: { open: model.settings },
onEmit: {
RequestedOpen: () => DialogNestedMessage.RequestedOpenSettings(),
RequestedClose: () => DialogNestedMessage.RequestedCloseSettings(),
Settled: () => undefined
},
view: (outerDialog) =>
h.div(
outerDialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Workspace settings"),
outerDialog.portal(h.dialog)?.children(
DialogBackdrop(h, outerDialog),
DialogViewport(h, outerDialog).children(
DialogPopup(h, outerDialog).children(
DialogHeader(h).children(
DialogTitle(h, outerDialog).children("Workspace settings"),
DialogDescription(h, outerDialog).children(
`Settings were reset ${model.resets} ${model.resets === 1 ? "time" : "times"}.`
)
),
DialogFooter(h, { class: "justify-between" }).children(
// Drawn inside the outer popup, so it is nested: it gets no backdrop
// of its own, and only it hears Escape while it is open.
Dialog(h, {
key: "confirm",
props: { open: model.confirm },
onEmit: {
RequestedOpen: () => DialogNestedMessage.RequestedOpenConfirm(),
RequestedClose: () => DialogNestedMessage.RequestedCloseConfirm(),
Settled: () => undefined
},
view: (innerDialog) =>
h.div(
innerDialog.trigger(h.button.class(buttonVariants({ variant: "ghost" }))).children(
"Reset to defaults"
),
innerDialog.portal(h.dialog)?.children(
DialogViewport(h, innerDialog).children(
DialogPopup(h, innerDialog, { size: "sm" }).children(
DialogHeader(h).children(
DialogTitle(h, innerDialog).children("Reset every setting?"),
DialogDescription(h, innerDialog).children(
"Members keep their access. Everything else goes back to its default."
)
),
DialogFooter(h).children(
innerDialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children(
"Cancel"
),
h.button.class(buttonVariants()).on("click", DialogNestedMessage.ClickedReset()).children("Reset")
)
)
)
)
)
}),
outerDialog.close(h.button.class(buttonVariants())).children("Done")
)
)
)
)
)
})
})
Modal, focus trap and non-modal
The modal prop decides whether the page behind takes presses and whether Tab stays inside.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const Mode = Schema.Literals(["modal", "trap-focus", "non-modal"])
const DialogModesMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: { mode: Mode },
RequestedCloseDialog: {},
ClickedPageButton: {}
})
const modes = [
{
mode: "modal",
modal: true,
label: "Modal",
text: "The page behind takes no presses and doesn't scroll, and Tab stays inside."
},
{
mode: "trap-focus",
modal: "trap-focus",
label: "Trap focus",
text: "Tab stays inside, but the page still scrolls and takes clicks. A press outside closes the dialog."
},
{
mode: "non-modal",
modal: false,
label: "Non-modal",
text: "The page stays usable. The dialog closes when you press outside or when focus leaves it."
}
] as const
export const DialogModes = Html.component({
name: "DialogModes",
model: Schema.Struct({ open: Schema.NullOr(Mode), presses: Schema.Number }),
message: DialogModesMessage
}).make({
init: () => ({ open: null, presses: 0 }),
update: {
RequestedOpenDialog: ($, { mode }) => $.evolve({ open: mode }),
RequestedCloseDialog: ($) => $.evolve({ open: null }),
ClickedPageButton: ($) => $.evolve({ presses: (presses) => presses + 1 })
},
view: (h, model) =>
h.div.class("flex flex-col items-center gap-3.5").children(
h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
...modes.map(({ label, modal, mode, text }) =>
Dialog(h, {
key: mode,
props: { open: model.open === mode, modal },
onEmit: {
RequestedOpen: () => DialogModesMessage.RequestedOpenDialog({ mode }),
RequestedClose: () => DialogModesMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children(label),
dialog.portal(h.dialog)?.children(
// Only the modal dims the page: the other two leave it in use.
modal === true && DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog, { size: "sm" }).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children(label),
DialogDescription(h, dialog).children(text)
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants())).children("Close")
)
)
)
)
)
})
)
),
h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
h.button.class(buttonVariants({ variant: "secondary" }))
.on("click", DialogModesMessage.ClickedPageButton())
.children("A button on the page"),
h.span.class("m-0 text-xs text-muted-foreground tabular-nums").children(`Pressed ${model.presses} times`)
)
)
})
Sizes and several triggers
One dialog opened from four triggers, in four sizes up to full screen.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogSizesMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: { triggerId: Schema.NullOr(Schema.String) },
RequestedCloseDialog: {}
})
const sizes = [
{ id: "dialog-size-sm", size: "sm", label: "Small" },
{ id: "dialog-size-default", size: "default", label: "Default" },
{ id: "dialog-size-lg", size: "lg", label: "Large" },
{ id: "dialog-size-full", size: "full", label: "Full screen" }
] as const
export const DialogSizes = Html.component({
name: "DialogSizes",
model: Schema.Struct({ open: Schema.Boolean, triggerId: Schema.NullOr(Schema.String) }),
message: DialogSizesMessage
}).make({
init: () => ({ open: false, triggerId: null }),
update: {
RequestedOpenDialog: ($, { triggerId }) => $.evolve({ open: true, triggerId }),
RequestedCloseDialog: ($) => $.evolve({ open: false })
},
view: (h, model) =>
// One dialog with a trigger per size: each trigger reports its id as it opens the dialog.
Dialog(h, {
props: { open: model.open, triggerId: model.triggerId },
onEmit: {
RequestedOpen: ({ triggerId }) => DialogSizesMessage.RequestedOpenDialog({ triggerId }),
RequestedClose: () => DialogSizesMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) => {
const current = sizes.find(({ id }) => id === dialog.triggerId) ?? sizes[1]
return h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
...sizes.map(({ id, label }) =>
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" })).attr("id", id)).children(label)
),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog, { size: current.size }).children(
DialogPopup(h, dialog, { size: current.size }).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children(`${current.label} dialog`),
DialogDescription(h, dialog).children(
current.size === "full"
? "The viewport drops its padding and the popup fills it."
: "The popup's width comes from the size option."
)
),
DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants())).children("Close")
)
)
)
)
)
}
})
})
Refusing a close
The consumer owns open, so a close with unsaved changes asks before it discards them.
No note yet
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
DialogBackdrop,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
DialogViewport
} from "#ui/dialog"
const DialogUnsavedChangesMessage = UiSchema.TaggedEnum({
RequestedOpenDialog: {},
RequestedCloseDialog: {},
UpdatedNote: { value: Schema.String },
ClickedKeepEditing: {},
ClickedDiscard: {},
ClickedSave: {}
})
const labelClass = "flex flex-col gap-1.5 text-[13px] font-medium"
const textareaClass =
"min-h-24 w-full resize-y rounded-md border border-input bg-background px-2.5 py-2 text-[13px] font-normal shadow-sm " +
"outline-none transition-[border-color,box-shadow] duration-150 focus-visible:border-ring focus-visible:ring-3 " +
"focus-visible:ring-ring/20"
export const DialogUnsavedChanges = Html.component({
name: "DialogUnsavedChanges",
model: Schema.Struct({
open: Schema.Boolean,
saved: Schema.String,
draft: Schema.String,
asking: Schema.Boolean
}),
message: DialogUnsavedChangesMessage
}).make({
init: () => ({ open: false, saved: "", draft: "", asking: false }),
update: {
RequestedOpenDialog: ($) => $.evolve({ open: true, draft: $.model.saved, asking: false }),
// The dialog stays open until `open` changes, so a close can be refused.
RequestedCloseDialog: ($) =>
$.model.draft === $.model.saved ? $.evolve({ open: false }) : $.evolve({ asking: true }),
UpdatedNote: ($, { value }) => $.evolve({ draft: value, asking: false }),
ClickedKeepEditing: ($) => $.evolve({ asking: false }),
ClickedDiscard: ($) => $.evolve({ open: false, asking: false }),
ClickedSave: ($) => $.evolve({ open: false, asking: false, saved: $.model.draft })
},
view: (h, model) =>
Dialog(h, {
props: { open: model.open },
onEmit: {
RequestedOpen: () => DialogUnsavedChangesMessage.RequestedOpenDialog(),
RequestedClose: () => DialogUnsavedChangesMessage.RequestedCloseDialog(),
Settled: () => undefined
},
view: (dialog) =>
h.div.class("flex flex-col items-center gap-3.5").children(
dialog.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children(
model.saved === "" ? "Add a note" : "Edit note"
),
h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(model.saved === "" ? "No note yet" : `Note: ${model.saved}`),
dialog.portal(h.dialog)?.children(
DialogBackdrop(h, dialog),
DialogViewport(h, dialog).children(
DialogPopup(h, dialog).children(
DialogHeader(h).children(
DialogTitle(h, dialog).children("Note"),
DialogDescription(h, dialog).children(
"Type something, then press Escape or click outside."
)
),
h.label.class(labelClass).children(
"Note",
h.textarea.class(textareaClass)
.value(model.draft)
.on("input", ({ value }) => DialogUnsavedChangesMessage.UpdatedNote({ value }))
),
model.asking
? h.div
.class(
"flex flex-wrap items-center justify-between gap-2.5 rounded-md border border-destructive/35 " +
"bg-destructive/8 px-3 py-2.5 text-[13px]"
)
.attr("role", "alert").children(
h.p.class("m-0 font-medium").children("Discard your changes?"),
h.div.class("flex gap-2").children(
h.button.class(buttonVariants({ variant: "outline", size: "sm" }))
.on("click", DialogUnsavedChangesMessage.ClickedKeepEditing())
.children("Keep editing"),
h.button.class(buttonVariants({ variant: "destructive", size: "sm" }))
.on("click", DialogUnsavedChangesMessage.ClickedDiscard())
.children("Discard")
)
)
: DialogFooter(h).children(
dialog.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Cancel"),
h.button.class(buttonVariants()).on("click", DialogUnsavedChangesMessage.ClickedSave()).children("Save")
)
)
)
)
)
})
})
Anatomy
The parts the view closure receives. Apply each one to an element of your own.
| Part | Description |
|---|---|
trigger | A <button> that opens it. Give it an id to tell several triggers apart. |
portal | The <dialog> in the top layer, around the parts below. undefined while closed, unless keepMounted. |
backdrop | A <div> that covers the page. undefined when nested, unless forceRenderBackdrop. |
viewport | A <div> that positions the popup. Optional. |
popup | A <div> with the content. |
title | A heading, <h1> to <h6>, that labels it. |
description | A <p> that describes it. |
close | A <button> that asks it to close. |
initialFocus | Any element, focused when it opens. |
finalFocus | Any element, focused when it closes instead of the trigger. |
API reference
Props
| Prop | Type | Description |
|---|---|---|
open | boolean | Whether the dialog shows. Required: the consumer owns it. |
modal | boolean | "trap-focus" | true by default. "trap-focus" keeps Tab inside but leaves the page usable, false does neither. |
disablePointerDismissal | boolean | A press outside the popup doesn't ask to close. |
triggerId | string | null | The id of the trigger the dialog is open for, when it has several. |
keepMounted | boolean | The portal stays in the page, hidden, while the dialog is closed. |
initialFocus | boolean | false leaves focus where it is when the dialog opens. |
finalFocus | boolean | false leaves focus where it is when the dialog closes. |
nested | boolean | false keeps a dialog drawn inside another one out of the nesting. |
holdExit | boolean | Keeps a closed dialog in its ending state while an exit animation of your own runs. |
topLayer | boolean | false draws the dialog in place, inside its positioned ancestor, and makes it non-modal. |
Events
| Event | Description |
|---|---|
RequestedOpen | A trigger was pressed. Carries the trigger's id, or null. |
RequestedClose | Carries the reason: trigger-press, outside-press, escape-key, close-press, focus-out or close-watcher. |
Settled | The transitions of an open or a close finished. |
Data attributes
| Attribute | Description |
|---|---|
data-popup-open | On the trigger while the popup is open for it. |
data-open / data-closed | On the backdrop, viewport and popup. |
data-starting-style | For the first frame after it opens, to transition from. |
data-ending-style | While it closes. It stays shown until the popup's transitions finish. |
data-nested | On the viewport and popup of one drawn inside another. |
data-nested-dialog-open | On the viewport and popup while a nested one is open. --nested-dialogs counts them. |
Related components
The components this page's file and examples import.
- Button: A native button that can stay focusable while disabled.