1"use client";2
3import React, { useEffect, useLayoutEffect, useRef, useState } from "react";4import {5 AnimatePresence,6 motion,7 useAnimate,8 useReducedMotion,9} from "motion/react";10import {11 AnimatedLabel,12 useKeyboardInput,13} from "@/components/ui/animated-label";14import { cn } from "@/lib/utils";15
16export type MorphButtonStatus = "idle" | "loading" | "success" | "error";17
18export type MorphButtonProps = {19 status?: MorphButtonStatus;20 onClick?: () => void;21 idleLabel?: string;22 loadingLabel?: string;23 successLabel?: string;24 errorLabel?: string;25 26 idleIcon?: React.ReactNode;27 28 resetAfterMs?: number;29 onReset?: () => void;30 disabled?: boolean;31 className?: string;32 type?: "button" | "submit" | "reset";33};34
35const EASE_OUT = [0.23, 1, 0.32, 1] as const;36const WIDTH_SPRING = { type: "spring" as const, bounce: 0, duration: 0.3 };37const PAD_X = 18;38
39function Spinner() {40 return (41 <motion.svg42 viewBox="0 0 16 16"43 className="size-full"44 animate={{ rotate: 360 }}45 transition={{ repeat: Infinity, ease: "linear", duration: 0.8 }}46 >47 <circle48 cx="8"49 cy="8"50 r="6"51 fill="none"52 stroke="currentColor"53 strokeOpacity="0.25"54 strokeWidth="2"55 />56 <path57 d="M14 8a6 6 0 0 0-6-6"58 fill="none"59 stroke="currentColor"60 strokeWidth="2"61 strokeLinecap="round"62 />63 </motion.svg>64 );65}66
67function DrawnGlyph({68 kind,69 reduce,70}: {71 kind: "check" | "cross";72 reduce: boolean;73}) {74 const draw = (delay = 0) => ({75 initial: { pathLength: reduce ? 1 : 0 },76 animate: { pathLength: 1 },77 transition: { duration: 0.32, ease: EASE_OUT, delay },78 });79 return (80 <svg81 viewBox="0 0 16 16"82 className="size-full"83 fill="none"84 stroke="currentColor"85 strokeWidth="2.2"86 strokeLinecap="round"87 strokeLinejoin="round"88 >89 {kind === "check" ? (90 <motion.path d="M3.5 8.5l3 3 6-7" {...draw(0.06)} />91 ) : (92 <>93 <motion.path d="M4.5 4.5l7 7" {...draw(0.04)} />94 <motion.path d="M11.5 4.5l-7 7" {...draw(0.14)} />95 </>96 )}97 </svg>98 );99}100
101export function MorphButton({102 status = "idle",103 onClick,104 idleLabel = "Send invite",105 loadingLabel = "Sending",106 successLabel = "Sent",107 errorLabel = "Failed",108 idleIcon,109 resetAfterMs = 0,110 onReset,111 disabled,112 className,113 type = "button",114}: MorphButtonProps) {115 const reducedMotion = useReducedMotion();116 const keyboard = useKeyboardInput();117 const reduce = !!reducedMotion || keyboard;118 const [scope, animate] = useAnimate<HTMLButtonElement>();119 const contentRef = useRef<HTMLSpanElement>(null);120 const [width, setWidth] = useState<number | null>(null);121 const [burst, setBurst] = useState(0);122 const prevStatus = useRef(status);123
124 125 126 const onResetRef = useRef(onReset);127 useEffect(() => {128 onResetRef.current = onReset;129 }, [onReset]);130
131 useEffect(() => {132 if (resetAfterMs <= 0 || (status !== "success" && status !== "error"))133 return;134 const t = window.setTimeout(() => onResetRef.current?.(), resetAfterMs);135 return () => window.clearTimeout(t);136 }, [status, resetAfterMs]);137
138 139 140 useLayoutEffect(() => {141 const el = contentRef.current;142 if (!el) return;143 const measure = () => setWidth(el.offsetWidth + PAD_X * 2);144 measure();145 const ro = new ResizeObserver(measure);146 ro.observe(el);147 return () => ro.disconnect();148 }, []);149
150 151 useEffect(() => {152 if (prevStatus.current === status) return;153 prevStatus.current = status;154 if (reduce) return;155 if (status === "success") setBurst((n) => n + 1);156 if (status === "error" && scope.current) {157 animate(158 scope.current,159 { x: [0, -7, 6, -4, 3, 0] },160 { duration: 0.42, ease: "easeOut" },161 );162 }163 }, [status, reduce, animate, scope]);164
165 const label = {166 idle: idleLabel,167 loading: loadingLabel,168 success: successLabel,169 error: errorLabel,170 }[status];171 const icon =172 status === "loading" ? (173 <Spinner />174 ) : status === "success" ? (175 <DrawnGlyph kind="check" reduce={reduce} />176 ) : status === "error" ? (177 <DrawnGlyph kind="cross" reduce={reduce} />178 ) : (179 (idleIcon ?? null)180 );181 const isBusy = status === "loading";182
183 return (184 <span className="relative inline-grid">185 <AnimatePresence>186 {burst > 0 && status === "success" ? (187 <motion.span188 key={burst}189 aria-hidden190 initial={{ opacity: 0.55, scale: 1 }}191 animate={{ opacity: 0, scale: 1.25 }}192 exit={{ opacity: 0 }}193 transition={{ duration: 0.7, ease: EASE_OUT }}194 className="pointer-events-none absolute inset-0 rounded-full bg-emerald-500/40"195 />196 ) : null}197 </AnimatePresence>198 <motion.button199 ref={scope}200 type={type}201 disabled={disabled || isBusy}202 onClick={onClick}203 aria-busy={isBusy}204 initial={false}205 animate={width ? { width } : undefined}206 transition={reduce ? { duration: 0 } : WIDTH_SPRING}207 whileTap={reduce || isBusy ? undefined : { scale: 0.97 }}208 className={cn(209 "relative inline-flex h-10 items-center justify-center overflow-hidden rounded-full",210 "text-[14px] font-medium whitespace-nowrap outline-none select-none",211 "shadow-[inset_0_1px_0_rgba(255,255,255,0.14),0_1px_2px_rgba(0,0,0,0.12),0_6px_16px_-6px_rgba(0,0,0,0.3)]",212 "transition-[background-color,color,opacity] duration-300 ease-out",213 "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-paper)",214 "disabled:cursor-default",215 disabled && "opacity-50",216 (status === "idle" || status === "loading") &&217 "bg-(--color-ink) text-(--color-paper)",218 status === "success" && "bg-emerald-600 text-white",219 status === "error" && "bg-red-600 text-white",220 className,221 )}222 style={{ paddingInline: PAD_X }}223 >224 <span225 ref={contentRef}226 className="relative inline-flex w-max items-center gap-2"227 >228 <AnimatePresence initial={false} mode="popLayout">229 {icon ? (230 <motion.span231 key={status}232 aria-hidden233 initial={234 reduce235 ? { opacity: 0 }236 : { opacity: 0, scale: 0.92, filter: "blur(3px)" }237 }238 animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}239 exit={240 reduce241 ? { opacity: 0 }242 : { opacity: 0, scale: 0.92, filter: "blur(3px)" }243 }244 transition={{ type: "spring", bounce: 0, duration: 0.24 }}245 className="flex size-4 shrink-0 items-center justify-center [&_svg]:size-full"246 >247 {icon}248 </motion.span>249 ) : null}250 </AnimatePresence>251 <AnimatedLabel autoSize={false}>{label}</AnimatedLabel>252 </span>253 </motion.button>254 {}255 <span role="status" aria-live="polite" className="sr-only">256 {status === "idle" ? "" : label}257 </span>258 </span>259 );260}