1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import {
5 motion,
6 type PanInfo,
7 useMotionValue,
8 useTransform,
9} from "motion/react";
10import {
11 Children,
12 cloneElement,
13 type HTMLAttributes,
14 type ReactElement,
15 useCallback,
16 useEffect,
17 useRef,
18 useState,
19} from "react";
20import { cn } from "@/lib/utils";
21
22export type DeckProps = HTMLAttributes<HTMLDivElement>;
23
24export const Deck = ({ className, ...props }: DeckProps) => (
25 <div className={cn("relative isolate", className)} {...props} />
26);
27
28export type DeckCardsProps = HTMLAttributes<HTMLDivElement> & {
29 onSwipe?: (index: number, direction: "left" | "right") => void;
30 onSwipeEnd?: (index: number, direction: "left" | "right") => void;
31 threshold?: number;
32 stackSize?: number;
33 perspective?: number;
34 scale?: number;
35 currentIndex?: number;
36 defaultCurrentIndex?: number;
37 onCurrentIndexChange?: (index: number) => void;
38 animateOnIndexChange?: boolean;
39 indexChangeDirection?: "left" | "right";
40};
41
42export const DeckCards = ({
43 children,
44 className,
45 onSwipe,
46 onSwipeEnd,
47 threshold = 150,
48 stackSize = 3,
49 perspective = 1000,
50 scale = 0.05,
51 currentIndex: currentIndexProp,
52 defaultCurrentIndex = 0,
53 onCurrentIndexChange,
54 animateOnIndexChange = true,
55 indexChangeDirection = "left",
56 ...props
57}: DeckCardsProps) => {
58 const childrenArray = Children.toArray(children) as ReactElement[];
59 const [currentIndex, setCurrentIndex] = useControllableState({
60 prop: currentIndexProp,
61 defaultProp: defaultCurrentIndex,
62 onChange: onCurrentIndexChange,
63 });
64 const [exitDirection, setExitDirection] = useState<"left" | "right" | null>(
65 null
66 );
67 const [displayIndex, setDisplayIndex] = useState(currentIndex);
68 const isInternalChangeRef = useRef(false);
69 const prevIndexRef = useRef(currentIndex);
70
71 // Detect external currentIndex changes and trigger animation
72 useEffect(() => {
73 const prevIndex = prevIndexRef.current;
74
75 // Skip initial mount and internal changes
76 if (prevIndex === currentIndex || isInternalChangeRef.current) {
77 isInternalChangeRef.current = false;
78 prevIndexRef.current = currentIndex;
79 setDisplayIndex(currentIndex);
80 return;
81 }
82
83 // Only animate if the option is enabled and we have cards to show
84 if (animateOnIndexChange && prevIndex < childrenArray.length) {
85 setExitDirection(indexChangeDirection);
86
87 // Update display index after animation completes
88 setTimeout(() => {
89 setExitDirection(null);
90 setDisplayIndex(currentIndex);
91 }, 300);
92 } else {
93 // No animation, update display index immediately
94 setDisplayIndex(currentIndex);
95 }
96
97 prevIndexRef.current = currentIndex;
98 }, [
99 currentIndex,
100 animateOnIndexChange,
101 indexChangeDirection,
102 childrenArray.length,
103 ]);
104
105 const handleSwipe = useCallback(
106 (direction: "left" | "right") => {
107 if (displayIndex >= childrenArray.length) {
108 return;
109 }
110
111 setExitDirection(direction);
112
113 if (direction === "left") {
114 onSwipe?.(displayIndex, "left");
115 } else {
116 onSwipe?.(displayIndex, "right");
117 }
118
119 onSwipeEnd?.(displayIndex, direction);
120
121 // Move to next card after animation
122 setTimeout(() => {
123 isInternalChangeRef.current = true;
124 const newIndex = displayIndex + 1;
125 setCurrentIndex(newIndex);
126 setDisplayIndex(newIndex);
127 setExitDirection(null);
128 }, 300);
129 },
130 [displayIndex, childrenArray.length, onSwipe, onSwipeEnd, setCurrentIndex]
131 );
132
133 const visibleCards = childrenArray.slice(
134 displayIndex,
135 displayIndex + stackSize
136 );
137
138 if (displayIndex >= childrenArray.length) {
139 return null;
140 }
141
142 return (
143 <div
144 className={cn("relative z-10 size-full", className)}
145 style={{ perspective }}
146 {...props}
147 >
148 {visibleCards.map((child, index) => {
149 const isTopCard = !index;
150 const zIndex = stackSize - index;
151 const scaleValue = 1 - index * scale;
152 const yOffset = index * 4;
153 const cardKey = `${displayIndex}-${child.key ?? index}`;
154
155 if (isTopCard) {
156 return (
157 <DeckCard
158 exitDirection={exitDirection}
159 key={cardKey}
160 onSwipe={handleSwipe}
161 style={{
162 zIndex,
163 scale: scaleValue,
164 y: yOffset,
165 }}
166 threshold={threshold}
167 >
168 {child}
169 </DeckCard>
170 );
171 }
172
173 const nextCardScale = index === 1 && exitDirection ? 1 : scaleValue;
174 const nextCardY = index === 1 && exitDirection ? 0 : yOffset;
175
176 return (
177 <motion.div
178 animate={{
179 scale: nextCardScale,
180 y: nextCardY,
181 }}
182 className="absolute inset-0"
183 key={cardKey}
184 style={{
185 zIndex,
186 scale: scaleValue,
187 y: yOffset,
188 }}
189 transition={{ duration: 0.3, ease: "easeOut" }}
190 >
191 {child}
192 </motion.div>
193 );
194 })}
195 </div>
196 );
197};
198
199type DeckCardProps = {
200 children: ReactElement;
201 onSwipe: (direction: "left" | "right") => void;
202 threshold: number;
203 style?: object;
204 exitDirection: "left" | "right" | null;
205};
206
207const DeckCard = ({
208 children,
209 onSwipe,
210 threshold,
211 style,
212 exitDirection,
213}: DeckCardProps) => {
214 const x = useMotionValue(0);
215 const rotate = useTransform(x, [-200, 200], [-25, 25]);
216 const opacity = useTransform(
217 x,
218 [-200, -threshold, 0, threshold, 200],
219 [0, 1, 1, 1, 0]
220 );
221
222 const handleDragEnd = (_: unknown, info: PanInfo) => {
223 const swipeThreshold = threshold;
224
225 if (Math.abs(info.offset.x) > swipeThreshold) {
226 const direction = info.offset.x > 0 ? "right" : "left";
227 onSwipe(direction);
228 }
229 };
230
231 let exitX = 0;
232
233 if (exitDirection === "left") {
234 exitX = -500;
235 } else if (exitDirection === "right") {
236 exitX = 500;
237 }
238
239 const castedChildren = children as ReactElement<
240 HTMLAttributes<HTMLDivElement>
241 >;
242
243 return (
244 <motion.div
245 animate={exitDirection ? { x: exitX, opacity: 0 } : undefined}
246 className="absolute inset-0 cursor-grab active:cursor-grabbing"
247 drag="x"
248 dragConstraints={{ left: 0, right: 0 }}
249 onDragEnd={handleDragEnd}
250 style={{
251 x,
252 rotate,
253 opacity,
254 ...style,
255 }}
256 transition={{ duration: 0.3, ease: "easeOut" }}
257 whileDrag={{ scale: 1.05 }}
258 >
259 {cloneElement(castedChildren, {
260 className: cn(
261 "h-full w-full select-none rounded-lg shadow-lg",
262 castedChildren.props.className
263 ),
264 })}
265 </motion.div>
266 );
267};
268
269export type DeckItemProps = HTMLAttributes<HTMLDivElement>;
270
271export const DeckItem = ({ className, ...props }: DeckItemProps) => (
272 <div
273 className={cn(
274 "flex h-full w-full items-center justify-center rounded-lg border bg-card text-card-foreground shadow-lg",
275 className
276 )}
277 {...props}
278 />
279);
280
281export type DeckEmptyProps = HTMLAttributes<HTMLDivElement>;
282
283export const DeckEmpty = ({
284 children,
285 className,
286 ...props
287}: HTMLAttributes<HTMLDivElement>) => (
288 <div
289 className={cn(
290 "absolute inset-0 flex items-center justify-center rounded-lg border border-dashed text-muted-foreground",
291 className
292 )}
293 {...props}
294 >
295 {children ?? <p className="text-sm">No more cards</p>}
296 </div>
297);
298