"use client";/* ───────────────────────────────────────────────────────── * SLIDE TO SEND: the confirm step of a payment * * The control at the foot of a send-money or checkout sheet. * The person you are paying sits at the end of the track. You * carry the thumb to them and the track fills behind it; the * words under the fill turn white so they stay readable. Let go * early and it springs home. Let go against their photo and the * fill drains into it: its tail runs up the track and the money * is gone into their avatar, which gives a little as it takes * it. A badge on the avatar turns while your `onSend` runs and * becomes a check when it resolves; the label says "Sent to * Priya" and stays. If it throws, the money comes back out of * the avatar and slides home, and the reason takes the label. * * One line in your app: <SlideToSend amount={240} to={{ name, * avatar }} onSend={() => api.transfer(...)} />. Your transfer * call, your errors; nothing else to wire. Remount it (a new * `key`) to take another payment. * ───────────────────────────────────────────────────────── */import * as React from "react";import { ArrowRight } from "lucide-react";import { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, createSpring, projectInertia, releaseVelocity, rubberBand, samplePointer, softenVelocity, type PointerSample, type Spring,} from "./ui-interaction-motion";import { playSound } from "./ui-sounds";export interface SlideRecipient { /** Full name; the first name goes in the labels. */ name: string; /** Photo URL. Without one, their initials. */ avatar?: string;}export type SlideToSendStatus = "idle" | "sending" | "sent" | "error";export interface SlideToSendProps { /** The amount being sent, written in the label with `format`. */ amount: number; /** Who it goes to, shown at the end of the track. */ to: SlideRecipient; /** Your transfer. Resolve when it went through; throw (an Error's message is shown) to give the money back. */ onSend: () => unknown | Promise<unknown>; format?: Intl.NumberFormatOptions; locales?: string | string[]; /** The words. `slide` replaces the whole "Slide to send $240.00". */ labels?: Partial<Record<"slide" | "sending" | "sent" | "failed", string>>; disabled?: boolean; /** Soft synthesised sounds as it reaches, lands, and goes through or fails. */ sound?: boolean; onStatusChange?: (status: SlideToSendStatus) => void; className?: string;}const USD: Intl.NumberFormatOptions = { style: "currency", currency: "USD" };// Geometry: a 56px track, 4px of room all round, a 48px thumb and a 48px avatar.const PAD = 4;const KNOB = 48;const GAP = 4; // the thumb stops this far short of the avatarconst COMMIT_FROM = 0.6; // a throw only counts from past this share of the trackconst MIN_PENDING = 560; // the badge turns at least this long, so "sending" is seenconst FOLLOW = { stiffness: 420, damping: 40 }; // home and the nudge: quick, no bounceconst HAND_OVER = { stiffness: 230, damping: 30 }; // the thumb into the avatar and back outconst DRAIN = { stiffness: 170, damping: 26 }; // the fill's tail running up after itconst clamp = (n: number, lo: number, hi: number) => (n < lo ? lo : n > hi ? hi : n);const smooth = (t: number) => t * t * (3 - 2 * t);const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(reducedQuery); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const subscribeNothing = () => () => {};const useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);// A light that sweeps the way you slide. A mask, not a text clip.const SHEEN = "[mask-image:linear-gradient(90deg,rgb(0_0_0/0.5)_35%,#000_50%,rgb(0_0_0/0.5)_65%)] [mask-size:200%_100%] animate-[ui-sheen_2s_linear_infinite] motion-reduce:animate-none motion-reduce:[mask-image:none]";function buzz(ms: number) { try { navigator.vibrate?.(ms); } catch {}}type Phase = "idle" | "handing" | "sending" | "sent";type Result = { ok: boolean; message?: string };type Springs = { head: Spring; tail: Spring; take: Spring };// The order lines come in: a later one rises from below, an earlier one comes back down from above.const LINES = ["slide", "failed", "sending", "sent"] as const;type Line = (typeof LINES)[number];export function SlideToSend({ amount, to, onSend, format = USD, locales, labels, disabled = false, sound = false, onStatusChange, className = "",}: SlideToSendProps) { const reduced = useReducedMotion(); const hydrated = useHydrated(); const money = new Intl.NumberFormat(locales ?? (hydrated ? undefined : "en-US"), format).format(amount); const first = to.name.trim().split(/\s+/)[0] || to.name; const initials = to.name.trim().split(/\s+/).slice(0, 2).map((part) => part[0]?.toUpperCase() ?? "").join(""); const words = { sending: `Sending to ${first}`, sent: `Sent to ${first}`, failed: "Couldn't send. Try again.", ...labels }; const slideText = labels?.slide; const hintId = React.useId(); const [phase, setPhase] = React.useState<Phase>("idle"); const [message, setMessage] = React.useState<string | null>(null); const rootRef = React.useRef<HTMLDivElement>(null); const trackRef = React.useRef<HTMLDivElement>(null); const thumbRef = React.useRef<HTMLButtonElement>(null); const windowRef = React.useRef<HTMLDivElement>(null); const barRef = React.useRef<HTMLDivElement>(null); const inkRef = React.useRef<HTMLDivElement>(null); const hintRef = React.useRef<HTMLSpanElement>(null); const avatarRef = React.useRef<HTMLSpanElement>(null); const width = React.useRef(0); const run = React.useRef({ committing: false, caught: false, caughtAt: 0, result: null as Result | null, reach: false }); const drag = React.useRef<{ id: number; start: number; samples: PointerSample[] } | null>(null); const timers = React.useRef(new Set<ReturnType<typeof setTimeout>>()); const paintRef = React.useRef<() => void>(() => {}); const latest = React.useRef({ onSend, sound, reduced, onStatusChange, failed: words.failed }); React.useLayoutEffect(() => { latest.current = { onSend, sound, reduced, onStatusChange, failed: words.failed }; }); // Three springs draw everything: the thumb (the fill's head), the fill's tail, and the avatar's give. // Made on first use, from an event or an effect, never while rendering. const springsRef = React.useRef<Springs | null>(null); const getSprings = React.useCallback(() => { if (!springsRef.current) { const paint = () => paintRef.current(); springsRef.current = { head: createSpring(0, FOLLOW, paint, 0.05), tail: createSpring(0, DRAIN, paint, 0.05), take: createSpring(0, { stiffness: 560, damping: 16 }, paint, 0.0005), }; } return springsRef.current; }, []); const later = React.useCallback((fn: () => void, ms: number) => { const id = setTimeout(() => { timers.current.delete(id); fn(); }, ms); timers.current.add(id); }, []); React.useEffect(() => { const all = timers.current; return () => { const springs = springsRef.current; springs?.head.stop(); springs?.tail.stop(); springs?.take.stop(); springsRef.current = null; all.forEach(clearTimeout); all.clear(); }; }, []); const finish = React.useCallback(() => { const state = run.current; const result = state.result; if (!result) return; const withSound = latest.current.sound; if (result.ok) { setPhase("sent"); if (withSound) playSound("success", 0.45); buzz(12); return; } // It didn't go: the money comes back out of their avatar and slides home, and the reason takes the label. state.committing = false; state.caught = false; state.result = null; setPhase("idle"); setMessage(result.message || latest.current.failed); const springs = getSprings(); springs.head.configure(HAND_OVER); springs.head.set(0); springs.tail.configure(DRAIN); springs.tail.set(0); avatarRef.current?.animate( [{ translate: "0 0" }, { translate: "-4px 0" }, { translate: "4px 0" }, { translate: "-3px 0" }, { translate: "2px 0" }, { translate: "0 0" }], { duration: latest.current.reduced ? 0 : 380, easing: "ease-out" }, ); if (withSound) playSound("error", 0.45); later(() => setMessage(null), 3600); }, [later, getSprings]); const settle = React.useCallback(() => { const state = run.current; if (!state.caught || !state.result) return; later(finish, Math.max(0, state.caughtAt + MIN_PENDING - performance.now())); }, [finish, later]); React.useLayoutEffect(() => { paintRef.current = () => { const W = width.current; const thumb = thumbRef.current, win = windowRef.current, bar = barRef.current, ink = inkRef.current, avatar = avatarRef.current; if (!W || !thumb || !win || !bar || !ink || !avatar) return; const springs = getSprings(); const inner = W - PAD * 2; const max = Math.max(1, inner - KNOB * 2 - GAP); // the thumb against the avatar const land = inner - KNOB; // the thumb right under the avatar const h = springs.head.get(); const t = Math.max(0, Math.min(springs.tail.get(), h)); // the tail never passes the head const p = clamp(h / max, 0, 1); const k = clamp((h - max) / (land - max), 0, 1); // how far it has gone into the avatar const gone = 1 - smooth(clamp((k - 0.35) / 0.65, 0, 1)); thumb.style.transform = `translate3d(${h.toFixed(2)}px,0,0) scale(${(1 - 0.35 * k).toFixed(4)})`; thumb.style.opacity = gone.toFixed(3); // The fill is a pill whose right end is the thumb and whose left end is the tail: a window that // moves with the tail, a bar inside it that moves with the head, and the white words inside the // bar held still on the track. Three transforms, nothing re-laid out. const end = Math.min(h, land) + KNOB - inner; win.style.transform = `translate3d(${t.toFixed(2)}px,0,0)`; // Once the tail is under the avatar there is nothing left to see. win.style.opacity = clamp((land - t) / 8, 0, 1).toFixed(3); bar.style.transform = `translate3d(${(end - t).toFixed(2)}px,0,0)`; ink.style.transform = `translate3d(${(-end).toFixed(2)}px,0,0)`; // The grey words ahead of the thumb step back as it comes, so only the white ones on the fill are read. if (hintRef.current) hintRef.current.style.opacity = (1 - smooth(clamp(p / 0.55, 0, 1))).toFixed(3); // In reach: the avatar leans in to take it. const reach = smooth(clamp((p - 0.7) / 0.3, 0, 1)) * (1 - k); avatar.style.transform = `scale(${(1 + 0.06 * reach + springs.take.get()).toFixed(4)})`; const state = run.current; if (state.committing && !state.caught && k > 0.75) { state.caught = true; state.caughtAt = performance.now(); if (!latest.current.reduced) springs.take.push(1.6); if (latest.current.sound) playSound("drop", 0.4); buzz(10); if (thumb === document.activeElement) rootRef.current?.focus({ preventScroll: true }); setPhase("sending"); settle(); } }; paintRef.current(); }); // The track's width, for the travel and the landing spot. React.useLayoutEffect(() => { const track = trackRef.current; if (!track) return; const measure = () => { width.current = track.clientWidth; paintRef.current(); }; measure(); const observer = new ResizeObserver(measure); observer.observe(track); return () => observer.disconnect(); }, []); const commit = (velocity: number) => { const state = run.current; if (state.committing) return; const inner = width.current - PAD * 2; state.committing = true; state.caught = false; state.result = null; setMessage(null); setPhase("handing"); // The transfer starts the moment you let go; the badge turns once the money is in their hands. new Promise((resolve) => resolve(latest.current.onSend())).then( () => { state.result = { ok: true }; settle(); }, (error: unknown) => { state.result = { ok: false, message: error instanceof Error ? error.message : undefined }; settle(); }, ); const springs = getSprings(); if (latest.current.reduced) { springs.head.jump(inner - KNOB); springs.tail.jump(inner - KNOB); return; } springs.head.configure(HAND_OVER); springs.head.push(Math.max(0, velocity)); springs.head.set(inner - KNOB); springs.tail.configure(DRAIN); springs.tail.set(inner - KNOB); }; const idle = phase === "idle" && !disabled; const onPointerDown = (event: React.PointerEvent<HTMLButtonElement>) => { if (!idle || run.current.committing || event.button !== 0 || !event.isPrimary) return; event.currentTarget.setPointerCapture(event.pointerId); const springs = getSprings(); springs.head.stop(); springs.head.configure(FOLLOW); springs.tail.jump(0); drag.current = { id: event.pointerId, start: event.clientX - springs.head.get(), samples: [] }; samplePointer(drag.current.samples, event.clientX, event.timeStamp); setMessage(null); }; const onPointerMove = (event: React.PointerEvent<HTMLButtonElement>) => { const current = drag.current; if (!current || current.id !== event.pointerId) return; const inner = width.current - PAD * 2; const max = Math.max(1, inner - KNOB * 2 - GAP); const land = inner - KNOB; const raw = event.clientX - current.start; // Free along the track and on under the avatar; past the start it gives only a few pixels. const value = raw < 0 ? rubberBand(raw, 6) : raw > land ? land + rubberBand(raw - land, 40) : raw; samplePointer(current.samples, event.clientX, event.timeStamp); getSprings().head.jump(value); const state = run.current; if (!state.reach && value >= max * 0.985) { state.reach = true; if (latest.current.sound) playSound("tick", 0.4); buzz(6); } else if (state.reach && value < max * 0.9) state.reach = false; }; const release = (event: React.PointerEvent<HTMLButtonElement>) => { const current = drag.current; if (!current || current.id !== event.pointerId) return; drag.current = null; run.current.reach = false; const max = Math.max(1, width.current - PAD * 2 - KNOB * 2 - GAP); const x = getSprings().head.get(); const velocity = event.type === "pointerup" ? releaseVelocity(current.samples, event.timeStamp) : 0; // px per ms if (event.type === "pointerup" && (x >= max * 0.97 || (x >= max * COMMIT_FROM && projectInertia(x, velocity) >= max * 0.97))) { commit(velocity * 1000); return; } // Let go early: home, keeping the speed it was let go with, softened so it doesn't slam into the start. if (latest.current.reduced) { getSprings().head.jump(0); return; } getSprings().head.push(softenVelocity(velocity * 1000, x)); getSprings().head.set(0); }; const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => { if (event.key === "Escape" && drag.current) { drag.current = null; getSprings().head.set(0); return; } if ((event.key === "Enter" || event.key === " ") && idle && !event.repeat) { event.preventDefault(); commit(0); } }; // A tap on the track instead of the thumb: the thumb hops toward the avatar and back, showing the way. const nudge = (event: React.PointerEvent<HTMLDivElement>) => { if (!idle || run.current.committing || latest.current.reduced) return; if (thumbRef.current?.contains(event.target as Node)) return; const head = getSprings().head; head.configure(FOLLOW); head.push(560); head.set(0); }; const status: SlideToSendStatus = phase === "sending" || phase === "handing" ? "sending" : phase === "sent" ? "sent" : message ? "error" : "idle"; React.useEffect(() => { latest.current.onStatusChange?.(status); }, [status]); const line: Line = phase === "sent" ? "sent" : phase === "sending" || phase === "handing" ? "sending" : message ? "failed" : "slide"; const announce = phase === "sending" ? words.sending : phase === "sent" ? `${words.sent}, ${money}` : (message ?? ""); const fade = (ms: number, delay = 0) => (reduced ? "none" : `opacity ${ms}ms ${EASE_OUT} ${delay}ms, transform ${ms + 120}ms ${EASE_OUT} ${delay}ms, filter ${ms}ms ${EASE_OUT} ${delay}ms`); // A line that is showing; the others wait below (later states) or above (earlier ones), blurred. const lineStyle = (name: Line): React.CSSProperties => { const on = name === line; const offset = LINES.indexOf(name) < LINES.indexOf(line) ? -6 : 6; return { opacity: on ? 1 : 0, transform: on ? "none" : `translate3d(0,${offset}px,0)`, filter: on ? "blur(0px)" : "blur(4px)", transition: on ? fade(300, 90) : fade(160), }; }; const slideWords = slideText ?? ( <> Slide to send <span className="font-semibold tabular-nums">{money}</span> </> ); const badge = phase === "sending" || phase === "sent"; const sent = phase === "sent"; return ( <div ref={rootRef} tabIndex={-1} role="group" aria-label={`Send ${money} to ${to.name}`} className={`w-full outline-none ${disabled ? "opacity-50" : ""} ${className}`} > <div ref={trackRef} onPointerDown={nudge} className="relative h-14 w-full min-w-[248px] rounded-full bg-background shadow-[inset_0_0_0_1px_var(--border)]" > {/* The words, under the fill. The slide line sits between the thumb and the avatar; the others take the whole track left of the avatar. */} <div aria-hidden="true" className="pointer-events-none absolute inset-0 text-[14px] font-medium tracking-[-0.01em]"> <span className="absolute inset-y-0 flex items-center justify-center" style={{ left: PAD + KNOB, right: PAD + KNOB, ...lineStyle("slide") }}> <span ref={hintRef} className="min-w-0"> <span className={`block truncate px-3 text-foreground ${SHEEN}`}>{slideWords}</span> </span> </span> <span className="absolute inset-y-0 flex items-center justify-center" style={{ left: PAD + KNOB, right: PAD + KNOB, ...lineStyle("failed") }}> <span className="truncate px-3 text-red-600 dark:text-red-400">{message ?? words.failed}</span> </span> <span className="absolute inset-y-0 flex items-center justify-center" style={{ left: PAD, right: PAD + KNOB, ...lineStyle("sending") }}> <span className={`truncate px-4 text-foreground ${SHEEN}`}>{words.sending}</span> </span> <span className="absolute inset-y-0 flex items-center justify-center" style={{ left: PAD, right: PAD + KNOB, ...lineStyle("sent") }}> <span className="truncate px-4 text-foreground">{words.sent}</span> </span> </div> {/* The fill: a window that follows the tail, a bar inside that follows the thumb, the words in white inside the bar. */} <div ref={windowRef} aria-hidden="true" className="pointer-events-none absolute inset-1 overflow-clip rounded-full will-change-transform"> <div ref={barRef} className="absolute inset-0 overflow-clip rounded-full bg-primary will-change-transform" style={{ transform: "translate3d(-100%,0,0)" }}> <div ref={inkRef} className="absolute inset-0 text-[14px] font-medium tracking-[-0.01em] text-primary-foreground will-change-transform"> <span className="absolute inset-y-0 flex items-center justify-center" style={{ left: KNOB, right: KNOB, opacity: line === "slide" ? 1 : 0 }}> <span className="truncate px-3">{slideWords}</span> </span> </div> </div> </div> <button ref={thumbRef} type="button" disabled={disabled} tabIndex={idle ? undefined : -1} aria-disabled={!idle || undefined} aria-label={`Slide to send ${money} to ${to.name}`} aria-describedby={hintId} onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={release} onPointerCancel={release} onLostPointerCapture={release} onKeyDown={onKeyDown} onClick={(event) => event.preventDefault()} className={`absolute left-1 top-1 z-[1] flex size-12 cursor-grab touch-none select-none items-center justify-center rounded-full bg-primary text-primary-foreground will-change-transform active:cursor-grabbing disabled:cursor-default aria-disabled:cursor-default ${INTERACTION_FOCUS}`} > <ArrowRight aria-hidden="true" className="size-[18px]" strokeWidth={2.25} /> </button> {/* The person. Above the thumb, so the money goes in under them. */} <span ref={avatarRef} aria-hidden="true" className="absolute right-1 top-1 z-[2] flex size-12"> {to.avatar ? ( // eslint-disable-next-line @next/next/no-img-element <img src={to.avatar} alt="" draggable={false} className="size-12 select-none rounded-full bg-muted object-cover" /> ) : ( <span className="flex size-12 items-center justify-center rounded-full bg-muted text-[14px] font-semibold text-foreground">{initials}</span> )} <span className="pointer-events-none absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.08)]" /> {/* The badge: turns while it sends, becomes a check when it went through. */} <span className={`absolute bottom-0 right-0 flex size-[18px] items-center justify-center rounded-full ring-2 ring-background ${sent ? "bg-emerald-500" : "bg-background"}`} style={{ opacity: badge ? 1 : 0, transform: badge ? "none" : "scale(0.4)", transition: reduced ? "none" : `opacity 200ms ${EASE_OUT}, transform 420ms ${EASE_THROW}, background-color 240ms ${EASE_OUT}`, }} > <svg viewBox="0 0 18 18" className={`absolute inset-0 size-[18px] ${phase === "sending" && !reduced ? "animate-spin" : ""}`} style={{ opacity: sent ? 0 : 1, filter: sent ? "blur(2px)" : "blur(0px)", transition: reduced ? "none" : `opacity 200ms ${EASE_OUT}, filter 200ms ${EASE_OUT}` }} > <circle cx="9" cy="9" r="6.5" fill="none" className="stroke-border" strokeWidth="2" /> <circle cx="9" cy="9" r="6.5" fill="none" stroke="var(--primary)" strokeWidth="2" strokeLinecap="round" pathLength={1} strokeDasharray="0.3 1" /> </svg> <svg viewBox="0 0 12 12" className="relative size-2.5 text-white"> <path d="m2.5 6.2 2.3 2.3 4.7-4.9" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" pathLength={1} style={{ strokeDasharray: 1, strokeDashoffset: sent ? 0 : 1, transition: reduced ? "none" : `stroke-dashoffset 320ms ease-out 140ms` }} /> </svg> </span> </span> </div> <span id={hintId} className="sr-only"> Drag to {to.name}, or press Enter, to send. </span> <span role="status" className="sr-only"> {announce} </span> </div> );}