Dialog
The shadcn/ui Dialog (modal) with a short, calm open and close animation, dimmed backdrop and scrollable content — plus three accessible React dialog blocks built with Motion and Radix: a card that morphs into a dialog, an async confirm dialog and a drag-to-dismiss bottom sheet drawer.
- Drop-in shadcn API
- Radix focus trap
- Motion blocks
- prefers-reduced-motion
import { Mountain } from "lucide-react";
import {
MorphingDialog,
MorphingDialogClose,
MorphingDialogContent,
MorphingDialogDescription,
MorphingDialogMedia,
MorphingDialogSubtitle,
MorphingDialogTitle,
MorphingDialogTrigger,
} from "@/components/dusk/dialog/morphing-dialog";
function Artwork() {
return (
<div className="grid size-full place-items-center bg-muted">
<Mountain className="size-10 text-muted-foreground" aria-hidden />
</div>
);
}
export default function MorphingDialogDemo() {
return (
<MorphingDialog>
<MorphingDialogTrigger className="w-64">
<MorphingDialogMedia className="h-40">
<Artwork />
</MorphingDialogMedia>
<span className="block p-4">
<MorphingDialogTitle>Northern Ridge</MorphingDialogTitle>
<MorphingDialogSubtitle>Photo series · 12 shots</MorphingDialogSubtitle>
</span>
</MorphingDialogTrigger>
<MorphingDialogContent>
<MorphingDialogMedia className="h-64">
<Artwork />
</MorphingDialogMedia>
<div className="p-6">
<MorphingDialogTitle>Northern Ridge</MorphingDialogTitle>
<MorphingDialogSubtitle>Photo series · 12 shots</MorphingDialogSubtitle>
<MorphingDialogDescription className="mt-4 space-y-3">
<p>
Shot over three mornings above the tree line, chasing the few minutes when the fog
lifts off the valley and the ridge catches the first light.
</p>
<p>Press Escape, click outside or use the close button — focus returns to the card.</p>
</MorphingDialogDescription>
</div>
<MorphingDialogClose />
</MorphingDialogContent>
</MorphingDialog>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/dialog.json1. Install the dependencies.
npm install @radix-ui/react-dialog lucide-react2. Copy the source into
components/ui/dialog.tsx.dialog.tsx "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { XIcon } from "lucide-react" import { cn } from "@/lib/utils" /** * DuskUI Dialog — a drop-in upgrade of the shadcn/ui Dialog. * * Same parts, props and data-slot attributes as shadcn, plus: * - A short entrance: fade + slight scale (200ms ease-out), and a quicker * exit, so closing never feels sluggish. * - A dimmed backdrop and a neutral shadow on the surface. * - A larger close button with hover and focus-visible states. * - Long content scrolls inside the dialog instead of overflowing the screen. * - Under `prefers-reduced-motion` it only fades (no scale). * CSS only (tw-animate-css), powered by Radix for focus trap, Escape and aria. */ function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) { return <DialogPrimitive.Root data-slot="dialog" {...props} /> } /** The element that opens the dialog. Use `asChild` to render your own Button. */ function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) { return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} /> } /** Portals the overlay and content to `document.body`. */ function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) { return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} /> } /** Closes the dialog. Use `asChild` to render your own Button. */ function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) { return <DialogPrimitive.Close data-slot="dialog-close" {...props} /> } /** The dimmed backdrop. Clicking it closes the dialog. */ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) { return ( <DialogPrimitive.Overlay data-slot="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 DialogContent({ className, children, showCloseButton = true, ...props }: React.ComponentProps<typeof DialogPrimitive.Content> & { /** Render the X button in the top-right corner. */ showCloseButton?: boolean }) { return ( <DialogPortal data-slot="dialog-portal"> <DialogOverlay /> <DialogPrimitive.Content data-slot="dialog-content" className={cn( "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 sm:max-w-lg", "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} > {children} {showCloseButton && ( <DialogPrimitive.Close data-slot="dialog-close" className={cn( "absolute top-3 right-3 inline-flex size-8 items-center justify-center rounded-md text-muted-foreground outline-none", "transition-[color,background-color,box-shadow] duration-150 hover:bg-accent hover:text-foreground", "focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4" )} > <XIcon /> <span className="sr-only">Close</span> </DialogPrimitive.Close> )} </DialogPrimitive.Content> </DialogPortal> ) } /** Wraps the title and description. Leaves room for the close button. */ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-center sm:pr-8 sm:text-left", className)} {...props} /> ) } /** Action row. Stacks on mobile with the primary action on top. */ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="dialog-footer" className={cn( "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className )} {...props} /> ) } /** Accessible title, announced when the dialog opens. Required by Radix. */ function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) { return ( <DialogPrimitive.Title data-slot="dialog-title" className={cn("text-lg leading-none font-semibold tracking-tight", className)} {...props} /> ) } /** Supporting text linked to the dialog via aria-describedby. */ function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) { return ( <DialogPrimitive.Description data-slot="dialog-description" className={cn("text-muted-foreground text-sm leading-relaxed", className)} {...props} /> ) } export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, }
Replaces components/ui/dialog.tsx with the same exports and props, so the Command palette and existing dialogs keep working. Animations are CSS (tw-animate-css, included with shadcn/ui), so the base needs no Motion.
Usage
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
export function EditProfile() {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">Edit profile</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit profile</DialogTitle>
<DialogDescription>Changes are visible to your team.</DialogDescription>
</DialogHeader>
{/* form */}
</DialogContent>
</Dialog>
)
}Examples
Default
Fades and scales in slightly with a short ease-out, then exits faster than it entered so closing feels instant. Focus moves into the dialog and returns to the trigger.
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
export default function DialogBasicDemo() {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">Edit profile</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit profile</DialogTitle>
<DialogDescription>Changes are visible to your team right away.</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-2">
<label htmlFor="profile-name" className="text-sm font-medium">Name</label>
<Input id="profile-name" defaultValue="Ada Kim" />
</div>
<div className="grid gap-2">
<label htmlFor="profile-handle" className="text-sm font-medium">Username</label>
<Input id="profile-handle" defaultValue="@ada" />
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<DialogClose asChild>
<Button>Save changes</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}Long content
Content taller than the screen scrolls inside the dialog instead of spilling off the viewport, while the page behind stays locked.
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
const sections = [
"Using the service",
"Your content",
"Privacy",
"Payments and refunds",
"Termination",
"Liability",
"Changes to these terms",
];
export default function DialogScrollableDemo() {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">Read the terms</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Terms of service</DialogTitle>
<DialogDescription>Last updated November 2026.</DialogDescription>
</DialogHeader>
<div className="space-y-4 text-sm leading-relaxed text-muted-foreground">
{sections.map((title, i) => (
<section key={title}>
<h3 className="mb-1 font-medium text-foreground">
{i + 1}. {title}
</h3>
<p>
This is placeholder legal copy to show how long content scrolls inside the dialog
instead of overflowing the screen. The header and close button stay inside the
surface and the page behind stays locked.
</p>
</section>
))}
</div>
<DialogFooter>
<DialogClose asChild>
<Button>I agree</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Morphing Dialog
A card that expands into a dialog. The surface, media, title and subtitle share a Motion layoutId, so each part flies to its new size and position; extra content fades in after the morph. Built on Radix Dialog, so focus trapping, Escape, outside click and focus return all work. Under reduced motion it simply fades.
import { Mountain } from "lucide-react";
import {
MorphingDialog,
MorphingDialogClose,
MorphingDialogContent,
MorphingDialogDescription,
MorphingDialogMedia,
MorphingDialogSubtitle,
MorphingDialogTitle,
MorphingDialogTrigger,
} from "@/components/dusk/dialog/morphing-dialog";
function Artwork() {
return (
<div className="grid size-full place-items-center bg-muted">
<Mountain className="size-10 text-muted-foreground" aria-hidden />
</div>
);
}
export default function MorphingDialogDemo() {
return (
<MorphingDialog>
<MorphingDialogTrigger className="w-64">
<MorphingDialogMedia className="h-40">
<Artwork />
</MorphingDialogMedia>
<span className="block p-4">
<MorphingDialogTitle>Northern Ridge</MorphingDialogTitle>
<MorphingDialogSubtitle>Photo series · 12 shots</MorphingDialogSubtitle>
</span>
</MorphingDialogTrigger>
<MorphingDialogContent>
<MorphingDialogMedia className="h-64">
<Artwork />
</MorphingDialogMedia>
<div className="p-6">
<MorphingDialogTitle>Northern Ridge</MorphingDialogTitle>
<MorphingDialogSubtitle>Photo series · 12 shots</MorphingDialogSubtitle>
<MorphingDialogDescription className="mt-4 space-y-3">
<p>
Shot over three mornings above the tree line, chasing the few minutes when the fog
lifts off the valley and the ridge catches the first light.
</p>
<p>Press Escape, click outside or use the close button — focus returns to the card.</p>
</MorphingDialogDescription>
</div>
<MorphingDialogClose />
</MorphingDialogContent>
</MorphingDialog>
);
}$ npx shadcn@latest add https://duskui.com/r/morphing-dialog.json1. Install the dependencies.
npm install motion @radix-ui/react-dialog lucide-react2. Copy the source into
components/dusk/dialog/morphing-dialog.tsx.morphing-dialog.tsx "use client"; import * as React from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { XIcon } from "lucide-react"; import { cn } from "@/lib/utils"; const morph: Transition = { type: "spring", bounce: 0.1, duration: 0.5 }; const fade: Transition = { duration: 0.2, ease: "easeOut" }; type MorphingDialogContextValue = { /** Base for every shared layoutId, unique per dialog. */ id: string; open: boolean; /** Layout morphs are switched off under reduced motion; the dialog just fades. */ reduceMotion: boolean; }; const MorphingDialogContext = React.createContext<MorphingDialogContextValue | null>(null); /** Whether a part is rendered inside the trigger card or the open dialog. */ const SurfaceContext = React.createContext<"trigger" | "content">("trigger"); function useMorphingDialog() { const context = React.useContext(MorphingDialogContext); if (!context) throw new Error("MorphingDialog parts must be used inside <MorphingDialog>."); return context; } /** Shared layoutId for a part, or none under reduced motion. */ function useLayoutId(part: string) { const { id, reduceMotion } = useMorphingDialog(); return reduceMotion ? undefined : `${id}-${part}`; } export interface MorphingDialogProps { children: React.ReactNode; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; } /** * A card that morphs into a dialog. Parts with the same role in the trigger * and the content (surface, media, title, subtitle) share a Motion `layoutId`, * so they fly to their new position and size. Built on Radix Dialog: focus is * trapped inside, Escape and outside clicks close it, focus returns to the card * and the title / description are wired to aria-labelledby / -describedby. */ export function MorphingDialog({ children, open: openProp, defaultOpen = false, onOpenChange }: MorphingDialogProps) { const id = React.useId(); const reduceMotion = useReducedMotion() ?? false; const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const open = openProp ?? internalOpen; const setOpen = React.useCallback( (next: boolean) => { if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }, [openProp, onOpenChange] ); const value = React.useMemo(() => ({ id, open, reduceMotion }), [id, open, reduceMotion]); return ( <MorphingDialogContext.Provider value={value}> <DialogPrimitive.Root open={open} onOpenChange={setOpen}> {children} </DialogPrimitive.Root> </MorphingDialogContext.Provider> ); } export interface MorphingDialogTriggerProps extends Omit<React.ComponentProps<typeof motion.button>, "layoutId" | "children"> { children?: React.ReactNode; } /** The card that opens the dialog. A real `<button>`, so put only inline content (spans) inside. */ export function MorphingDialogTrigger({ className, style, children, ...props }: MorphingDialogTriggerProps) { const layoutId = useLayoutId("surface"); return ( <SurfaceContext.Provider value="trigger"> <DialogPrimitive.Trigger asChild> <motion.button type="button" layoutId={layoutId} transition={morph} // borderRadius set in style so Motion keeps corners round while scaling. style={{ borderRadius: 16, ...style }} className={cn( "relative flex flex-col overflow-hidden border bg-card text-left text-card-foreground outline-none", "transition-colors duration-150 hover:border-foreground/20", "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40", className )} {...props} > {children} </motion.button> </DialogPrimitive.Trigger> </SurfaceContext.Provider> ); } export interface MorphingDialogContentProps extends Omit<React.ComponentProps<typeof motion.div>, "layoutId" | "children"> { children?: React.ReactNode; /** Classes for the dimmed backdrop. */ overlayClassName?: string; } /** The open dialog. Rendered in a portal, centered, and scrolls if it's taller than the screen. */ export function MorphingDialogContent({ className, overlayClassName, style, children, ...props }: MorphingDialogContentProps) { const { open, reduceMotion } = useMorphingDialog(); const layoutId = useLayoutId("surface"); return ( <AnimatePresence> {open && ( // forceMount hands mounting to AnimatePresence so exit animations can play. <DialogPrimitive.Portal forceMount> <DialogPrimitive.Overlay forceMount asChild> <motion.div className={cn("fixed inset-0 z-50 bg-black/60 backdrop-blur-sm", overlayClassName)} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={fade} /> </DialogPrimitive.Overlay> <div className="pointer-events-none fixed inset-0 z-50 grid place-items-center p-4"> <SurfaceContext.Provider value="content"> <DialogPrimitive.Content forceMount asChild> <motion.div layoutId={layoutId} transition={morph} initial={reduceMotion ? { opacity: 0 } : undefined} animate={reduceMotion ? { opacity: 1 } : undefined} exit={reduceMotion ? { opacity: 0 } : undefined} style={{ borderRadius: 24, ...style }} className={cn( "pointer-events-auto relative flex max-h-[calc(100dvh-2rem)] w-full max-w-lg flex-col overflow-y-auto overflow-x-hidden border bg-card text-card-foreground outline-none", "shadow-lg", className )} {...props} > {children} </motion.div> </DialogPrimitive.Content> </SurfaceContext.Provider> </div> </DialogPrimitive.Portal> )} </AnimatePresence> ); } /** Image, illustration or color block shared by the card and the dialog. */ export function MorphingDialogMedia({ className, ...props }: Omit<React.ComponentProps<typeof motion.div>, "layoutId">) { const layoutId = useLayoutId("media"); return ( <motion.div layoutId={layoutId} transition={morph} className={cn("relative overflow-hidden", className)} {...props} /> ); } /** Title shared by the card and the dialog. Inside the dialog it's the accessible Radix title. */ export function MorphingDialogTitle({ className, ...props }: Omit<React.ComponentProps<typeof motion.h2>, "layoutId" | "layout">) { const surface = React.useContext(SurfaceContext); const layoutId = useLayoutId("title"); const shared = { layoutId, // "position" moves the text without stretching it while it re-wraps. layout: "position" as const, transition: morph, className: cn("block font-semibold tracking-tight", className), }; if (surface === "trigger") { return <motion.span {...shared} {...(props as React.ComponentProps<typeof motion.span>)} />; } return ( <DialogPrimitive.Title asChild> <motion.h2 {...shared} {...props} /> </DialogPrimitive.Title> ); } /** Secondary line shared by the card and the dialog. */ export function MorphingDialogSubtitle({ className, ...props }: Omit<React.ComponentProps<typeof motion.span>, "layoutId" | "layout">) { const layoutId = useLayoutId("subtitle"); return ( <motion.span layoutId={layoutId} layout="position" transition={morph} className={cn("block text-sm text-muted-foreground", className)} {...props} /> ); } /** * Content that only exists in the open dialog. Fades up after the morph and * fades out before the dialog shrinks back. Linked as the aria description. */ export function MorphingDialogDescription({ className, ...props }: Omit<React.ComponentProps<typeof motion.div>, "initial" | "animate" | "exit">) { const { reduceMotion } = useMorphingDialog(); return ( <DialogPrimitive.Description asChild> <motion.div className={cn("text-sm leading-relaxed text-muted-foreground", className)} initial={{ opacity: 0, y: reduceMotion ? 0 : 8 }} animate={{ opacity: 1, y: 0, transition: { ...fade, delay: reduceMotion ? 0 : 0.15 } }} exit={{ opacity: 0, y: reduceMotion ? 0 : 4, transition: { duration: 0.1 } }} {...props} /> </DialogPrimitive.Description> ); } /** Round close button pinned to the dialog's top-right corner. */ export function MorphingDialogClose({ className, children, ...props }: Omit<React.ComponentProps<typeof motion.button>, "initial" | "animate" | "exit">) { const { reduceMotion } = useMorphingDialog(); return ( <DialogPrimitive.Close asChild> <motion.button type="button" className={cn( "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full bg-black/40 text-white/80 outline-none backdrop-blur", "transition-colors hover:bg-black/60 hover:text-white focus-visible:ring-[3px] focus-visible:ring-ring/50", className )} initial={{ opacity: 0, scale: reduceMotion ? 1 : 0.96 }} animate={{ opacity: 1, scale: 1, transition: { duration: 0.2, ease: "easeOut", delay: reduceMotion ? 0 : 0.15 } }} exit={{ opacity: 0, scale: reduceMotion ? 1 : 0.96, transition: { duration: 0.1 } }} {...props} > {children ?? ( <> <XIcon className="size-4" aria-hidden /> <span className="sr-only">Close</span> </> )} </motion.button> </DialogPrimitive.Close> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state (on MorphingDialog). |
| defaultOpen | boolean | false | Uncontrolled initial state. |
| MorphingDialogTrigger | motion.button props | — | The card. Put only inline content (spans) inside. |
| MorphingDialogContent | motion.div props & { overlayClassName } | — | The open dialog, portalled and centered. |
| MorphingDialogMedia / Title / Subtitle | motion props | — | Shared parts. Use them in both the trigger and the content. |
| MorphingDialogDescription | motion.div props | — | Content-only body that fades in; wired to aria-describedby. |
| MorphingDialogClose | motion.button props | — | Round close button; children replace the X icon. |
Confirm Dialog
A confirmation dialog for risky actions. Return a promise from onConfirm and the confirm button shows the DuskUI Button loading state; Escape and outside clicks are blocked mid-request, it closes on success, and a failure shakes the dialog and shows the error inline. Optional type-to-confirm for destructive actions. Try both buttons.
"use client";
import * as React from "react";
import { Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/dusk/dialog/confirm-dialog";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default function ConfirmDialogDemo() {
return (
<>
<ConfirmDialog
trigger={
<Button variant="destructive">
<Trash2 />
Delete project
</Button>
}
variant="destructive"
title="Delete “dusk-web”?"
description="This permanently deletes the project, its deployments and domains. This can't be undone."
confirmText="dusk-web"
confirmLabel="Delete project"
pendingLabel="Deleting…"
onConfirm={async () => {
await wait(1400);
toast.success("Project deleted");
}}
/>
<ConfirmDialog
trigger={<Button variant="outline">Publish (fails)</Button>}
title="Publish to production?"
description="Your changes go live for every visitor."
confirmLabel="Publish"
onConfirm={async () => {
await wait(1200);
throw new Error("Build failed: 2 type errors. Fix them and try again.");
}}
/>
</>
);
}$ npx shadcn@latest add https://duskui.com/r/confirm-dialog.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/dialog/confirm-dialog.tsx.confirm-dialog.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useAnimate, useReducedMotion } from "motion/react"; import { TriangleAlert } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; export interface ConfirmDialogProps { /** 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; /** 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; /** Label shown next to the spinner while confirming. */ pendingLabel?: React.ReactNode; /** `destructive` turns the icon and confirm button red. */ variant?: "default" | "destructive"; /** Icon at the top. Defaults to a warning triangle for destructive dialogs; pass `null` to hide. */ icon?: React.ReactNode; /** Require the user to type this text before confirming (e.g. a project name). */ confirmText?: string; /** Message shown when `onConfirm` throws. Defaults to the error's message. */ errorMessage?: React.ReactNode; } /** * A confirmation dialog for risky actions. The confirm button shows a spinner * while your async `onConfirm` runs (keeping its width), Escape and outside * clicks are blocked mid-request, and a failure shakes the dialog and shows * the error inline. Opens with focus on Cancel and uses role="alertdialog". */ export function ConfirmDialog({ trigger, open: openProp, onOpenChange, title, description, onConfirm, confirmLabel = "Confirm", cancelLabel = "Cancel", pendingLabel, variant = "default", icon, confirmText, errorMessage, }: ConfirmDialogProps) { const id = React.useId(); const reduceMotion = useReducedMotion(); const [scope, animate] = useAnimate<HTMLDivElement>(); const cancelRef = React.useRef<HTMLButtonElement>(null); 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 destructive = variant === "destructive"; const canConfirm = !confirmText || typed === confirmText; const shownIcon = icon === undefined ? (destructive ? <TriangleAlert /> : null) : icon; const setOpen = (next: boolean) => { if (pending) return; if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }; const handleConfirm = async () => { if (pending || !canConfirm) 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, -8, 8, -5, 5, 0] }, { duration: 0.4 }); } } }; const blockWhilePending = (event: Event) => { if (pending) event.preventDefault(); }; return ( <Dialog open={open} onOpenChange={setOpen}> {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>} <DialogContent role="alertdialog" showCloseButton={false} aria-busy={pending || undefined} className="sm:max-w-md" onOpenAutoFocus={(event) => { // Fresh state on every open, starting on the safe choice // (or the text field when one is required). setError(null); setTyped(""); event.preventDefault(); (confirmText ? inputRef.current : cancelRef.current)?.focus(); }} onEscapeKeyDown={blockWhilePending} onInteractOutside={blockWhilePending} > <div ref={scope} className="grid gap-4"> <DialogHeader className="sm:pr-0"> {shownIcon && ( <motion.div aria-hidden className={cn( "mx-auto mb-2 grid size-11 place-items-center rounded-full sm:mx-0 [&_svg]:size-5", destructive ? "bg-destructive/15 text-destructive" : "border bg-muted text-foreground" )} initial={reduceMotion ? false : { scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ duration: 0.2, ease: "easeOut", delay: 0.05 }} > {shownIcon} </motion.div> )} <DialogTitle>{title}</DialogTitle> {description && <DialogDescription>{description}</DialogDescription>} </DialogHeader> {confirmText && ( <div className="grid gap-2"> <label htmlFor={`${id}-confirm-text`} className="text-sm text-muted-foreground"> Type <span className="font-mono font-medium text-foreground">{confirmText}</span> to confirm. </label> <Input ref={inputRef} id={`${id}-confirm-text`} value={typed} onChange={(event) => setTyped(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") handleConfirm(); }} readOnly={pending} autoComplete="off" spellCheck={false} /> </div> )} <AnimatePresence initial={false}> {error && ( <motion.p role="alert" className="text-sm text-destructive" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} transition={{ type: "spring", duration: 0.3, bounce: 0 }} > {error} </motion.p> )} </AnimatePresence> <DialogFooter> <Button ref={cancelRef} variant="outline" aria-disabled={pending || undefined} className="aria-disabled:opacity-50" onClick={() => setOpen(false)} > {cancelLabel} </Button> <Button variant={destructive ? "destructive" : "default"} loading={pending} loadingText={pendingLabel} // Set here too: this prop overrides the one Button derives from `loading`. aria-disabled={pending || !canConfirm || undefined} className={cn(!canConfirm && "cursor-not-allowed opacity-50")} onClick={handleConfirm} > {confirmLabel} </Button> </DialogFooter> </div> </DialogContent> </Dialog> ); }
| 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. |
| onConfirm | () => unknown | Promise<unknown> | — | Runs on confirm. Throw to keep the dialog open with an error. |
| variant | "default" | "destructive" | "default" | Destructive turns the icon and button red. |
| confirmText | string | — | Text the user must type before confirming. |
| confirmLabel / cancelLabel | ReactNode | "Confirm" / "Cancel" | Button labels. |
| pendingLabel | ReactNode | — | Shown next to the spinner while confirming. |
| icon | ReactNode | null | — | Top icon. Defaults to a warning for destructive; null hides it. |
| errorMessage | ReactNode | — | Replaces the thrown error's message. |
Drawer Dialog
A bottom sheet that slides up and can be dragged down by its handle or header to dismiss. A quick flick or a drag past closeThreshold closes it, anything less springs back, and the backdrop fades as you drag. It's still a Radix Dialog underneath, so Escape, the backdrop and the close button work too.
"use client";
import * as React from "react";
import { SlidersHorizontal } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DrawerDialog } from "@/components/dusk/dialog/drawer-dialog";
const options = ["Ready to ship", "In review", "Has open issues", "Archived"];
export default function DrawerDialogDemo() {
const [open, setOpen] = React.useState(false);
const [selected, setSelected] = React.useState<string[]>(["Ready to ship"]);
return (
<DrawerDialog
open={open}
onOpenChange={setOpen}
trigger={
<Button variant="outline">
<SlidersHorizontal />
Filters
</Button>
}
title="Filter projects"
description="Drag the handle down, flick, or press Escape to close."
footer={
<>
<Button variant="outline" onClick={() => setSelected([])}>
Clear
</Button>
<Button onClick={() => setOpen(false)}>Show results</Button>
</>
}
>
<fieldset className="grid gap-2">
<legend className="mb-2 text-sm font-medium">Status</legend>
{options.map((option) => (
<label
key={option}
className="flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-sm transition-colors hover:bg-accent/50 has-[:checked]:border-primary/40 has-[:checked]:bg-primary/5"
>
<input
type="checkbox"
className="size-4 accent-[var(--color-primary)]"
checked={selected.includes(option)}
onChange={(e) =>
setSelected((s) => (e.target.checked ? [...s, option] : s.filter((o) => o !== option)))
}
/>
{option}
</label>
))}
</fieldset>
</DrawerDialog>
);
}$ npx shadcn@latest add https://duskui.com/r/drawer-dialog.json1. Install the dependencies.
npm install motion @radix-ui/react-dialog lucide-react2. Copy the source into
components/dusk/dialog/drawer-dialog.tsx.drawer-dialog.tsx "use client"; import * as React from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { animate, AnimatePresence, motion, useDragControls, useMotionValue, useReducedMotion, useTransform, type PanInfo, } from "motion/react"; import { XIcon } from "lucide-react"; import { cn } from "@/lib/utils"; export interface DrawerDialogProps { /** Element that opens the drawer, usually a Button. Omit when controlling `open` yourself. */ trigger?: React.ReactElement; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; title: React.ReactNode; description?: React.ReactNode; /** The drawer body. Scrolls when taller than the screen allows. */ children?: React.ReactNode; /** Sticky actions under the body. */ footer?: React.ReactNode; /** Render an X button next to the title. */ showCloseButton?: boolean; /** Fraction of the drawer's height it must be dragged down to close (0–1). */ closeThreshold?: number; className?: string; } const slide = { type: "spring", duration: 0.45, bounce: 0 } as const; /** * A bottom sheet built on Radix Dialog. Slides up from the bottom, and can be * dragged down by its handle or header to dismiss — a fast flick or a drag past * `closeThreshold` closes it, anything less springs back. The backdrop fades * as you drag. Escape, the backdrop and the close button also close it, focus * is trapped inside, and with reduced motion it simply fades. */ export function DrawerDialog({ trigger, open: openProp, defaultOpen = false, onOpenChange, title, description, children, footer, showCloseButton = true, closeThreshold = 0.3, className, }: DrawerDialogProps) { const reduceMotion = useReducedMotion(); const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const open = openProp ?? internalOpen; const sheetRef = React.useRef<HTMLDivElement>(null); const dragControls = useDragControls(); // Drag offset in px. Kept separate from the enter/exit slide so they don't fight. const dragY = useMotionValue(0); const backdropOpacity = useTransform(dragY, [0, 320], [1, 0]); const setOpen = (next: boolean) => { if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }; const handleDragEnd = (_: PointerEvent, info: PanInfo) => { const height = sheetRef.current?.offsetHeight ?? 400; if (info.offset.y > height * closeThreshold || info.velocity.y > 600) { setOpen(false); } else { animate(dragY, 0, { type: "spring", duration: 0.35, bounce: 0.15 }); } }; return ( <DialogPrimitive.Root open={open} onOpenChange={setOpen}> {trigger && <DialogPrimitive.Trigger asChild>{trigger}</DialogPrimitive.Trigger>} <AnimatePresence onExitComplete={() => dragY.set(0)}> {open && ( // forceMount hands mounting to AnimatePresence so exit animations can play. <DialogPrimitive.Portal forceMount> <DialogPrimitive.Overlay forceMount asChild> <motion.div className="fixed inset-0 z-50" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.25 }} > <motion.div className="absolute inset-0 bg-black/60" style={{ opacity: backdropOpacity }} /> </motion.div> </DialogPrimitive.Overlay> <DialogPrimitive.Content forceMount asChild> <motion.div ref={sheetRef} className="fixed inset-x-0 bottom-0 z-50 mx-auto flex max-h-[calc(100dvh-3rem)] w-full max-w-lg flex-col outline-none" initial={reduceMotion ? { opacity: 0 } : { y: "100%" }} animate={reduceMotion ? { opacity: 1 } : { y: 0 }} exit={reduceMotion ? { opacity: 0 } : { y: "100%" }} transition={slide} > {/* The surface carries the drag, so the slide-in `y` above stays independent. */} <motion.div className={cn( "flex min-h-0 flex-1 flex-col rounded-t-2xl border border-b-0 bg-background", "shadow-lg", className )} style={{ y: dragY }} drag="y" dragControls={dragControls} dragListener={false} dragConstraints={{ top: 0 }} dragElastic={{ top: 0.05, bottom: 1 }} dragMomentum={false} onDragEnd={handleDragEnd} > {/* Drag zone: the handle and header. touch-none stops the page from scrolling instead. */} <div className="shrink-0 cursor-grab touch-none select-none active:cursor-grabbing" onPointerDown={(event) => { // Let buttons in the header (the close X) receive clicks. if ((event.target as HTMLElement).closest("button")) return; dragControls.start(event); }} > <div aria-hidden className="mx-auto mt-3 h-1.5 w-10 rounded-full bg-white/15" /> <div className="flex items-start gap-4 px-6 pt-4 pb-2"> <div className="grid flex-1 gap-1.5"> <DialogPrimitive.Title className="text-lg leading-none font-semibold tracking-tight"> {title} </DialogPrimitive.Title> {description ? ( <DialogPrimitive.Description className="text-sm leading-relaxed text-muted-foreground"> {description} </DialogPrimitive.Description> ) : null} </div> {showCloseButton && ( <DialogPrimitive.Close className="-mt-1 -mr-2 inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"> <XIcon className="size-4" aria-hidden /> <span className="sr-only">Close</span> </DialogPrimitive.Close> )} </div> </div> <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 py-4">{children}</div> {footer && ( <div className="flex shrink-0 flex-col-reverse gap-2 border-t px-6 pt-4 pb-[max(1.5rem,env(safe-area-inset-bottom))] sm:flex-row sm:justify-end"> {footer} </div> )} {!footer && <div aria-hidden className="h-[max(0.5rem,env(safe-area-inset-bottom))] shrink-0" />} </motion.div> </motion.div> </DialogPrimitive.Content> </DialogPrimitive.Portal> )} </AnimatePresence> </DialogPrimitive.Root> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| trigger | ReactElement | — | Element that opens the drawer. |
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state. |
| title / description | ReactNode | — | Header text, wired to aria-labelledby / -describedby. |
| footer | ReactNode | — | Actions pinned under the scrollable body. |
| showCloseButton | boolean | true | Render an X next to the title. |
| closeThreshold | number | 0.3 | Fraction of the height to drag before it closes. |
API Reference
Same parts as shadcn/ui: Dialog, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, DialogClose, DialogOverlay and DialogPortal. Each forwards the Radix Dialog props.
| Prop | Type | Default | Description |
|---|---|---|---|
| open / onOpenChange | boolean / (open: boolean) => void | — | Controlled state (on Dialog). |
| modal | boolean | true | Trap focus and lock page scroll (on Dialog). |
| showCloseButton | boolean | true | Render the X button (on DialogContent). |
| onOpenAutoFocus / onEscapeKeyDown / onInteractOutside | (event) => void | — | Radix hooks on DialogContent; call preventDefault() to override. |
Accessibility
- Built on Radix Dialog: focus is trapped inside, Escape closes, focus returns to the trigger and the page behind is hidden from screen readers.
- Always render a
DialogTitle(visually hidden withsr-onlyif needed) and a description oraria-describedby={undefined}. - Confirm Dialog uses
role="alertdialog", focuses Cancel first and keeps both buttons focusable while pending. - Under prefers-reduced-motion the base dialog only fades, the morph becomes a fade and the drawer fades instead of sliding.