"use client"; import { Heart, RotateCcw, X } from "lucide-react"; import { AnimatePresence, type AnimationPlaybackControls, animate, motion, type MotionValue, type PanInfo, useMotionValue, useMotionValueEvent, usePresence, useReducedMotion, useSpring, useTransform, useVelocity, } from "motion/react"; import { type PointerEvent, type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react"; import { Tooltip } from "@/components/motion/tooltip"; import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease"; import { useControllable } from "@/lib/hooks/use-controllable"; import { useMessages } from "@/lib/i18n"; import { useSound } from "@/lib/sound"; import { liftSound } from "@/lib/sounds/lift"; import { swipeSound } from "@/lib/sounds/swipe"; import { TOUCH_GESTURE_CLASS } from "@/lib/touch"; import { cn } from "@/lib/utils"; /** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */ export const swipeDeckMessages = { label: "Card deck", card: "Card {index} of {count}", left: "Pass", right: "Like", undo: "Undo", swipedLeft: "Passed on {label}", swipedRight: "Liked {label}", restored: "Brought back {label}", empty: "No more cards", }; export type SwipeDeckMessages = typeof swipeDeckMessages; export type SwipeDirection = "left" | "right"; export interface SwipeDeckItem { /** Unique key for the card, also used in `value`. */ id: string; /** Accessible name for the card, used in announcements such as "Liked {label}". */ label: string; } export interface SwipeDeckDecision { /** The `id` of the swiped card. */ id: string; /** Which way the card was swiped. */ direction: SwipeDirection; } export interface SwipeDeckProps { /** Every card, top of the deck first. Swiped cards stay in the list and are skipped. */ items: T[]; /** The card's content. Fills the card frame. */ renderCard: (item: T) => ReactNode; /** Swipes made so far, oldest first, for controlled use. */ value?: SwipeDeckDecision[]; /** Swipes already made when uncontrolled. Default: [] */ defaultValue?: SwipeDeckDecision[]; /** Called with every swipe made so far after a swipe or an undo. */ onValueChange?: (value: SwipeDeckDecision[]) => void; /** Called with the card and direction when a card is swiped away. */ onSwipe?: (item: T, direction: SwipeDirection) => void; /** Called with the card and the direction it had left in when an undo brings it back. */ onUndo?: (item: T, direction: SwipeDirection) => void; /** Drag distance that swipes a card away on release (px). A fast flick needs less. Default: 110 */ threshold?: number; /** Cards drawn in the stack, the top card included. Default: 3 */ visible?: number; /** Show the pass, undo and like buttons under the deck. Default: true */ controls?: boolean; /** Icon for the pass button. Default: an X icon */ leftIcon?: ReactNode; /** Icon for the like button. Default: a heart icon */ rightIcon?: ReactNode; /** Shown once every card is swiped. Default: the "No more cards" message */ empty?: ReactNode; /** Play a whoosh on each swipe and a lift on undo. Default: false */ sound?: boolean; /** Accessible name for the deck. Default: "Card deck" */ "aria-label"?: string; /** Override any built-in string. */ labels?: Partial; /** Classes merged onto the root element. */ className?: string; /** Classes merged onto each card frame. */ cardClassName?: string; } const NONE: SwipeDeckDecision[] = []; // Each card behind the top one sits this much smaller and lower, so its // bottom edge peeks out under the card in front. const DEPTH_SCALE = 0.05; const DEPTH_OFFSET = 12; // Tilt follows the drag, about 7 degrees per 100px, up to a cap. const ROTATE_PER_PX = 0.07; const MAX_ROTATE = 20; // A flick counts as a swipe once it is this fast (px/s) and has moved this far // (px), so a fast drag across a short distance still throws the card. const FLICK_VELOCITY = 600; const FLICK_DISTANCE = 30; // A thrown card keeps its release speed: a soft spring aimed well past the // edge, faded out over EXIT_DURATION and removed then, so it never settles. const FLING = { type: "spring", stiffness: 180, damping: 30, mass: 0.6 } as const; const EXIT_DURATION = 0.3; // Far enough out that an undone card enters from beyond the deck's edge. const OFFSCREEN = 1.4; // The card body is elastic: the tilt trails the drag on an underdamped // spring, and the card shears against fast moves, so it wobbles when the // pointer stops or changes direction. About half critical damping. const WOBBLE = { stiffness: 260, damping: 12, mass: 0.6 } as const; // Drag speed (px/s) that reaches the full shear, and the shear there (deg). const SHEAR_SPEED = 1800; const MAX_SHEAR = 7; // A card let go early, or undone, springs home and overshoots once. const SPRING_BACK = { type: "spring", stiffness: 320, damping: 16, mass: 0.8 } as const; // Vertical drag rubber-bands: the card gives less the further it is pulled, // and never travels more than this (px). const MAX_LIFT = 90; const rubber = (value: number) => Math.sign(value) * MAX_LIFT * (1 - 1 / (1 + (Math.abs(value) * 0.55) / MAX_LIFT)); // Freezes a leaving card's depth pose: clamped to the front whatever the // shared lean and catch-up values do while the next card settles. const FROZEN = -1e6; const poseScale = (depth: number) => 1 - depth * DEPTH_SCALE; const poseY = (depth: number) => depth * DEPTH_OFFSET; /** * A stack of cards to swipe left or right, like a dating or discovery app. * The top card follows the pointer and tilts from where it was grabbed; past * the threshold, or on a fast flick, it flies off with the release speed. The * cards behind lean forward as you drag and settle into place once it goes. * Undo brings the last card back in from the side it left. */ export function SwipeDeck({ items, renderCard, value, defaultValue = NONE, onValueChange, onSwipe, onUndo, threshold = 110, visible = 3, controls = true, leftIcon, rightIcon, empty, sound = false, "aria-label": ariaLabel, labels, className, cardClassName, }: SwipeDeckProps) { const t = useMessages("swipeDeck", swipeDeckMessages, labels); const reduce = useReducedMotion() ?? false; const [decisions, setDecisions] = useControllable(value, defaultValue, onValueChange); const playSwipe = useSound(swipeSound, { enabled: sound }); const playUndo = useSound(liftSound, { enabled: sound }); // How far the top card has been dragged toward a swipe, 0 to 1. The cards // behind move forward by it. const lean = useMotionValue(0); // Depth the stack still has to travel after a swipe, eased back to 0 so the // cards behind glide forward instead of jumping a slot. const catchUp = useMotionValue(0); const catchUpAnim = useRef(null); // Written by the handlers that change the stack, applied in the commit that // shows the change so the stack never paints a frame out of step. const pendingAdvance = useRef(null); const exits = useRef(new Map()); const [restoring, setRestoring] = useState(null); const [announcement, setAnnouncement] = useState(""); // Cards that mount after the first render fade in at the back of the stack. const [ready, setReady] = useState(false); useEffect(() => setReady(true), []); const decided = new Set(decisions.map((decision) => decision.id)); const remaining = items.filter((item) => !decided.has(item.id)); const top = remaining[0]; const shown = remaining.slice(0, Math.max(1, visible)); const last = decisions.at(-1); const lastItem = last ? items.find((item) => item.id === last.id) : undefined; useLayoutEffect(() => { const leaned = pendingAdvance.current; if (leaned === null) return; pendingAdvance.current = null; // Every card moved up a slot; start them where they were drawn. catchUpAnim.current?.stop(); catchUp.set(Math.max(catchUp.get() + leaned - 1, -visible)); lean.set(0); if (reduce) catchUp.set(0); else catchUpAnim.current = animate(catchUp, 0, SPRING_LAYOUT); }); useEffect(() => () => catchUpAnim.current?.stop(), []); const swipe = (direction: SwipeDirection, velocity?: { x: number; y: number }) => { if (!top) return; exits.current.set(top.id, { direction, vx: velocity?.x ?? 0, vy: velocity?.y ?? 0 }); pendingAdvance.current = lean.get(); setRestoring(null); setDecisions([...decisions, { id: top.id, direction }]); setAnnouncement(t(direction === "left" ? "swipedLeft" : "swipedRight", { label: top.label })); playSwipe(); onSwipe?.(top, direction); }; const undo = () => { if (!last) return; exits.current.delete(last.id); setRestoring(last); setDecisions(decisions.slice(0, -1)); if (lastItem) { setAnnouncement(t("restored", { label: lastItem.label })); onUndo?.(lastItem, last.direction); } playUndo(); }; const position = decisions.length + 1; return (
{empty ?? t("empty")}
{shown.map((item, depth) => ( {renderCard(item)} ))}
{controls ? (
swipe("left")} className="size-12 hover:text-destructive" > {leftIcon ?? } swipe("right")} className="size-12 hover:text-success" > {rightIcon ?? }
) : null}
{announcement}
); } function DeckButton({ label, disabled, reduce, onClick, className, children, }: { label: string; disabled: boolean; reduce: boolean; onClick: () => void; className?: string; children: ReactNode; }) { return ( {children} ); } function DeckCard({ id, depth, count, threshold, lean, catchUp, reduce, fadeIn, enterFrom, exits, onRelease, label, leftLabel, rightLabel, className, children, }: { id: string; depth: number; count: number; threshold: number; lean: MotionValue; catchUp: MotionValue; reduce: boolean; fadeIn: boolean; enterFrom: SwipeDirection | undefined; exits: { current: Map }; onRelease: (direction: SwipeDirection, velocity: { x: number; y: number }) => void; label: string | undefined; leftLabel: string; rightLabel: string; className?: string; children: ReactNode; }) { const [isPresent, safeToRemove] = usePresence(); const frame = useRef(null); const x = useMotionValue(0); const y = useMotionValue(0); const opacity = useMotionValue(1); const slot = useMotionValue(depth); const running = useRef([]); const leaving = useRef(false); // +1 when grabbed on the top half, -1 on the bottom, so the card swings // around the pointer like a held card instead of always the same way. const grab = useRef(1); const isTop = depth === 0 && isPresent; const active = useRef(isTop); const effective = useTransform(() => Math.max(0, slot.get() - lean.get() - catchUp.get())); const scale = useTransform(() => poseScale(effective.get())); const offsetY = useTransform(() => poseY(effective.get())); const tilt = useTransform(() => reduce ? 0 : Math.max(-MAX_ROTATE, Math.min(MAX_ROTATE, x.get() * ROTATE_PER_PX * grab.current)), ); const rotate = useSpring(tilt, WOBBLE); // The far half of the card trails the half you hold, like a soft sheet. const xVelocity = useVelocity(x); const shear = useTransform(() => { if (reduce) return 0; const pull = Math.max(-1, Math.min(1, xVelocity.get() / SHEAR_SPEED)); return -pull * MAX_SHEAR * grab.current; }); const skewX = useSpring(shear, WOBBLE); const liftY = useTransform(y, (value) => (reduce ? value : rubber(value))); const rightStamp = useTransform(x, [threshold * 0.25, threshold], [0, 1]); const leftStamp = useTransform(x, [-threshold, -threshold * 0.25], [1, 0]); const stop = () => { for (const animation of running.current) animation.stop(); running.current = []; }; useMotionValueEvent(x, "change", (latest) => { if (active.current) lean.set(Math.min(1, Math.abs(latest) / threshold)); }); useLayoutEffect(() => { const was = active.current; active.current = isTop; // A card that becomes the top one owns the lean from where it stands: 0 // for the next card up, still far out for one undone mid-throw. if (isTop && !was) lean.set(Math.min(1, Math.abs(x.get()) / threshold)); slot.set(isPresent ? depth : FROZEN); }); // Entrance: an undone card flies back in from the side it left, and a card // joining the back of the stack fades in. Runs once, on mount. // biome-ignore lint/correctness/useExhaustiveDependencies: mount only; later prop changes are not entrances. useLayoutEffect(() => { const width = frame.current?.offsetWidth ?? 0; if (enterFrom && !reduce) { x.set((enterFrom === "right" ? 1 : -1) * width * OFFSCREEN); opacity.set(0); if (depth === 0) lean.set(1); running.current = [animate(x, 0, SPRING_BACK), animate(opacity, 1, { duration: EXIT_DURATION, ease: EASE_OUT })]; } else if (enterFrom || fadeIn) { opacity.set(0); running.current = [animate(opacity, 1, { duration: 0.2, ease: EASE_OUT })]; } return stop; }, []); // Exit: a swiped card is thrown off along its release speed, anything else // fades. Undo before it finishes brings it straight back. // biome-ignore lint/correctness/useExhaustiveDependencies: presence is the only trigger; the other values are read at that moment. useEffect(() => { if (isPresent) { if (!leaving.current) return; leaving.current = false; stop(); running.current = [ animate(x, 0, SPRING_BACK), animate(y, 0, SPRING_BACK), animate(opacity, 1, { duration: 0.2, ease: EASE_OUT }), ]; return; } leaving.current = true; stop(); const exit = exits.current.get(id); if (!exit || reduce) { const fade = animate(opacity, 0, { duration: 0.15, ease: EASE_OUT }); running.current = [fade]; fade.then(() => safeToRemove()); return; } const width = frame.current?.offsetWidth ?? 300; const sign = exit.direction === "right" ? 1 : -1; // A button press has no release speed: throw at a flick's speed with a // little lift, as a flicked card would leave. const fade = animate(opacity, [1, 1, 0], { duration: EXIT_DURATION, times: [0, 0.5, 1] }); running.current = [ animate(x, sign * width * OFFSCREEN * 1.5, { ...FLING, velocity: exit.vx || sign * 900 }), animate(y, y.get() + (exit.vy ? exit.vy * 0.12 : -width * 0.08), { ...FLING, velocity: exit.vy }), fade, ]; fade.then(() => { stop(); safeToRemove(); }); }, [isPresent]); // Read where the pointer lands before the drag starts, in viewport space, // so the swing side is set before the first move. const onPointerDown = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); grab.current = event.clientY < rect.top + rect.height / 2 ? 1 : -1; }; const onDragEnd = (_event: unknown, info: PanInfo) => { const dx = x.get(); const vx = info.velocity.x; const direction: SwipeDirection | null = dx > threshold || (vx > FLICK_VELOCITY && dx > FLICK_DISTANCE) ? "right" : dx < -threshold || (vx < -FLICK_VELOCITY && dx < -FLICK_DISTANCE) ? "left" : null; if (direction) { onRelease(direction, info.velocity); return; } if (reduce) { x.set(0); y.set(0); return; } running.current = [ animate(x, 0, { ...SPRING_BACK, velocity: vx }), animate(y, 0, { ...SPRING_BACK, velocity: info.velocity.y }), ]; }; return ( {children} ); }