# Destructive actions

Undo over confirm: make a destructive action reversible and offer Undo, and confirm only what cannot be taken back.

API [ConfirmDialog](/ui/storybook/?path=/docs/ui-confirmdialog--docs) [Button](/ui/storybook/?path=/docs/ui-primitives-button--docs) [Toaster](/ui/storybook/?path=/docs/ui-primitives-toaster--docs) [DropdownMenu](/ui/storybook/?path=/docs/ui-primitives-dropdownmenu--docs) [UnsavedChangesDialog](/ui/storybook/?path=/docs/ui-unsavedchangesdialog--docs) [Tooltip](/ui/storybook/?path=/docs/ui-primitives-tooltip--docs) [Input](/ui/storybook/?path=/docs/ui-primitives-input--docs)

**Make a destructive action reversible and offer Undo afterwards, rather than asking first. Confirm only the step that cannot be undone, and say exactly what it destroys.**

```tsx
import { INBOX_THREADS } from "@orz/fixtures/inbox.ts";
import { Button } from "@orz/ui/components/button";
import { ConfirmDialog } from "@orz/ui/components/confirm-dialog";
import { EmptyState } from "@orz/ui/components/empty-state";
import { List, ListItem } from "@orz/ui/components/list";
import { Separator } from "@orz/ui/components/separator";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@orz/ui/components/tooltip";
import { ArchiveIcon, Trash2Icon } from "lucide-react";
import { useLayoutEffect, useRef, useState } from "react";
import { toast } from "sonner";

type Folder = "inbox" | "archive" | "trash" | "gone";
type Move = "archive" | "trash";

const THREADS = INBOX_THREADS.filter(({ folder }) => folder === undefined)
  .slice(0, 4)
  .map(({ id, subject }) => ({ id, subject, folder: "inbox" as Folder }));

const MOVED = { archive: "archived", trash: "moved to Trash" };

const conversations = (n: number) =>
  n === 1 ? "Conversation" : `${n} conversations`;

export function DeleteWithUndo() {
  const [threads, setThreads] = useState(THREADS);
  const [confirming, setConfirming] = useState(false);
  // Kept apart from `confirming` so the dialog keeps its title while it fades out.
  const [deleting, setDeleting] = useState<typeof THREADS>([]);
  const inbox = threads.filter(({ folder }) => folder === "inbox");
  const trash = threads.filter(({ folder }) => folder === "trash");
  // A row's button goes with its row, focus and all: the same button on the row now in its
  // place takes the focus, else the one on the row before it, else the empty inbox.
  const inboxList = useRef<HTMLDivElement>(null);
  const place = useRef<{ row: number; action: Move } | null>(null);
  useLayoutEffect(() => {
    const kept = place.current;
    place.current = null;
    if (!kept || !inboxList.current) return;
    const rows = inboxList.current.querySelectorAll("li");
    const row = rows[Math.min(kept.row, rows.length - 1)];
    const target = row
      ? row.querySelector<HTMLElement>(`[data-action=${kept.action}]`)
      : inboxList.current.querySelector<HTMLElement>("[data-slot=empty-state]");
    target?.focus();
  });
  const fileAs = (id: string, folder: Folder) =>
    setThreads((list) =>
      list.map((thread) => (thread.id === id ? { ...thread, folder } : thread)),
    );
  const move = (id: string, to: Move, button: HTMLElement) => {
    if (document.activeElement === button) {
      place.current = {
        row: inbox.findIndex((thread) => thread.id === id),
        action: to,
      };
    }
    fileAs(id, to);
    toast(`Conversation ${MOVED[to]}`, {
      action: { label: "Undo", onClick: () => fileAs(id, "inbox") },
    });
  };
  const one = deleting.length === 1;
  return (
    <TooltipProvider>
      <div className="grid grid-cols-1 gap-3">
        <List ref={inboxList} purpose="collection">
          {inbox.length > 0 ? (
            <ul>
              {inbox.map(({ id, subject }) => (
                <ListItem key={id} asChild>
                  <li className="flex min-h-row items-center gap-1">
                    <span className="min-w-0 flex-1 truncate text-ui">
                      {subject}
                    </span>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon-xs"
                          aria-label={`Archive “${subject}”`}
                          data-action="archive"
                          onClick={(event) =>
                            move(id, "archive", event.currentTarget)
                          }
                        >
                          <ArchiveIcon />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>Archive</TooltipContent>
                    </Tooltip>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon-xs"
                          aria-label={`Delete “${subject}”`}
                          data-action="trash"
                          onClick={(event) =>
                            move(id, "trash", event.currentTarget)
                          }
                        >
                          <Trash2Icon />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>Delete</TooltipContent>
                    </Tooltip>
                  </li>
                </ListItem>
              ))}
            </ul>
          ) : (
            <EmptyState
              title="Nothing in Inbox"
              tabIndex={-1}
              className="py-2 outline-none"
            >
              New mail lands here. Archive what you have dealt with.
            </EmptyState>
          )}
        </List>
        <Separator />
        <div className="flex items-center gap-2">
          <span className="flex-1 text-muted-foreground text-ui">
            Trash:{" "}
            {trash.length === 0
              ? "empty"
              : conversations(trash.length).toLowerCase()}
          </span>
          <Button
            variant="destructive"
            size="sm"
            disabled={trash.length === 0}
            onClick={() => {
              setDeleting(trash);
              setConfirming(true);
            }}
          >
            Delete forever…
          </Button>
        </div>
        <ConfirmDialog
          open={confirming}
          onOpenChange={setConfirming}
          title={
            one
              ? `Delete “${deleting[0]?.subject}” forever?`
              : `Delete ${deleting.length} conversations forever?`
          }
          description={
            one
              ? "It cannot be restored. To keep it, move it back to the inbox instead."
              : "They cannot be restored. To keep them, move them back to the inbox instead."
          }
          confirmLabel={
            one ? "Delete forever" : `Delete ${deleting.length} conversations`
          }
          destructive
          onConfirm={() => {
            setThreads((list) =>
              list.map((thread) =>
                deleting.some(({ id }) => id === thread.id)
                  ? { ...thread, folder: "gone" }
                  : thread,
              ),
            );
            setConfirming(false);
            // Their Undo would bring back conversations that no longer exist.
            toast.dismiss();
            toast(`${conversations(deleting.length)} deleted forever`);
          }}
        />
      </div>
    </TooltipProvider>
  );
}
```

Mail's conversations, as in the Mail demo. Archiving one, or deleting it into Trash, happens at once, with **Undo** in the toast: nothing is lost yet, so nothing is asked. **Delete forever…** cannot be undone, so it is the one step that asks, naming the conversation or how many go, and pointing at the way to keep them. A conversation that goes takes its button's focus with it, so the same button on the row now in its place takes it, as [Accessibility](/ui/guidelines/content/accessibility/index.md#focus) asks.

## Do and don't

**Do**

Ask a question that names the thing and the count, and label the button with the same verb: **Delete 3 conversations**.

**Don't**

Ask "Are you sure?" with **OK**: people learn to press it without reading.

**Do**

Archive, move to the trash or hide, and toast with **Undo**. The fast path stays fast and a slip costs one tap.

**Don't**

Confirm every delete. A dialog on each one teaches people to click through it, so it no longer protects the one delete that mattered.

## Which safeguard

| The action                                           | Can it be reversed?        | Safeguard                                                                   |
| ---------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------- |
| Archive, hide, move to the trash, remove from a list | Yes                        | Do it, toast with **Undo**                                                  |
| Remove a past query from a search box's history      | Yes, by searching it again | Do it, with no toast, see [Search](/ui/guidelines/patterns/search/index.md) |
| Delete, where the app keeps a trash or history       | Yes, from there            | Do it, toast with **Undo** and say where it went                            |
| Discard unsaved edits by leaving                     | No                         | `UnsavedChangesDialog`, see [Forms](/ui/guidelines/patterns/forms/index.md) |
| Delete for good, empty the trash, revoke a token     | No                         | `ConfirmDialog` with `destructive`                                          |
| Delete something large or shared that others rely on | No                         | `ConfirmDialog`, and say what else goes with it                             |

```tsx
import { type AccessToken, TOKENS } from "@orz/fixtures/account.ts";
import { Button } from "@orz/ui/components/button";
import { ConfirmDialog } from "@orz/ui/components/confirm-dialog";
import { EmptyState } from "@orz/ui/components/empty-state";
import { List, ListItem } from "@orz/ui/components/list";
import { KeyRoundIcon } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

export function RevokeToken() {
  const [tokens, setTokens] = useState(TOKENS);
  const [revoking, setRevoking] = useState<AccessToken>();
  // Kept apart from `revoking` so the dialog keeps its title while it fades out.
  const [open, setOpen] = useState(false);
  return (
    <div className="grid">
      <List purpose="collection">
        {tokens.length > 0 ? (
          <ul>
            {tokens.map((token) => (
              <ListItem key={token.id} asChild>
                <li className="flex min-h-row items-center gap-3 py-3">
                  <KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
                  <div className="grid min-w-0 flex-1 gap-0.5">
                    <span className="truncate font-medium font-mono text-ui">
                      {token.name}
                    </span>
                    <span className="text-muted-foreground text-ui-sm">
                      {token.scopes} · {token.lastUsed}
                    </span>
                  </div>
                  <Button
                    variant="destructive"
                    size="sm"
                    aria-label={`Revoke ${token.name}`}
                    onClick={() => {
                      setRevoking(token);
                      setOpen(true);
                    }}
                  >
                    Revoke…
                  </Button>
                </li>
              </ListItem>
            ))}
          </ul>
        ) : (
          <EmptyState title="No access tokens" className="py-3">
            Scripts and bots that need one get it from the command line.
          </EmptyState>
        )}
      </List>
      <ConfirmDialog
        open={open}
        onOpenChange={setOpen}
        title={`Revoke the token for ${revoking?.name}?`}
        description="Anything that signs in with it stops working at once. A revoked token cannot be restored: you would create a new one and update everything that used the old."
        confirmLabel="Revoke"
        destructive
        onConfirm={() => {
          setTokens((list) => list.filter((each) => each !== revoking));
          setOpen(false);
          toast(`Revoked the token for ${revoking?.name}`);
        }}
      />
    </div>
  );
}
```

The Settings demo's access tokens. A revoked token cannot be restored, and every script that signs in with it stops, so **Revoke…** asks first and says both.

`ConfirmDialog` asks no one to type a name back. It is sized for actions whose irreversible step has a reversible alternative the wording can point at ("Archive it instead to keep its history"). An action with no such alternative, that destroys a lot, deserves more than this dialog.

A delete inside a Dialog, a Sheet or a menu follows the same table. Do it and toast with **Undo** while the overlay stays open: the toast comes up over it and takes the pointer there, and **Undo** runs without closing the overlay. From the keyboard Alt+T reaches it, and the focus comes back to the overlay afterwards.

## Writing the confirmation

- The title is the question, with the object: "Delete 3 conversations forever?", "Revoke the token for ci-runner?".
- The description says what cannot be undone and, if there is one, the reversible alternative. Where the title already says it all ("Discard changes?"), leave the description out: the title then stands straight over the buttons.
- The confirm button repeats the verb: **Delete**, **Revoke**. The cancel button is **Cancel**.
- The confirm button uses `destructive`. `ConfirmDialog` opens with focus on **Cancel**, so a stray Enter cancels.

## Placement

- In a menu, a destructive item comes last, after a separator, with `variant="destructive"`.
- In a toolbar or a row, a destructive action is a ghost or `destructive` button away from the primary one, never the primary button itself.
- Bulk actions say their count in the label: **Delete 3 conversations**.

## On each platform

### Desktop & pointer

- Undo is also a shortcut where the app has one (Ctrl+Z or ⌘Z) for the last destructive action.
- A row's delete button is always drawn, quiet and small, or waits in the row's `⋯` menu: never only on hover.

### Touch

- Nothing appears only on hover: a row's delete action is always visible, or lives in the row's menu.
- A toast sits at the screen's edge, away from the thumb. Keep it up long enough for **Undo** to be reached, and offer the same undo where the item was, if the app has a place for it.
- A swipe that deletes is still followed by **Undo**: a swipe is easy to make by accident.

## In the demos

- [Releases](/ui/demos/releases/index.md): Roll back, Promote, Retry and a tag act at once and offer Undo in their toast. Delete release… is the one step that asks, naming the release and what goes with it.
- [Settings](/ui/demos/settings/index.md): Discard changes in Profile acts at once and offers Undo. Revoke… a token is the one step that asks first, naming the token and that it cannot be restored.
- [Admin](/ui/demos/admin/index.md): In Members, changing a role and revoking an invitation act at once and offer Undo in their toast. In Settings, Delete workspace… asks first, and Cancel deletion stands in its place for the thirty days before it goes.
- [Tasks](/ui/demos/tasks/index.md): Select a few tasks and close them: they go at once, with Undo in the toast. Delete… is last in every row's menu, after a separator, and it is the one action that asks first, naming the tasks.
- [Mail](/ui/demos/mail/index.md): Archive or delete a conversation: it moves at once, and the toast says where it went with Undo. In Trash, Delete forever… is the one step that asks, and it sits last in More actions.
- [Notes](/ui/demos/notes/index.md): More actions → Delete note: the note goes at once, and Undo in the toast puts it back where it was. Nothing asks first.
- [Config editor](/ui/demos/config-editor/index.md): Review changes, then Discard changes: the edits go at once, and Undo in the toast brings them back. Only switching files over unsaved edits asks first.
- [Binary inspector](/ui/demos/binary-inspector/index.md): Edit a few bytes: Undo takes each one back. Revert… drops them all, so it is the one step that asks, and its dialog points at Download as the way to keep a copy.
