1"use client"
2
3import React, { ReactNode, useEffect, useRef } from "react"
4
5export interface BaseParticle {
6 element: HTMLElement | SVGSVGElement
7 left: number
8 size: number
9 top: number
10}
11
12export interface BaseParticleOptions {
13 particle?: string
14 size?: number
15}
16
17export interface CoolParticle extends BaseParticle {
18 direction: number
19 speedHorz: number
20 speedUp: number
21 spinSpeed: number
22 spinVal: number
23}
24
25export interface CoolParticleOptions extends BaseParticleOptions {
26 particleCount?: number
27 speedHorz?: number
28 speedUp?: number
29}
30
31const SVG_NS = "http://www.w3.org/2000/svg"
32
33const getContainer = () => {
34 const id = "_coolMode_effect"
35 const existingContainer = document.getElementById(id)
36
37 if (existingContainer) {
38 return existingContainer
39 }
40
41 const container = document.createElement("div")
42 container.setAttribute("id", id)
43 container.setAttribute(
44 "style",
45 "overflow:hidden; position:fixed; height:100%; top:0; left:0; right:0; bottom:0; pointer-events:none; z-index:2147483647"
46 )
47
48 document.body.appendChild(container)
49
50 return container
51}
52
53let instanceCounter = 0
54
55const applyParticleEffect = (
56 element: HTMLElement,
57 options?: CoolParticleOptions
58): (() => void) => {
59 instanceCounter++
60
61 const defaultParticle = "circle"
62 const particleType = options?.particle || defaultParticle
63 const sizes = [15, 20, 25, 35, 45]
64 const limit = 45
65
66 let particles: CoolParticle[] = []
67 let autoAddParticle = false
68 let mouseX = 0
69 let mouseY = 0
70
71 const container = getContainer()
72
73 const appendCircleParticle = (particle: HTMLDivElement, size: number) => {
74 const circleSVG = document.createElementNS(SVG_NS, "svg")
75 const circle = document.createElementNS(SVG_NS, "circle")
76
77 circle.setAttributeNS(null, "cx", (size / 2).toString())
78 circle.setAttributeNS(null, "cy", (size / 2).toString())
79 circle.setAttributeNS(null, "r", (size / 2).toString())
80 circle.setAttributeNS(null, "fill", `hsl(${Math.random() * 360}, 70%, 50%)`)
81
82 circleSVG.appendChild(circle)
83 circleSVG.setAttribute("width", size.toString())
84 circleSVG.setAttribute("height", size.toString())
85
86 particle.appendChild(circleSVG)
87 }
88
89 const appendImageParticle = (
90 particle: HTMLDivElement,
91 imageSrc: string,
92 size: number
93 ) => {
94 const image = document.createElement("img")
95 image.src = imageSrc
96 image.width = size
97 image.height = size
98 image.alt = ""
99 image.style.borderRadius = "50%"
100
101 particle.appendChild(image)
102 }
103
104 const appendTextParticle = (
105 particle: HTMLDivElement,
106 particleContent: string,
107 size: number
108 ) => {
109 const fontSizeMultiplier = 3
110 const emojiSize = size * fontSizeMultiplier
111 const content = document.createElement("div")
112
113 content.textContent = particleContent
114 content.style.fontSize = `${emojiSize}px`
115 content.style.lineHeight = "1"
116 content.style.textAlign = "center"
117 content.style.width = `${size}px`
118 content.style.height = `${size}px`
119 content.style.display = "flex"
120 content.style.alignItems = "center"
121 content.style.justifyContent = "center"
122 content.style.transform = `scale(${fontSizeMultiplier})`
123 content.style.transformOrigin = "center"
124
125 particle.appendChild(content)
126 }
127
128 function generateParticle() {
129 const size =
130 options?.size || sizes[Math.floor(Math.random() * sizes.length)]
131 const speedHorz = options?.speedHorz || Math.random() * 10
132 const speedUp = options?.speedUp || Math.random() * 25
133 const spinVal = Math.random() * 360
134 const spinSpeed = Math.random() * 35 * (Math.random() <= 0.5 ? -1 : 1)
135 const top = mouseY - size / 2
136 const left = mouseX - size / 2
137 const direction = Math.random() <= 0.5 ? -1 : 1
138
139 const particle = document.createElement("div")
140
141 if (particleType === "circle") {
142 appendCircleParticle(particle, size)
143 } else if (
144 particleType.startsWith("http") ||
145 particleType.startsWith("/")
146 ) {
147 appendImageParticle(particle, particleType, size)
148 } else {
149 appendTextParticle(particle, particleType, size)
150 }
151
152 particle.style.position = "absolute"
153 particle.style.transform = `translate3d(${left}px, ${top}px, 0px) rotate(${spinVal}deg)`
154
155 container.appendChild(particle)
156
157 particles.push({
158 direction,
159 element: particle,
160 left,
161 size,
162 speedHorz,
163 speedUp,
164 spinSpeed,
165 spinVal,
166 top,
167 })
168 }
169
170 function refreshParticles() {
171 particles.forEach((p) => {
172 p.left = p.left - p.speedHorz * p.direction
173 p.top = p.top - p.speedUp
174 p.speedUp = Math.min(p.size, p.speedUp - 1)
175 p.spinVal = p.spinVal + p.spinSpeed
176
177 if (
178 p.top >=
179 Math.max(window.innerHeight, document.body.clientHeight) + p.size
180 ) {
181 particles = particles.filter((o) => o !== p)
182 p.element.remove()
183 }
184
185 p.element.setAttribute(
186 "style",
187 [
188 "position:absolute",
189 "will-change:transform",
190 `top:${p.top}px`,
191 `left:${p.left}px`,
192 `transform:rotate(${p.spinVal}deg)`,
193 ].join(";")
194 )
195 })
196 }
197
198 let animationFrame: number | undefined
199
200 let lastParticleTimestamp = 0
201 const particleGenerationDelay = 30
202
203 function loop() {
204 const currentTime = performance.now()
205 if (
206 autoAddParticle &&
207 particles.length < limit &&
208 currentTime - lastParticleTimestamp > particleGenerationDelay
209 ) {
210 generateParticle()
211 lastParticleTimestamp = currentTime
212 }
213
214 refreshParticles()
215 animationFrame = requestAnimationFrame(loop)
216 }
217
218 loop()
219
220 const isTouchInteraction = "ontouchstart" in window
221
222 const tap = isTouchInteraction ? "touchstart" : "mousedown"
223 const tapEnd = isTouchInteraction ? "touchend" : "mouseup"
224 const move = isTouchInteraction ? "touchmove" : "mousemove"
225
226 const updateMousePosition = (e: MouseEvent | TouchEvent) => {
227 if ("touches" in e) {
228 mouseX = e.touches?.[0].clientX
229 mouseY = e.touches?.[0].clientY
230 } else {
231 mouseX = e.clientX
232 mouseY = e.clientY
233 }
234 }
235
236 const tapHandler = (e: MouseEvent | TouchEvent) => {
237 updateMousePosition(e)
238 autoAddParticle = true
239 }
240
241 const disableAutoAddParticle = () => {
242 autoAddParticle = false
243 }
244
245 element.addEventListener(move, updateMousePosition, { passive: true })
246 element.addEventListener(tap, tapHandler, { passive: true })
247 element.addEventListener(tapEnd, disableAutoAddParticle, { passive: true })
248 element.addEventListener("mouseleave", disableAutoAddParticle, {
249 passive: true,
250 })
251
252 return () => {
253 element.removeEventListener(move, updateMousePosition)
254 element.removeEventListener(tap, tapHandler)
255 element.removeEventListener(tapEnd, disableAutoAddParticle)
256 element.removeEventListener("mouseleave", disableAutoAddParticle)
257
258 const interval = setInterval(() => {
259 if (animationFrame && particles.length === 0) {
260 cancelAnimationFrame(animationFrame)
261 clearInterval(interval)
262
263 if (--instanceCounter === 0) {
264 container.remove()
265 }
266 }
267 }, 500)
268 }
269}
270
271interface CoolModeProps {
272 children: ReactNode
273 options?: CoolParticleOptions
274}
275
276export const CoolMode: React.FC<CoolModeProps> = ({ children, options }) => {
277 const ref = useRef<HTMLSpanElement>(null)
278
279 useEffect(() => {
280 const element = ref.current
281 let cleanup: (() => void) | null = null
282
283 if (element) {
284 cleanup = applyParticleEffect(element, options)
285 }
286
287 return () => {
288 if (cleanup) {
289 cleanup()
290 }
291 }
292 }, [options])
293
294 return <span ref={ref}>{children}</span>
295}
296