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/alert-dialog.ts
    import type { Html } from "@effect/ui/html"
    import type { AlertDialogParts } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const sizes = {
      sm: "w-full max-w-[340px]",
      default: "w-full max-w-[440px]"
    } as const
    
    export type AlertDialogSize = keyof typeof sizes
    
    /** The layer that dims the page. A press on it doesn't close an alert dialog. */
    export const AlertDialogBackdrop = <Msg>(h: Html.H<Msg>, alertDialog: AlertDialogParts, options: ClassOption = {}) =>
      alertDialog.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. */
    export const AlertDialogViewport = <Msg>(h: Html.H<Msg>, alertDialog: AlertDialogParts, options: ClassOption = {}) =>
      alertDialog.viewport(h.div.class(cn("pointer-events-none fixed inset-0 grid place-items-center p-4", options.class)))
    
    export const AlertDialogPopup = <Msg>(
      h: Html.H<Msg>,
      alertDialog: AlertDialogParts,
      options: ClassOption & { readonly size?: AlertDialogSize | undefined } = {}
    ) =>
      alertDialog.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] duration-200 ease-out",
          "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
          "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
          sizes[options.size ?? "default"],
          options.class
        ))
      )
    
    export const AlertDialogHeader = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.div.class(cn("flex flex-col gap-1.5", options.class))
    
    export const AlertDialogTitle = <Msg>(h: Html.H<Msg>, alertDialog: AlertDialogParts, options: ClassOption = {}) =>
      alertDialog.title(
        h.h2.class(cn("m-0 border-0 p-0 text-[16px] leading-snug font-semibold tracking-tight", options.class))
      )
    
    export const AlertDialogDescription = <Msg>(h: Html.H<Msg>, alertDialog: AlertDialogParts, options: ClassOption = {}) =>
      alertDialog.description(
        h.p.class(cn(
          "m-0 text-[13px] leading-normal text-muted-foreground",
          "[&_code]:rounded-xs [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-xs " +
            "[&_code]:text-foreground",
          options.class
        ))
      )
    
    export const AlertDialogFooter = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.div.class(cn("flex flex-wrap items-center justify-end gap-2", options.class))
    
  3. Import it

    import { AlertDialogBackdrop, AlertDialogViewport, AlertDialogPopup, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter } from "#ui/alert-dialog"
    

Usage

Confirm a destructive action.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { AlertDialog } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  AlertDialogBackdrop,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogPopup,
  AlertDialogTitle,
  AlertDialogViewport
} from "#ui/alert-dialog"

const AlertDialogBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenAlertDialog: {},
  RequestedCloseAlertDialog: {},
  ClickedDelete: {},
  ClickedRestore: {}
})

export const AlertDialogBasic = Html.component({
  name: "AlertDialogBasic",
  model: Schema.Struct({ open: Schema.Boolean, deleted: Schema.Boolean }),
  message: AlertDialogBasicMessage
}).make({
  init: () => ({ open: false, deleted: false }),
  update: {
    RequestedOpenAlertDialog: ($) => $.evolve({ open: true }),
    RequestedCloseAlertDialog: ($) => $.evolve({ open: false }),
    ClickedDelete: ($) => $.evolve({ open: false, deleted: true }),
    ClickedRestore: ($) => $.evolve({ deleted: false })
  },
  view: (h, model) =>
    model.deleted
      ? h.div.class("flex flex-col items-center gap-3.5").children(
        h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children("The project was deleted."),
        h.button.class(buttonVariants({ variant: "outline" }))
          .on("click", AlertDialogBasicMessage.ClickedRestore())
          .children("Undo")
      )
      : AlertDialog(h, {
        props: { open: model.open },
        onEmit: {
          RequestedOpen: () => AlertDialogBasicMessage.RequestedOpenAlertDialog(),
          RequestedClose: () => AlertDialogBasicMessage.RequestedCloseAlertDialog(),
          Settled: () => undefined
        },
        view: (alertDialog) =>
          h.div(
            alertDialog.trigger(h.button.class(buttonVariants({ variant: "destructive" }))).children(
              "Delete project"
            ),
            alertDialog.portal(h.dialog)?.children(
              AlertDialogBackdrop(h, alertDialog),
              AlertDialogViewport(h, alertDialog).children(
                AlertDialogPopup(h, alertDialog).children(
                  AlertDialogHeader(h).children(
                    AlertDialogTitle(h, alertDialog).children("Delete this project?"),
                    AlertDialogDescription(h, alertDialog).children(
                      "The project, its deployments and its logs are removed for everyone. You can't undo this."
                    )
                  ),
                  AlertDialogFooter(h).children(
                    // Focus starts on the safe choice, and a press outside doesn't close an alert dialog.
                    alertDialog.initialFocus(
                      alertDialog.close(h.button.class(buttonVariants({ variant: "outline" })))
                    ).children("Cancel"),
                    h.button.class(buttonVariants({ variant: "destructive" }))
                      .on("click", AlertDialogBasicMessage.ClickedDelete())
                      .children("Delete project")
                  )
                )
              )
            )
          )
      })
})

Examples

Async confirm

The dialog stays open, and refuses Escape, until the request finishes.

Signed in on 4 devices

Discard changes

A small confirmation in front of a draft the user would lose.

Type to confirm

The confirm button is disabled until the name matches, and Enter submits.

You own acme-production

One dialog for a list

Each row's trigger reports its id, so one alert dialog serves every row.

  • CI deployssk_live_8f2a…
  • Stagingsk_test_c41d…
  • Ada's laptopsk_live_02be…

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 alert dialog shows. Required: the consumer owns it.
triggerIdstring | nullThe id of the trigger it is open for, when it has several.
keepMountedbooleanThe portal stays in the page, hidden, while it is closed.
initialFocusbooleanfalse leaves focus where it is when it opens.
finalFocusbooleanfalse leaves focus where it is when it closes.
holdExitbooleanKeeps it in its ending state while an exit animation of your own runs.

Events

EventDescription
RequestedOpenA trigger was pressed. Carries the trigger's id, or null.
RequestedCloseCarries the reason: trigger-press, escape-key, close-press or close-watcher. Never outside-press.
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.