1"use client"
2
3import {
4 useCallback,
5 useEffect,
6 useId,
7 useRef,
8 useState,
9 type ComponentPropsWithoutRef,
10} from "react"
11import { motion } from "motion/react"
12
13import { cn } from "@/lib/utils"
14
15export interface AnimatedGridPatternProps extends ComponentPropsWithoutRef<"svg"> {
16 width?: number
17 height?: number
18 x?: number
19 y?: number
20 strokeDasharray?: number
21 numSquares?: number
22 maxOpacity?: number
23 duration?: number
24 repeatDelay?: number
25}
26
27type Square = {
28 id: number
29 pos: [number, number]
30 iteration: number
31}
32
33export function AnimatedGridPattern({
34 width = 40,
35 height = 40,
36 x = -1,
37 y = -1,
38 strokeDasharray = 0,
39 numSquares = 50,
40 className,
41 maxOpacity = 0.5,
42 duration = 4,
43 repeatDelay = 0.5,
44 ...props
45}: AnimatedGridPatternProps) {
46 const id = useId()
47 const containerRef = useRef<SVGSVGElement | null>(null)
48 const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
49 const [squares, setSquares] = useState<Array<Square>>([])
50
51 const getPos = useCallback((): [number, number] => {
52 return [
53 Math.floor((Math.random() * dimensions.width) / width),
54 Math.floor((Math.random() * dimensions.height) / height),
55 ]
56 }, [dimensions.height, dimensions.width, height, width])
57
58 const generateSquares = useCallback(
59 (count: number) => {
60 return Array.from({ length: count }, (_, i) => ({
61 id: i,
62 pos: getPos(),
63 iteration: 0,
64 }))
65 },
66 [getPos]
67 )
68
69 const updateSquarePosition = useCallback(
70 (squareId: number) => {
71 setSquares((currentSquares) => {
72 const current = currentSquares[squareId]
73 if (!current || current.id !== squareId) return currentSquares
74
75 const nextSquares = currentSquares.slice()
76 nextSquares[squareId] = {
77 ...current,
78 pos: getPos(),
79 iteration: current.iteration + 1,
80 }
81
82 return nextSquares
83 })
84 },
85 [getPos]
86 )
87
88 useEffect(() => {
89 if (dimensions.width && dimensions.height) {
90 setSquares(generateSquares(numSquares))
91 }
92 }, [dimensions.width, dimensions.height, generateSquares, numSquares])
93
94 useEffect(() => {
95 const element = containerRef.current
96 let resizeObserver: ResizeObserver | null = null
97
98 if (element) {
99 resizeObserver = new ResizeObserver((entries) => {
100 for (const entry of entries) {
101 setDimensions((currentDimensions) => {
102 const nextWidth = entry.contentRect.width
103 const nextHeight = entry.contentRect.height
104 if (
105 currentDimensions.width === nextWidth &&
106 currentDimensions.height === nextHeight
107 ) {
108 return currentDimensions
109 }
110 return { width: nextWidth, height: nextHeight }
111 })
112 }
113 })
114
115 resizeObserver.observe(element)
116 }
117
118 return () => {
119 if (resizeObserver) {
120 resizeObserver.disconnect()
121 }
122 }
123 }, [])
124
125 return (
126 <svg
127 ref={containerRef}
128 aria-hidden="true"
129 className={cn(
130 "pointer-events-none absolute inset-0 h-full w-full fill-gray-400/30 stroke-gray-400/30",
131 className
132 )}
133 {...props}
134 >
135 <defs>
136 <pattern
137 id={id}
138 width={width}
139 height={height}
140 patternUnits="userSpaceOnUse"
141 x={x}
142 y={y}
143 >
144 <path
145 d={`M.5 ${height}V.5H${width}`}
146 fill="none"
147 strokeDasharray={strokeDasharray}
148 />
149 </pattern>
150 </defs>
151 <rect width="100%" height="100%" fill={`url(#${id})`} />
152 <svg x={x} y={y} className="overflow-visible">
153 {squares.map(({ pos: [squareX, squareY], id, iteration }, index) => (
154 <motion.rect
155 initial={{ opacity: 0 }}
156 animate={{ opacity: maxOpacity }}
157 transition={{
158 duration,
159 repeat: 1,
160 delay: index * 0.1,
161 repeatType: "reverse",
162 repeatDelay,
163 }}
164 onAnimationComplete={() => updateSquarePosition(id)}
165 key={`${id}-${iteration}`}
166 width={width - 1}
167 height={height - 1}
168 x={squareX * width + 1}
169 y={squareY * height + 1}
170 fill="currentColor"
171 strokeWidth="0"
172 />
173 ))}
174 </svg>
175 </svg>
176 )
177}
178