Confirm Button
SaveA destructive button that confirms in place: the first press turns it into its own Confirm step, the second runs the action, then it offers Undo with a draining ring, or it fills while held in hold mode.
- Category
- Forms
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Confirm Button preview
API keys
Production worker
sk_live_…8f3a, used 2 minutes ago
Staging deploys
sk_test_…41c9, used yesterday
Laptop, Ines
sk_test_…0d77, never used
Installation
npx @shakenui/cli add confirm-buttonReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add confirm-button --dry-runUsage
confirm-button-example.tsx
"use client";
import { useState } from "react";
import { ConfirmButton } from "@/components/shaken/ui/confirm-button";
function TrashIcon() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M2.75 4.25h10.5M6.25 4.25V2.75h3.5v1.5M4 4.25l.6 8.4a1 1 0 0 0 1 .85h4.8a1 1 0 0 0 1-.85l.6-8.4" />
</svg>
);
}
export default function ConfirmButtonExample() {
const [archived, setArchived] = useState(false);
return (
<div className="grid w-full max-w-md gap-3">
<div className="flex items-center gap-3 rounded-xl border border-zinc-950/10 bg-white px-4 py-3 dark:border-white/10 dark:bg-black">
<div className="grid min-w-0 flex-1 gap-0.5">
<p className={"truncate text-sm font-medium text-zinc-950 dark:text-white " + (archived ? "line-through decoration-zinc-400" : "")}>
q3-board-deck-final.pdf
</p>
<p className="text-xs text-zinc-500">4.2 MB, shared with 6 people</p>
</div>
<ConfirmButton
icon={<TrashIcon />}
confirmLabel="Delete file?"
doneLabel="Deleted"
onConfirm={() => setArchived(true)}
onUndo={() => setArchived(false)}
>
Delete
</ConfirmButton>
</div>
<div className="flex items-center gap-3 rounded-xl border border-zinc-950/10 bg-white px-4 py-3 dark:border-white/10 dark:bg-black">
<div className="grid min-w-0 flex-1 gap-0.5">
<p className="truncate font-mono text-sm text-zinc-950 dark:text-white">sk_live_…8f3a</p>
<p className="text-xs text-zinc-500">Used by the billing worker 2 minutes ago</p>
</div>
<ConfirmButton mode="hold" doneLabel="Revoked" undoTimeout={0}>
Hold to revoke
</ConfirmButton>
</div>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| children | ReactNode | — | The resting label, such as Delete. |
| icon | ReactNode | — | A 16px icon before the label. |
| mode | "click" | "hold" | "click" | Press twice, or press and hold until the fill completes. |
| onConfirm | () => void | Promise<void> | — | Runs on the confirming press or when the hold completes. A promise shows a pending spinner; a rejection returns to rest and announces the failure. |
| onUndo / onUndoExpire | () => void | — | Undo is offered when onUndo is set. onUndoExpire runs when the window closes; commit deferred work there. |
| confirmLabel / pendingLabel / doneLabel / undoLabel / restoredLabel | string | "Confirm?" / confirmLabel / "Deleted" / "Undo" / "Restored" | Text for each step, also used in announcements. |
| confirmTimeout | number | 3000 | Milliseconds before an unanswered confirmation reverts. |
| holdDuration | number | 1200 | Milliseconds to hold in hold mode. |
| undoTimeout | number | 5000 | Milliseconds the undo window stays open; 0 skips it. The countdown pauses while hovered or focused from the keyboard. |
| size | "sm" | "md" | "lg" | "sm" | Height and padding. |
Accessibility
- It stays one native button through every step, so focus never moves; its accessible name follows the step ("Delete file? Delete", "Undo delete").
- Each step is announced in a polite live region: "Press again to confirm", the done label with how long Undo lasts, and "Restored".
- Escape or moving focus away cancels a pending confirmation, and an unanswered one reverts after confirmTimeout.
- Hold mode works with Space or Enter held down as well as the pointer, and is described as "Press and hold for 1.2 seconds to confirm". Releasing early drains the fill.
- Under reduced motion the width and label changes are instant; the hold fill and undo ring still show progress because they carry timing information.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/confirm-button.tsxconfirm-button- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/confirm-button/0.1.0.json.
ui/confirm-button.tsxShowHide
ui/confirm-button.tsx
"use client";
import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useTransform, type AnimationPlaybackControls } from "motion/react";
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type ButtonHTMLAttributes,
type ReactNode,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = [0.23, 1, 0.32, 1] as const;
const sizes = {
sm: "h-8 px-3 text-sm",
md: "h-9 px-3.5 text-sm",
lg: "h-10 px-4 text-[15px]",
} as const;
type Phase = "idle" | "confirm" | "pending" | "undo" | "done";
export interface ConfirmButtonProps
extends Omit<
ButtonHTMLAttributes<HTMLButtonElement>,
"onClick" | "children" | "type" | "onDrag" | "onDragStart" | "onDragEnd" | "onAnimationStart" | "onAnimationEnd" | "onAnimationIteration"
> {
/** The resting label, such as "Delete". */
children: ReactNode;
/** A 16px icon before the label, shown at rest and while confirming. */
icon?: ReactNode;
/** `click` asks for a second press; `hold` fills while the button is held. */
mode?: "click" | "hold";
/** Label of the second step in click mode. */
confirmLabel?: string;
/** Label while `onConfirm` is still running, if it returns a promise. Defaults to `confirmLabel`. */
pendingLabel?: string;
/** Shown after the action ran. */
doneLabel?: string;
/** Label of the undo control. */
undoLabel?: string;
/** Announced after undo. */
restoredLabel?: string;
/** Milliseconds before an unanswered "Confirm?" reverts. */
confirmTimeout?: number;
/** Milliseconds the button must be held in hold mode. */
holdDuration?: number;
/** Milliseconds the undo window stays open. `0` skips it. The countdown pauses while hovered or focused. */
undoTimeout?: number;
/** Runs on the confirming press, or when the hold completes. May return a promise. */
onConfirm?: () => void | Promise<void>;
/** Runs when the undo control is pressed. Offering undo needs this. */
onUndo?: () => void;
/** Runs when the undo window closes without undo. Commit deferred work here. */
onUndoExpire?: () => void;
size?: keyof typeof sizes;
}
/**
* A destructive action that confirms in place. The first press turns the button into its own
* "Confirm?" step (the width follows the label); the second press runs the action; then the
* button offers Undo with a draining ring. Hold mode fills the button while it is held instead.
* Escape or moving focus away cancels a pending confirmation.
*/
export function ConfirmButton({
children,
icon,
mode = "click",
confirmLabel = "Confirm?",
pendingLabel,
doneLabel = "Deleted",
undoLabel = "Undo",
restoredLabel = "Restored",
confirmTimeout = 3000,
holdDuration = 1200,
undoTimeout = 5000,
onConfirm,
onUndo,
onUndoExpire,
size = "sm",
disabled,
className,
onKeyDown,
onKeyUp,
onBlur,
onPointerDown,
onPointerUp,
onPointerLeave,
onPointerEnter,
onFocus,
...props
}: ConfirmButtonProps) {
const reduce = useReducedMotion();
const hintId = useId();
const buttonRef = useRef<HTMLButtonElement>(null);
const [phase, setPhase] = useState<Phase>("idle");
const [message, setMessage] = useState("");
const [width, setWidth] = useState<number | null>(null);
const offerUndo = undoTimeout > 0 && onUndo != null;
const actionText = typeof children === "string" ? children : "Action";
// 1 = undo window full, 0 = expired. Drives the ring.
const remaining = useMotionValue(1);
const ring = useTransform(remaining, (v) => 34.56 * (1 - v));
const undoControls = useRef<AnimationPlaybackControls | null>(null);
// 0 to 1 while held. Drives the fill's clip.
const hold = useMotionValue(0);
const holdClip = useTransform(hold, (v) => `inset(0 ${(1 - v) * 100}% 0 0)`);
const holdControls = useRef<AnimationPlaybackControls | null>(null);
const holding = useRef(false);
const announce = (text: string) => {
// Clear first so repeating the same sentence is announced again.
setMessage("");
requestAnimationFrame(() => setMessage(text));
};
// Revert an unanswered confirmation.
useEffect(() => {
if (phase !== "confirm") return;
const id = window.setTimeout(() => setPhase("idle"), confirmTimeout);
return () => window.clearTimeout(id);
}, [phase, confirmTimeout]);
// "Done" without undo rests briefly, then returns.
useEffect(() => {
if (phase !== "done") return;
const id = window.setTimeout(() => setPhase("idle"), 1600);
return () => window.clearTimeout(id);
}, [phase]);
const expireRef = useRef(onUndoExpire);
expireRef.current = onUndoExpire;
const startUndoWindow = useCallback(() => {
remaining.set(1);
undoControls.current?.stop();
undoControls.current = animate(remaining, 0, {
duration: undoTimeout / 1000,
ease: "linear",
onComplete: () => {
setPhase("idle");
expireRef.current?.();
},
});
// Starts paused when the pointer or focus is already on the button.
const el = buttonRef.current;
if (el && (el.matches(":hover") || el.matches(":focus-visible"))) undoControls.current.pause();
}, [remaining, undoTimeout]);
useEffect(() => () => undoControls.current?.stop(), []);
const run = async () => {
const result = onConfirm?.();
if (result && typeof (result as Promise<void>).then === "function") {
setPhase("pending");
try {
await result;
} catch {
setPhase("idle");
announce("That did not work. Try again.");
return;
}
}
if (offerUndo) {
setPhase("undo");
startUndoWindow();
announce(`${doneLabel}. ${undoLabel} is available for ${Math.round(undoTimeout / 1000)} seconds.`);
} else {
setPhase("done");
announce(doneLabel);
}
};
const undo = () => {
undoControls.current?.stop();
setPhase("idle");
onUndo?.();
announce(restoredLabel);
};
const handleClick = () => {
if (disabled) return;
if (phase === "undo") return undo();
if (mode === "hold") return;
if (phase === "idle") {
setPhase("confirm");
announce(`${confirmLabel} Press again to confirm.`);
} else if (phase === "confirm") {
void run();
}
};
const startHold = () => {
if (disabled || mode !== "hold" || phase !== "idle" || holding.current) return;
holding.current = true;
holdControls.current?.stop();
holdControls.current = animate(hold, 1, {
duration: (holdDuration / 1000) * (1 - hold.get()),
ease: "linear",
onComplete: () => {
holding.current = false;
hold.set(0);
void run();
},
});
};
const releaseHold = () => {
if (!holding.current) return;
holding.current = false;
holdControls.current?.stop();
holdControls.current = animate(hold, 0, reduce ? { duration: 0 } : { duration: 0.22, ease: "easeOut" });
};
// The button's width follows its current content.
const measure = useCallback((el: HTMLSpanElement | null) => {
const button = buttonRef.current;
if (!el || !button) return;
const style = getComputedStyle(button);
const chrome =
parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);
setWidth(Math.ceil(el.scrollWidth + chrome));
}, []);
// Re-measure when fonts settle or the label changes.
useLayoutEffect(() => {
const el = buttonRef.current?.querySelector<HTMLSpanElement>(`[data-phase-content="${phase}"]`);
if (!el) return;
const observer = new ResizeObserver(() => measure(el));
observer.observe(el);
return () => observer.disconnect();
}, [phase, measure]);
const tone =
phase === "confirm" || phase === "pending"
? cx(
"border-red-600 bg-red-600 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.16),0_1px_2px_rgb(0_0_0/0.2)]",
"hover:border-red-700 hover:bg-red-700",
)
: phase === "undo" || phase === "done"
? cx(
"border-zinc-950/12 bg-white text-zinc-950 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03]",
"dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
)
: cx(
"border-zinc-950/12 bg-white text-red-600 hover:border-red-500/35 hover:bg-red-500/[0.06]",
"dark:border-white/15 dark:bg-black dark:text-red-400 dark:hover:border-red-500/40 dark:hover:bg-red-500/[0.1]",
);
const content = (() => {
switch (phase) {
case "confirm":
return (
<>
{icon ? <Icon>{icon}</Icon> : null}
{confirmLabel}
</>
);
case "pending":
return (
<>
<Spinner reduce={!!reduce} />
{pendingLabel ?? confirmLabel}
</>
);
case "undo":
return (
<>
<span className="text-zinc-500 dark:text-zinc-400">{doneLabel}</span>
<span aria-hidden="true" className="h-3.5 w-px bg-zinc-950/10 dark:bg-white/15" />
<svg aria-hidden="true" viewBox="0 0 14 14" className="size-3.5 -rotate-90">
<circle cx="7" cy="7" r="5.5" fill="none" strokeWidth="1.5" className="stroke-zinc-950/10 dark:stroke-white/15" />
<motion.circle
cx="7"
cy="7"
r="5.5"
fill="none"
strokeWidth="1.5"
strokeLinecap="round"
strokeDasharray="34.56"
style={{ strokeDashoffset: ring }}
className="stroke-zinc-950 dark:stroke-white"
/>
</svg>
{undoLabel}
</>
);
case "done":
return (
<>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4 text-emerald-600 dark:text-emerald-400">
<circle cx="8" cy="8" r="6.25" />
<path d="m5.5 8.25 1.75 1.75 3.25-3.5" />
</svg>
{doneLabel}
</>
);
default:
return (
<>
{icon ? <Icon>{icon}</Icon> : null}
{children}
</>
);
}
})();
const accessibleName =
phase === "undo" ? `${undoLabel} ${actionText.toLowerCase()}` : phase === "confirm" ? `${confirmLabel} ${actionText}` : undefined;
return (
<>
<motion.button
ref={buttonRef}
type="button"
disabled={disabled}
aria-label={accessibleName}
aria-describedby={mode === "hold" && phase === "idle" ? hintId : undefined}
aria-busy={phase === "pending" || undefined}
data-phase={phase}
initial={false}
animate={width == null ? undefined : { width }}
transition={reduce ? { duration: 0 } : { type: "spring", bounce: 0.15, duration: 0.38 }}
onClick={handleClick}
onKeyDown={(event) => {
onKeyDown?.(event);
if (event.key === "Escape" && phase === "confirm") {
event.stopPropagation();
setPhase("idle");
announce("Cancelled.");
}
if (mode === "hold" && phase === "idle" && (event.key === " " || event.key === "Enter")) {
event.preventDefault();
if (!event.repeat) startHold();
}
}}
onKeyUp={(event) => {
onKeyUp?.(event);
if (mode === "hold" && (event.key === " " || event.key === "Enter")) releaseHold();
}}
onBlur={(event) => {
onBlur?.(event);
if (phase === "confirm") setPhase("idle");
releaseHold();
if (phase === "undo") undoControls.current?.play();
}}
onFocus={(event) => {
onFocus?.(event);
if (phase === "undo" && event.currentTarget.matches(":focus-visible")) undoControls.current?.pause();
}}
onPointerDown={(event) => {
onPointerDown?.(event);
if (event.button === 0) startHold();
}}
onPointerUp={(event) => {
onPointerUp?.(event);
releaseHold();
}}
onPointerEnter={(event) => {
onPointerEnter?.(event);
if (phase === "undo") undoControls.current?.pause();
}}
onPointerLeave={(event) => {
onPointerLeave?.(event);
releaseHold();
if (phase === "undo" && !event.currentTarget.matches(":focus-visible")) undoControls.current?.play();
}}
onContextMenu={mode === "hold" ? (event) => event.preventDefault() : undefined}
className={cx(
"relative isolate inline-flex shrink-0 items-center justify-center overflow-hidden rounded-lg border font-medium whitespace-nowrap select-none",
"transition-[background-color,border-color,color,box-shadow,scale] duration-200 ease-out active:duration-100 motion-reduce:transition-none",
mode === "click" && "motion-safe:active:scale-[0.97]",
mode === "hold" && "touch-none [-webkit-touch-callout:none]",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
"disabled:pointer-events-none disabled:opacity-50",
sizes[size],
tone,
className,
)}
{...props}
>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={phase}
data-phase-content={phase}
ref={measure}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10, filter: "blur(2px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, y: -8, filter: "blur(2px)", transition: { duration: 0.14, ease: "easeOut" } }}
transition={reduce ? { duration: 0 } : { duration: 0.24, ease }}
className="inline-flex items-center gap-2"
>
{content}
</motion.span>
</AnimatePresence>
{mode === "hold" && phase === "idle" ? (
// The fill: a red copy of the button clipped to the held share, so the label inverts as it passes.
<motion.span
aria-hidden="true"
style={{ clipPath: holdClip }}
className={cx("absolute -inset-px flex items-center justify-center bg-red-600 text-white", sizes[size].replace(/h-\d+ /, ""))}
>
<span className="inline-flex items-center gap-2">
{icon ? <Icon>{icon}</Icon> : null}
{children}
</span>
</motion.span>
) : null}
</motion.button>
{mode === "hold" ? (
<span id={hintId} hidden>
Press and hold for {Math.round(holdDuration / 100) / 10} seconds to confirm.
</span>
) : null}
<span role="status" aria-live="polite" className="sr-only">
{message}
</span>
</>
);
}
function Icon({ children }: { children: ReactNode }) {
return (
<span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4">
{children}
</span>
);
}
function Spinner({ reduce }: { reduce: boolean }) {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className={cx("size-4", !reduce && "animate-spin")}>
<circle cx="8" cy="8" r="6" strokeWidth="1.5" className="stroke-white/30" />
<path d="M8 2a6 6 0 0 1 6 6" strokeWidth="1.5" strokeLinecap="round" className="stroke-white" />
</svg>
);
}