Skip to main content

Alert Dialog

Confirm, inform, or report a result from an imperative call.

Props
Slots

Anatomy#

AlertDialog [component; no DOM]
└── content [slot]
    ├── header [slot]
    │   ├── icon [slot]
    │   └── wrapper [slot]
    └── footer [slot]
        ├── cancel [slot]
        └── action [slot]

<AlertDialog> mounts a host with no DOM of its own. Each call opens a dialog whose panel is content, with a header for the icon and copy, and a footer for the cancel and action buttons.

Usage#

Use Alert Dialog for a short confirm, info, warning, error, or success prompt opened from an event handler. Use Dialog when the task has its own trigger, body, and footer.

Mount <AlertDialog> once. It renders no children and holds no open state. Props on the host are live defaults for every dialog, and options passed to a method override them. Only undefined falls back to the host: false, 0, and null on a call are kept, so closable: false or align: null overrides a host default. A call before the host is mounted throws. On the server, a call returns a handle whose result() is already 'api'.

Give each host a unique id when more than one is mounted. A call without hostId goes to the host without an id and throws if only hosts with an id are mounted. Pass hostId to target <AlertDialog id="billing" />. Unmounting a host settles its open dialogs as 'api' and removes them immediately.

import { AlertDialog, Button, MoraineProvider } from 'moraine'

export function App() {
  return (
    <MoraineProvider>
      <AlertDialog maxWidth={420} />
      <Button
        onClick={() => {
          void AlertDialog.confirm({
            type: 'error',
            title: 'Delete this project?',
            description: 'This action cannot be undone.',
          })
        }}
      >
        Delete
      </Button>
    </MoraineProvider>
  )
}

Shared model#

Alert Dialog and Toast use the same options, actions, handle, and close reasons. Every instance is created with a static method that takes an options object.

interface Action {
  label?: JSX.Element
  variant?: ButtonT.Variants['variant']
  tone?: ButtonT.Variants['tone']
  leading?: IconT.Name
  disabled?: boolean
  class?: SlotClassValue
  style?: SlotStyleValue
  onClick?: (event?: MouseEvent) => void | Promise<unknown>
}

type CloseReason = 'action' | 'cancel' | 'dismiss' | 'timeout' | 'api'

interface Handle {
  id: string | number
  update: (options: UpdateOptions) => void
  close: () => void
  result: () => Promise<CloseReason>
}

action.onClick and cancel.onClick run before the instance closes. A returned promise shows loading on that button and disables the other one. A dialog also blocks Escape, the overlay, and the corner close button while that promise is pending. A toast pauses its timer. Calling event.preventDefault(), rejecting, or throwing leaves the instance open. A throw or rejection is reported with console.error. Otherwise the instance closes with 'action' or 'cancel'.

handle.close() and close(id) close with 'api'. Escape, the overlay, the corner close button, and a toast swipe close with 'dismiss' and do not run the cancel handler. A toast timer closes with 'timeout'. result() resolves once with that reason, and calling it again returns the same promise. The handle itself is not a promise.

const handle = AlertDialog.confirm({ title: 'Delete this project?', type: 'error' })
if ((await handle.result()) === 'action') {
  deleteProject()
}

update merges the next options into an open instance; options set to undefined are ignored. An update after close does not reopen it. Reusing an open id with the same method and render updates that instance in place. With a different method or render, the open dialog closes with 'api' and a new one opens. update replaces action and cancel as a whole, so include onClick again when the label changes.

Custom content has two entry points. AlertDialog.custom(render, options?) supplies a render for that call, either a static JSX.Element or a Component<DialogRenderProps>. The host’s <AlertDialog dialogRender={render} /> supplies a reusable render for every other call on that host. It must be a Component<DialogRenderProps>, because the host creates a fresh instance for each dialog. A .custom() render wins, then the host dialogRender, then the built-in layout. The render receives the id, the resolved options, pending(), action(), cancel(), close(), update(), titleId, and descriptionId. It replaces the inner content. The dialog keeps its overlay, focus trap, role="alertdialog", and panel width.

Methods#

show, info, warning, error, and success show the action button only. confirm shows cancel as well. Set cancel: true to use the locale label, cancel: { label } to change it, or cancel: false to hide it on a confirm. info, success, warning, and error set type, which picks the leading icon and its color; icon replaces the icon. The action button keeps its neutral tone, so pass action: { tone: 'danger' } for a destructive action.

close() closes every open dialog. close(id) closes one. close({ hostId }) closes every dialog on that host, and close({ hostId, id }) closes one dialog there. All settle with 'api' before the exit transition finishes. Unmounting a host also closes its dialogs with 'api' and calls onClose. AlertDialog.update(id, options) updates the open dialog with that id on any host, like handle.update.

AlertDialog.show(options)
AlertDialog.confirm(options)
AlertDialog.info(options)
AlertDialog.success(options)
AlertDialog.warning(options)
AlertDialog.error(options)
AlertDialog.custom(render, options?)
AlertDialog.update(id, options)
AlertDialog.close(id?)
AlertDialog.close({ hostId?, id? })

Defaults#

Action and cancel labels use the dialog message group (ok, cancel) when label is omitted. Set translations on the host or a call to change these labels and the corner button’s close label. closable shows the corner close button and defaults to false. title names the dialog. Only custom calls may omit it; they name the dialog with ariaLabel, or by putting titleId on the custom heading so aria-labelledby points at it.

Layout#

variant="subtle" gives the footer a top border and muted background. align="center" stacks the icon, title, and description and stretches the actions into an equal row. Both are props of the host and options of a call.

AlertDialog.confirm({
  title: 'Allow accessory to connect?',
  description: 'Do you want to allow the USB accessory to connect to this device?',
  icon: 'i-lucide:bluetooth',
  align: 'center',
  variant: 'subtle',
  action: { label: 'Allow' },
  cancel: { label: "Don't allow" },
})

Dismissal#

A pointer press on the overlay dismisses the dialog when closeOnOverlayClick is true (default false). Escape dismisses it unless closeOnEscape is false (default true). The corner close button appears when closable is true. Escape closes only the topmost dialog. All three settle with 'dismiss'.

transition on the host sets the default for every dialog on it, and the same option in a call overrides it. transition: false unmounts a closed dialog without its exit animation.

Custom content#

custom is for a layout the built-in title, description, and actions cannot express. Call props.action() and props.cancel() so loading, dismissal, and result() stay shared with the default buttons.

AlertDialog.custom(
  (props) => {
    const [name, setName] = createSignal('')
    return (
      <>
        <h2 id={props.titleId}>{props.options.title}</h2>
        <Input value={name()} onValueChange={setName} />
        <Button variant="outline" onClick={(event) => void props.cancel(event)}>
          Cancel
        </Button>
        <Button
          tone="danger"
          disabled={name() !== 'moraine'}
          autoLoading
          onClick={(event) => props.action(event)}
        >
          Delete
        </Button>
      </>
    )
  },
  { title: 'Delete repository?', action: { onClick: deleteRepo } },
)

Examples#

Revoke an API key#

confirm returns a handle. Wait on result() and continue when the reason is 'action'.

import { AlertDialog, Badge, Button } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function AlertConfirm() {
  const [revoked, setRevoked] = createSignal(false)

  const confirmRevoke = async () => {
    const result = await AlertDialog.confirm({
      title: 'Revoke secret API key?',
      description:
        'Active background workers and webhook integrations using "Production Sync Key" will immediately lose API access.',
      action: {
        tone: 'danger',
        label: 'Revoke key',
        onClick: async () => {
          await new Promise((resolve) => setTimeout(resolve, 600))
        },
      },
      cancel: { label: 'Keep key' },
    }).result()
    if (result === 'action') {
      setRevoked(true)
    }
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl bg-card/50 flex flex-col gap-3 max-w-md w-full">
      <div class="flex items-center justify-between">
        <div class="flex gap-2 items-center">
          <span class="text-sm font-medium">Production Sync Key</span>
          <Show
            when={!revoked()}
            fallback={
              <Badge variant="outline" class="text-xs text-muted-foreground">
                Revoked
              </Badge>
            }
          >
            <Badge variant="outline" class="text-xs text-success border-success/30 bg-success/10">
              Active
            </Badge>
          </Show>
        </div>
        <span class="text-xs text-muted-foreground font-mono">sk_live_•••94f2</span>
      </div>
      <p class="text-xs text-muted-foreground">
        Created on Oct 12, 2026. Last used 2 minutes ago by ingest worker.
      </p>
      <div class="pt-2 b-border b-t-1 flex items-center justify-between">
        <span class="text-xs text-muted-foreground">
          {revoked() ? 'Key access has been revoked.' : 'Full access to sync endpoints.'}
        </span>
        <Show
          when={!revoked()}
          fallback={
            <Button size="sm" variant="ghost" onClick={() => setRevoked(false)}>
              Restore key
            </Button>
          }
        >
          <Button
            size="sm"
            variant="outline"
            class="text-danger border-danger/30 hover:text-danger hover:bg-danger/10"
            onClick={() => void confirmRevoke()}
          >
            Revoke key
          </Button>
        </Show>
      </div>
    </div>
  )
}

Show info, warning, error, and success#

Each method sets the type, which picks the icon and its color. Cancel stays hidden until you set cancel.

import { AlertDialog, Button } from 'moraine'

export function AlertTypes() {
  return (
    <div class="flex flex-wrap gap-3 items-center">
      <Button
        variant="outline"
        leading="i-lucide:refresh-cw"
        onClick={() =>
          void AlertDialog.info({
            title: 'System update available',
            description:
              'Version 2.5.0 has been downloaded in the background. Restart your workspace to apply performance improvements.',
            action: { label: 'Restart now' },
          })
        }
      >
        Update ready
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:alert-triangle"
        onClick={() =>
          void AlertDialog.warning({
            title: 'Storage threshold reached',
            description:
              'Your team organization has utilized 92% of allocated disk capacity. Automatic snapshots may be throttled soon.',
            action: { label: 'Manage quota' },
          })
        }
      >
        Storage warning
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:alert-circle"
        onClick={() =>
          void AlertDialog.error({
            title: 'Pipeline deployment failed',
            description:
              'Worker process exited with code 137 (Out of Memory) during asset minification. Inspect build logs for diagnostics.',
            action: { label: 'View logs' },
          })
        }
      >
        Build failure
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:check"
        onClick={() =>
          void AlertDialog.success({
            title: 'Database snapshot completed',
            description:
              'Encrypted database backup "prod_db_20261013" was successfully uploaded to cold storage.',
            action: { label: 'Done' },
          })
        }
      >
        Backup created
      </Button>
    </div>
  )
}

Update a publish confirm when checks finish#

update changes the open dialog when background verification passes. Include onClick again, because the next action replaces the previous one.

import { AlertDialog, Badge, Button } from 'moraine'
import { createSignal, onCleanup, Show } from 'solid-js'

export function AlertPublish() {
  const [stage, setStage] = createSignal<'running' | 'passed' | 'published'>('running')
  const [publishedAt, setPublishedAt] = createSignal<string>()
  let timer: ReturnType<typeof setTimeout> | undefined

  onCleanup(() => {
    if (timer) {
      clearTimeout(timer)
    }
  })

  const reset = () => {
    if (timer) {
      clearTimeout(timer)
    }
    setStage('running')
    setPublishedAt(undefined)
  }

  const publishRelease = async () => {
    await new Promise((resolve) => setTimeout(resolve, 800))
    setStage('published')
    setPublishedAt(new Date().toLocaleTimeString())
  }

  const publish = () => {
    if (stage() === 'passed') {
      void AlertDialog.confirm({
        title: 'Publish release v2.4.0?',
        description: 'All 18 automated checks passed. Ready to deploy to production.',
        maxWidth: 440,
        action: { label: 'Publish release', onClick: publishRelease },
        cancel: { label: 'Cancel' },
      })
      return
    }

    const dialog = AlertDialog.confirm({
      title: 'Publish release v2.4.0?',
      description:
        'Automated checks are still running (1 pending: e2e-regression). Publishing now will bypass remaining verification.',
      maxWidth: 440,
      action: { label: 'Publish anyway', tone: 'danger', onClick: publishRelease },
      cancel: { label: 'Wait for checks' },
    })

    let settled = false
    void dialog.result().then(() => {
      settled = true
      if (timer) {
        clearTimeout(timer)
      }
    })

    timer = setTimeout(() => {
      setStage('passed')
      if (settled) {
        return
      }
      dialog.update({
        title: 'All checks passed — Publish release v2.4.0?',
        description:
          'Automated checks finished successfully (18/18 passed). Ready to deploy to production.',
        type: 'default',
        action: { label: 'Publish release', onClick: publishRelease },
        cancel: { label: 'Cancel' },
      })
    }, 2000)
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl bg-card/50 flex flex-col gap-3 max-w-lg w-full">
      <div class="flex items-center justify-between">
        <div class="flex gap-2 items-center">
          <span class="text-sm font-semibold">Release v2.4.0</span>
          <Show when={stage() === 'running'}>
            <Badge variant="outline" class="text-xs text-warning border-warning/30 bg-warning/10">
              <span class="mr-1 rounded-full bg-warning size-1.5 inline-block animate-pulse" />1
              check running
            </Badge>
          </Show>
          <Show when={stage() === 'passed'}>
            <Badge variant="outline" class="text-xs text-success border-success/30 bg-success/10">
              <span class="mr-1 rounded-full bg-success size-1.5 inline-block" />
              All checks passed
            </Badge>
          </Show>
          <Show when={stage() === 'published'}>
            <Badge variant="solid" class="text-xs">
              Published
            </Badge>
          </Show>
        </div>
        <span class="text-xs text-muted-foreground font-mono">main@8f3a1d</span>
      </div>

      <p class="text-xs text-muted-foreground">
        <Show when={stage() === 'running'}>
          Pipeline: Unit tests & build passed, E2E regression check in progress (~2s).
        </Show>
        <Show when={stage() === 'passed'}>
          Pipeline: 18/18 tests passed. Artifact verified for production deployment.
        </Show>
        <Show when={stage() === 'published'}>
          Deployed to production cluster (us-east-1) at {publishedAt()}.
        </Show>
      </p>

      <div class="pt-2 b-border b-t-1 flex items-center justify-between">
        <div class="text-xs text-muted-foreground">
          <Show when={stage() === 'running'}>
            Click publish to open confirmation while checks run.
          </Show>
          <Show when={stage() === 'passed'}>Checks completed. Safe to deploy.</Show>
          <Show when={stage() === 'published'}>Release live in production.</Show>
        </div>
        <div class="flex gap-2 items-center">
          <Show when={stage() !== 'running'}>
            <Button size="sm" variant="ghost" onClick={reset}>
              Reset demo
            </Button>
          </Show>
          <Button
            size="sm"
            variant={stage() === 'published' ? 'outline' : 'solid'}
            disabled={stage() === 'published'}
            leading={stage() === 'published' ? 'i-lucide:check' : 'i-lucide:rocket'}
            onClick={publish}
          >
            {stage() === 'published' ? 'Deployed' : 'Publish release'}
          </Button>
        </div>
      </div>
    </div>
  )
}

Authorize a hardware security key#

align="center" stacks the icon and copy. variant="subtle" gives the action row a muted background and a top border.

import { AlertDialog, Badge, Button } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function AlertCenter() {
  const [status, setStatus] = createSignal<'idle' | 'allowed' | 'blocked'>('idle')

  const connect = async () => {
    const result = await AlertDialog.confirm({
      title: 'Allow security key to connect?',
      description:
        'Hardware key "YubiKey 5C NFC" is requesting permission to authenticate and read security credentials.',
      icon: 'i-lucide:usb',
      align: 'center',
      variant: 'subtle',
      maxWidth: 380,
      action: { label: 'Allow key' },
      cancel: { label: "Don't allow" },
    }).result()
    setStatus(result === 'action' ? 'allowed' : 'blocked')
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl bg-card/50 flex flex-col gap-3 max-w-md w-full">
      <div class="flex items-center justify-between">
        <div class="flex gap-2 items-center">
          <span class="text-sm font-medium">YubiKey 5C NFC</span>
          <Show when={status() === 'idle'}>
            <Badge variant="outline" class="text-xs text-muted-foreground">
              Not connected
            </Badge>
          </Show>
          <Show when={status() === 'allowed'}>
            <Badge variant="outline" class="text-xs text-success border-success/30 bg-success/10">
              Connected
            </Badge>
          </Show>
          <Show when={status() === 'blocked'}>
            <Badge variant="outline" class="text-xs text-danger border-danger/30 bg-danger/10">
              Blocked
            </Badge>
          </Show>
        </div>
        <span class="text-xs text-muted-foreground font-mono">USB-C / NFC</span>
      </div>
      <p class="text-xs text-muted-foreground">
        Hardware FIDO2 / WebAuthn token used for multi-factor authentication.
      </p>
      <div class="pt-2 b-border b-t-1 flex items-center justify-between">
        <span class="text-xs text-muted-foreground">
          {status() === 'idle' && 'Waiting for authorization...'}
          {status() === 'allowed' && 'Hardware credentials authorized.'}
          {status() === 'blocked' && 'Access request denied by user.'}
        </span>
        <Button size="sm" variant="outline" onClick={() => void connect()}>
          {status() === 'allowed' ? 'Reconnect' : 'Connect key'}
        </Button>
      </div>
    </div>
  )
}

Type the name to confirm#

.custom() replaces the inner content and still uses props.action() for the pending state and the close reason.

import { AlertDialog, Button, Input } from 'moraine'
import { createSignal } from 'solid-js'

export function AlertCustom() {
  const remove = () => {
    void AlertDialog.custom(
      (props) => {
        const [name, setName] = createSignal('')
        return (
          <div class="flex flex-col gap-4">
            <h2 id={props.titleId} class="text-lg text-foreground font-semibold">
              {props.options.title}
            </h2>
            <p id={props.descriptionId} class="text-sm text-muted-foreground">
              {props.options.description}
            </p>
            <Input value={name()} placeholder="Repository name" onValueChange={setName} />
            <div class="flex gap-2 justify-end">
              <Button
                variant="outline"
                disabled={props.pending() !== undefined}
                onClick={(event) => void props.cancel(event)}
              >
                Cancel
              </Button>
              <Button
                variant="solid"
                tone="danger"
                disabled={name() !== 'moraine'}
                autoLoading
                onClick={(event) => props.action(event)}
              >
                Delete
              </Button>
            </div>
          </div>
        )
      },
      {
        title: 'Delete repository?',
        description: 'Type moraine to confirm. This removes the repository and its history.',
        action: {
          onClick: async () => {
            await new Promise((resolve) => setTimeout(resolve, 400))
          },
        },
      },
    )
  }

  return (
    <Button variant="solid" tone="danger" leading="i-lucide:trash-2" onClick={remove}>
      Delete repository
    </Button>
  )
}

API Reference#

Props#

Props for the AlertDialog host component.

Prop