"use client"; import { motion, useMotionValue, useTransform } from 'motion/react'; import { useState, useEffect } from 'react'; import './Stack.css'; function CardRotate({ children, onSendToBack, sensitivity, disableDrag = false }) { const x = useMotionValue(0); const y = useMotionValue(0); const rotateX = useTransform(y, [-100, 100], [60, -60]); const rotateY = useTransform(x, [-100, 100], [-60, 60]); function handleDragEnd(_, info) { if (Math.abs(info.offset.x) > sensitivity || Math.abs(info.offset.y) > sensitivity) { onSendToBack(); } else { x.set(0); y.set(0); } } if (disableDrag) { return ( {children} ); } return ( {children} ); } export default function Stack({ randomRotation = false, sensitivity = 200, cards = [], animationConfig = { stiffness: 260, damping: 20 }, sendToBackOnClick = false, autoplay = false, autoplayDelay = 3000, pauseOnHover = false, mobileClickOnly = false, mobileBreakpoint = 768 }) { const [isMobile, setIsMobile] = useState(false); const [isPaused, setIsPaused] = useState(false); useEffect(() => { const checkMobile = () => { setIsMobile(window.innerWidth < mobileBreakpoint); }; checkMobile(); window.addEventListener('resize', checkMobile); return () => window.removeEventListener('resize', checkMobile); }, [mobileBreakpoint]); const shouldDisableDrag = mobileClickOnly && isMobile; const shouldEnableClick = sendToBackOnClick || shouldDisableDrag; const [stack, setStack] = useState(() => { if (cards.length) { return cards.map((content, index) => ({ id: index + 1, content })); } else { return [ { id: 1, content: ( card-1 ) }, { id: 2, content: ( card-2 ) }, { id: 3, content: ( card-3 ) }, { id: 4, content: ( card-4 ) } ]; } }); useEffect(() => { if (cards.length) { setStack(cards.map((content, index) => ({ id: index + 1, content }))); } }, [cards]); const sendToBack = id => { setStack(prev => { const newStack = [...prev]; const index = newStack.findIndex(card => card.id === id); const [card] = newStack.splice(index, 1); newStack.unshift(card); return newStack; }); }; useEffect(() => { if (autoplay && stack.length > 1 && !isPaused) { const interval = setInterval(() => { const topCardId = stack[stack.length - 1].id; sendToBack(topCardId); }, autoplayDelay); return () => clearInterval(interval); } }, [autoplay, autoplayDelay, stack, isPaused]); return (
pauseOnHover && setIsPaused(true)} onMouseLeave={() => pauseOnHover && setIsPaused(false)} > {stack.map((card, index) => { const randomRotate = randomRotation ? Math.random() * 10 - 5 : 0; return ( sendToBack(card.id)} sensitivity={sensitivity} disableDrag={shouldDisableDrag} > shouldEnableClick && sendToBack(card.id)} animate={{ rotateZ: (stack.length - index - 1) * 4 + randomRotate, scale: 1 + index * 0.06 - stack.length * 0.06, transformOrigin: '90% 90%' }} initial={false} transition={{ type: 'spring', stiffness: animationConfig.stiffness, damping: animationConfig.damping }} > {card.content} ); })}
); }