1"use client"
2
3import React, {
4 useEffect,
5 useMemo,
6 useState,
7 type ComponentPropsWithoutRef,
8} from "react"
9import { AnimatePresence, motion, type MotionProps } from "motion/react"
10
11import { cn } from "@/lib/utils"
12
13export function AnimatedListItem({ children }: { children: React.ReactNode }) {
14 const animations: MotionProps = {
15 initial: { scale: 0, opacity: 0 },
16 animate: { scale: 1, opacity: 1, originY: 0 },
17 exit: { scale: 0, opacity: 0 },
18 transition: { type: "spring", stiffness: 350, damping: 40 },
19 }
20
21 return (
22 <motion.div {...animations} layout className="mx-auto w-full">
23 {children}
24 </motion.div>
25 )
26}
27
28export interface AnimatedListProps extends ComponentPropsWithoutRef<"div"> {
29 children: React.ReactNode
30 delay?: number
31}
32
33export const AnimatedList = React.memo(
34 ({ children, className, delay = 1000, ...props }: AnimatedListProps) => {
35 const [index, setIndex] = useState(0)
36 const childrenArray = useMemo(
37 () => React.Children.toArray(children),
38 [children]
39 )
40
41 useEffect(() => {
42 let timeout: ReturnType<typeof setTimeout> | null = null
43
44 if (index < childrenArray.length - 1) {
45 timeout = setTimeout(() => {
46 setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length)
47 }, delay)
48 }
49
50 return () => {
51 if (timeout !== null) {
52 clearTimeout(timeout)
53 }
54 }
55 }, [index, delay, childrenArray.length])
56
57 const itemsToShow = useMemo(() => {
58 const result = childrenArray.slice(0, index + 1).reverse()
59 return result
60 }, [index, childrenArray])
61
62 return (
63 <div
64 className={cn(`flex flex-col items-center gap-4`, className)}
65 {...props}
66 >
67 <AnimatePresence>
68 {itemsToShow.map((item) => (
69 <AnimatedListItem key={(item as React.ReactElement).key}>
70 {item}
71 </AnimatedListItem>
72 ))}
73 </AnimatePresence>
74 </div>
75 )
76 }
77)
78
79AnimatedList.displayName = "AnimatedList"
80