Components
Alert dialog
A question that needs an answer before anything else, on the #262626 overlay surface over a Black scrim: a Funnel Display title, one line saying what happens, Cancel and the action (red for what removes something).
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add alert-dialog<script type="module" src="/spyglass-ds/elements/alert-dialog.js"></script>Usage
Confirming what can't be undone: deleting a board, removing a teammate, canceling a plan. Say exactly what goes away.
Never
- Confirming what can be undone: do it and offer undo
- A scrim that closes it: only a choice does
- A vague action label ("OK", "Yes"): name the action ("Delete board")
- A shadow around the window
Adds with it: button
Props
The web component takes the same as attributes or properties (<spyglass-alert-dialog>); title is heading there.
<AlertDialog>
| Prop | Type | Default |
|---|---|---|
title | string The question. | |
description | string One line saying what happens. | |
action | string The action button's label. | |
cancel | string The Cancel button's label. | 'Cancel' |
danger | boolean The red fill for the action (the default); false draws the White primary. | true |
open | boolean | |
defaultOpen | boolean | false |
onOpenChange | (open: boolean) => void | |
onConfirm | () => void | |
onCancel | () => void | |
children | ReactNode More about what happens, under the line. |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { Button } from '@/react/components/ui/Button'
import { AlertDialog } from '@/react/components/ui/AlertDialog'
// Deleting a board asks first: focus starts on Cancel, and only a choice closes it. The line under says what happened.
export default function Delete() {
const [open, setOpen] = useState(false)
const [note, setNote] = useState('Acme summer ads: 48 saved creatives.')
return (
<div className="flex min-h-72 flex-col items-center justify-center gap-3">
<Button variant="secondary" onClick={() => setOpen(true)}>Delete board</Button>
<p className="type-caption text-fg-muted" aria-live="polite">{note}</p>
<AlertDialog
open={open}
onOpenChange={setOpen}
title="Delete this board?"
description="Acme summer ads and its 48 saved creatives go away for everyone on the team. This can't be undone."
action="Delete board"
onConfirm={() => setNote('Board deleted.')}
onCancel={() => setNote('Kept the board.')}
/>
</div>
)
}<!-- Deleting a board asks first: focus starts on Cancel, and only a choice closes it. The line under says what happened. -->
<div class="flex min-h-72 flex-col items-center justify-center gap-3">
<spyglass-button id="delete-board" variant="secondary">Delete board</spyglass-button>
<p id="delete-board-note" class="type-caption text-fg-muted" aria-live="polite">Acme summer ads: 48 saved creatives.</p>
<spyglass-alert-dialog id="delete-board-dialog" heading="Delete this board?" description="Acme summer ads and its 48 saved creatives go away for everyone on the team. This can't be undone." action="Delete board"></spyglass-alert-dialog>
</div>
<script type="module">
const dialog = document.getElementById('delete-board-dialog')
const note = document.getElementById('delete-board-note')
document.getElementById('delete-board').addEventListener('click', () => { dialog.open = true })
dialog.addEventListener('confirm', () => { note.textContent = 'Board deleted.' })
dialog.addEventListener('cancel', () => { note.textContent = 'Kept the board.' })
</script>Source
'use client'
import { useEffect, useId, useRef, type ReactNode, type SyntheticEvent } from 'react'
import { Button } from '@/react/components/ui/Button'
import { useControllable } from '@/react/hooks/useControllable'
// shadcn's alert dialog in the brand: a question that needs an answer before anything else, on the #262626 overlay
// surface in a neutral hairline with the brand corner and no shadow, over a Black scrim. A Funnel Display title, one
// line saying what happens, then Cancel (secondary) and the action: the red fill for what removes something
// (`danger`, the default), the White primary otherwise. Focus starts on Cancel; the scrim does nothing, so only a
// choice closes it; Escape cancels and focus returns to what opened it. It comes in over 360ms (a fade and a scale
// from 0.96, centered, ease-out) and leaves at once; reduced motion keeps the fade. `open` with `onOpenChange` (or
// `defaultOpen` alone); `onConfirm` and `onCancel` say which was chosen.
export interface AlertDialogProps {
/** The question. */
title: string
/** One line saying what happens. */
description: string
/** The action button's label. */
action: string
/** The Cancel button's label. */
cancel?: string
/** The red fill for the action (the default); false draws the White primary. */
danger?: boolean
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
onConfirm?: () => void
onCancel?: () => void
/** More about what happens, under the line. */
children?: ReactNode
}
// The button's md shape with the danger fill (the seed button has no danger variant).
export const DANGER_BUTTON = 'inline-flex h-control-md shrink-0 cursor-pointer items-center justify-center gap-2 rounded-control px-4 whitespace-nowrap select-none type-ui-strong bg-action-danger text-ds-neutral-15 transition-[background-color] duration-160 ease-out hover:bg-action-danger-hover'
export function AlertDialog({ title, description, action, cancel = 'Cancel', danger = true, open: openProp, defaultOpen = false, onOpenChange, onConfirm, onCancel, children }: AlertDialogProps) {
const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)
const dialog = useRef<HTMLDialogElement | null>(null)
const id = useId()
const returnTo = useRef<HTMLElement | null>(null)
const mounted = useRef(false)
useEffect(() => {
const d = dialog.current
const first = !mounted.current
mounted.current = true
if (!d) return
if (open) {
if (d.open) return
returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
d.showModal()
d.querySelector<HTMLElement>('[data-cancel]')?.focus()
}
else if (!first) {
if (d.open) d.close()
returnTo.current?.focus({ preventScroll: true })
returnTo.current = null
}
}, [open])
function cancelled(event: SyntheticEvent) {
event.preventDefault()
onCancel?.()
setOpen(false)
}
function choose(confirmed: boolean) {
if (confirmed) onConfirm?.()
else onCancel?.()
setOpen(false)
}
return (
<>
<style href="ds-alert-dialog" precedence="ds">{css}</style>
<dialog data-ds="alert-dialog" ref={dialog} className="ds-alert" role="alertdialog" aria-labelledby={`${id}-title`} aria-describedby={`${id}-text`} onCancel={cancelled}>
<h2 id={`${id}-title`} className="type-heading-3">{title}</h2>
<p id={`${id}-text`} className="mt-3 type-ui text-fg-muted">{description}</p>
{children}
<div className="mt-6 flex flex-wrap justify-end gap-2">
<Button data-cancel variant="secondary" onClick={() => choose(false)}>{cancel}</Button>
{danger
? <button type="button" className={DANGER_BUTTON} onClick={() => choose(true)}>{action}</button>
: <Button onClick={() => choose(true)}>{action}</Button>}
</div>
</dialog>
</>
)
}
export default AlertDialog
const css = `
.ds-alert { width: min(440px, calc(100vw - 32px)); margin: auto; padding: var(--ds-space-xl); border: var(--ds-border-hairline) solid var(--ds-color-edge); border-radius: var(--ds-radius-container); background: var(--ds-color-surface-raised); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-alert::backdrop { background: var(--ds-color-scrim); }
.ds-alert[open] { animation: ds-alert-in var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-alert[open]::backdrop { animation: ds-alert-fade var(--ds-duration-entrance) var(--ds-easing-out); }
@keyframes ds-alert-in { from { opacity: 0; transform: scale(0.96); } }
@keyframes ds-alert-fade { from { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-alert[open] { animation-name: ds-alert-fade; } }
`'use client'
import { useCallback, useRef, useState } from 'react'
// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
const [inner, setInner] = useState<T>(defaultValue)
const controlled = value !== undefined
const current = controlled ? value : inner
const ref = useRef(onChange)
ref.current = onChange
const set = useCallback((next: T) => {
if (!controlled) setInner(next)
ref.current?.(next)
}, [controlled])
return [current, set] as const
}import { html, type LitElement, type PropertyValues } from 'lit'
import { DsElement, define, tag, uid } from '@/elements/lib/element'
import { html as staticHtml } from 'lit/static-html.js'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'
// The button's md shape with the danger fill (the seed button has no danger variant), as in AlertDialog.tsx.
const DANGER_BUTTON = 'inline-flex h-control-md shrink-0 cursor-pointer items-center justify-center gap-2 rounded-control px-4 whitespace-nowrap select-none type-ui-strong bg-action-danger text-ds-neutral-15 transition-[background-color] duration-160 ease-out hover:bg-action-danger-hover'
// AlertDialog.tsx as <spyglass-alert-dialog>: a question that needs an answer before anything else, on the #262626
// overlay surface in a neutral hairline with the brand corner, over a Black scrim. A Funnel Display heading, one line
// saying what happens, then Cancel (secondary) and the action: the red fill for what removes something (`danger`, the
// default), the White primary with danger="false". Focus starts on Cancel; the scrim does nothing, so only a choice
// closes it; Escape cancels and focus returns to what opened it. It comes in over 360ms (a fade and a scale from 0.96)
// and leaves at once. React's `open` with `onOpenChange` is the `open` attribute with `open-change`; React's `title`
// is `heading` (title is HTML's tooltip attribute); `cancel` is the Cancel button's label, and the `cancel` event fires
// when it is chosen (or on Escape).
/**
* @summary A question that needs an answer before anything else.
* @slot - More about what happens, under the line.
* @fires confirm - The action was chosen.
* @fires cancel - Cancel was chosen, or Escape pressed.
* @fires open-change - It opened or closed (detail.value).
*/
export class AlertDialog extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { heading: {}, description: {}, action: {}, cancel: {}, danger: { converter: { fromAttribute: (v: string | null) => v !== 'false' } }, open: { type: Boolean, reflect: true } }
/** The question (React's `title`). */
heading = ''
/** One line saying what happens. */
description = ''
/** The action button's label. */
action = ''
/** The Cancel button's label. */
cancel = 'Cancel'
/** The red fill for the action; danger="false" draws the White primary. */
danger = true
open = false
private dialogId = uid('alert')
private returnTo: HTMLElement | null = null
private get dialog() {
return this.renderRoot.querySelector('dialog')
}
private async show() {
const d = this.dialog
if (!d || d.open) return
let a = document.activeElement as Element | null
while (a?.shadowRoot?.activeElement) a = a.shadowRoot.activeElement
this.returnTo = a instanceof HTMLElement ? a : null
d.showModal()
const cancel = d.querySelector<LitElement>('[data-cancel]')
await cancel?.updateComplete
;(cancel?.shadowRoot?.querySelector('button') ?? cancel)?.focus()
}
private close() {
if (this.dialog?.open) this.dialog.close()
this.returnTo?.focus({ preventScroll: true })
this.returnTo = null
}
protected updated(changed: PropertyValues<this>) {
super.updated(changed)
if (!changed.has('open')) return
if (this.open) void this.show()
else if (changed.get('open') !== undefined) this.close()
}
private setOpen(open: boolean) {
if (this.open === open) return
this.open = open
this.emit('open-change', { value: open })
}
private onCancel = (event: Event) => {
event.preventDefault()
this.emit('cancel')
this.setOpen(false)
}
private choose(confirmed: boolean) {
this.emit(confirmed ? 'confirm' : 'cancel')
this.setOpen(false)
}
render() {
const button = tag('button')
return html`<dialog data-ds="alert-dialog" class="ds-alert" role="alertdialog" aria-labelledby=${`${this.dialogId}-title`} aria-describedby=${`${this.dialogId}-text`} @cancel=${this.onCancel}>
<h2 id=${`${this.dialogId}-title`} class="type-heading-3">${this.heading}</h2>
<p id=${`${this.dialogId}-text`} class="mt-3 type-ui text-fg-muted">${this.description}</p>
<slot></slot>
<div class="mt-6 flex flex-wrap justify-end gap-2">
${staticHtml`<${button} data-cancel variant="secondary" @click=${() => this.choose(false)}>${this.cancel}</${button}>`}${this.danger
? html`<button type="button" class=${DANGER_BUTTON} @click=${() => this.choose(true)}>${this.action}</button>`
: staticHtml`<${button} @click=${() => this.choose(true)}>${this.action}</${button}>`}
</div>
</dialog>`
}
}
define('alert-dialog', AlertDialog)/* AlertDialog.tsx's styles. */
.ds-alert { width: min(440px, calc(100vw - 32px)); margin: auto; padding: var(--ds-space-xl); border: var(--ds-border-hairline) solid var(--ds-color-edge); border-radius: var(--ds-radius-container); background: var(--ds-color-surface-raised); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-alert::backdrop { background: var(--ds-color-scrim); }
.ds-alert[open] { animation: ds-alert-in var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-alert[open]::backdrop { animation: ds-alert-fade var(--ds-duration-entrance) var(--ds-easing-out); }
@keyframes ds-alert-in { from { opacity: 0; transform: scale(0.96); } }
@keyframes ds-alert-fade { from { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-alert[open] { animation-name: ds-alert-fade; } }Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here), Funnel Display titles, DM Sans lines, the White primary and #262626 secondary buttons. shadcn's alert dialog for anatomy, focus and keys..