Hold to confirm
Press and hold to confirm something you cannot undo. The fill runs at the speed of time, an early release snaps back in 200ms, and it reports its progress so other parts can draw with your hold.
npx shadcn@latest add https://uimaxxer.com/r/hold-to-confirm.jsonPasskeysFix the duplicate Stripe charge
agent/pricing-table is merged. Clean it up.
Captain
agent/pricing-table
14 commits, merged into main 2 days ago
"use client";
// uimaxxer · Hold to confirm, MIT. The fill runs at the speed of time, linear, and an early release snaps it back in 200ms. Delight: the fill reports its progress, so other parts (Approval's command) can draw with your hold.
import { animate, motion, useMotionValue, useMotionValueEvent, useReducedMotion, useTransform, type AnimationPlaybackControls, type MotionValue } 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;
/** danger: a tinted fill. solid: a full danger fill, for a hold that is the whole moment. ink: the primary colour. */
tone?: "danger" | "solid" | "ink";
size?: "sm" | "md" | "lg";
/** Return to idle this many ms after confirming. `null` keeps the done state. */
resetAfter?: number | null;
disabled?: boolean;
className?: string;
"aria-label"?: string;
/** Called every frame with the fill, 0 to 1. Linear while held, eased on the way back. */
onProgress?: (progress: number) => void;
/** Pass your own motion value to draw with the hold without re-rendering. The button writes 0 to 1 into it. */
progress?: MotionValue<number>;
/** Called when a hold starts (true) and when it ends, early or complete (false). */
onHoldChange?: (holding: boolean) => void;
};
const TONES = {
danger: "bg-[color-mix(in_srgb,var(--captain-danger)_10%,var(--captain-surface))] text-danger",
solid: "bg-[var(--captain-danger)] text-[var(--captain-surface)]",
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, onProgress, progress, onHoldChange, ...rest },
ref,
) {
const own = useMotionValue(0);
const p = progress ?? own;
const reduce = useReducedMotion();
const progressRef = useRef(onProgress);
progressRef.current = onProgress;
const holdRef = useRef(onHoldChange);
holdRef.current = onHoldChange;
useMotionValueEvent(p, "change", (v) => progressRef.current?.(v));
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");
holdRef.current?.(false);
if (typeof navigator !== "undefined" && "vibrate" in navigator) navigator.vibrate?.(12);
confirmRef.current();
if (resetAfter !== null) {
reset.current = setTimeout(() => {
setState("idle");
animate(p, 0, { duration: reduce ? 0 : 0.2, ease: EASE });
}, resetAfter);
}
};
const start = () => {
if (disabled || stateRef.current !== "idle") return;
setState("holding");
holdRef.current?.(true);
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");
holdRef.current?.(false);
// The cancel is fast and eased: the deliberate phase is slow, letting go is near instant.
anim.current = animate(p, 0, { duration: reduce ? 0.08 : 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 : size === "lg" ? 18 : 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]" : size === "lg" ? "h-12 px-5 text-[15px]" : "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" | "solid" | "ink" | "danger" | Colour of the fill. solid fills with the full danger colour. |
| size | "sm" | "md" | "lg" | "md" | 32, 40 or 48px 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. |
| progress | MotionValue<number> | Your own motion value; the hold writes 0 to 1 into it every frame, so you can draw with it without re-rendering. | |
| onProgress | (p: number) => void | Called every frame with the fill. | |
| onHoldChange | (holding: boolean) => void | A hold started or ended. |
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.