1"use client";
2
3import React, {
4 useEffect,
5 useRef,
6 useCallback,
7 type ReactNode,
8 type CSSProperties,
9} from "react";
10
11type HorizontalDirection = "left" | "center" | "right";
12type VerticalDirection = "top" | "center" | "bottom";
13
14interface ExplodingInputProps {
15 /** Content to render as particles (React nodes) */
16 content?: ReactNode[];
17 /** Number of particles to spawn per input event */
18 count?: number;
19 /** Direction of particle movement */
20 direction?: {
21 horizontal?: HorizontalDirection;
22 vertical?: VerticalDirection;
23 };
24 /** Gravity value from -1 to 1 (negative = upward, positive = downward) */
25 gravity?: number;
26 /** Duration of particle animation in seconds */
27 duration?: number;
28 /** Scale configuration for particles */
29 scale?: {
30 value?: number;
31 randomize?: boolean;
32 randomVariation?: number;
33 };
34 /** Rotation configuration for particles */
35 rotation?: {
36 value?: number;
37 animate?: boolean;
38 };
39 /** Custom styles for the container */
40 style?: CSSProperties;
41 /** Class name for the container */
42 className?: string;
43}
44
45interface Particle {
46 id: number;
47 x: number;
48 y: number;
49 scale: number;
50 rotate: number;
51 opacity: number;
52 vx: number;
53 vy: number;
54 gravity: number;
55 birthTime: number;
56 lifeMs: number;
57 contentIdx: number;
58 scaleStart: number;
59 scaleEnd: number;
60 rotateStart: number;
61 rotateEnd: number;
62 element: HTMLDivElement;
63 isDead: boolean;
64}
65
66function mapLinear(
67 value: number,
68 inMin: number,
69 inMax: number,
70 outMin: number,
71 outMax: number
72): number {
73 if (inMax === inMin) return outMin;
74 const t = (value - inMin) / (inMax - inMin);
75 return outMin + t * (outMax - outMin);
76}
77
78function createPRNG(seed: number): () => number {
79 let s = seed;
80 return function () {
81 s |= 0;
82 s = (s + 1831565813) | 0;
83 let t = Math.imul(s ^ (s >>> 15), 1 | s);
84 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
85 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
86 };
87}
88
89export function ExplodingInput({
90 content = [],
91 count = 1,
92 direction = { horizontal: "center", vertical: "top" },
93 gravity = 0.7,
94 duration = 3,
95 scale = { value: 1, randomize: false, randomVariation: 0 },
96 rotation = { value: 0, animate: false },
97 style,
98 className,
99}: ExplodingInputProps) {
100 const particleIdCounter = useRef(0);
101 const containerRef = useRef<HTMLDivElement>(null);
102 const particleContainerRef = useRef<HTMLDivElement>(null);
103 const particlesRef = useRef<Particle[]>([]);
104 const randRef = useRef<() => number>(() => Math.random());
105 const inputRef = useRef<HTMLInputElement | null>(null);
106 const rafIdRef = useRef<number | null>(null);
107
108 // Initialize PRNG and cleanup on unmount
109 useEffect(() => {
110 const timeBits = (Date.now() & 4294967295) >>> 0;
111 const extra = Math.floor(Math.random() * 4294967295) >>> 0;
112 const seed = (timeBits ^ extra) >>> 0;
113 randRef.current = createPRNG(seed);
114
115 return () => {
116 particlesRef.current.forEach((p) => {
117 if (p.element && p.element.parentNode) {
118 p.element.parentNode.removeChild(p.element);
119 }
120 });
121 particlesRef.current = [];
122 if (rafIdRef.current !== null) {
123 cancelAnimationFrame(rafIdRef.current);
124 }
125 };
126 }, []);
127
128 const getInputSpawnPosition = useCallback(
129 (input: HTMLInputElement): { x: number; y: number } | null => {
130 const container = containerRef.current;
131 if (!container || !input) return null;
132
133 const inputRect = input.getBoundingClientRect();
134 const containerRect = container.getBoundingClientRect();
135 const inputValue = input.value;
136
137 const getTextWidth = (text: string, inp: HTMLInputElement): number => {
138 const canvas = document.createElement("canvas");
139 const context = canvas.getContext("2d");
140 if (!context) return 0;
141 const computedStyle = window.getComputedStyle(inp);
142 context.font = `${computedStyle.fontSize} ${computedStyle.fontFamily}`;
143 return context.measureText(text).width;
144 };
145
146 const computedStyle = window.getComputedStyle(input);
147 const paddingLeft = parseInt(computedStyle.paddingLeft, 10) || 0;
148 const paddingRight = parseInt(computedStyle.paddingRight, 10) || 0;
149
150 let x = 0;
151 let y = 0;
152
153 if (inputValue.length > 0) {
154 const textWidth = getTextWidth(inputValue, input);
155 const inputStartX = inputRect.left - containerRect.left;
156 const maxX = inputStartX + inputRect.width - paddingRight;
157 x = Math.min(textWidth + inputStartX + paddingLeft, maxX);
158 } else {
159 x = inputRect.left - containerRect.left;
160 }
161 y = inputRect.top - containerRect.top + inputRect.height / 2;
162
163 return { x, y };
164 },
165 []
166 );
167
168 const createParticlesAtPosition = useCallback(
169 (x: number, y: number) => {
170 const spawnOne = () => {
171 const horizontalValue =
172 direction.horizontal === "left"
173 ? -0.4
174 : direction.horizontal === "right"
175 ? 0.4
176 : 0;
177 const baseVx = mapLinear(horizontalValue, -1, 1, -800, 800);
178 const spreadVx = 300;
179 const vx = baseVx + (randRef.current() * 2 - 1) * spreadVx;
180
181 const verticalValue =
182 direction.vertical === "top"
183 ? -0.7
184 : direction.vertical === "bottom"
185 ? 0.7
186 : 0;
187 const baseVy = mapLinear(verticalValue, -1, 1, -800, 800);
188 const spreadVy = 300;
189 const vy = baseVy + (randRef.current() * 2 - 1) * spreadVy;
190
191 particleIdCounter.current += 1;
192
193 const randBetween = (min: number, max: number) =>
194 min + randRef.current() * (max - min);
195
196 const baseScale = scale.value ?? 1;
197 let particleScale = baseScale;
198 if (
199 scale.randomize &&
200 scale.randomVariation !== undefined &&
201 scale.randomVariation > 0
202 ) {
203 const variation = (scale.randomVariation / 100) * baseScale;
204 const minScale = baseScale - variation;
205 const maxScale = baseScale + variation;
206 particleScale = randBetween(minScale, maxScale);
207 }
208 const safeScale = Math.max(0.1, Math.min(4, particleScale));
209
210 const baseRotation = rotation.value ?? 0;
211 let initRot = baseRotation;
212 let endRot = baseRotation;
213 if (rotation.animate) {
214 initRot = randBetween(-180, 180);
215 const rotationDelta = randBetween(-360, 360);
216 endRot = initRot + rotationDelta;
217 }
218
219 const el = document.createElement("div");
220 el.style.position = "absolute";
221 el.style.left = "0";
222 el.style.top = "0";
223 el.style.display = "flex";
224 el.style.alignItems = "center";
225 el.style.justifyContent = "center";
226 el.style.pointerEvents = "none";
227 el.style.willChange = "transform, opacity";
228 el.style.transformOrigin = "50% 50%";
229 el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%) scale(${safeScale}) rotate(${initRot}deg)`;
230 el.style.opacity = "1";
231
232 if (particleContainerRef.current) {
233 particleContainerRef.current.appendChild(el);
234 }
235
236 const newParticle: Particle = {
237 id: particleIdCounter.current,
238 x,
239 y,
240 scale: safeScale,
241 rotate: initRot,
242 opacity: 1,
243 vx,
244 vy,
245 gravity: mapLinear(
246 Math.max(-1, Math.min(1, gravity ?? 0.45)),
247 -1,
248 1,
249 -2000,
250 2000
251 ),
252 birthTime: performance.now(),
253 lifeMs: duration * 1000,
254 contentIdx:
255 content.length > 0
256 ? (particleIdCounter.current - 1) % content.length
257 : -1,
258 scaleStart: safeScale,
259 scaleEnd: safeScale,
260 rotateStart: initRot,
261 rotateEnd: endRot,
262 element: el,
263 isDead: false,
264 };
265
266 // Render content
267 if (content.length > 0 && newParticle.contentIdx >= 0) {
268 const contentElement = content[newParticle.contentIdx];
269 if (contentElement) {
270 import("react-dom/client").then(({ createRoot }) => {
271 const root = createRoot(el);
272 root.render(<>{contentElement}</>);
273 });
274 }
275 } else {
276 const fallback = document.createElement("div");
277 fallback.style.width = "16px";
278 fallback.style.height = "16px";
279 fallback.style.borderRadius = "6px";
280 fallback.style.backgroundColor = "#6366f1";
281 el.appendChild(fallback);
282 }
283
284 particlesRef.current.push(newParticle);
285
286 setTimeout(() => {
287 newParticle.isDead = true;
288 if (newParticle.element && newParticle.element.parentNode) {
289 newParticle.element.parentNode.removeChild(newParticle.element);
290 }
291 particlesRef.current = particlesRef.current.filter(
292 (p) => p.id !== newParticle.id
293 );
294 }, duration * 1000);
295 };
296
297 const particlesToSpawn = Math.max(1, Math.min(5, Math.round(count)));
298 for (let i = 0; i < particlesToSpawn; i++) spawnOne();
299 },
300 [content, count, direction, duration, gravity, rotation, scale]
301 );
302
303 // Find input element and listen to changes
304 useEffect(() => {
305 const container = containerRef.current;
306 if (!container) return;
307
308 const label = container.closest("label");
309 const input = label?.querySelector("input") ?? null;
310 if (!input) return;
311
312 inputRef.current = input;
313
314 const handleInput = () => {
315 const pos = getInputSpawnPosition(input);
316 if (pos) {
317 createParticlesAtPosition(pos.x, pos.y);
318 }
319 };
320
321 input.addEventListener("input", handleInput);
322 return () => {
323 input.removeEventListener("input", handleInput);
324 inputRef.current = null;
325 };
326 }, [createParticlesAtPosition, getInputSpawnPosition]);
327
328 // Physics animation loop
329 useEffect(() => {
330 let lastTime = performance.now();
331
332 const updateParticles = (currentTime: number) => {
333 const delta = currentTime - lastTime;
334 lastTime = currentTime;
335 const dtMs = Math.min(32, delta);
336 const dt = dtMs / 1000;
337 const now = performance.now();
338
339 particlesRef.current.forEach((p) => {
340 if (p.isDead) return;
341 const age = now - p.birthTime;
342 if (!p.element || age >= p.lifeMs) return;
343
344 const progress = age / p.lifeMs;
345
346 p.vy = p.vy + p.gravity * dt;
347 p.x = p.x + p.vx * dt;
348 p.y = p.y + p.vy * dt;
349
350 p.scale = mapLinear(progress, 0, 1, p.scaleStart, p.scaleEnd);
351 p.rotate = mapLinear(progress, 0, 1, p.rotateStart, p.rotateEnd);
352
353 const fadeStart = 0.7;
354 p.opacity = progress > fadeStart ? mapLinear(progress, fadeStart, 1, 1, 0) : 1;
355
356 if (isNaN(p.x) || isNaN(p.y) || isNaN(p.scale)) return;
357
358 const clampedScale = Math.max(0.1, Math.min(3, p.scale));
359 p.element.style.transform = `translate(${p.x}px, ${p.y}px) translate(-50%, -50%) scale(${clampedScale}) rotate(${p.rotate}deg)`;
360 p.element.style.opacity = String(p.opacity);
361 });
362
363 rafIdRef.current = requestAnimationFrame(updateParticles);
364 };
365
366 rafIdRef.current = requestAnimationFrame(updateParticles);
367
368 return () => {
369 if (rafIdRef.current !== null) {
370 cancelAnimationFrame(rafIdRef.current);
371 }
372 };
373 }, []);
374
375 return (
376 <div
377 ref={containerRef}
378 className={className}
379 style={{
380 ...style,
381 position: "relative",
382 width: "0px",
383 height: "0px",
384 overflow: "visible",
385 backgroundColor: "transparent",
386 transform: "translateZ(0)",
387 }}
388 >
389 <div
390 ref={particleContainerRef}
391 style={{
392 position: "absolute",
393 left: 0,
394 top: 0,
395 width: "100%",
396 height: "100%",
397 pointerEvents: "none",
398 }}
399 />
400 </div>
401 );
402}
403
404export default ExplodingInput;