1"use client"
2
3import { useEffect, useRef, useState } from "react"
4import {
5 AnimatePresence,
6 HTMLMotionProps,
7 motion,
8 useMotionValue,
9} from "motion/react"
10
11import { cn } from "@/lib/utils"
12
13/**
14 * A custom pointer component that displays an animated cursor.
15 * Add this as a child to any component to enable a custom pointer when hovering.
16 * You can pass custom children to render as the pointer.
17 *
18 * @component
19 * @param {HTMLMotionProps<"div">} props - The component props
20 */
21export function Pointer({
22 className,
23 style,
24 children,
25 ...props
26}: HTMLMotionProps<"div">): React.ReactNode {
27 const x = useMotionValue(0)
28 const y = useMotionValue(0)
29 const [isActive, setIsActive] = useState<boolean>(false)
30 const containerRef = useRef<HTMLDivElement>(null)
31
32 useEffect(() => {
33 const parentElement =
34 typeof window !== "undefined"
35 ? (containerRef.current?.parentElement ?? null)
36 : null
37
38 const handleMouseMove = (e: MouseEvent) => {
39 x.set(e.clientX)
40 y.set(e.clientY)
41 setIsActive(true)
42 }
43
44 const handleMouseEnter = (e: MouseEvent) => {
45 x.set(e.clientX)
46 y.set(e.clientY)
47 setIsActive(true)
48 }
49
50 const handleMouseLeave = () => {
51 setIsActive(false)
52 }
53
54 if (parentElement) {
55 parentElement.style.cursor = "none"
56 parentElement.addEventListener("mousemove", handleMouseMove)
57 parentElement.addEventListener("mouseenter", handleMouseEnter)
58 parentElement.addEventListener("mouseleave", handleMouseLeave)
59 }
60
61 return () => {
62 if (parentElement) {
63 parentElement.style.cursor = ""
64 parentElement.removeEventListener("mousemove", handleMouseMove)
65 parentElement.removeEventListener("mouseenter", handleMouseEnter)
66 parentElement.removeEventListener("mouseleave", handleMouseLeave)
67 }
68 }
69 }, [x, y])
70
71 return (
72 <>
73 <div ref={containerRef} />
74 <AnimatePresence>
75 {isActive && (
76 <motion.div
77 className="pointer-events-none fixed z-50 transform-[translate(-50%,-50%)]"
78 style={{
79 top: y,
80 left: x,
81 ...style,
82 }}
83 initial={{
84 scale: 0,
85 opacity: 0,
86 }}
87 animate={{
88 scale: 1,
89 opacity: 1,
90 }}
91 exit={{
92 scale: 0,
93 opacity: 0,
94 }}
95 {...props}
96 >
97 {children || (
98 <svg
99 stroke="currentColor"
100 fill="currentColor"
101 strokeWidth="1"
102 viewBox="0 0 16 16"
103 height="24"
104 width="24"
105 xmlns="http://www.w3.org/2000/svg"
106 className={cn(
107 "rotate-[-70deg] stroke-white text-black",
108 className
109 )}
110 >
111 <path d="M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z" />
112 </svg>
113 )}
114 </motion.div>
115 )}
116 </AnimatePresence>
117 </>
118 )
119}
120