Hold to confirm
Press and hold to confirm something you cannot undo. The fill runs at the speed of time; let go early and it snaps back.
npx shadcn@latest add https://captain-ui.vercel.app/r/hold-to-confirm.jsonagent/pricing-table
14 commits, merged 2 days ago
Deploy key, staging
Ends in 4f2c, last used 06:40 today
"use client";
// Captain UI · Hold to confirm, MIT. Press and hold (pointer, Space or Enter): a linear fill shows time passing, an early release snaps it back.
import { animate, motion, useMotionValue, useTransform, type AnimationPlaybackControls } from "motion/react";
import { forwardRef, useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
import { EASE, cx } from "@/registry/captain/ui/captain";
import { Icon, type IconName } from "@/registry/captain/ui/icons";
type HoldToConfirmProps = {
/** The label, e.g. "Delete branch". */
children: ReactNode;
onConfirm: () => void;
/** How long to hold, in ms. */
duration?: number;
icon?: IconName;
/** Shown once confirmed, e.g. "Deleted". */
doneLabel?: ReactNode;
tone?: "danger" | "ink";
size?: "sm" | "md";
/** Return to idle this many ms after confirming. `null` keeps the done state. */
resetAfter?: number | null;
disabled?: boolean;
className?: string;
"aria-label"?: string;
};
const TONES = {
danger: "bg-[color-mix(in_srgb,var(--captain-danger)_10%,var(--captain-surface))] text-danger",
ink: "bg-primary text-primary-ink",
} as const;
export const HoldToConfirm = forwardRef<HTMLButtonElement, HoldToConfirmProps>(function HoldToConfirm(
{ children, onConfirm, duration = 1600, icon, doneLabel, tone = "danger", size = "md", resetAfter = 2200, disabled, className, ...rest },
ref,
) {
const p = useMotionValue(0);
const clip = useTransform(p, (v) => `inset(0 ${(1 - v) * 100}% 0 0)`);
const [state, setState] = useState<"idle" | "holding" | "done">("idle");
const stateRef = useRef(state);
stateRef.current = state;
const anim = useRef<AnimationPlaybackControls | null>(null);
const confirmRef = useRef(onConfirm);
confirmRef.current = onConfirm;
const reset = useRef<ReturnType<typeof setTimeout> | null>(null);
const origin = useRef<DOMRect | null>(null);
const descId = useId();
useEffect(() => () => {
anim.current?.stop();
if (reset.current) clearTimeout(reset.current);
}, []);
const finish = () => {
setState("done");
if (typeof navigator !== "undefined" && "vibrate" in navigator) navigator.vibrate?.(12);
confirmRef.current();
if (resetAfter !== null) {
reset.current = setTimeout(() => {
setState("idle");
animate(p, 0, { duration: 0.2, ease: EASE });
}, resetAfter);
}
};
const start = () => {
if (disabled || stateRef.current !== "idle") return;
setState("holding");
anim.current?.stop();
// Time passes linearly, so the fill does too. Resume from wherever a snap-back left it.
anim.current = animate(p, 1, { duration: ((1 - p.get()) * duration) / 1000, ease: "linear", onComplete: finish });
};
const cancel = () => {
if (stateRef.current !== "holding") return;
anim.current?.stop();
setState("idle");
// The cancel is fast and eased: the deliberate phase is slow, letting go is instant.
anim.current = animate(p, 0, { duration: 0.2, ease: EASE });
};
const down = (e: PointerEvent<HTMLButtonElement>) => {
if (e.button !== 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
origin.current = e.currentTarget.getBoundingClientRect();
start();
};
const move = (e: PointerEvent<HTMLButtonElement>) => {
const r = origin.current;
if (!r || stateRef.current !== "holding") return;
const slop = 24;
if (e.clientX < r.left - slop || e.clientX > r.right + slop || e.clientY < r.top - slop || e.clientY > r.bottom + slop) cancel();
};
const up = () => {
origin.current = null;
cancel();
};
const keyDown = (e: KeyboardEvent<HTMLButtonElement>) => {
if (e.key !== " " && e.key !== "Enter") return;
e.preventDefault();
if (!e.repeat) start();
};
const keyUp = (e: KeyboardEvent<HTMLButtonElement>) => {
if (e.key === " " || e.key === "Enter") cancel();
};
const done = state === "done";
const g = size === "sm" ? 15 : 16;
// Both labels share one grid cell, so the button never changes width when it flips to done.
const label = (
<span className="grid">
<span className={cx("col-start-1 row-start-1 inline-flex items-center justify-center", size === "sm" ? "gap-1.5" : "gap-2", done && doneLabel ? "invisible" : "")}>
{done ? <Icon name="check" size={g} /> : icon ? <Icon name={icon} size={g} /> : null}
<span>{children}</span>
</span>
{doneLabel ? (
<span className={cx("col-start-1 row-start-1 inline-flex items-center justify-center", size === "sm" ? "gap-1.5" : "gap-2", done ? "" : "invisible")}>
<Icon name="check" size={g} />
<span>{doneLabel}</span>
</span>
) : null}
</span>
);
return (
<button
ref={ref}
type="button"
disabled={disabled}
aria-label={rest["aria-label"]}
aria-describedby={descId}
data-state={state}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
onKeyDown={keyDown}
onKeyUp={keyUp}
onBlur={cancel}
onContextMenu={(e) => e.preventDefault()}
className={cx(
"raised group relative inline-flex shrink-0 touch-none select-none items-center justify-center rounded-inner font-medium text-ink",
"transition-transform duration-150 ease-snap [-webkit-tap-highlight-color:transparent] [-webkit-touch-callout:none]",
"before:absolute before:inset-x-0 before:-inset-y-1 before:content-[''] disabled:cursor-not-allowed disabled:opacity-45",
state === "holding" && "scale-[0.97]",
size === "sm" ? "h-8 px-3 text-[13px]" : "h-10 px-4 text-[14px]",
className,
)}
>
<span className="absolute inset-0 rounded-[inherit] transition-colors duration-150 group-hover:bg-hover group-focus-visible:bg-press" />
<span className="relative">{label}</span>
<motion.span
aria-hidden="true"
className={cx("absolute inset-0 grid place-items-center rounded-[inherit]", TONES[tone])}
style={{ clipPath: clip }}
>
{label}
</motion.span>
<span id={descId} className="sr-only">{`Press and hold for ${(duration / 1000).toFixed(1)} seconds`}</span>
<span className="sr-only" aria-live="polite">
{done ? (doneLabel ?? "Confirmed") : ""}
</span>
</button>
);
});Usage
import { HoldToConfirm } from "@/components/ui/hold-to-confirm"
<HoldToConfirm icon="trash" doneLabel="Deleted" onConfirm={deleteBranch}>
Delete branch
</HoldToConfirm>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| children | ReactNode | The label, e.g. Delete branch. | |
| onConfirm | () => void | Called once the hold completes. | |
| duration | number | 1600 | Hold length in ms. The fill is linear because time is. |
| icon | IconName | Leading icon. Turns into a check when confirmed. | |
| doneLabel | ReactNode | Label after confirming, e.g. Deleted. | |
| tone | "danger" | "ink" | "danger" | Colour of the fill. |
| size | "sm" | "md" | "md" | 32 or 40px tall. The hit area is always 44px or more. |
| resetAfter | number | null | 2200 | Return to idle after this many ms; null keeps the done state. |
Keyboard
- Space (hold)
- Fill
- Enter (hold)
- Fill
Accessibility
- A real button; the hold length is announced through aria-describedby.
- Space and Enter hold works the same as a pointer hold, and releasing early cancels.
- The result is announced in a polite live region.
- Dragging off the button by more than 24px cancels, so a slipped finger never confirms.