Consequence List Alert Dialog
Confirmation that lists every effect with its count, split into what is lost and what is kept, and holds the confirm button until an acknowledgement is ticked. Use it before deleting an account, workspace or dataset.
How it differs. The body is a framed list of counted effects in a lost group and a quieter kept band, and the confirm button stays gated behind one acknowledgement checkbox that it points to when pressed early.
Install
pnpm dlx shadcn@latest add @hazine/alert-dialog-consequence-listAdds 1 file, 4 shadcn primitives (alert-dialog, button, checkbox, label), 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/alert-dialog-consequence-list.tsx, 450 lines
"use client"
import * as React from "react"
import {
Check,
CircleAlert,
CircleMinus,
LoaderCircle,
ShieldCheck,
X,
} from "lucide-react"
import { cn } from "@/lib/utils"
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { useControllableState } from "@/hooks/use-controllable-state"
export interface Consequence {
id: string
/** Reads on from the count ("projects deleted", singular when the count is 1). Without a count it is a full phrase. */
label: string
/** Shown as a tabular figure before the label. From 10,000 it is shortened on screen and still read out in full. */
count?: number
/** One quieter line under the label: a date, a scope or a way back. */
detail?: string
}
export interface ConsequenceGroup {
/** "lost" sits on the dialog surface in full weight, "kept" on a quieter raised band. */
effect: "lost" | "kept"
title: string
items: Consequence[]
}
/** `className` and every other prop reach the dialog content, which carries the alertdialog role. */
export interface AlertDialogConsequenceListProps
extends Omit<
React.ComponentProps<typeof AlertDialogContent>,
"title" | "children"
>,
Pick<
React.ComponentProps<typeof AlertDialog>,
"open" | "defaultOpen" | "onOpenChange"
> {
/** A single button element that opens the dialog. Focus returns to it on close. */
trigger?: React.ReactNode
title?: string
/** One sentence under the title. It is the text read out when the dialog opens. */
description?: string
/** Effects in reading order. A group with no items is not rendered. */
groups?: ConsequenceGroup[]
/** The statement beside the checkbox. Name what is lost, with its numbers. */
acknowledgementLabel?: string
acknowledged?: boolean
defaultAcknowledged?: boolean
onAcknowledgedChange?: (acknowledged: boolean) => void
confirmLabel?: string
cancelLabel?: string
/** Called on confirm with the box ticked. An uncontrolled dialog then closes. A controlled one stays open, so `loading` and `error` show in place. */
onConfirm?: () => void
/** The action is running. Both buttons and Escape stop responding and keep focus. */
loading?: boolean
/** Progressive verb that replaces the confirm label while loading. */
loadingLabel?: string
/** Why the action failed and what to do next. Announced as an alert. */
error?: string
locale?: string
}
const DEFAULT_GROUPS: ConsequenceGroup[] = [
{
effect: "lost",
title: "Lost for good",
items: [
{
id: "projects",
count: 14,
label: "projects deleted",
detail: "Boards, files and comments included",
},
{
id: "api-keys",
count: 3,
label: "API keys revoked",
detail: "Requests signed with them start failing at once",
},
{ id: "members", count: 9, label: "members lose access" },
{ id: "subdomain", label: "The workspace address is released" },
{ id: "plan", label: "The paid plan ends with the current cycle" },
],
},
{
effect: "kept",
title: "Stays with you",
items: [
{ id: "invoices", count: 26, label: "paid invoices stay downloadable" },
{ id: "workspaces", count: 2, label: "other workspaces are untouched" },
],
},
]
const GROUP_ICONS = {
lost: { heading: CircleMinus, marker: X },
kept: { heading: ShieldCheck, marker: Check },
} as const
const COMPACT_FROM = 10000
const COMPACT_FORMAT = { notation: "compact", maximumFractionDigits: 1 } as const
// Used instead of `disabled` so a button that is focused when the state
// changes keeps focus, and the gated confirm button can still be reached.
const softDisabled =
"aria-disabled:pointer-events-none aria-disabled:opacity-50"
const labelLayer =
"col-start-1 row-start-1 flex items-center justify-center gap-1.5"
function ConsequenceRow({
item,
effect,
locale,
}: {
item: Consequence
effect: ConsequenceGroup["effect"]
locale: string
}) {
const Marker = GROUP_ICONS[effect].marker
const { count } = item
const full =
count === undefined ? null : new Intl.NumberFormat(locale).format(count)
const short =
count !== undefined && Math.abs(count) >= COMPACT_FROM
? new Intl.NumberFormat(locale, COMPACT_FORMAT).format(count)
: null
return (
<li
data-slot="alert-dialog-consequence-list-item"
className="flex items-start gap-3 text-sm"
>
{full === null ? (
<span
aria-hidden="true"
className="flex h-5 w-12 shrink-0 items-center justify-end text-muted-foreground"
>
<Marker className="size-3.5" />
</span>
) : (
<span
className={cn(
"relative min-w-12 shrink-0 text-end whitespace-nowrap tabular-nums",
effect === "lost" && "font-semibold"
)}
>
{/* The short form is for the eye. Assistive tech gets the exact count. */}
<span aria-hidden={short !== null} title={short === null ? undefined : full}>
{short ?? full}
</span>
{short === null ? null : <span className="sr-only">{full}</span>}
</span>
)}
<span className="min-w-0 flex-1 wrap-anywhere">
{item.label}
{item.detail ? (
<span className="block text-xs text-pretty text-muted-foreground">
{item.detail}
</span>
) : null}
</span>
</li>
)
}
type OptionalKey = "acknowledged" | "onAcknowledgedChange" | "error"
type RequiredKey =
| ("title" | "description" | "groups" | "locale" | "loading" | "onConfirm")
| ("loadingLabel" | "acknowledgementLabel" | "defaultAcknowledged")
| ("confirmLabel" | "cancelLabel")
type BodyProps = Required<Pick<AlertDialogConsequenceListProps, RequiredKey>> &
Pick<AlertDialogConsequenceListProps, OptionalKey>
// Mounted with the dialog content, so an uncontrolled acknowledgement starts
// unticked every time the dialog opens.
function Body({
title,
description,
groups,
acknowledgementLabel,
acknowledged: acknowledgedProp,
defaultAcknowledged,
onAcknowledgedChange,
confirmLabel,
cancelLabel,
onConfirm,
loading,
loadingLabel,
error,
locale,
}: BodyProps) {
const baseId = React.useId()
const checkboxId = `${baseId}-acknowledgement`
const labelId = `${baseId}-acknowledgement-label`
const [acknowledged, setAcknowledged] = useControllableState({
value: acknowledgedProp,
defaultValue: defaultAcknowledged,
onChange: onAcknowledgedChange,
})
const checkbox = React.useRef<HTMLButtonElement>(null)
const frame = React.useRef<HTMLDivElement>(null)
const [scrollable, setScrollable] = React.useState(false)
// A list taller than the dialog scrolls inside its frame. Only then does the
// frame join the tab order, so the keyboard can scroll it. Measured again
// when the groups change, because new rows do not resize a capped frame.
React.useEffect(() => {
const node = frame.current
if (!node) return
const observer = new ResizeObserver(() =>
setScrollable(node.scrollHeight > node.clientHeight)
)
observer.observe(node)
return () => observer.disconnect()
}, [groups])
const filled = groups
.map((group, index) => ({ group, id: `${baseId}-group-${index}` }))
.filter(({ group }) => group.items.length > 0)
const scrollProps = scrollable
? {
role: "group",
tabIndex: 0,
"aria-labelledby": filled.map(({ id }) => id).join(" "),
}
: null
function handleConfirm() {
if (loading) return
// The gate answers a press by pointing at what is missing.
if (!acknowledged) {
checkbox.current?.focus()
return
}
onConfirm()
}
return (
<>
<AlertDialogHeader className="place-items-start text-start">
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription className="text-pretty">
{description}
</AlertDialogDescription>
</AlertDialogHeader>
{filled.length > 0 && (
<div
ref={frame}
data-slot="alert-dialog-consequence-list-effects"
className="min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground"
{...scrollProps}
>
{filled.map(({ group, id }) => {
const HeadingIcon = GROUP_ICONS[group.effect].heading
return (
<div
key={id}
data-slot="alert-dialog-consequence-list-group"
data-effect={group.effect}
className="px-4 py-3 data-[effect=kept]:bg-muted/50"
>
<p
id={id}
className="flex items-center gap-3 font-mono text-xs font-medium tracking-wider text-muted-foreground uppercase"
>
<span aria-hidden="true" className="flex w-12 shrink-0 justify-end">
<HeadingIcon className="size-3.5" />
</span>
{group.title}
</p>
<ul aria-labelledby={id} className="mt-2 grid gap-2">
{group.items.map((item) => (
<ConsequenceRow
key={item.id}
item={item}
effect={group.effect}
locale={locale}
/>
))}
</ul>
</div>
)
})}
</div>
)}
<div data-slot="alert-dialog-consequence-list-acknowledgement">
<div className="flex items-start gap-3">
<Checkbox
ref={checkbox}
id={checkboxId}
checked={acknowledged}
onCheckedChange={(checked) => setAcknowledged(checked === true)}
disabled={loading}
required
className="mt-0.5"
/>
<Label
id={labelId}
htmlFor={checkboxId}
className="min-w-0 leading-snug text-pretty wrap-anywhere"
>
{acknowledgementLabel}
</Label>
</div>
<div role="alert">
{error ? (
<p className="mt-3 flex items-start gap-1.5 text-sm text-destructive">
<CircleAlert
aria-hidden="true"
className="mt-0.5 size-3.5 shrink-0"
/>
{error}
</p>
) : null}
</div>
<p role="status" className="sr-only">
{loading ? loadingLabel : ""}
</p>
</div>
<AlertDialogFooter>
<AlertDialogCancel
aria-disabled={loading || undefined}
className={softDisabled}
>
{cancelLabel}
</AlertDialogCancel>
<Button
type="button"
aria-disabled={loading || !acknowledged || undefined}
aria-busy={loading || undefined}
aria-describedby={acknowledged ? undefined : labelId}
onClick={handleConfirm}
// Solid, because destructive text on the stock destructive tint measures 4:1.
className={cn(
"bg-destructive text-background hover:bg-destructive",
softDisabled
)}
>
{/* Both labels share one cell, so the width never changes. */}
<span className="grid">
<span
aria-hidden={loading}
className={cn(labelLayer, loading && "invisible")}
>
{confirmLabel}
</span>
<span
aria-hidden={!loading}
className={cn(labelLayer, !loading && "invisible")}
>
<LoaderCircle
aria-hidden="true"
className="size-4 motion-safe:animate-spin"
/>
{loadingLabel}
</span>
</span>
</Button>
</AlertDialogFooter>
</>
)
}
export function AlertDialogConsequenceList({
open: openProp,
defaultOpen = false,
onOpenChange,
trigger,
title = "Delete this workspace?",
description = "Deleting takes effect at once for every member and cannot be reversed.",
groups = DEFAULT_GROUPS,
acknowledgementLabel = "I understand that this cannot be undone.",
acknowledged,
defaultAcknowledged = false,
onAcknowledgedChange,
confirmLabel = "Delete workspace",
cancelLabel = "Keep workspace",
onConfirm,
loading = false,
loadingLabel = "Deleting",
error,
locale = "en-US",
className,
...props
}: AlertDialogConsequenceListProps) {
const [open, setOpen] = useControllableState({
value: openProp,
defaultValue: defaultOpen,
onChange: onOpenChange,
})
const content = {
title, description, groups, locale, loading, loadingLabel, error,
acknowledgementLabel, acknowledged, defaultAcknowledged,
onAcknowledgedChange, confirmLabel, cancelLabel,
}
return (
<AlertDialog
open={open}
onOpenChange={(next) => {
// A running action cannot be cancelled, by Escape or by the cancel button.
if (loading && !next) return
setOpen(next)
}}
>
{trigger ? (
<AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>
) : null}
<AlertDialogContent
data-slot="alert-dialog-consequence-list"
aria-busy={loading || undefined}
// Capped to the viewport: the header, the acknowledgement and the
// actions stay in view and only the list scrolls.
className={cn("flex max-h-dvh flex-col", className)}
{...props}
>
<Body
{...content}
onConfirm={() => {
onConfirm?.()
if (openProp === undefined) setOpen(false)
}}
/>
</AlertDialogContent>
</AlertDialog>
)
}
The demo in the preview, 273 lines
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import {
AlertDialogConsequenceList,
type ConsequenceGroup,
} from "@/components/hazine/alert-dialog-consequence-list"
const WORKSPACE = "Tidewater Studio"
const DELETE_MS = 1400
const SESSIONS = 6
const TOKENS = 2
const GROUPS: ConsequenceGroup[] = [
{
effect: "lost",
title: "Lost for good",
items: [
{
id: "projects",
count: 14,
label: "projects deleted",
detail: "Boards, files and comments included",
},
{
id: "api-keys",
count: 3,
label: "API keys revoked",
detail: "Requests signed with them start failing at once",
},
{ id: "members", count: 9, label: "members lose access" },
{ id: "address", label: "tidewater.example is released" },
{
id: "plan",
label: "The Team plan is cancelled",
detail: "Billing stops on the next cycle. No charge on Dec 1, 2026",
},
],
},
{
effect: "kept",
title: "Stays with you",
items: [
{
id: "invoices",
count: 26,
label: "paid invoices stay downloadable",
detail: "Under billing history on your account",
},
{ id: "workspaces", count: 2, label: "other workspaces are untouched" },
],
},
]
const OVERFLOW_GROUPS: ConsequenceGroup[] = [
{
effect: "lost",
title: "Lost for good",
items: [
{
id: "events",
count: 1284500,
label: "tracked events deleted from every dashboard and saved report",
detail: "Exports already downloaded to your own storage are not affected",
},
{ id: "sessions", count: 96240, label: "session recordings deleted" },
{ id: "projects", count: 9412, label: "projects deleted" },
{ id: "dashboards", count: 318, label: "dashboards deleted" },
{ id: "alerts", count: 127, label: "alert rules switched off" },
{ id: "api-keys", count: 48, label: "API keys revoked" },
{ id: "webhooks", count: 36, label: "webhook endpoints stop receiving" },
{ id: "members", count: 212, label: "members lose access" },
{ id: "guests", count: 57, label: "guest links stop working" },
{ id: "integrations", count: 11, label: "integrations disconnected" },
{
id: "address",
label:
"analytics-and-reporting-platform-team.meridian-harbour-logistics.example is released",
},
{ id: "sso", label: "Single sign-on is switched off for the domain" },
],
},
{
effect: "kept",
title: "Stays with you",
items: [
{ id: "invoices", count: 143, label: "paid invoices stay downloadable" },
{ id: "workspaces", count: 4, label: "other workspaces are untouched" },
{
id: "audit-log",
label: "The audit log is kept for 90 days",
detail: "Owners can request a copy until Feb 9, 2027",
},
],
},
]
type Phase = "idle" | "deleting" | "failed" | "deleted"
interface DangerZoneProps {
defaultOpen?: boolean
defaultAcknowledged?: boolean
initialPhase?: Phase
workspace?: string
groups?: ConsequenceGroup[]
}
// The sentences around the dialog repeat counts from the list, so they are
// read from the same rows and cannot drift apart.
function countOf(groups: ConsequenceGroup[], id: string) {
const items = groups.flatMap((group) => group.items)
return items.find((item) => item.id === id)?.count ?? 0
}
function DangerZone({
defaultOpen = false,
defaultAcknowledged = false,
initialPhase = "idle",
workspace = WORKSPACE,
groups = GROUPS,
}: DangerZoneProps) {
const projects = countOf(groups, "projects")
const apiKeys = countOf(groups, "api-keys")
const members = countOf(groups, "members")
const [open, setOpen] = React.useState(defaultOpen)
const [phase, setPhase] = React.useState<Phase>(initialPhase)
const timer = React.useRef<number | null>(null)
const count = new Intl.NumberFormat("en-US")
React.useEffect(
() => () => {
if (timer.current !== null) window.clearTimeout(timer.current)
},
[]
)
function deleteWorkspace() {
setPhase("deleting")
timer.current = window.setTimeout(() => {
setPhase("deleted")
setOpen(false)
}, DELETE_MS)
}
return (
<div className="w-xl max-w-full">
<div className="@container">
<div className="flex flex-col items-start gap-4 @md:flex-row @md:items-center @md:justify-between">
<div className="min-w-0">
<p className="text-sm font-semibold wrap-anywhere">
Delete {workspace}
</p>
<p className="mt-0.5 text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{count.format(projects)} projects, {count.format(members)}{" "}
members, {count.format(apiKeys)} API keys.
</span>{" "}
Only an owner can delete a workspace.
</p>
</div>
<AlertDialogConsequenceList
open={open}
onOpenChange={(next) => {
setOpen(next)
if (phase !== "deleting") setPhase("idle")
}}
trigger={<Button variant="outline">Delete workspace</Button>}
title={`Delete ${workspace}?`}
description={`This removes the workspace for all ${count.format(members)} members at once and cannot be reversed.`}
groups={groups}
acknowledgementLabel={`I understand that ${count.format(projects)} projects and ${count.format(apiKeys)} API keys cannot be restored.`}
defaultAcknowledged={defaultAcknowledged}
onConfirm={deleteWorkspace}
loading={phase === "deleting"}
loadingLabel="Deleting workspace"
error={
phase === "failed"
? "The workspace was not deleted because the connection dropped. Nothing has changed. Delete it again."
: undefined
}
/>
</div>
<p role="status" className="mt-4 text-sm text-muted-foreground">
{phase === "deleted" ? (
<>
<span className="font-medium text-foreground">
{workspace} was deleted.
</span>{" "}
{count.format(projects)} projects, {count.format(apiKeys)} API keys
and {count.format(members)} member seats went with it. Open the
dialog to run it again.
</>
) : null}
</p>
</div>
</div>
)
}
export default function AlertDialogConsequenceListDemo() {
return <DangerZone defaultOpen />
}
function AlertDialogConsequenceListNothingKept() {
return (
<AlertDialogConsequenceList
defaultOpen
trigger={<Button variant="outline">Revoke all sessions</Button>}
title="Sign out of every device?"
description="Each device has to sign in again with a password and a second factor."
groups={[
{
effect: "lost",
title: "Ends now",
items: [
{
id: "sessions",
count: SESSIONS,
label: "active sessions signed out",
},
{
id: "tokens",
count: TOKENS,
label: "personal access tokens revoked",
},
{ id: "devices", label: "Trusted devices are forgotten" },
],
},
]}
acknowledgementLabel={`I understand that ${SESSIONS} sessions and ${TOKENS} tokens end now.`}
confirmLabel="Sign out everywhere"
cancelLabel="Stay signed in"
loadingLabel="Signing out"
/>
)
}
function AlertDialogConsequenceListEmpty() {
return (
<AlertDialogConsequenceList
defaultOpen
trigger={<Button variant="outline">Delete draft workspace</Button>}
title="Delete the empty draft workspace?"
description="Nothing has been added to it yet, so there is nothing to lose or keep."
groups={[]}
acknowledgementLabel="I understand that the draft cannot be restored."
confirmLabel="Delete draft"
cancelLabel="Keep draft"
/>
)
}
export const scenarios = {
closed: () => <DangerZone />,
acknowledged: () => <DangerZone defaultOpen defaultAcknowledged />,
loading: () => (
<DangerZone defaultOpen defaultAcknowledged initialPhase="deleting" />
),
error: () => (
<DangerZone defaultOpen defaultAcknowledged initialPhase="failed" />
),
overflow: () => (
<DangerZone
defaultOpen
workspace="Meridian Harbour Logistics Analytics and Reporting Platform Team"
groups={OVERFLOW_GROUPS}
/>
),
"nothing-kept": AlertDialogConsequenceListNothingKept,
empty: AlertDialogConsequenceListEmpty,
}
Props15
- trigger
- React.ReactNode
- A single button element that opens the dialog. Focus returns to it on close.
- title
- string = "Delete this workspace?"
- description
- string = "Deleting takes effect at once for every member and cannot be reversed."
- One sentence under the title. It is the text read out when the dialog opens.
- groups
- ConsequenceGroup[] = DEFAULT_GROUPS
- Effects in reading order. A group with no items is not rendered.
- acknowledgementLabel
- string = "I understand that this cannot be undone."
- The statement beside the checkbox. Name what is lost, with its numbers.
- acknowledged
- boolean
- defaultAcknowledged
- boolean = false
- onAcknowledgedChange
- (acknowledged: boolean) => void
- confirmLabel
- string = "Delete workspace"
- cancelLabel
- string = "Keep workspace"
- onConfirm
- () => void
- Called on confirm with the box ticked. An uncontrolled dialog then closes. A controlled one stays open, so `loading` and `error` show in place.
- loading
- boolean = false
- The action is running. Both buttons and Escape stop responding and keep focus.
- loadingLabel
- string = "Deleting"
- Progressive verb that replaces the confirm label while loading.
- error
- string
- Why the action failed and what to do next. Announced as an alert.
- locale
- string = "en-US"
Also accepts every prop of Omit< React.ComponentProps<typeof AlertDialogContent>, "title" | "children" > and Pick< React.ComponentProps<typeof AlertDialog>, "open" | "defaultOpen" | "onOpenChange" >.
Accessibility
- Keyboard
Keyboard support for Consequence List Alert Dialog Key Effect Tab, Shift+Tab Cycles through the acknowledgement, the cancel button and the confirm button. Focus stays inside the dialog and starts on cancel. While the action is running the acknowledgement is skipped Space on the acknowledgement Ticks or clears it, which opens or closes the confirm button Enter or Space on confirm Runs the action when the box is ticked. Otherwise moves focus to the acknowledgement Enter or Space on cancel Closes the dialog without running the action and returns focus to the trigger. Ignored while the action is running Escape Cancels and returns focus to the trigger. Ignored while the action is running Arrow Up, Arrow Down on the list Scrolls the list. It is a tab stop only when it is taller than the dialog - Screen reader
Modal alertdialog named by its title and described by the one-sentence summary. Each group is a list labelled by its heading. The confirm button is aria-disabled, not disabled, and described by the acknowledgement until the box is ticked. A count shortened on screen is read out in full.
- Announces: {loadingLabel}
- Announces: {error}
- Reduced motion
- The loading spinner does not rotate. The dialog fade and scale come from the host alert-dialog primitive.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies6
- alert-dialog
- button
- checkbox
- label
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.