1"use client"
2
3import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
4import { AnimatePresence, motion } from "motion/react"
5
6interface FractalDotGridProps {
7 /** Size of each dot in pixels */
8 dotSize?: number
9 /** Spacing between dots in pixels */
10 dotSpacing?: number
11 /** Opacity of dots (0-1) */
12 dotOpacity?: number
13 /** Intensity of the wave effect when hovering */
14 waveIntensity?: number
15 /** Radius of the wave effect in pixels */
16 waveRadius?: number
17 /** Color of the dots (supports any valid CSS color) */
18 dotColor?: string
19 /** Color of the dot glow effect (supports any valid CSS color) */
20 glowColor?: string
21 /** Enable or disable the noise overlay */
22 enableNoise?: boolean
23 /** Opacity of the noise overlay (0-1) */
24 noiseOpacity?: number
25 /** Enable or disable the mouse glow effect */
26 enableMouseGlow?: boolean
27 /** Set the initial performance level */
28 initialPerformance?: "low" | "medium" | "high"
29}
30
31const NoiseSVG = React.memo(() => (
32 <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
33 <filter id="noise">
34 <feTurbulence
35 type="fractalNoise"
36 baseFrequency="0.65"
37 numOctaves="3"
38 stitchTiles="stitch"
39 />
40 </filter>
41 <rect width="100%" height="100%" filter="url(#noise)" />
42 </svg>
43))
44
45NoiseSVG.displayName = "NoiseSVG"
46
47const NoiseOverlay: React.FC<{ opacity: number }> = ({ opacity }) => (
48 <div
49 className="absolute inset-0 h-full w-full mix-blend-overlay"
50 style={{ opacity }}
51 >
52 <NoiseSVG />
53 </div>
54)
55
56const useResponsive = () => {
57 const [windowSize, setWindowSize] = useState({
58 width: typeof window !== "undefined" ? window.innerWidth : 0,
59 height: typeof window !== "undefined" ? window.innerHeight : 0,
60 })
61
62 useEffect(() => {
63 const handleResize = () => {
64 setWindowSize({
65 width: window.innerWidth,
66 height: window.innerHeight,
67 })
68 }
69
70 window.addEventListener("resize", handleResize)
71 return () => window.removeEventListener("resize", handleResize)
72 }, [])
73
74 return {
75 isMobile: windowSize.width < 768,
76 isTablet: windowSize.width >= 768 && windowSize.width < 1024,
77 isDesktop: windowSize.width >= 1024,
78 }
79}
80
81const usePerformance = (
82 initialPerformance: "low" | "medium" | "high" = "medium"
83) => {
84 const [performance, setPerformance] = useState(initialPerformance)
85 const [fps, setFps] = useState(60)
86
87 useEffect(() => {
88 let frameCount = 0
89 let lastTime = globalThis.performance.now()
90 let framerId: number
91
92 const measureFps = (time: number) => {
93 frameCount++
94 if (time - lastTime > 1000) {
95 setFps(Math.round((frameCount * 1000) / (time - lastTime)))
96 frameCount = 0
97 lastTime = time
98 }
99 framerId = requestAnimationFrame(measureFps)
100 }
101
102 framerId = requestAnimationFrame(measureFps)
103
104 return () => cancelAnimationFrame(framerId)
105 }, [])
106
107 useEffect(() => {
108 if (fps < 30 && performance !== "low") {
109 setPerformance("low")
110 } else if (fps >= 30 && fps < 50 && performance !== "medium") {
111 setPerformance("medium")
112 } else if (fps >= 50 && performance !== "high") {
113 setPerformance("high")
114 }
115 }, [fps, performance])
116
117 return { performance, fps }
118}
119
120const DotCanvas: React.FC<{
121 dotSize: number
122 dotSpacing: number
123 dotOpacity: number
124 waveIntensity: number
125 waveRadius: number
126 dotColor: string
127 glowColor: string
128 performance: "low" | "medium" | "high"
129 mousePos: { x: number; y: number }
130}> = React.memo(
131 ({
132 dotSize,
133 dotSpacing,
134 dotOpacity,
135 waveIntensity,
136 waveRadius,
137 dotColor,
138 glowColor,
139 performance,
140 mousePos,
141 }) => {
142 const canvasRef = useRef<HTMLCanvasElement>(null)
143 const animationRef = useRef<number | null>(null)
144
145 const drawDots = useCallback(
146 (ctx: CanvasRenderingContext2D, time: number) => {
147 const { width, height } = ctx.canvas
148 ctx.clearRect(0, 0, width, height)
149
150 const performanceSettings = {
151 low: { skip: 3 },
152 medium: { skip: 2 },
153 high: { skip: 1 },
154 }
155
156 const skip = performanceSettings[performance].skip
157
158 const cols = Math.ceil(width / dotSpacing)
159 const rows = Math.ceil(height / dotSpacing)
160
161 const centerX = mousePos.x * width
162 const centerY = mousePos.y * height
163
164 for (let i = 0; i < cols; i += skip) {
165 for (let j = 0; j < rows; j += skip) {
166 const x = i * dotSpacing
167 const y = j * dotSpacing
168
169 const distanceX = x - centerX
170 const distanceY = y - centerY
171 const distance = Math.sqrt(
172 distanceX * distanceX + distanceY * distanceY
173 )
174
175 let dotX = x
176 let dotY = y
177
178 if (distance < waveRadius) {
179 const waveStrength = Math.pow(1 - distance / waveRadius, 2)
180 const angle = Math.atan2(distanceY, distanceX)
181 const waveOffset =
182 Math.sin(distance * 0.05 - time * 0.005) *
183 waveIntensity *
184 waveStrength
185 dotX += Math.cos(angle) * waveOffset
186 dotY += Math.sin(angle) * waveOffset
187
188 const glowRadius = dotSize * (1 + waveStrength)
189 const gradient = ctx.createRadialGradient(
190 dotX,
191 dotY,
192 0,
193 dotX,
194 dotY,
195 glowRadius
196 )
197 gradient.addColorStop(
198 0,
199 glowColor.replace("1)", `${dotOpacity * (1 + waveStrength)})`)
200 )
201 gradient.addColorStop(1, glowColor.replace("1)", "0)"))
202 ctx.fillStyle = gradient
203 } else {
204 ctx.fillStyle = dotColor.replace("1)", `${dotOpacity})`)
205 }
206
207 ctx.beginPath()
208 ctx.arc(dotX, dotY, dotSize / 2, 0, Math.PI * 2)
209 ctx.fill()
210 }
211 }
212 },
213 [
214 dotSize,
215 dotSpacing,
216 dotOpacity,
217 waveIntensity,
218 waveRadius,
219 dotColor,
220 glowColor,
221 performance,
222 mousePos,
223 ]
224 )
225
226 useEffect(() => {
227 const canvas = canvasRef.current
228 if (!canvas) return
229
230 const ctx = canvas.getContext("2d")
231 if (!ctx) return
232
233 const resizeCanvas = () => {
234 canvas.width = window.innerWidth
235 canvas.height = window.innerHeight
236 }
237
238 resizeCanvas()
239 window.addEventListener("resize", resizeCanvas)
240
241 let lastTime = 0
242 const animate = (time: number) => {
243 if (time - lastTime > 16) {
244 drawDots(ctx, time)
245 lastTime = time
246 }
247 animationRef.current = requestAnimationFrame(animate)
248 }
249
250 animationRef.current = requestAnimationFrame(animate)
251
252 return () => {
253 window.removeEventListener("resize", resizeCanvas)
254 if (animationRef.current) {
255 cancelAnimationFrame(animationRef.current)
256 }
257 }
258 }, [drawDots])
259
260 return (
261 <canvas
262 ref={canvasRef}
263 className="absolute inset-0 h-full w-full bg-gray-100"
264 style={{ mixBlendMode: "multiply" }}
265 />
266 )
267 }
268)
269
270DotCanvas.displayName = "DotCanvas"
271
272const MouseGlow: React.FC<{
273 glowColor: string
274 mousePos: { x: number; y: number }
275}> = React.memo(({ glowColor, mousePos }) => (
276 <>
277 <div
278 className="absolute w-40 h-40 rounded-full pointer-events-none"
279 style={{
280 background: `radial-gradient(circle, ${glowColor.replace(
281 "1)",
282 "0.2)"
283 )} 0%, ${glowColor.replace("1)", "0)")} 70%)`,
284 left: `${mousePos.x * 100}%`,
285 top: `${mousePos.y * 100}%`,
286 transform: "translate(-50%, -50%)",
287 filter: "blur(10px)",
288 }}
289 />
290 <div
291 className="absolute w-20 h-20 rounded-full pointer-events-none"
292 style={{
293 background: `radial-gradient(circle, ${glowColor.replace(
294 "1)",
295 "0.4)"
296 )} 0%, ${glowColor.replace("1)", "0)")} 70%)`,
297 left: `${mousePos.x * 100}%`,
298 top: `${mousePos.y * 100}%`,
299 transform: "translate(-50%, -50%)",
300 }}
301 />
302 </>
303))
304
305MouseGlow.displayName = "MouseGlow"
306
307export function FractalDotGrid({
308 dotSize = 4,
309 dotSpacing = 20,
310 dotOpacity = 0.3,
311 waveIntensity = 30,
312 waveRadius = 200,
313 dotColor = "rgba(100, 100, 255, 1)",
314 glowColor = "rgba(100, 100, 255, 1)",
315 enableNoise = true,
316 noiseOpacity = 0.03,
317 enableMouseGlow = true,
318 initialPerformance = "medium",
319}: FractalDotGridProps) {
320 const containerRef = useRef<HTMLDivElement>(null)
321 const { isMobile, isTablet } = useResponsive()
322 const { performance } = usePerformance(initialPerformance)
323 const [mousePos, setMousePos] = useState({ x: 0, y: 0 })
324
325 const handleMouseMove = useCallback((event: MouseEvent) => {
326 const { clientX, clientY } = event
327 const { left, top, width, height } =
328 containerRef.current?.getBoundingClientRect() ?? {
329 left: 0,
330 top: 0,
331 width: 0,
332 height: 0,
333 }
334 const x = (clientX - left) / width
335 const y = (clientY - top) / height
336 setMousePos({ x, y })
337 }, [])
338
339 useEffect(() => {
340 window.addEventListener("mousemove", handleMouseMove)
341 return () => window.removeEventListener("mousemove", handleMouseMove)
342 }, [handleMouseMove])
343
344 const responsiveDotSize = useMemo(() => {
345 if (isMobile) return dotSize * 0.75
346 if (isTablet) return dotSize * 0.9
347 return dotSize
348 }, [isMobile, isTablet, dotSize])
349
350 const responsiveDotSpacing = useMemo(() => {
351 if (isMobile) return dotSpacing * 1.5
352 if (isTablet) return dotSpacing * 1.25
353 return dotSpacing
354 }, [isMobile, isTablet, dotSpacing])
355
356 return (
357 <AnimatePresence>
358 <motion.div
359 ref={containerRef}
360 key="fractal-dot-grid"
361 initial={{ opacity: 0 }}
362 animate={{ opacity: 1 }}
363 exit={{ opacity: 0 }}
364 transition={{ duration: 1.5, ease: "easeOut" }}
365 className="absolute inset-0 overflow-hidden w-full h-full"
366 >
367 <DotCanvas
368 dotSize={responsiveDotSize}
369 dotSpacing={responsiveDotSpacing}
370 dotOpacity={dotOpacity}
371 waveIntensity={waveIntensity}
372 waveRadius={waveRadius}
373 dotColor={dotColor}
374 glowColor={glowColor}
375 performance={performance}
376 mousePos={mousePos}
377 />
378 {enableNoise && <NoiseOverlay opacity={noiseOpacity} />}
379 {enableMouseGlow && (
380 <MouseGlow glowColor={glowColor} mousePos={mousePos} />
381 )}
382 </motion.div>
383 </AnimatePresence>
384 )
385}
386
387export default FractalDotGrid
388