Dialog
A modal that traps focus and closes on Esc.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/, installsradix-ui@base-ui/reactand the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.$ pnpm dlx asta-ui@latest add dialog --radixOr install the package
Don’t want the file? Import from
asta-uiasta-ui/baseand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-ui radix-ui @base-ui/reactimport { Dialog } from "asta-ui";import { Dialog } from "asta-ui/base";Or copy it by hand
Install
radix-ui@base-ui/react, then copy this file. Keep the paths, or fix the@/imports. Then add the tokens fromglobals.css."use client"; import { Dialog as D } from "radix-ui"; import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const EASE = "cubic-bezier(.16,1,.3,1)"; const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'; export interface DialogProps { open: boolean; onOpenChange: (open: boolean) => void; title: ReactNode; description?: ReactNode; children?: ReactNode; /** Buttons row at the bottom. */ footer?: ReactNode; /** Keep the overlay inside the nearest positioned parent instead of the whole viewport. */ contained?: boolean; className?: string; } /** * A modal on Radix Dialog that grows out of whatever opened it (the focused element when `open` turns true) * and shrinks back into it on close. Radix traps focus, closes on Escape or a click outside, hides the rest * of the page from screen readers and locks scrolling; focus goes back to the trigger afterwards. * Put `data-autofocus` on the field that should take focus first. */ export function Dialog({ open, onOpenChange, title, description, children, footer, contained = false, className }: DialogProps) { // Stays mounted through the exit animation, so Radix gets `forceMount` and we unmount ourselves. const [mounted, setMounted] = useState(open); if (open && !mounted) setMounted(true); const panel = useRef<HTMLDivElement>(null); const backdrop = useRef<HTMLDivElement>(null); const opener = useRef<HTMLElement | null>(null); const fromTrigger = () => { const p = panel.current?.getBoundingClientRect(); const t = opener.current?.getBoundingClientRect(); if (!p || !t || !t.width) return "translateY(12px) scale(.96)"; const dx = t.left + t.width / 2 - (p.left + p.width / 2); const dy = t.top + t.height / 2 - (p.top + p.height / 2); return `translate(${dx}px, ${dy}px) scale(${Math.max(0.15, t.width / p.width)}, ${Math.max(0.1, t.height / p.height)})`; }; const still = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; // Enter: grow out of the trigger. Layout effects run before Radix moves focus, so the active element is the opener. useLayoutEffect(() => { if (!open || !panel.current) return; const p = panel.current; if (!p.contains(document.activeElement)) opener.current = document.activeElement as HTMLElement | null; // Reopened mid-exit: drop the held exit frame, or the panel stays invisible once the enter ends. for (const el of [p, backdrop.current]) el?.getAnimations().forEach((a) => a.cancel()); const from = still() ? "none" : fromTrigger(); p.animate([{ transform: from, opacity: 0 }, { transform: "none", opacity: 1 }], { duration: 520, easing: EASE }); backdrop.current?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: "ease-out" }); }, [open]); // Exit: shrink back into the trigger, then unmount (Radix returns focus via onCloseAutoFocus). useEffect(() => { if (open || !mounted) return; const p = panel.current; if (!p || still()) return setMounted(false); backdrop.current?.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200, easing: "ease-out", fill: "forwards" }); const a = p.animate([{ transform: "none", opacity: 1 }, { transform: fromTrigger(), opacity: 0 }], { duration: 280, easing: EASE, fill: "forwards" }); a.onfinish = () => setMounted(false); return () => { a.onfinish = null; }; }, [open, mounted]); if (!mounted) return null; const layer = ( <div className={cx(contained ? "absolute" : "fixed", "inset-0 z-50 flex items-center justify-center p-4")}> <D.Overlay forceMount ref={backdrop} className={cx("absolute inset-0 bg-[color-mix(in_srgb,var(--color-ink)_38%,transparent)] will-change-[opacity]", contained && "rounded-[inherit]")} /> <D.Content forceMount ref={panel} // No description: tell Radix on purpose, so it doesn't warn. {...(description ? {} : { "aria-describedby": undefined })} onOpenAutoFocus={(e) => { e.preventDefault(); const p = panel.current; const first = p?.querySelector<HTMLElement>("[data-autofocus]") ?? p?.querySelector<HTMLElement>(FOCUSABLE); (first ?? p)?.focus({ preventScroll: true }); }} onCloseAutoFocus={(e) => { e.preventDefault(); opener.current?.focus({ preventScroll: true }); opener.current = null; }} className={cx( "relative max-h-full w-full max-w-[400px] overflow-y-auto overscroll-contain rounded-2xl bg-paper p-6 outline-none", "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent),0_24px_60px_-20px_rgb(0_0_0/0.45)]", className, )} > <D.Close aria-label="Close" className="absolute right-3.5 top-3.5 flex h-8 w-8 items-center justify-center rounded-full text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50" > <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.55" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m6 6 12 12" /> <path d="M18 6 6 18" /> </svg> </D.Close> <D.Title className="pr-8 text-[18px] font-medium tracking-[-0.02em] text-ink">{title}</D.Title> {description && <D.Description className="mt-1.5 text-[14px] leading-relaxed text-mute">{description}</D.Description>} {children && <div className="mt-5">{children}</div>} {footer && <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">{footer}</div>} </D.Content> </div> ); return ( <D.Root open={open} onOpenChange={onOpenChange}> {contained ? layer : <D.Portal forceMount>{layer}</D.Portal>} </D.Root> ); } export default Dialog;"use client"; import { Dialog as D } from "@base-ui/react/dialog"; import { useCallback, useLayoutEffect, useRef, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const EASE = "cubic-bezier(.16,1,.3,1)"; const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'; export interface DialogProps { open: boolean; onOpenChange: (open: boolean) => void; title: ReactNode; description?: ReactNode; children?: ReactNode; /** Buttons row at the bottom. */ footer?: ReactNode; /** Keep the overlay inside the nearest positioned parent instead of the whole viewport. */ contained?: boolean; className?: string; } const still = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; /** * A modal on Base UI Dialog that grows out of whatever opened it (the focused element when `open` turns true) * and shrinks back into it on close. Base UI traps focus, closes on Escape or a click outside, hides the rest * of the page from screen readers and locks scrolling; focus goes back to the trigger afterwards. * Put `data-autofocus` on the field that should take focus first. */ export function Dialog({ open, onOpenChange, title, description, children, footer, contained = false, className }: DialogProps) { const panel = useRef<HTMLDivElement | null>(null); const backdrop = useRef<HTMLDivElement>(null); const opener = useRef<HTMLElement | null>(null); const host = useRef<HTMLSpanElement>(null); const fromTrigger = useCallback(() => { const p = panel.current?.getBoundingClientRect(); const t = opener.current?.getBoundingClientRect(); if (!p || !t || !t.width) return "translateY(12px) scale(.96)"; const dx = t.left + t.width / 2 - (p.left + p.width / 2); const dy = t.top + t.height / 2 - (p.top + p.height / 2); return `translate(${dx}px, ${dy}px) scale(${Math.max(0.15, t.width / p.width)}, ${Math.max(0.1, t.height / p.height)})`; }, []); // Remember the opener before Base UI moves focus into the dialog. const enter = useCallback( (el: HTMLElement) => { el.animate([{ transform: still() ? "none" : fromTrigger(), opacity: 0 }, { transform: "none", opacity: 1 }], { duration: still() ? 160 : 520, easing: EASE }); backdrop.current?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: "ease-out" }); }, [fromTrigger], ); useLayoutEffect(() => { if (open && !panel.current?.contains(document.activeElement)) opener.current = document.activeElement as HTMLElement | null; // Reopened mid-exit: the popup is still mounted with the exit frame held. Drop it and play the enter again. const p = panel.current; if (!open || !p || !p.getAnimations().some((a) => a.effect?.getTiming().fill === "forwards")) return; for (const el of [p, backdrop.current]) el?.getAnimations().forEach((a) => a.cancel()); enter(p); }, [open, enter]); // Enter: grow out of the trigger as soon as the popup is in the DOM. const attach = useCallback( (el: HTMLDivElement | null) => { panel.current = el; if (!el || !el.hasAttribute("data-open")) return; enter(el); }, [enter], ); // Exit: shrink back into the trigger. Base UI waits for this animation before it unmounts the popup. useLayoutEffect(() => { const p = panel.current; if (open || !p || still()) return; backdrop.current?.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200, easing: "ease-out", fill: "forwards" }); p.animate([{ transform: "none", opacity: 1 }, { transform: fromTrigger(), opacity: 0 }], { duration: 280, easing: EASE, fill: "forwards" }); }, [open, fromTrigger]); return ( <> {contained && <span ref={host} className="contents" />} <D.Root open={open} onOpenChange={(next) => onOpenChange(next)}> <D.Portal container={contained ? host : undefined}> <div className={cx(contained ? "absolute" : "fixed", "inset-0 z-50 flex items-center justify-center p-4")}> <D.Backdrop ref={backdrop} className={cx("absolute inset-0 bg-[color-mix(in_srgb,var(--color-ink)_38%,transparent)] will-change-[opacity]", contained && "rounded-[inherit]")} /> <D.Popup ref={attach} initialFocus={() => { const p = panel.current; return p?.querySelector<HTMLElement>("[data-autofocus]") ?? p?.querySelector<HTMLElement>(FOCUSABLE) ?? p ?? true; }} finalFocus={() => { const back = opener.current; opener.current = null; return back && back.isConnected ? back : true; }} className={cx( "relative max-h-full w-full max-w-[400px] overflow-y-auto overscroll-contain rounded-2xl bg-paper p-6 outline-none", "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent),0_24px_60px_-20px_rgb(0_0_0/0.45)]", className, )} > <D.Close aria-label="Close" className="absolute right-3.5 top-3.5 flex h-8 w-8 items-center justify-center rounded-full text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50" > <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.55" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m6 6 12 12" /> <path d="M18 6 6 18" /> </svg> </D.Close> <D.Title className="pr-8 text-[18px] font-medium tracking-[-0.02em] text-ink">{title}</D.Title> {description && <D.Description className="mt-1.5 text-[14px] leading-relaxed text-mute">{description}</D.Description>} {children && <div className="mt-5">{children}</div>} {footer && <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">{footer}</div>} </D.Popup> </div> </D.Portal> </D.Root> </> ); } export default Dialog;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Dialog component to my project. A modal that traps focus and closes on Esc. It includes: confirm, focus trap, escape. Install it (Radix build): ```sh pnpm dlx asta-ui@latest add dialog --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/dialog.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { Dialog } from "@/components/astabyte/dialog"; ``` Usage example and props: https://ui.astabyte.com/dialog Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package). - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Add the Astabyte UI Dialog component to my project. A modal that traps focus and closes on Esc. It includes: confirm, focus trap, escape. Install it (Base UI build): ```sh pnpm dlx asta-ui@latest add dialog ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/dialog.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { Dialog } from "@/components/astabyte/dialog"; ``` Usage example and props: https://ui.astabyte.com/dialog Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package). - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- Needs asta.js: data-asta-open opens the dialog, data-asta-close and Escape close it with the exit motion. --> <button type="button" class="asta-btn asta-btn-accent" data-asta-open="ex-invite"><span class="asta-btn-label">Invite teammate</span></button> <dialog id="ex-invite" class="asta-dialog" aria-labelledby="ex-invite-title" aria-describedby="ex-invite-desc"> <button type="button" class="asta-dialog-close" data-asta-close aria-label="Close"><svg viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><path d="M3 3l8 8M11 3 3 11"/></svg></button> <h2 id="ex-invite-title" class="asta-dialog-title">Invite to Astabyte</h2> <p id="ex-invite-desc" class="asta-dialog-desc">They get an email with a link to join.</p> <form class="asta-dialog-body" hx-post="/invite" hx-target="this" hx-swap="outerHTML"> <label class="asta-input"><input class="asta-input-control" name="email" type="email" autocomplete="email" inputmode="email" autocapitalize="none" spellcheck="false" placeholder="[email protected]"></label> <div class="asta-dialog-footer"> <button type="button" class="asta-btn asta-btn-ghost" data-asta-close><span class="asta-btn-label">Cancel</span></button> <button type="submit" class="asta-btn asta-btn-accent"><span class="asta-btn-label">Send invite</span></button> </div> </form> </dialog>
Usage
The demo above, as code.
"use client";
import { useState } from "react";
import { Button } from "@/components/astabyte/button";
import { Dialog } from "@/components/astabyte/dialog";
const NAME = "astabyte-web";
export default function DialogDemo() {
const [open, setOpen] = useState(false);
const [typed, setTyped] = useState("");
const [busy, setBusy] = useState(false);
const [deleted, setDeleted] = useState(false);
const close = (v: boolean) => {
setOpen(v);
if (!v) setTyped("");
};
const confirm = () => {
setBusy(true);
setTimeout(() => {
setBusy(false);
setDeleted(true);
close(false);
}, 900);
};
return (
<div className="relative flex min-h-[420px] w-full flex-col items-center justify-center gap-4 overflow-hidden p-6 sm:p-10">
<div className="flex w-full max-w-sm items-center justify-between gap-4 rounded-xl bg-paper p-4 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent)]">
<div className="min-w-0">
<p className={`truncate font-mono text-[13px] ${deleted ? "text-mute line-through" : "text-ink"}`}>{NAME}</p>
<p className="mt-0.5 text-[12px] text-mute">{deleted ? "Deleted just now" : "Production · 12 deploys"}</p>
</div>
{deleted ? (
<Button size="sm" variant="soft" onClick={() => setDeleted(false)}>
Restore
</Button>
) : (
<Button size="sm" variant="outline" className="text-ink" onClick={() => setOpen(true)}>
Delete
</Button>
)}
</div>
<Dialog
contained
open={open}
onOpenChange={close}
title="Delete this project?"
description="This removes every deploy and domain. It cannot be undone."
footer={
<>
<Button variant="outline" onClick={() => close(false)}>
Cancel
</Button>
<Button variant="danger" disabled={typed !== NAME} loading={busy} onClick={confirm}>
Delete project
</Button>
</>
}
>
<label className="block text-[13px] text-ink-2">
Type <span className="font-mono text-ink">{NAME}</span> to confirm
<input
data-autofocus
name="confirm"
value={typed}
onChange={(e) => setTyped(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && typed === NAME && confirm()}
spellCheck={false}
autoComplete="off"
autoCapitalize="none"
className="mt-2 h-10 w-full rounded-lg bg-paper px-3 font-mono text-[16px] sm:text-[13px] text-ink outline-none shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] transition-shadow focus:shadow-[inset_0_0_0_1px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_14%,transparent)]"
/>
</label>
</Dialog>
<p className="text-[12px] text-mute">Tab stays inside the dialog · Esc closes it</p>
</div>
);
}