Skip to content
Shaken UI
Sign in

Alert Dialog

Save

A confirmation dialog for destructive or irreversible actions, built on Base UI Alert Dialog, with a destructive tone, a typed confirmation field, and an async action that holds the dialog open while it runs.

Category
Overlays
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Alert Dialog preview

Installation

npx @shakenui/cli add alert-dialog

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add alert-dialog --dry-run

Usage

alert-dialog-example.tsx
"use client";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogConfirmation,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/shaken/ui/alert-dialog";
import { Button } from "@/components/shaken/ui/button";

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export default function AlertDialogExample() {
  return (
    <div className="flex flex-wrap items-center justify-center gap-3">
      <AlertDialog>
        <AlertDialogTrigger render={<Button variant="secondary" />}>Stop run</AlertDialogTrigger>
        <AlertDialogContent size="sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Stop this run?</AlertDialogTitle>
            <AlertDialogDescription>
              The agent finishes the tool call in progress, then stops. Two queued steps will not run, and you can resume
              from the last completed step.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Keep running</AlertDialogCancel>
            <AlertDialogAction>Stop run</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <AlertDialog>
        <AlertDialogTrigger render={<Button variant="destructive" />}>Delete project</AlertDialogTrigger>
        <AlertDialogContent tone="destructive">
          <AlertDialogHeader>
            <AlertDialogTitle>Delete acme-web?</AlertDialogTitle>
            <AlertDialogDescription>
              This removes 14 deployments, 3 environment groups, and every preview URL. It cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogConfirmation value="acme-web" />
          <AlertDialogFooter>
            <AlertDialogCancel />
            <AlertDialogAction onAction={() => wait(1400)}>Delete project</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

API

PropTypeDefaultDescription
AlertDialog open / defaultOpen / onOpenChangeboolean / boolean / (open, details) => void—Root state. Leave open unset for an uncontrolled dialog. Close requests are cancelled while an async action runs.
AlertDialogTriggerBase UI AlertDialog.Trigger props—Unstyled button that opens the dialog. Pass className, or render={<Button />}.
AlertDialogContent tone"default" | "destructive""default"Destructive adds a red warning mark beside the heading and makes AlertDialogAction a destructive button.
AlertDialogContent iconReactNode—Replaces the tone's mark. Pass null to hide it.
AlertDialogContent size"sm" | "md""md"Maximum width of the panel.
AlertDialogAction onAction() => void | Promise<unknown>—Runs the action. A returned promise keeps the dialog open with the button loading; it closes on resolve and stays open on reject.
AlertDialogAction variantButton variant—Defaults to destructive inside a destructive dialog, primary otherwise.
AlertDialogCancelButton props—Secondary button that closes without acting. Label defaults to Cancel. Disabled while the action runs.
AlertDialogConfirmation valuestring—Text the person must type, such as the project name, before the action is enabled. Compared after trimming spaces.
AlertDialogConfirmation onValueChange(typed: string, matches: boolean) => void—Called on every keystroke.
AlertDialogHeader / AlertDialogFooterComponentProps<"div">—Layout for the title block and the actions. The footer stacks on narrow screens with the action on top.
AlertDialogTitle / AlertDialogDescriptionBase UI Title / Description props—Heading and the consequence, wired to aria-labelledby and aria-describedby.

Accessibility

  • The panel has role="alertdialog" and aria-modal, is named by AlertDialogTitle, and described by AlertDialogDescription so the consequence is read when it opens.
  • Focus moves into the dialog and is trapped there; with the footer order Cancel then action, Cancel is reached before the destructive button. Closing returns focus to the trigger.
  • A click on the backdrop does not close it. Escape cancels, except while an async action is running.
  • The action is a native button that is disabled until the typed confirmation matches; a polite live region announces when the text matches, and Enter in the field confirms.
  • While the action runs, the button keeps its width and accessible name and sets aria-busy; Cancel is disabled.
  • The warning mark is decorative (aria-hidden); the danger is stated in the title and description text.
  • With reduced motion the fade, scale, and slide are removed.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/alert-dialog.tsxalert-dialog
  • Also installs button@0.2.1registry dependency
  • Also installs input@0.1.1registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/alert-dialog/0.1.1.json.

ui/alert-dialog.tsxShow
ui/alert-dialog.tsx
"use client";

import { AlertDialog as BaseAlertDialog } from "@base-ui/react/alert-dialog";
import {
  type ComponentProps,
  type KeyboardEvent,
  type MouseEvent,
  type ReactNode,
  createContext,
  useCallback,
  useContext,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { Button, type ButtonProps } from "./button";
import { Input, type InputProps } from "./input";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

export type AlertDialogTone = "default" | "destructive";

interface AlertDialogContextValue {
  /** True while an async `onAction` is running. Blocks every way of closing. */
  pending: boolean;
  setPending: (pending: boolean) => void;
  /** The text a typed confirmation expects, or null when none is rendered. */
  expected: string | null;
  setExpected: (value: string | null) => void;
  typed: string;
  setTyped: (value: string) => void;
  close: () => void;
  actionRef: React.RefObject<HTMLButtonElement | null>;
}

const AlertDialogContext = createContext<AlertDialogContextValue | null>(null);
const ToneContext = createContext<AlertDialogTone>("default");

function useAlertDialog(part: string) {
  const context = useContext(AlertDialogContext);
  if (!context) throw new Error(`${part} must be rendered inside <AlertDialog>.`);
  return context;
}

function matches(typed: string, expected: string | null) {
  return expected === null || typed.trim() === expected;
}

export interface AlertDialogProps extends BaseAlertDialog.Root.Props {}

/**
 * Groups the alert dialog parts and holds its open state. Pass `open`/`onOpenChange` to control it.
 * Unlike a Dialog, a click on the backdrop never closes it: the person has to choose an action
 * (Escape still cancels). While an async action runs, Escape and Cancel are ignored.
 */
export function AlertDialog({ onOpenChange, actionsRef: actionsRefProp, children, ...props }: AlertDialogProps) {
  const ownActionsRef = useRef<BaseAlertDialog.Root.Actions | null>(null);
  const actionsRef = actionsRefProp ?? ownActionsRef;
  const actionRef = useRef<HTMLButtonElement | null>(null);
  const [pending, setPending] = useState(false);
  const pendingRef = useRef(false);
  const [expected, setExpected] = useState<string | null>(null);
  const [typed, setTyped] = useState("");

  const updatePending = useCallback((next: boolean) => {
    pendingRef.current = next;
    setPending(next);
  }, []);

  const close = useCallback(() => actionsRef.current?.close(), [actionsRef]);

  const value = useMemo<AlertDialogContextValue>(
    () => ({ pending, setPending: updatePending, expected, setExpected, typed, setTyped, close, actionRef }),
    [pending, updatePending, expected, typed, close],
  );

  return (
    <AlertDialogContext.Provider value={value}>
      <BaseAlertDialog.Root
        actionsRef={actionsRef}
        onOpenChange={(open, details) => {
          // Nothing closes the dialog while its action is still running.
          if (!open && pendingRef.current && details.reason !== "imperative-action") {
            details.cancel();
            return;
          }
          if (!open) setTyped("");
          onOpenChange?.(open, details);
        }}
        {...props}
      >
        {children}
      </BaseAlertDialog.Root>
    </AlertDialogContext.Provider>
  );
}

/** A button that opens the alert dialog. Unstyled; pass `className`, or `render={<Button />}` to reuse your button. */
export const AlertDialogTrigger = BaseAlertDialog.Trigger;

const sizes = {
  sm: "max-w-sm",
  md: "max-w-md",
} as const;

export type AlertDialogSize = keyof typeof sizes;

export interface AlertDialogContentProps extends BaseAlertDialog.Popup.Props {
  /**
   * `destructive` adds a red warning mark beside the heading and makes AlertDialogAction a red
   * button. Use it for deleting, revoking, or anything that cannot be undone.
   */
  tone?: AlertDialogTone;
  /** Replaces the tone's mark beside the heading. Pass `null` to hide it. */
  icon?: ReactNode;
  /** Maximum width of the panel. */
  size?: AlertDialogSize;
  /** Classes for the backdrop behind the panel. */
  backdropClassName?: string;
  /** Element to portal into. Defaults to `document.body`. */
  container?: BaseAlertDialog.Portal.Props["container"];
}

function WarningMark() {
  return (
    <span
      aria-hidden="true"
      className={cx(
        "flex size-9 shrink-0 items-center justify-center rounded-full border border-red-500/30 bg-red-500/[0.08] text-red-600",
        "dark:border-red-500/35 dark:bg-red-500/[0.1] dark:text-red-400",
      )}
    >
      <svg viewBox="0 0 16 16" fill="none" className="size-4">
        <path
          d="M7.13 2.75a1 1 0 0 1 1.74 0l5.2 9.25a1 1 0 0 1-.87 1.5H2.8a1 1 0 0 1-.87-1.5l5.2-9.25Z"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
        />
        <path d="M8 6.5v2.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
        <circle cx="8" cy="11.25" r="0.85" fill="currentColor" />
      </svg>
    </span>
  );
}

/**
 * The alert dialog panel, rendered in a portal above a backdrop. It has role="alertdialog".
 * Lay it out with AlertDialogHeader, optional body content, and AlertDialogFooter.
 */
export function AlertDialogContent({
  tone = "default",
  icon,
  size = "md",
  backdropClassName,
  container,
  className,
  children,
  ...props
}: AlertDialogContentProps) {
  const mark = icon === undefined ? (tone === "destructive" ? <WarningMark /> : null) : icon;

  return (
    <ToneContext.Provider value={tone}>
      <BaseAlertDialog.Portal container={container}>
        <BaseAlertDialog.Backdrop
          className={cx(
            "fixed inset-0 z-50 bg-black/40 dark:bg-black/70",
            "transition-opacity duration-220 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
            "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-150",
            backdropClassName,
          )}
        />
        <BaseAlertDialog.Popup
          data-tone={tone}
          className={withBase(
            cx(
              // Centered with inset + auto margins so `translate` stays free for the motion.
              "fixed inset-0 z-50 m-auto flex h-fit max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col gap-5 overflow-y-auto overscroll-contain p-6",
              "rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_24px_64px_-16px_rgb(0_0_0/0.28),0_2px_6px_rgb(0_0_0/0.04)]",
              "dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_24px_64px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
              "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
              // Enter: 220ms quint ease-out from 96% and 8px low. Exit: 150ms, a smaller move.
              "transition-[opacity,scale,translate] duration-220 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
              "data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:translate-y-2 motion-safe:data-[starting-style]:scale-96",
              "data-[ending-style]:opacity-0 data-[ending-style]:duration-150 motion-safe:data-[ending-style]:translate-y-1 motion-safe:data-[ending-style]:scale-98",
              sizes[size],
            ),
            className,
          )}
          {...props}
        >
          {mark ? (
            <div className="flex items-start gap-4 max-sm:flex-col max-sm:gap-3">
              {mark}
              <div className="grid min-w-0 flex-1 gap-5">{children}</div>
            </div>
          ) : (
            children
          )}
        </BaseAlertDialog.Popup>
      </BaseAlertDialog.Portal>
    </ToneContext.Provider>
  );
}

/** Wraps the title and description. */
export function AlertDialogHeader({ className, ...props }: ComponentProps<"div">) {
  return <div className={cx("grid gap-1.5", className)} {...props} />;
}

/**
 * Holds Cancel and the action, right-aligned on wider screens and stacked on narrow ones with the
 * action on top. Put AlertDialogCancel first so it receives focus before the action.
 */
export function AlertDialogFooter({ className, ...props }: ComponentProps<"div">) {
  return <div className={cx("flex flex-col-reverse gap-2 pt-1 sm:flex-row sm:justify-end", className)} {...props} />;
}

/** The heading. Labels the alert dialog with aria-labelledby. */
export function AlertDialogTitle({ className, ...props }: BaseAlertDialog.Title.Props) {
  return <BaseAlertDialog.Title className={withBase("text-base leading-6 font-semibold tracking-[-0.01em]", className)} {...props} />;
}

/** States what will happen. Describes the alert dialog with aria-describedby, so it is read on open. */
export function AlertDialogDescription({ className, ...props }: BaseAlertDialog.Description.Props) {
  return (
    <BaseAlertDialog.Description
      className={withBase("text-sm leading-relaxed text-pretty text-zinc-600 dark:text-zinc-400", className)}
      {...props}
    />
  );
}

export interface AlertDialogCancelProps extends Omit<ButtonProps, "variant"> {}

/** Closes the alert dialog without acting. Disabled while an async action runs. */
export function AlertDialogCancel({ children = "Cancel", disabled, ...props }: AlertDialogCancelProps) {
  const { pending } = useAlertDialog("AlertDialogCancel");
  return (
    <BaseAlertDialog.Close disabled={disabled || pending} render={<Button variant="secondary" {...props} />}>
      {children}
    </BaseAlertDialog.Close>
  );
}

export interface AlertDialogActionProps extends Omit<ButtonProps, "variant"> {
  /** Defaults to `destructive` inside a destructive AlertDialogContent and `primary` otherwise. */
  variant?: ButtonProps["variant"];
  /**
   * Runs the action. Return a promise to keep the dialog open with the button in its loading state
   * until it settles: it closes when the promise resolves and stays open when it rejects, so you
   * can show what went wrong. Nothing else can close the dialog while it runs.
   */
  onAction?: () => void | Promise<unknown>;
}

/**
 * The button that confirms. Stays disabled until an AlertDialogConfirmation in the same dialog
 * matches. Call `event.preventDefault()` in `onClick` to keep the dialog open.
 */
export function AlertDialogAction({ variant, onAction, onClick, disabled, ...props }: AlertDialogActionProps) {
  const { pending, setPending, close, expected, typed, actionRef } = useAlertDialog("AlertDialogAction");
  const tone = useContext(ToneContext);
  const confirmed = matches(typed, expected);

  async function handleClick(event: MouseEvent<HTMLButtonElement>) {
    onClick?.(event);
    if (event.defaultPrevented || pending || !confirmed) return;
    const result = onAction?.();
    if (result && typeof (result as Promise<unknown>).then === "function") {
      setPending(true);
      try {
        await result;
        setPending(false);
        close();
      } catch {
        // Stay open so the caller can show the error inside the dialog.
        setPending(false);
      }
      return;
    }
    close();
  }

  return (
    <Button
      ref={actionRef}
      variant={variant ?? (tone === "destructive" ? "destructive" : "primary")}
      loading={pending}
      disabled={disabled || !confirmed}
      onClick={handleClick}
      {...props}
    />
  );
}

export interface AlertDialogConfirmationProps extends Omit<InputProps, "value" | "defaultValue" | "onChange"> {
  /** The exact text the person must type, such as the project name. Compared after trimming spaces. */
  value: string;
  /** Called with the typed text and whether it matches. */
  onValueChange?: (typed: string, matches: boolean) => void;
}

/**
 * A field that asks the person to type `value` before AlertDialogAction is enabled, for actions
 * where a slip would be costly. Enter in the field confirms once the text matches.
 */
export function AlertDialogConfirmation({
  value,
  onValueChange,
  label,
  description,
  onKeyDown,
  ...props
}: AlertDialogConfirmationProps) {
  const { setExpected, typed, setTyped, pending, actionRef } = useAlertDialog("AlertDialogConfirmation");
  const hintId = useId();

  useEffect(() => {
    setExpected(value);
    return () => setExpected(null);
  }, [value, setExpected]);

  const ok = matches(typed, value);

  function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    onKeyDown?.(event);
    if (event.defaultPrevented || event.key !== "Enter" || !ok) return;
    event.preventDefault();
    actionRef.current?.click();
  }

  return (
    <div className="grid gap-1.5">
      <Input
        autoComplete="off"
        autoCapitalize="off"
        autoCorrect="off"
        spellCheck={false}
        containerClassName="gap-2"
        className="font-mono"
        {...props}
        label={
          label ?? (
            <span className="font-normal text-zinc-600 dark:text-zinc-400">
              Type{" "}
              <code className="rounded-md border border-zinc-950/[0.07] bg-zinc-950/[0.03] px-1.5 py-0.5 font-mono text-xs font-medium text-zinc-950 select-all dark:border-white/[0.1] dark:bg-transparent dark:text-white">
                {value}
              </code>{" "}
              to confirm
            </span>
          )
        }
        description={description}
        value={typed}
        onChange={(event) => {
          setTyped(event.target.value);
          onValueChange?.(event.target.value, matches(event.target.value, value));
        }}
        onKeyDown={handleKeyDown}
        disabled={pending || props.disabled}
        aria-describedby={cx(hintId, props["aria-describedby"])}
      />
      {/* Announces the moment the text matches, since the enabled button is out of view for screen readers. */}
      <span id={hintId} aria-live="polite" className="sr-only">
        {ok && typed ? "Text matches. The action is now enabled." : ""}
      </span>
    </div>
  );
}