Alert Dialog
The shadcn/ui Alert Dialog with the DuskUI open and close animation, an icon slot and a compact size — plus two accessible React alert dialog blocks built with Motion and Radix: a destructive confirmation with type-to-confirm and async loading, and a session-timeout warning with a live countdown ring.
- Drop-in shadcn API
- role=alertdialog
- Motion blocks
- prefers-reduced-motion
"use client";
import { Trash2, UserX } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { DestructiveAlertDialog } from "@/components/dusk/alert-dialog/destructive-alert-dialog";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default function DestructiveAlertDialogDemo() {
return (
<div className="flex flex-wrap items-center justify-center gap-3">
<DestructiveAlertDialog
trigger={
<Button variant="destructive">
<Trash2 />
Delete project
</Button>
}
title="Delete dusk-web?"
description="This permanently deletes the project and everything in it."
consequences={["14 deployments and their logs", "2 custom domains", "All environment variables"]}
confirmText="dusk-web"
confirmLabel="Delete project"
pendingLabel="Deleting…"
onConfirm={async () => {
await wait(1400);
toast.success("dusk-web was deleted");
}}
/>
<DestructiveAlertDialog
trigger={
<Button variant="outline">
<UserX />
Remove member (fails)
</Button>
}
icon={<UserX />}
title="Remove Ada Kim from the team?"
description="She loses access to every project right away."
confirmLabel="Remove"
onConfirm={async () => {
await wait(1100);
throw new Error("Ada is the only owner. Transfer ownership first.");
}}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/alert-dialog.json1. Install the dependencies.
npm install @radix-ui/react-alert-dialog class-variance-authority2. Copy the source into
components/ui/alert-dialog.tsx.alert-dialog.tsx "use client"; import * as React from "react"; import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"; import type { VariantProps } from "class-variance-authority"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; /** * DuskUI Alert Dialog — a drop-in upgrade of the shadcn/ui Alert Dialog. * * Same parts, props and data-slot attributes as shadcn, plus: * - The DuskUI Dialog motion: a short fade + slight scale, ease-out, with a * quicker exit, over a dimmed backdrop. * - `size="sm"` on AlertDialogContent for compact, centered confirmations. * - `AlertDialogMedia`: an icon slot above the title. * - `variant` and `size` on AlertDialogAction / AlertDialogCancel (DuskUI * Button variants), e.g. `variant="destructive"`. * - Long content scrolls inside the dialog. * - Under `prefers-reduced-motion` it only fades. * Unlike Dialog, clicking outside does NOT close it, and focus starts on * Cancel — an alert dialog always needs an explicit answer. * CSS only (tw-animate-css), powered by Radix for focus trap, Escape and aria. */ function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) { return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />; } /** The element that opens the dialog. Use `asChild` to render your own Button. */ function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) { return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />; } /** Portals the overlay and content to `document.body`. */ function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) { return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />; } /** The dimmed backdrop. Clicking it does nothing, by design. */ function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) { return ( <AlertDialogPrimitive.Overlay data-slot="alert-dialog-overlay" className={cn( "fixed inset-0 z-50 bg-black/60", "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:duration-200", "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:duration-150", className )} {...props} /> ); } /** The dialog surface, centered on screen with its overlay. */ function AlertDialogContent({ className, size = "default", ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content> & { /** `sm` is narrower and centers the header and stacks the footer buttons evenly. */ size?: "default" | "sm"; }) { return ( <AlertDialogPortal> <AlertDialogOverlay /> <AlertDialogPrimitive.Content data-slot="alert-dialog-content" data-size={size} className={cn( "group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-xl border bg-background p-6 outline-none", "data-[size=default]:sm:max-w-lg data-[size=sm]:sm:max-w-sm", "shadow-lg ease-out", "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-[0.97] data-[state=open]:duration-200", "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-[0.97] data-[state=closed]:duration-150", "motion-reduce:data-[state=open]:zoom-in-100 motion-reduce:data-[state=closed]:zoom-out-100", className )} {...props} /> </AlertDialogPortal> ); } /** Wraps the media, title and description. Centered on mobile and for `size="sm"`. */ function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="alert-dialog-header" className={cn( "flex flex-col items-center gap-1.5 text-center", "sm:group-data-[size=default]/alert-dialog-content:items-start sm:group-data-[size=default]/alert-dialog-content:text-left", className )} {...props} /> ); } /** Action row. Stacks on mobile with the primary action on top; `size="sm"` splits it evenly. */ function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="alert-dialog-footer" className={cn( "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", "group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2", className )} {...props} /> ); } /** A neutral icon badge above the title. Recolor it with classes, e.g. `bg-destructive/10 text-destructive`. */ function AlertDialogMedia({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="alert-dialog-media" className={cn( "mb-2 inline-grid size-11 shrink-0 place-items-center rounded-full bg-muted text-foreground [&_svg:not([class*='size-'])]:size-5", className )} {...props} /> ); } /** Accessible title, announced when the dialog opens. Required by Radix. */ function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) { return ( <AlertDialogPrimitive.Title data-slot="alert-dialog-title" className={cn("text-lg leading-snug font-semibold tracking-tight", className)} {...props} /> ); } /** Supporting text, linked to the dialog via aria-describedby. Required by Radix (or pass aria-describedby={undefined}). */ function AlertDialogDescription({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Description>) { return ( <AlertDialogPrimitive.Description data-slot="alert-dialog-description" className={cn("text-sm leading-relaxed text-muted-foreground", className)} {...props} /> ); } type ButtonStyleProps = Pick<VariantProps<typeof buttonVariants>, "variant" | "size">; /** Confirms and closes the dialog. Styled as a DuskUI Button (`variant`, `size`). */ function AlertDialogAction({ className, variant = "default", size = "default", ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action> & ButtonStyleProps) { return ( <AlertDialogPrimitive.Action data-slot="alert-dialog-action" className={cn(buttonVariants({ variant, size }), className)} {...props} /> ); } /** Closes the dialog without acting. Receives focus when the dialog opens. Outline by default. */ function AlertDialogCancel({ className, variant = "outline", size = "default", ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> & ButtonStyleProps) { return ( <AlertDialogPrimitive.Cancel data-slot="alert-dialog-cancel" className={cn(buttonVariants({ variant, size }), className)} {...props} /> ); } export { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogMedia, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, };
Full shadcn/ui API plus AlertDialogMedia, size="sm" on the content and variant / size on the action and cancel buttons. It styles those buttons with the DuskUI Button's buttonVariants. Animations are CSS (tw-animate-css), so the base needs no Motion.
Usage
import { Button } from "@/components/ui/button"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
export function DiscardDraft() {
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline">Discard draft</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Discard this draft?</AlertDialogTitle>
<AlertDialogDescription>You can't get it back.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Keep editing</AlertDialogCancel>
<AlertDialogAction variant="destructive">Discard</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}Examples
Default
Fades and scales in slightly, then exits faster than it entered. Unlike Dialog, clicking the backdrop does nothing and focus starts on Cancel: the user has to answer. Give AlertDialogAction a variant to make it destructive.
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
export default function AlertDialogBasicDemo() {
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline">Discard draft</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Discard this draft?</AlertDialogTitle>
<AlertDialogDescription>
Your post and its attachments will be removed. You can't get them back.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Keep editing</AlertDialogCancel>
<AlertDialogAction variant="destructive">Discard</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}Compact with icon
size="sm" narrows the dialog, centers the header and splits the footer into two equal buttons. AlertDialogMedia adds a tinted icon badge above the title.
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
export default function AlertDialogMediaDemo() {
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="secondary">
<LogOut />
Sign out
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogMedia>
<LogOut />
</AlertDialogMedia>
<AlertDialogTitle>Sign out of all devices?</AlertDialogTitle>
<AlertDialogDescription>You'll need to sign in again on your phone and laptop.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction>Sign out</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Destructive Alert Dialog
For deleting things that can't come back. A red icon marks the danger, consequences lists what will be lost, and with confirmText each character turns red as it matches. Return a promise from onConfirm and the button shows the DuskUI Button loading state; Escape and Cancel are blocked mid-request, and a failure shakes the dialog and shows the error inline. Unlike the Dialog's Confirm Dialog, it uses Alert Dialog semantics, so clicking outside never closes it. Try both buttons.
"use client";
import { Trash2, UserX } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { DestructiveAlertDialog } from "@/components/dusk/alert-dialog/destructive-alert-dialog";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default function DestructiveAlertDialogDemo() {
return (
<div className="flex flex-wrap items-center justify-center gap-3">
<DestructiveAlertDialog
trigger={
<Button variant="destructive">
<Trash2 />
Delete project
</Button>
}
title="Delete dusk-web?"
description="This permanently deletes the project and everything in it."
consequences={["14 deployments and their logs", "2 custom domains", "All environment variables"]}
confirmText="dusk-web"
confirmLabel="Delete project"
pendingLabel="Deleting…"
onConfirm={async () => {
await wait(1400);
toast.success("dusk-web was deleted");
}}
/>
<DestructiveAlertDialog
trigger={
<Button variant="outline">
<UserX />
Remove member (fails)
</Button>
}
icon={<UserX />}
title="Remove Ada Kim from the team?"
description="She loses access to every project right away."
confirmLabel="Remove"
onConfirm={async () => {
await wait(1100);
throw new Error("Ada is the only owner. Transfer ownership first.");
}}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/destructive-alert-dialog.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/alert-dialog/destructive-alert-dialog.tsx.destructive-alert-dialog.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useAnimate, useReducedMotion } from "motion/react"; import { Trash2 } from "lucide-react"; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export interface DestructiveAlertDialogProps { /** Element that opens the dialog, usually a Button. Omit when controlling `open` yourself. */ trigger?: React.ReactElement; open?: boolean; onOpenChange?: (open: boolean) => void; title: React.ReactNode; description?: React.ReactNode; /** What will be lost, shown as a list that staggers in, e.g. ["12 deployments", "3 domains"]. */ consequences?: React.ReactNode[]; /** Runs on confirm. Return a promise to show a loading state; the dialog closes when it resolves and stays open (with the error) if it throws. */ onConfirm: () => unknown | Promise<unknown>; confirmLabel?: React.ReactNode; cancelLabel?: React.ReactNode; /** Shown next to the spinner while `onConfirm` runs. */ pendingLabel?: React.ReactNode; /** Require the user to type this exact text before confirming, e.g. a project name. */ confirmText?: string; /** Icon in the red badge. Defaults to a trash can. */ icon?: React.ReactNode; /** Message shown when `onConfirm` throws. Defaults to the error's message. */ errorMessage?: React.ReactNode; } const spring = { type: "spring", duration: 0.35, bounce: 0 } as const; /** * A destructive confirmation built on Alert Dialog semantics: clicking outside * never closes it, focus starts on Cancel (or the confirm field), and Escape * is blocked while the action runs. A red icon marks the danger, an * optional list spells out what will be lost, and type-to-confirm lights up * each character as it matches. The confirm button uses the DuskUI Button * `loading` state for async work; a failure shakes the dialog and shows the * error inline. */ export function DestructiveAlertDialog({ trigger, open: openProp, onOpenChange, title, description, consequences, onConfirm, confirmLabel = "Delete", cancelLabel = "Cancel", pendingLabel, confirmText, icon = <Trash2 />, errorMessage, }: DestructiveAlertDialogProps) { const id = React.useId(); const reduceMotion = useReducedMotion(); const [scope, animate] = useAnimate<HTMLDivElement>(); const inputRef = React.useRef<HTMLInputElement>(null); const [internalOpen, setInternalOpen] = React.useState(false); const [pending, setPending] = React.useState(false); const [error, setError] = React.useState<React.ReactNode>(null); const [typed, setTyped] = React.useState(""); const open = openProp ?? internalOpen; const matched = !confirmText || typed === confirmText; const setOpen = (next: boolean) => { if (pending) return; if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }; const handleConfirm = async () => { if (pending) return; if (!matched) { inputRef.current?.focus(); return; } setError(null); setPending(true); try { await onConfirm(); setPending(false); if (openProp === undefined) setInternalOpen(false); onOpenChange?.(false); } catch (err) { setPending(false); setError(errorMessage ?? (err instanceof Error ? err.message : "Something went wrong.")); if (!reduceMotion && scope.current) { animate(scope.current, { x: [0, -10, 9, -6, 4, 0] }, { duration: 0.45, ease: "easeOut" }); } } }; return ( <AlertDialog open={open} onOpenChange={setOpen}> {trigger && <AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>} <AlertDialogContent aria-busy={pending || undefined} className="sm:max-w-md" onOpenAutoFocus={(event) => { // Fresh state on every open, however it was opened. setError(null); setTyped(""); // Radix focuses Cancel by default; jump to the field when typing is required. if (confirmText) { event.preventDefault(); inputRef.current?.focus(); } }} onEscapeKeyDown={(event) => { if (pending) event.preventDefault(); }} > <div ref={scope} className="grid gap-5"> <AlertDialogHeader> <PulseIcon>{icon}</PulseIcon> <AlertDialogTitle>{title}</AlertDialogTitle> {description ? ( <AlertDialogDescription>{description}</AlertDialogDescription> ) : ( <AlertDialogDescription className="sr-only">This action can't be undone.</AlertDialogDescription> )} </AlertDialogHeader> {consequences?.length ? ( <motion.ul className="grid gap-1.5 rounded-lg border border-destructive/20 bg-destructive/[0.06] p-3 text-sm" initial="hidden" animate="visible" variants={{ visible: { transition: { staggerChildren: 0.05, delayChildren: 0.15 } } }} > {consequences.map((item, index) => ( <motion.li key={index} className="flex items-start gap-2 text-foreground/85" variants={{ hidden: { opacity: 0, x: reduceMotion ? 0 : -6 }, visible: { opacity: 1, x: 0, transition: spring }, }} > <span aria-hidden className="mt-[0.45rem] size-1.5 shrink-0 rounded-full bg-destructive" /> <span>{item}</span> </motion.li> ))} </motion.ul> ) : null} {confirmText && ( <div className="grid gap-2"> <label htmlFor={`${id}-confirm`} className="text-sm text-muted-foreground"> Type <MatchedText target={confirmText} typed={typed} /> to confirm. </label> <input ref={inputRef} id={`${id}-confirm`} value={typed} onChange={(event) => setTyped(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); void handleConfirm(); } }} readOnly={pending} autoComplete="off" autoCapitalize="off" spellCheck={false} aria-invalid={typed.length > 0 && !confirmText.startsWith(typed) ? true : undefined} className={cn( "h-9 w-full rounded-md border border-input bg-input/30 px-3 font-mono text-sm outline-none", "transition-[border-color,box-shadow] duration-200 placeholder:text-muted-foreground", "focus-visible:border-destructive/60 focus-visible:ring-[3px] focus-visible:ring-destructive/20", "aria-invalid:border-destructive aria-invalid:ring-destructive/20", matched && "border-destructive/60" )} /> </div> )} <AnimatePresence initial={false}> {error && ( <motion.p role="alert" className="overflow-hidden text-sm text-destructive" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} transition={spring} > {error} </motion.p> )} </AnimatePresence> <AlertDialogFooter> <AlertDialogCancel aria-disabled={pending || undefined} className="aria-disabled:opacity-50" onClick={(event) => { // Keep the dialog open while the action runs. if (pending) event.preventDefault(); }} > {cancelLabel} </AlertDialogCancel> <Button variant="destructive" loading={pending} loadingText={pendingLabel} // Set here too: this prop overrides the one Button derives from `loading`. aria-disabled={pending || !matched || undefined} className={cn(!matched && "cursor-not-allowed opacity-50")} onClick={handleConfirm} > {confirmLabel} </Button> </AlertDialogFooter> </div> </AlertDialogContent> </AlertDialog> ); } /** The red icon badge. Fades in with the dialog; static under reduced motion. */ function PulseIcon({ children }: { children: React.ReactNode }) { const reduceMotion = useReducedMotion(); return ( <motion.div aria-hidden className="relative mb-2 grid size-12 shrink-0 place-items-center rounded-full bg-destructive/15 text-destructive [&_svg]:size-5" initial={reduceMotion ? { opacity: 0 } : { scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ duration: 0.2, ease: "easeOut", delay: 0.05 }} > {children} </motion.div> ); } /** Renders the text to type, lighting up each character that already matches. */ function MatchedText({ target, typed }: { target: string; typed: string }) { let matchedCount = 0; while (matchedCount < target.length && typed[matchedCount] === target[matchedCount]) matchedCount++; return ( <span className="rounded bg-muted px-1 py-0.5 font-mono font-medium text-foreground"> {/* Screen readers get the plain text once, not one span per letter. */} <span className="sr-only">{target}</span> <span aria-hidden> {target.split("").map((char, index) => ( <span key={index} className={cn( "transition-colors duration-150", index < matchedCount ? "text-destructive" : "text-foreground" )} > {char} </span> ))} </span> </span> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| trigger | ReactElement | — | Element that opens the dialog. Omit when controlling open. |
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state. |
| title | ReactNode | — | Dialog title. Required. |
| description | ReactNode | — | Supporting text. A screen-reader-only fallback is used when omitted. |
| consequences | ReactNode[] | — | What will be lost, shown as a list that staggers in. |
| onConfirm | () => unknown | Promise<unknown> | — | Runs on confirm. Throw to keep the dialog open with an error. |
| confirmText | string | — | Text the user must type before confirming. Focus starts in that field. |
| confirmLabel / cancelLabel | ReactNode | "Delete" / "Cancel" | Button labels. |
| pendingLabel | ReactNode | — | Shown next to the spinner while confirming. |
| icon | ReactNode | <Trash2 /> | Icon inside the red badge. |
| errorMessage | ReactNode | — | Replaces the thrown error's message. |
Session Timeout Dialog
“Are you still there?” Open it from your idle timer: a ring drains around the seconds left and turns red for the last ten, then onSignOut("timeout") runs. Focus lands on Stay signed in, and Escape also counts as staying. The countdown uses wall-clock time, so it stays correct after the tab has been in the background.
"use client";
import * as React from "react";
import { Timer } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { SessionTimeoutDialog } from "@/components/dusk/alert-dialog/session-timeout-dialog";
export default function SessionTimeoutDialogDemo() {
const [open, setOpen] = React.useState(false);
return (
<>
<Button variant="outline" onClick={() => setOpen(true)}>
<Timer />
Simulate 15 min idle
</Button>
<SessionTimeoutDialog
open={open}
onOpenChange={setOpen}
seconds={20}
onStay={() => toast.success("Session extended")}
onSignOut={(reason) =>
toast(reason === "timeout" ? "Signed out after inactivity" : "Signed out")
}
/>
</>
);
}$ npx shadcn@latest add https://duskui.com/r/session-timeout-dialog.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/alert-dialog/session-timeout-dialog.tsx.session-timeout-dialog.tsx "use client"; import * as React from "react"; import { motion, useReducedMotion } from "motion/react"; import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export interface SessionTimeoutDialogProps { /** Show the warning. Open it from your idle timer; it closes itself when the user answers or time runs out. */ open: boolean; onOpenChange: (open: boolean) => void; /** Seconds the user has to respond. */ seconds?: number; /** The user chose to stay (button or Escape). Refresh the session here. */ onStay?: () => void; /** The user chose to leave, or time ran out (`reason === "timeout"`). Sign out here. */ onSignOut?: (reason: "manual" | "timeout") => void; title?: React.ReactNode; /** Text under the title. Receives the seconds left. */ description?: React.ReactNode | ((secondsLeft: number) => React.ReactNode); stayLabel?: React.ReactNode; signOutLabel?: React.ReactNode; } const RADIUS = 26; const CIRCUMFERENCE = 2 * Math.PI * RADIUS; /** * "Are you still there?" A session-timeout warning built on Alert Dialog: it * can't be dismissed by clicking outside, focus lands on "Stay signed in", * and Escape also counts as staying. A ring drains around the seconds left * and turns red for the last ten; when it empties, `onSignOut("timeout")` * runs. The countdown uses wall-clock time, so it stays accurate even if the * tab was in the background. Screen readers hear the time left when it opens * and once more at ten seconds, not every tick. */ export function SessionTimeoutDialog({ open, onOpenChange, seconds = 60, onStay, onSignOut, title = "Are you still there?", description = (left: number) => `For your security, you'll be signed out in ${left} seconds.`, stayLabel = "Stay signed in", signOutLabel = "Sign out", }: SessionTimeoutDialogProps) { // Any close that isn't a sign-out (Escape, the stay button) means "stay". const signingOut = React.useRef(false); const stayRef = React.useRef<HTMLButtonElement>(null); const handleOpenChange = (next: boolean) => { if (!next && !signingOut.current) onStay?.(); signingOut.current = false; onOpenChange(next); }; const signOut = (reason: "manual" | "timeout") => { signingOut.current = true; onSignOut?.(reason); handleOpenChange(false); }; return ( <AlertDialog open={open} onOpenChange={handleOpenChange}> <AlertDialogContent size="sm" onOpenAutoFocus={(event) => { // Start on the safe, expected answer. event.preventDefault(); stayRef.current?.focus(); }} > {/* Mounted only while open, so the countdown restarts on every open. */} <Countdown seconds={seconds} title={title} description={description} stayLabel={stayLabel} signOutLabel={signOutLabel} onSignOut={signOut} stayRef={stayRef} active={open} /> </AlertDialogContent> </AlertDialog> ); } function Countdown({ seconds, title, description, stayLabel, signOutLabel, onSignOut, stayRef, active, }: Required<Pick<SessionTimeoutDialogProps, "seconds" | "title" | "description" | "stayLabel" | "signOutLabel">> & { onSignOut: (reason: "manual" | "timeout") => void; stayRef: React.Ref<HTMLButtonElement>; /** False during the close animation, so a late tick can't sign the user out after they chose to stay. */ active: boolean; }) { const reduceMotion = useReducedMotion(); const [deadline] = React.useState(() => Date.now() + seconds * 1000); const [msLeft, setMsLeft] = React.useState(seconds * 1000); const secondsLeft = Math.ceil(msLeft / 1000); const urgent = secondsLeft <= 10; const timeout = React.useEffectEvent(() => onSignOut("timeout")); React.useEffect(() => { if (!active) return; const tick = () => { const left = Math.max(0, deadline - Date.now()); setMsLeft(left); if (left === 0) { window.clearInterval(interval); timeout(); } }; const interval = window.setInterval(tick, 200); return () => window.clearInterval(interval); }, [deadline, active]); const text = typeof description === "function" ? description(secondsLeft) : description; // Only re-announce at the 10-second mark, not every second. const announced = typeof description === "function" ? description(urgent ? Math.min(10, seconds) : seconds) : description; return ( <> <AlertDialogHeader> <div className="relative mb-2 grid size-16 place-items-center" aria-hidden> <svg viewBox="0 0 64 64" className="absolute inset-0 -rotate-90"> <circle cx="32" cy="32" r={RADIUS} fill="none" strokeWidth="4" className="stroke-muted" /> <motion.circle cx="32" cy="32" r={RADIUS} fill="none" strokeWidth="4" strokeLinecap="round" strokeDasharray={CIRCUMFERENCE} className={cn( "transition-[stroke] duration-300", urgent ? "stroke-destructive" : "stroke-primary" )} initial={{ strokeDashoffset: 0 }} animate={{ strokeDashoffset: CIRCUMFERENCE * (1 - msLeft / (seconds * 1000)) }} transition={{ duration: 0.2, ease: "linear" }} /> </svg> <motion.span key={secondsLeft} className={cn( "font-mono text-lg font-semibold tabular-nums", urgent ? "text-destructive" : "text-foreground" )} initial={reduceMotion ? false : { opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} transition={{ type: "spring", duration: 0.3, bounce: 0 }} > {secondsLeft} </motion.span> </div> <AlertDialogTitle>{title}</AlertDialogTitle> {/* Read once when the dialog opens; the live region below re-announces only at ten seconds. */} <AlertDialogDescription>{text}</AlertDialogDescription> <p className="sr-only" aria-live="polite"> {announced} </p> </AlertDialogHeader> <AlertDialogFooter> <Button variant="outline" onClick={() => onSignOut("manual")}> {signOutLabel} </Button> <AlertDialogAction ref={stayRef}>{stayLabel}</AlertDialogAction> </AlertDialogFooter> </> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state. Required. |
| seconds | number | 60 | Seconds the user has to respond. |
| onStay | () => void | — | The user stayed (button or Escape). Refresh the session. |
| onSignOut | (reason: "manual" | "timeout") => void | — | The user left or time ran out. |
| title | ReactNode | "Are you still there?" | Dialog title. |
| description | ReactNode | (secondsLeft: number) => ReactNode | — | Text under the title; a function receives the seconds left. |
| stayLabel / signOutLabel | ReactNode | "Stay signed in" / "Sign out" | Button labels. |
API Reference
Same parts as shadcn/ui: AlertDialog, AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle, AlertDialogDescription, AlertDialogAction, AlertDialogCancel, AlertDialogOverlay and AlertDialogPortal, plus AlertDialogMedia. Each forwards the Radix Alert Dialog props.
| Prop | Type | Default | Description |
|---|---|---|---|
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state (on AlertDialog). |
| size | "default" | "sm" | "default" | sm is narrower, centered, with equal-width footer buttons (on AlertDialogContent). |
| variant / size | Button variant / size | "default" / "outline" | Button style of AlertDialogAction / AlertDialogCancel. |
| onOpenAutoFocus / onEscapeKeyDown | (event) => void | — | Radix hooks on AlertDialogContent; call preventDefault() to override. |
Accessibility
- Built on Radix Alert Dialog:
role="alertdialog", focus is trapped, the page behind is hidden from screen readers and focus returns to the trigger. - Clicking outside never closes it, and focus starts on Cancel, the safe choice. Escape still closes it, except while a block's async action is running.
- Always render an
AlertDialogTitleand anAlertDialogDescription; they become the dialog's accessible name and description. - The Destructive Alert Dialog keeps both buttons focusable while pending (aria-disabled + aria-busy) and reads the confirm text once instead of letter by letter.
- The Session Timeout Dialog announces the time left when it opens and once more at ten seconds, not on every tick.
- Under prefers-reduced-motion the dialog only fades, the shake is skipped, and the countdown digits swap without sliding.