Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. 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"))
      )
    
  3. Import it

    import { DialogBackdrop, DialogViewport, DialogPopup, DialogHeader, DialogTitle, DialogDescription, DialogBody, DialogFooter, DialogCloseIcon } from "#ui/dialog"
    

Usage

Basic.ts
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

Scrollable content

The popup never grows past the viewport: its body scrolls between a fixed header and footer.

Terms not accepted yet

Nested

A dialog drawn inside another's popup. The outer one steps back using --nested-dialogs.

Modal, focus trap and non-modal

The modal prop decides whether the page behind takes presses and whether Tab stays inside.

Pressed 0 times

Sizes and several triggers

One dialog opened from four triggers, in four sizes up to full screen.

Refusing a close

The consumer owns open, so a close with unsaved changes asks before it discards them.

No note yet

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
triggerA <button> that opens it. Give it an id to tell several triggers apart.
portalThe <dialog> in the top layer, around the parts below. undefined while closed, unless keepMounted.
backdropA <div> that covers the page. undefined when nested, unless forceRenderBackdrop.
viewportA <div> that positions the popup. Optional.
popupA <div> with the content.
titleA heading, <h1> to <h6>, that labels it.
descriptionA <p> that describes it.
closeA <button> that asks it to close.
initialFocusAny element, focused when it opens.
finalFocusAny element, focused when it closes instead of the trigger.

API reference

Props

PropTypeDescription
openbooleanWhether the dialog shows. Required: the consumer owns it.
modalboolean | "trap-focus"true by default. "trap-focus" keeps Tab inside but leaves the page usable, false does neither.
disablePointerDismissalbooleanA press outside the popup doesn't ask to close.
triggerIdstring | nullThe id of the trigger the dialog is open for, when it has several.
keepMountedbooleanThe portal stays in the page, hidden, while the dialog is closed.
initialFocusbooleanfalse leaves focus where it is when the dialog opens.
finalFocusbooleanfalse leaves focus where it is when the dialog closes.
nestedbooleanfalse keeps a dialog drawn inside another one out of the nesting.
holdExitbooleanKeeps a closed dialog in its ending state while an exit animation of your own runs.
topLayerbooleanfalse draws the dialog in place, inside its positioned ancestor, and makes it non-modal.

Events

EventDescription
RequestedOpenA trigger was pressed. Carries the trigger's id, or null.
RequestedCloseCarries the reason: trigger-press, outside-press, escape-key, close-press, focus-out or close-watcher.
SettledThe transitions of an open or a close finished.

Data attributes

AttributeDescription
data-popup-openOn the trigger while the popup is open for it.
data-open / data-closedOn the backdrop, viewport and popup.
data-starting-styleFor the first frame after it opens, to transition from.
data-ending-styleWhile it closes. It stays shown until the popup's transitions finish.
data-nestedOn the viewport and popup of one drawn inside another.
data-nested-dialog-openOn the viewport and popup while a nested one is open. --nested-dialogs counts them.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.