|
| 1 | +'use client'; |
| 2 | +import { createContext, useContext, useEffect, useRef, useState } from 'react'; |
| 3 | +import type { ReactNode } from 'react'; |
| 4 | + |
| 5 | +interface MouseGlowContext { |
| 6 | + position: { x: number; y: number }; |
| 7 | + radius: number; |
| 8 | +} |
| 9 | +export const GlowContext = createContext<MouseGlowContext>({ |
| 10 | + position: { x: -9999, y: -9999 }, |
| 11 | + radius: 100, |
| 12 | +}); |
| 13 | +export const useGlowStack = (): MouseGlowContext => { |
| 14 | + const context = useContext(GlowContext); |
| 15 | + |
| 16 | + return context ?? { position: { x: -9999, y: -9999 }, radius: 100 }; |
| 17 | +}; |
| 18 | + |
| 19 | +interface GlowStackProps { |
| 20 | + children: ReactNode; |
| 21 | + radius?: number; |
| 22 | + className?: string; |
| 23 | +} |
| 24 | + |
| 25 | +export function GlowStack({ |
| 26 | + children, |
| 27 | + radius = 100, |
| 28 | + className, |
| 29 | +}: GlowStackProps) { |
| 30 | + const [pos, setPos] = useState({ x: -9999, y: -9999 }); |
| 31 | + const rafRef = useRef<number>(0); |
| 32 | + |
| 33 | + useEffect(() => { |
| 34 | + const onMove = (e: MouseEvent) => { |
| 35 | + cancelAnimationFrame(rafRef.current); |
| 36 | + rafRef.current = requestAnimationFrame(() => |
| 37 | + setPos({ x: e.clientX, y: e.clientY }), |
| 38 | + ); |
| 39 | + }; |
| 40 | + |
| 41 | + window.addEventListener('mousemove', onMove, { passive: true }); |
| 42 | + |
| 43 | + return () => { |
| 44 | + window.removeEventListener('mousemove', onMove); |
| 45 | + cancelAnimationFrame(rafRef.current); |
| 46 | + }; |
| 47 | + }, []); |
| 48 | + |
| 49 | + return ( |
| 50 | + <GlowContext.Provider value={{ position: pos, radius }}> |
| 51 | + <div className={className}>{children}</div> |
| 52 | + </GlowContext.Provider> |
| 53 | + ); |
| 54 | +} |
0 commit comments