1"use client"
2
3import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
4
5import { cn } from "@/lib/utils"
6
7interface FlickeringGridProps extends React.HTMLAttributes<HTMLDivElement> {
8 squareSize?: number
9 gridGap?: number
10 flickerChance?: number
11 color?: string
12 width?: number
13 height?: number
14 className?: string
15 maxOpacity?: number
16}
17
18export const FlickeringGrid: React.FC<FlickeringGridProps> = ({
19 squareSize = 4,
20 gridGap = 6,
21 flickerChance = 0.3,
22 color = "rgb(0, 0, 0)",
23 width,
24 height,
25 className,
26 maxOpacity = 0.3,
27 ...props
28}) => {
29 const canvasRef = useRef<HTMLCanvasElement>(null)
30 const containerRef = useRef<HTMLDivElement>(null)
31 const [isInView, setIsInView] = useState(false)
32 const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 })
33
34 const memoizedColor = useMemo(() => {
35 const toRGBA = (color: string) => {
36 if (typeof window === "undefined") {
37 return `rgba(0, 0, 0,`
38 }
39 const canvas = document.createElement("canvas")
40 canvas.width = canvas.height = 1
41 const ctx = canvas.getContext("2d")
42 if (!ctx) return "rgba(255, 0, 0,"
43 ctx.fillStyle = color
44 ctx.fillRect(0, 0, 1, 1)
45 const [r, g, b] = Array.from(ctx.getImageData(0, 0, 1, 1).data)
46 return `rgba(${r}, ${g}, ${b},`
47 }
48 return toRGBA(color)
49 }, [color])
50
51 const setupCanvas = useCallback(
52 (canvas: HTMLCanvasElement, width: number, height: number) => {
53 const dpr = window.devicePixelRatio || 1
54 canvas.width = width * dpr
55 canvas.height = height * dpr
56 canvas.style.width = `${width}px`
57 canvas.style.height = `${height}px`
58 const cols = Math.ceil(width / (squareSize + gridGap))
59 const rows = Math.ceil(height / (squareSize + gridGap))
60
61 const squares = new Float32Array(cols * rows)
62 for (let i = 0; i < squares.length; i++) {
63 squares[i] = Math.random() * maxOpacity
64 }
65
66 return { cols, rows, squares, dpr }
67 },
68 [squareSize, gridGap, maxOpacity]
69 )
70
71 const updateSquares = useCallback(
72 (squares: Float32Array, deltaTime: number) => {
73 for (let i = 0; i < squares.length; i++) {
74 if (Math.random() < flickerChance * deltaTime) {
75 squares[i] = Math.random() * maxOpacity
76 }
77 }
78 },
79 [flickerChance, maxOpacity]
80 )
81
82 const drawGrid = useCallback(
83 (
84 ctx: CanvasRenderingContext2D,
85 width: number,
86 height: number,
87 cols: number,
88 rows: number,
89 squares: Float32Array,
90 dpr: number
91 ) => {
92 ctx.clearRect(0, 0, width, height)
93 ctx.fillStyle = "transparent"
94 ctx.fillRect(0, 0, width, height)
95
96 for (let i = 0; i < cols; i++) {
97 for (let j = 0; j < rows; j++) {
98 const opacity = squares[i * rows + j]
99 ctx.fillStyle = `${memoizedColor}${opacity})`
100 ctx.fillRect(
101 i * (squareSize + gridGap) * dpr,
102 j * (squareSize + gridGap) * dpr,
103 squareSize * dpr,
104 squareSize * dpr
105 )
106 }
107 }
108 },
109 [memoizedColor, squareSize, gridGap]
110 )
111
112 useEffect(() => {
113 const canvas = canvasRef.current
114 const container = containerRef.current
115 const ctx = canvas?.getContext("2d") ?? null
116 let animationFrameId: number | null = null
117 let resizeObserver: ResizeObserver | null = null
118 let intersectionObserver: IntersectionObserver | null = null
119 let gridParams: ReturnType<typeof setupCanvas> | null = null
120
121 if (canvas && container && ctx) {
122 const updateCanvasSize = () => {
123 const newWidth = width || container.clientWidth
124 const newHeight = height || container.clientHeight
125 setCanvasSize({ width: newWidth, height: newHeight })
126 gridParams = setupCanvas(canvas, newWidth, newHeight)
127 }
128
129 updateCanvasSize()
130
131 let lastTime = 0
132 const animate = (time: number) => {
133 if (!isInView || !gridParams) return
134
135 const deltaTime = (time - lastTime) / 1000
136 lastTime = time
137
138 updateSquares(gridParams.squares, deltaTime)
139 drawGrid(
140 ctx,
141 canvas.width,
142 canvas.height,
143 gridParams.cols,
144 gridParams.rows,
145 gridParams.squares,
146 gridParams.dpr
147 )
148 animationFrameId = requestAnimationFrame(animate)
149 }
150
151 resizeObserver = new ResizeObserver(() => {
152 updateCanvasSize()
153 })
154 resizeObserver.observe(container)
155
156 intersectionObserver = new IntersectionObserver(
157 ([entry]) => {
158 setIsInView(entry.isIntersecting)
159 },
160 { threshold: 0 }
161 )
162 intersectionObserver.observe(canvas)
163
164 if (isInView) {
165 animationFrameId = requestAnimationFrame(animate)
166 }
167 }
168
169 return () => {
170 if (animationFrameId !== null) {
171 cancelAnimationFrame(animationFrameId)
172 }
173 if (resizeObserver) {
174 resizeObserver.disconnect()
175 }
176 if (intersectionObserver) {
177 intersectionObserver.disconnect()
178 }
179 }
180 }, [setupCanvas, updateSquares, drawGrid, width, height, isInView])
181
182 return (
183 <div
184 ref={containerRef}
185 className={cn(`h-full w-full ${className}`)}
186 {...props}
187 >
188 <canvas
189 ref={canvasRef}
190 className="pointer-events-none"
191 style={{
192 width: canvasSize.width,
193 height: canvasSize.height,
194 }}
195 />
196 </div>
197 )
198}
199