# Undo Pill

> Undo toast for React and shadcn: a pill with a draining countdown ring that commits the destructive action only when it runs out.

A pill that rises after a destructive action with a draining countdown ring. Undo (or ⌘Z / Ctrl+Z) reverts it; only expiry commits it. Hover or focus pauses the countdown.

Also known as an undo toast or an undo snackbar.

- Tier: Free (MIT)
- Interaction: Press
- Page: https://eased.dev/components/undo-pill
- Installs: motion
- Registry: https://eased.dev/r/undo-pill.json

## Install

```bash
npx shadcn add https://eased.dev/r/undo-pill.json
```

The never-act-immediately pattern: a destructive action shows a floating pill with a draining ring; Undo reverts it, and only expiry commits it.

## When to use

- Deleting, archiving or moving things people may regret: files, messages, rows. The action looks instant and stays reversible for five seconds.
- Repeated actions in a row: with `useUndoQueue`, everything done while the pill is open joins one batch ("Deleted 3 files") and one Undo restores it all.
- Lists and tables where a confirm dialog on every delete would slow people down.

## When not to use

- Actions that cannot be reversed once they start (sending an email to a list, charging a card): confirm first, with a dialog.
- Confirming a success that needs no action ("Saved"): announce it with a status message instead.
- Errors: show them inline beside what failed.

## Usage

Remove the item from view at once, and commit the real delete only in `onCommit`.

```tsx files.tsx
import { useState } from "react";
import { UndoPill, useUndoQueue } from "@/components/eased/undo-pill/undo-pill";

type File = { id: string; name: string };

export function Files({ initial, remove }: { initial: File[]; remove: (ids: string[]) => Promise<void> }) {
  const [files, setFiles] = useState(initial);
  const queue = useUndoQueue<File>({
    message: (items) => (items.length === 1 ? `Deleted “${items[0].name}”` : `Deleted ${items.length} files`),
    onUndo: (items) => setFiles((current) => [...current, ...items]),
    onCommit: (items) => remove(items.map((f) => f.id)),
  });

  const del = (file: File) => {
    setFiles((current) => current.filter((f) => f.id !== file.id));
    queue.push(file);
  };

  return (
    <div className="relative">
      {/* … the list, with a delete button calling del(file) … */}
      <UndoPill {...queue.pill} />
    </div>
  );
}
```

The pill positions itself in its nearest positioned parent, so give that parent `relative`.

## Examples

### At the top

For layouts with a bottom bar, place it at the top; it then enters from above.

```tsx
<UndoPill {...queue.pill} placement="top" />
```

### Without the hook

Drive it yourself: keep it mounted and toggle `open`, so the exit animates.

```tsx
<UndoPill
  open={pending !== null}
  message={`Archived “${pending?.subject}”`}
  onUndo={() => restore(pending)}
  onExpire={() => commitArchive(pending)}
  duration={8000}
/>
```

## API reference

### UndoPill

| Prop | Type | Default | Description |
|---|---|---|---|
| `open` | `boolean` | | Show the pill. Keep it mounted and toggle this so the exit animates. |
| `message` | `string` | | What happened, e.g. `Deleted "Q3 roadmap.pdf"`. Changing it restarts the countdown. |
| `onUndo` | `() => void` | | Put things back. |
| `onExpire` | `() => void` | | The countdown ran out: commit the destructive action here. |
| `duration` | `number` | `5000` | Countdown length in ms. Changing it while open restarts the countdown. |
| `shortcut` | `boolean` | `true` | Bind ⌘Z / Ctrl+Z to Undo while the pill is open. Ignored while typing in a field. |
| `pauseOnHover` | `boolean` | `true` | Pause the countdown while the pointer is over the pill. |
| `pauseOnFocus` | `boolean` | `true` | Pause the countdown while focus is inside the pill. |
| `onPause` / `onResume` | `() => void` | | Called when hover or focus pauses the countdown, and when it resumes. |
| `placement` | `"bottom" \| "top" \| "none"` | `"bottom"` | Centred at the bottom or top of the positioned parent, or `"none"` to place it yourself. |
| `labels` | `{ undo?: string; shortcut?: (mac: boolean) => string }` | `"Undo"`, `"⌘ Z"` / `"Ctrl Z"` | Translate the button and the shortcut hint. |
| `className` | `string` | | Appended to the pill's classes; placement is kept. |

### useUndoQueue

`useUndoQueue<T>({ message, onUndo?, onCommit? })` returns `{ pending, push, undo, commit, pill }`. `push(item)` adds an item to the open batch; spread `pill` onto `<UndoPill>`.

## Keyboard

| Key | Action |
|---|---|
| `⌘ Z` / `Ctrl Z` | Undo while the pill is open, unless focus is in a text field. |
| `Tab` | Reaches the Undo button; focus inside the pill pauses the countdown. |
| `Enter` / `Space` | Undo, on the focused button. |

## Accessibility

- A `role="status"` live region, mounted before the pill opens, announces the message, so screen readers hear "Deleted Q3 roadmap.pdf" without focus moving.
- Hover and focus pause the countdown, so nobody loses the window while reaching for the button.
- The countdown is driven by a timer, not by the animation, so reduced motion or a global animation clamp never shortens it.

## Motion

The pill rises 12px from below (or drops from above with `placement="top"`) with a blur-to-sharp fade, and its size springs on the smooth spring as the message changes. A new message swaps with y + blur. The ring drains linearly over `duration`. It leaves faster than it came, travelling 6px with a slight scale-down and no overshoot. Reduced motion keeps opacity fades only; the ring still drains.

## Notes for AI

Use Undo Pill for any reversible destructive action in a list or table: remove the item from state immediately, `push` it to `useUndoQueue`, and do the real delete in `onCommit`. Render one pill per surface, inside a `relative` parent, and keep it mounted.

Do not call the delete API before expiry, do not add a confirm dialog on top of it, and do not unmount it on close: toggling `open` is what runs the exit and keeps the live region working.

## Related

- [Button](/components/button): the delete action that opens the pill.
- [Kbd](/components/kbd): the keycaps in the shortcut hint.
- [Sortable Table](/components/sortable-table): a table to pair it with.

## Example

`components/eased/undo-pill/undo-pill-demo.tsx`

```tsx
"use client";

import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
import { DemoFrame } from "../lib/demo-frame";
import { enter, exit, reducedFade, smooth, useSafeReducedMotion } from "../lib/motion";
import { press, pressIcon } from "../lib/press";
import { UndoPill, useUndoQueue } from "./undo-pill";

type File = { id: string; name: string; size: string; edited: string; kind: "pdf" | "fig" | "doc" | "sheet" };

const FILES: File[] = [
  { id: "1", name: "Q3 roadmap.pdf", size: "2.4\u00a0MB", edited: "2h ago", kind: "pdf" },
  { id: "2", name: "Onboarding flow.fig", size: "18.1\u00a0MB", edited: "Yesterday", kind: "fig" },
  { id: "3", name: "Launch checklist.md", size: "4\u00a0KB", edited: "Mon", kind: "doc" },
  { id: "4", name: "Pricing experiments.csv", size: "312\u00a0KB", edited: "Oct 9", kind: "sheet" },
  { id: "5", name: "Brand guidelines.pdf", size: "7.8\u00a0MB", edited: "Sep 28", kind: "pdf" },
  { id: "6", name: "Investor update.md", size: "9\u00a0KB", edited: "Sep 21", kind: "doc" },
];

const order = (ids: string[]) => FILES.filter((f) => ids.includes(f.id));

export function UndoPillDemo() {
  const reduce = useSafeReducedMotion();
  const [visible, setVisible] = useState(FILES.map((f) => f.id));
  const queue = useUndoQueue<string>({
    message: (ids) =>
      ids.length === 1 ? `Deleted “${FILES.find((f) => f.id === ids[0])?.name}”` : `Deleted ${ids.length} files`,
    onUndo: (ids) => setVisible((v) => [...v, ...ids]),
  });

  const remove = (id: string) => {
    setVisible((v) => v.filter((x) => x !== id));
    queue.push(id);
  };
  const reset = () => setVisible(FILES.map((f) => f.id));

  return (
    <DemoFrame title="Files" meta={`${visible.length} ${visible.length === 1 ? "item" : "items"}`}>

      <ul className="relative p-1.5">
        <AnimatePresence mode="popLayout" initial={false}>
          {order(visible).map((file) => (
            <motion.li
              key={file.id}
              layout
              initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.98, filter: "blur(4px)" }}
              animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
              exit={
                reduce
                  ? { opacity: 0, transition: reducedFade }
                  : { opacity: 0, x: -12, filter: "blur(4px)", transition: exit }
              }
              transition={reduce ? reducedFade : { ...smooth, opacity: enter, filter: enter }}
              className="group flex h-14 min-w-0 items-center gap-3 rounded-control pr-0.5 pl-2.5 transition-colors duration-150 ease-standard hover-fine:bg-surface-hover"
            >
              <FileIcon kind={file.kind} />
              <div className="min-w-0 flex-1">
                <p className="truncate text-ui text-text">{file.name}</p>
                <p className="text-ui-sm text-text-muted tabular-nums">
                  {file.size} · {file.edited}
                </p>
              </div>
              <button
                type="button"
                onClick={() => remove(file.id)}
                aria-label={`Delete ${file.name}`}
                className={`hit-area inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-control-sm text-text-muted hover-fine:bg-surface-hover hover-fine:text-text active:bg-surface-active [@media(hover:hover)]:opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 ${pressIcon}`}
              >
                <svg viewBox="0 0 16 16" className="size-4" fill="none" aria-hidden>
                  <path
                    d="M2.75 4.25h10.5M6.25 4.25V3a.75.75 0 0 1 .75-.75h2a.75.75 0 0 1 .75.75v1.25M4.25 4.25l.6 8.4a1 1 0 0 0 1 .93h4.3a1 1 0 0 0 1-.93l.6-8.4"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
            </motion.li>
          ))}
        </AnimatePresence>
      </ul>

      {visible.length === 0 && queue.pending.length === 0 && (
        <div className="absolute inset-0 top-12 flex flex-col items-center justify-center gap-3">
          <p className="text-ui text-text-muted">All files deleted.</p>
          <button
            type="button"
            onClick={reset}
            className={`h-control-sm cursor-pointer rounded-control-sm bg-surface-hover px-3 text-ui-sm font-medium text-text hover-fine:bg-surface-active ${press}`}
          >
            Restore demo
          </button>
        </div>
      )}

      <UndoPill {...queue.pill} />
    </DemoFrame>
  );
}

function FileIcon({ kind }: { kind: File["kind"] }) {
  const label = { pdf: "PDF", fig: "FIG", doc: "MD", sheet: "CSV" }[kind];
  return (
    <span className="inline-flex size-9 shrink-0 items-center justify-center rounded-control-sm border border-line-subtle bg-surface-sunken font-mono text-ui-2xs font-medium tracking-caps text-text-secondary">
      {label}
    </span>
  );
}
```
