|
| 1 | +import React, { useEffect, useMemo, useState } from 'react' |
| 2 | + |
| 3 | +import { AnimatePresence, motion } from 'motion/react' |
| 4 | +import clsx from 'clsx' |
| 5 | + |
| 6 | +const AnimatedListItem = ({ children }) => { |
| 7 | + const animations = { |
| 8 | + initial: { scale: 0, opacity: 0 }, |
| 9 | + animate: { scale: 1, opacity: 1, originY: 0 }, |
| 10 | + exit: { scale: 0, opacity: 0 }, |
| 11 | + transition: { type: 'spring', stiffness: 350, damping: 40 }, |
| 12 | + } |
| 13 | + |
| 14 | + return ( |
| 15 | + <motion.div {...animations} layout className="mx-auto w-full"> |
| 16 | + {children} |
| 17 | + </motion.div> |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +const AnimatedList = React.memo(({ children, className, delay = 1000, ...props }) => { |
| 22 | + const [index, setIndex] = useState(0) |
| 23 | + const childrenArray = useMemo(() => React.Children.toArray(children), [children]) |
| 24 | + |
| 25 | + useEffect(() => { |
| 26 | + if (index < childrenArray.length - 1) { |
| 27 | + const timeout = setTimeout(() => { |
| 28 | + setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length) |
| 29 | + }, delay) |
| 30 | + |
| 31 | + return () => clearTimeout(timeout) |
| 32 | + } |
| 33 | + }, [index, delay, childrenArray.length]) |
| 34 | + |
| 35 | + const itemsToShow = useMemo(() => { |
| 36 | + const result = childrenArray.slice(0, index + 1).reverse() |
| 37 | + return result |
| 38 | + }, [index, childrenArray]) |
| 39 | + |
| 40 | + return ( |
| 41 | + <div className={clsx(`flex flex-col items-center gap-4`, className)} {...props}> |
| 42 | + <AnimatePresence> |
| 43 | + {itemsToShow.map((item) => ( |
| 44 | + <AnimatedListItem key={item.key}>{item}</AnimatedListItem> |
| 45 | + ))} |
| 46 | + </AnimatePresence> |
| 47 | + </div> |
| 48 | + ) |
| 49 | +}) |
| 50 | + |
| 51 | +export default AnimatedList |
0 commit comments