Skip to main content
Multi-State Action Button

Multi-State Action Button

Kinetic action button with layout-morphed async states, spring error shake, and press-and-hold confirmation.

Tactile
11/16

1. Install Dependencies

$npm install framer-motion lucide-react

2. Copy Component Code

components/ui/MultiStateActionButton.tsx
1"use client";
2
3import React, { useEffect, useRef, useState } from "react";
4import {
5 animate,
6 AnimatePresence,
7 motion,
8 useMotionValue,
9 useReducedMotion,
10 useTransform,
11} from "framer-motion";
12import { AlertCircle, Check, Loader2, Trash2 } from "lucide-react";
13
14const APPLE_EASE = [0.22, 1, 0.36, 1] as const;
15
16export type ActionButtonMode = "async" | "hold";
17export type AsyncActionStatus = "idle" | "loading" | "success" | "error";
18
19export interface MultiStateActionButtonProps {
20 /** Interaction mode: one-click async lifecycle or press-and-hold confirmation. */
21 mode?: ActionButtonMode;
22 /** Controlled status for async mode. */
23 status?: AsyncActionStatus;
24 /** Initial status for uncontrolled async mode. */
25 defaultStatus?: AsyncActionStatus;
26 /** Callback fired when async status changes internally. */
27 onStatusChange?: (status: AsyncActionStatus) => void;
28 /** Custom async/sync action invoked when clicked in async mode. */
29 onAction?: () => Promise<void> | void;
30 /** Callback invoked when press-and-hold completes. */
31 onConfirm?: () => Promise<void> | void;
32 /** Label shown in async idle state. */
33 idleLabel?: string;
34 /** Label shown during async loading state. */
35 loadingLabel?: string;
36 /** Label shown in async success state. */
37 successLabel?: string;
38 /** Label shown in async error state. */
39 errorLabel?: string;
40 /** Label shown in hold-to-confirm state. */
41 holdLabel?: string;
42 /** Label shown once hold confirmation succeeds. */
43 holdSuccessLabel?: string;
44 /** Duration in milliseconds required to complete hold mode. */
45 holdDurationMs?: number;
46 /** Optional static fill percentage (0-100) for decorative gallery thumbnails. */
47 previewHoldProgress?: number;
48 /** Optional wrapper classes. */
49 className?: string;
50}
51
52/** Tactile action button with layout-morphed async states, spring error shake, and hold confirmation. */
53export function MultiStateActionButton({
54 mode = "async",
55 status,
56 defaultStatus = "idle",
57 onStatusChange,
58 onAction,
59 onConfirm,
60 idleLabel = "Deploy Production",
61 loadingLabel = "Deploying...",
62 successLabel = "Deployed",
63 errorLabel = "Deploy Failed",
64 holdLabel = "Hold to Delete",
65 holdSuccessLabel = "Confirmed",
66 holdDurationMs = 1200,
67 previewHoldProgress,
68 className = "",
69}: MultiStateActionButtonProps) {
70 const prefersReducedMotion = useReducedMotion();
71
72 const [internalStatus, setInternalStatus] =
73 useState<AsyncActionStatus>(defaultStatus);
74 const activeStatus = status !== undefined ? status : internalStatus;
75 const isControlled = status !== undefined;
76
77 const [isHolding, setIsHolding] = useState(false);
78 const [holdPct, setHoldPct] = useState(previewHoldProgress ?? 0);
79 const [holdCompleted, setHoldCompleted] = useState(false);
80
81 const progressMV = useMotionValue(previewHoldProgress ?? 0);
82 const clipPath = useTransform(
83 progressMV,
84 (latest) => `inset(0 ${Math.max(0, 100 - latest)}% 0 0)`
85 );
86
87 const holdAnimRef = useRef<{ stop: () => void } | null>(null);
88 const resetTimerRef = useRef<number | null>(null);
89 const holdResetTimerRef = useRef<number | null>(null);
90 const mountedRef = useRef(true);
91
92 useEffect(() => {
93 mountedRef.current = true;
94 return () => {
95 mountedRef.current = false;
96 holdAnimRef.current?.stop();
97 if (resetTimerRef.current !== null) {
98 window.clearTimeout(resetTimerRef.current);
99 }
100 if (holdResetTimerRef.current !== null) {
101 window.clearTimeout(holdResetTimerRef.current);
102 }
103 };
104 }, []);
105
106 useEffect(() => {
107 const unsubscribe = progressMV.on("change", (latest) => {
108 setHoldPct(Math.round(latest));
109 });
110 return unsubscribe;
111 }, [progressMV]);
112
113 useEffect(() => {
114 if (previewHoldProgress !== undefined) {
115 progressMV.set(previewHoldProgress);
116 }
117 }, [previewHoldProgress, progressMV]);
118
119 function updateAsyncStatus(next: AsyncActionStatus) {
120 if (!isControlled) {
121 setInternalStatus(next);
122 }
123 onStatusChange?.(next);
124 }
125
126 // Auto-reset after terminal async states ("success" | "error")
127 useEffect(() => {
128 if (mode !== "async") return;
129 if (activeStatus !== "success" && activeStatus !== "error") return;
130
131 if (resetTimerRef.current !== null) {
132 window.clearTimeout(resetTimerRef.current);
133 }
134 resetTimerRef.current = window.setTimeout(() => {
135 if (!mountedRef.current) return;
136 updateAsyncStatus("idle");
137 resetTimerRef.current = null;
138 }, 2200);
139
140 return () => {
141 if (resetTimerRef.current !== null) {
142 window.clearTimeout(resetTimerRef.current);
143 resetTimerRef.current = null;
144 }
145 };
146 // eslint-disable-next-line react-hooks/exhaustive-deps
147 }, [activeStatus, mode, isControlled]);
148
149 async function handleAsyncClick() {
150 if (mode !== "async" || activeStatus !== "idle") return;
151
152 updateAsyncStatus("loading");
153
154 if (onAction) {
155 try {
156 await onAction();
157 if (mountedRef.current) {
158 updateAsyncStatus("success");
159 }
160 } catch {
161 if (mountedRef.current) {
162 updateAsyncStatus("error");
163 }
164 }
165 return;
166 }
167
168 window.setTimeout(() => {
169 if (mountedRef.current) {
170 updateAsyncStatus("success");
171 }
172 }, 1100);
173 }
174
175 function completeHold() {
176 if (!mountedRef.current) return;
177 setIsHolding(false);
178 setHoldCompleted(true);
179 void onConfirm?.();
180
181 if (holdResetTimerRef.current !== null) {
182 window.clearTimeout(holdResetTimerRef.current);
183 }
184 holdResetTimerRef.current = window.setTimeout(() => {
185 if (!mountedRef.current) return;
186 setHoldCompleted(false);
187 progressMV.set(0);
188 holdResetTimerRef.current = null;
189 }, 2000);
190 }
191
192 function startHold() {
193 if (mode !== "hold" || holdCompleted || previewHoldProgress !== undefined) {
194 return;
195 }
196 holdAnimRef.current?.stop();
197 setIsHolding(true);
198
199 const current = progressMV.get();
200 const remainingRatio = Math.max(0, (100 - current) / 100);
201 const durationSec = prefersReducedMotion
202 ? 0.05
203 : (holdDurationMs / 1000) * remainingRatio;
204
205 holdAnimRef.current = animate(progressMV, 100, {
206 duration: durationSec,
207 ease: "linear",
208 onComplete: () => {
209 completeHold();
210 },
211 });
212 }
213
214 function cancelHold() {
215 if (mode !== "hold" || holdCompleted || !isHolding) return;
216 setIsHolding(false);
217 holdAnimRef.current?.stop();
218
219 if (prefersReducedMotion) {
220 progressMV.set(0);
221 return;
222 }
223
224 holdAnimRef.current = animate(progressMV, 0, {
225 type: "spring",
226 stiffness: 450,
227 damping: 32,
228 });
229 }
230
231 const contentTransition = prefersReducedMotion
232 ? { duration: 0 }
233 : { duration: 0.16, ease: APPLE_EASE };
234
235 if (mode === "hold") {
236 const showProgressNumeral = isHolding || (previewHoldProgress ?? 0) > 0;
237 const renderHoldInner = () => (
238 <>
239 <Trash2
240 className="h-3.5 w-3.5 shrink-0"
241 strokeWidth={1.75}
242 aria-hidden="true"
243 />
244 <span>{holdLabel}</span>
245 {showProgressNumeral && (
246 <span className="font-mono text-xs leading-4 tabular-nums opacity-70">
247 {holdPct}%
248 </span>
249 )}
250 </>
251 );
252
253 return (
254 <motion.button
255 type="button"
256 layout={!prefersReducedMotion}
257 onPointerDown={(e) => {
258 if (e.button === 0) startHold();
259 }}
260 onPointerUp={cancelHold}
261 onPointerLeave={cancelHold}
262 onPointerCancel={cancelHold}
263 onKeyDown={(e) => {
264 if ((e.key === " " || e.key === "Enter") && !e.repeat) {
265 e.preventDefault();
266 startHold();
267 }
268 }}
269 onKeyUp={(e) => {
270 if (e.key === " " || e.key === "Enter") {
271 e.preventDefault();
272 cancelHold();
273 }
274 }}
275 animate={
276 holdCompleted && !prefersReducedMotion
277 ? { scale: [1, 1.03, 1] }
278 : { scale: 1 }
279 }
280 whileTap={
281 prefersReducedMotion || holdCompleted ? undefined : { scale: 0.97 }
282 }
283 transition={{
284 layout: prefersReducedMotion
285 ? { duration: 0 }
286 : { type: "spring", stiffness: 520, damping: 36 },
287 scale: { duration: 0.24, ease: APPLE_EASE },
288 }}
289 aria-label={holdCompleted ? holdSuccessLabel : holdLabel}
290 className={`relative inline-flex min-h-10 max-w-full items-center justify-center gap-2 overflow-hidden rounded-[12px] px-4 py-2 text-xs leading-4 font-medium tracking-[-0.01em] whitespace-nowrap select-none ${
291 holdCompleted
292 ? "bg-[#047857] text-white"
293 : "bg-white text-black shadow-[0_2px_10px_rgba(0,0,0,0.05)] dark:bg-[#141416] dark:text-white dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_6px_20px_rgba(0,0,0,0.5)]"
294 } ${className}`}
295 >
296 <span className="visually-hidden" aria-live="polite">
297 {holdCompleted ? holdSuccessLabel : isHolding ? `${holdPct}%` : ""}
298 </span>
299 <AnimatePresence mode="popLayout" initial={false}>
300 {holdCompleted ? (
301 <motion.span
302 key="hold-confirmed"
303 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
304 animate={{ opacity: 1, y: 0 }}
305 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
306 transition={contentTransition}
307 className="relative z-10 inline-flex items-center gap-2"
308 >
309 <Check
310 className="h-3.5 w-3.5 shrink-0"
311 strokeWidth={1.75}
312 aria-hidden="true"
313 />
314 <span>{holdSuccessLabel}</span>
315 </motion.span>
316 ) : (
317 <motion.span
318 key="hold-idle"
319 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
320 animate={{ opacity: 1, y: 0 }}
321 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
322 transition={contentTransition}
323 className="inline-flex items-center gap-2"
324 >
325 {renderHoldInner()}
326 </motion.span>
327 )}
328 </AnimatePresence>
329
330 {/* Clipped Inverted Progress Sweep */}
331 {!holdCompleted && (
332 <motion.span
333 aria-hidden="true"
334 style={{ clipPath }}
335 className="pointer-events-none absolute inset-0 inline-flex items-center justify-center gap-2 rounded-[12px] bg-black px-4 text-white dark:bg-white dark:text-black"
336 >
337 {renderHoldInner()}
338 </motion.span>
339 )}
340 </motion.button>
341 );
342 }
343
344 const asyncAppearance =
345 activeStatus === "success"
346 ? "bg-[#047857] text-white"
347 : activeStatus === "error"
348 ? "bg-[#18181B] text-white dark:bg-[#222226] dark:text-white"
349 : "bg-black text-white hover:bg-black/90 shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:bg-white dark:text-black dark:hover:bg-white/90 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.4),0_6px_20px_rgba(0,0,0,0.5)]";
350
351 const liveAsyncLabel =
352 activeStatus === "idle"
353 ? ""
354 : activeStatus === "loading"
355 ? loadingLabel
356 : activeStatus === "success"
357 ? successLabel
358 : errorLabel;
359
360 return (
361 <motion.button
362 type="button"
363 layout={!prefersReducedMotion}
364 onClick={() => void handleAsyncClick()}
365 whileTap={
366 prefersReducedMotion || activeStatus !== "idle"
367 ? undefined
368 : { scale: 0.97 }
369 }
370 animate={
371 activeStatus === "error" && !prefersReducedMotion
372 ? { x: [0, -6, 6, -4, 4, 0] }
373 : { x: 0 }
374 }
375 transition={{
376 layout: prefersReducedMotion
377 ? { duration: 0 }
378 : { type: "spring", stiffness: 520, damping: 36 },
379 x: { duration: 0.36, ease: APPLE_EASE },
380 }}
381 className={`relative inline-flex min-h-10 max-w-full items-center justify-center gap-2 overflow-hidden rounded-[12px] px-4 py-2 text-xs leading-4 font-medium tracking-[-0.01em] whitespace-nowrap select-none transition-colors duration-150 ${asyncAppearance} ${className}`}
382 >
383 <span className="visually-hidden" aria-live="polite">
384 {liveAsyncLabel}
385 </span>
386 <AnimatePresence mode="popLayout" initial={false}>
387 {activeStatus === "idle" && (
388 <motion.span
389 key="idle"
390 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
391 animate={{ opacity: 1, y: 0 }}
392 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
393 transition={contentTransition}
394 className="inline-flex items-center gap-2"
395 >
396 <span>{idleLabel}</span>
397 </motion.span>
398 )}
399
400 {activeStatus === "loading" && (
401 <motion.span
402 key="loading"
403 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
404 animate={{ opacity: 1, y: 0 }}
405 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
406 transition={contentTransition}
407 className="inline-flex items-center gap-2"
408 >
409 <Loader2
410 className={`h-3.5 w-3.5 shrink-0 ${
411 prefersReducedMotion ? "" : "animate-spin"
412 }`}
413 strokeWidth={1.75}
414 aria-hidden="true"
415 />
416 <span>{loadingLabel}</span>
417 </motion.span>
418 )}
419
420 {activeStatus === "success" && (
421 <motion.span
422 key="success"
423 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
424 animate={{ opacity: 1, y: 0 }}
425 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
426 transition={contentTransition}
427 className="inline-flex items-center gap-2"
428 >
429 <Check
430 className="h-3.5 w-3.5 shrink-0"
431 strokeWidth={1.75}
432 aria-hidden="true"
433 />
434 <span>{successLabel}</span>
435 </motion.span>
436 )}
437
438 {activeStatus === "error" && (
439 <motion.span
440 key="error"
441 initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
442 animate={{ opacity: 1, y: 0 }}
443 exit={prefersReducedMotion ? undefined : { opacity: 0, y: -6 }}
444 transition={contentTransition}
445 className="inline-flex items-center gap-2"
446 >
447 <AlertCircle
448 className="h-3.5 w-3.5 shrink-0"
449 strokeWidth={1.75}
450 aria-hidden="true"
451 />
452 <span>{errorLabel}</span>
453 </motion.span>
454 )}
455 </AnimatePresence>
456 </motion.button>
457 );
458}

Usage Example

import { MultiStateActionButton } from "@/components/ui/MultiStateActionButton";
export default function DeployControls() {
return (
<div className="flex items-center gap-4">
<MultiStateActionButton mode="async" />
<MultiStateActionButton mode="hold" />
</div>
);
}

3. Props Reference

Multi-State Action Button props API reference
PropTypeDefaultDescription
mode"async" | "hold""async"Chooses between one-click async deploy lifecycle or press-and-hold confirmation.
status"idle" | "loading" | "success" | "error"undefinedControlled async state.
defaultStatus"idle" | "loading" | "success" | "error""idle"Initial state when uncontrolled in async mode.
onAction() => Promise<void> | voidundefinedAsync action triggered on click in async mode; rejects into error shake.
onConfirm() => Promise<void> | voidundefinedCallback triggered once the hold progress reaches 100%.
holdDurationMsnumber1200Continuous press duration in milliseconds before hold confirmation completes.