1"use client"
2
3import { FC, useEffect, useRef, useState } from "react"
4import { motion, useSpring } from "motion/react"
5
6interface Position {
7 x: number
8 y: number
9}
10
11export interface SmoothCursorProps {
12 cursor?: React.ReactNode
13 springConfig?: {
14 damping: number
15 stiffness: number
16 mass: number
17 restDelta: number
18 }
19}
20
21const DESKTOP_POINTER_QUERY = "(any-hover: hover) and (any-pointer: fine)"
22
23function isTrackablePointer(pointerType: string) {
24 return pointerType !== "touch"
25}
26
27const DefaultCursorSVG: FC = () => {
28 return (
29 <svg
30 xmlns="http://www.w3.org/2000/svg"
31 width={50}
32 height={54}
33 viewBox="0 0 50 54"
34 fill="none"
35 style={{ scale: 0.5 }}
36 >
37 <g filter="url(#filter0_d_91_7928)">
38 <path
39 d="M42.6817 41.1495L27.5103 6.79925C26.7269 5.02557 24.2082 5.02558 23.3927 6.79925L7.59814 41.1495C6.75833 42.9759 8.52712 44.8902 10.4125 44.1954L24.3757 39.0496C24.8829 38.8627 25.4385 38.8627 25.9422 39.0496L39.8121 44.1954C41.6849 44.8902 43.4884 42.9759 42.6817 41.1495Z"
40 fill="black"
41 />
42 <path
43 d="M43.7146 40.6933L28.5431 6.34306C27.3556 3.65428 23.5772 3.69516 22.3668 6.32755L6.57226 40.6778C5.3134 43.4156 7.97238 46.298 10.803 45.2549L24.7662 40.109C25.0221 40.0147 25.2999 40.0156 25.5494 40.1082L39.4193 45.254C42.2261 46.2953 44.9254 43.4347 43.7146 40.6933Z"
44 stroke="white"
45 strokeWidth={2.25825}
46 />
47 </g>
48 <defs>
49 <filter
50 id="filter0_d_91_7928"
51 x={0.602397}
52 y={0.952444}
53 width={49.0584}
54 height={52.428}
55 filterUnits="userSpaceOnUse"
56 colorInterpolationFilters="sRGB"
57 >
58 <feFlood floodOpacity={0} result="BackgroundImageFix" />
59 <feColorMatrix
60 in="SourceAlpha"
61 type="matrix"
62 values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
63 result="hardAlpha"
64 />
65 <feOffset dy={2.25825} />
66 <feGaussianBlur stdDeviation={2.25825} />
67 <feComposite in2="hardAlpha" operator="out" />
68 <feColorMatrix
69 type="matrix"
70 values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.08 0"
71 />
72 <feBlend
73 mode="normal"
74 in2="BackgroundImageFix"
75 result="effect1_dropShadow_91_7928"
76 />
77 <feBlend
78 mode="normal"
79 in="SourceGraphic"
80 in2="effect1_dropShadow_91_7928"
81 result="shape"
82 />
83 </filter>
84 </defs>
85 </svg>
86 )
87}
88
89export function SmoothCursor({
90 cursor = <DefaultCursorSVG />,
91 springConfig = {
92 damping: 45,
93 stiffness: 400,
94 mass: 1,
95 restDelta: 0.001,
96 },
97}: SmoothCursorProps) {
98 const lastMousePos = useRef<Position>({ x: 0, y: 0 })
99 const velocity = useRef<Position>({ x: 0, y: 0 })
100 const lastUpdateTime = useRef(Date.now())
101 const previousAngle = useRef(0)
102 const accumulatedRotation = useRef(0)
103 const [isEnabled, setIsEnabled] = useState(false)
104 const [isVisible, setIsVisible] = useState(false)
105
106 const cursorX = useSpring(0, springConfig)
107 const cursorY = useSpring(0, springConfig)
108 const rotation = useSpring(0, {
109 ...springConfig,
110 damping: 60,
111 stiffness: 300,
112 })
113 const scale = useSpring(1, {
114 ...springConfig,
115 stiffness: 500,
116 damping: 35,
117 })
118
119 useEffect(() => {
120 const mediaQuery = window.matchMedia(DESKTOP_POINTER_QUERY)
121
122 const updateEnabled = () => {
123 const nextIsEnabled = mediaQuery.matches
124 setIsEnabled(nextIsEnabled)
125
126 if (!nextIsEnabled) {
127 setIsVisible(false)
128 }
129 }
130
131 updateEnabled()
132 mediaQuery.addEventListener("change", updateEnabled)
133
134 return () => {
135 mediaQuery.removeEventListener("change", updateEnabled)
136 }
137 }, [])
138
139 useEffect(() => {
140 if (!isEnabled) {
141 return
142 }
143
144 let timeout: ReturnType<typeof setTimeout> | null = null
145
146 const updateVelocity = (currentPos: Position) => {
147 const currentTime = Date.now()
148 const deltaTime = currentTime - lastUpdateTime.current
149
150 if (deltaTime > 0) {
151 velocity.current = {
152 x: (currentPos.x - lastMousePos.current.x) / deltaTime,
153 y: (currentPos.y - lastMousePos.current.y) / deltaTime,
154 }
155 }
156
157 lastUpdateTime.current = currentTime
158 lastMousePos.current = currentPos
159 }
160
161 const smoothPointerMove = (e: PointerEvent) => {
162 if (!isTrackablePointer(e.pointerType)) {
163 return
164 }
165
166 setIsVisible(true)
167
168 const currentPos = { x: e.clientX, y: e.clientY }
169 updateVelocity(currentPos)
170
171 const speed = Math.sqrt(
172 Math.pow(velocity.current.x, 2) + Math.pow(velocity.current.y, 2)
173 )
174
175 cursorX.set(currentPos.x)
176 cursorY.set(currentPos.y)
177
178 if (speed > 0.1) {
179 const currentAngle =
180 Math.atan2(velocity.current.y, velocity.current.x) * (180 / Math.PI) +
181 90
182
183 let angleDiff = currentAngle - previousAngle.current
184 if (angleDiff > 180) angleDiff -= 360
185 if (angleDiff < -180) angleDiff += 360
186 accumulatedRotation.current += angleDiff
187 rotation.set(accumulatedRotation.current)
188 previousAngle.current = currentAngle
189
190 scale.set(0.95)
191
192 if (timeout !== null) {
193 clearTimeout(timeout)
194 }
195
196 timeout = setTimeout(() => {
197 scale.set(1)
198 }, 150)
199 }
200 }
201
202 let rafId = 0
203 const throttledPointerMove = (e: PointerEvent) => {
204 if (!isTrackablePointer(e.pointerType)) {
205 return
206 }
207
208 if (rafId) return
209
210 rafId = requestAnimationFrame(() => {
211 smoothPointerMove(e)
212 rafId = 0
213 })
214 }
215
216 document.body.style.cursor = "none"
217 window.addEventListener("pointermove", throttledPointerMove, {
218 passive: true,
219 })
220
221 return () => {
222 window.removeEventListener("pointermove", throttledPointerMove)
223 document.body.style.cursor = "auto"
224 if (rafId) cancelAnimationFrame(rafId)
225 if (timeout !== null) {
226 clearTimeout(timeout)
227 }
228 }
229 }, [cursorX, cursorY, rotation, scale, isEnabled])
230
231 if (!isEnabled) {
232 return null
233 }
234
235 return (
236 <motion.div
237 style={{
238 position: "fixed",
239 left: cursorX,
240 top: cursorY,
241 translateX: "-50%",
242 translateY: "-50%",
243 rotate: rotation,
244 scale: scale,
245 zIndex: 100,
246 pointerEvents: "none",
247 willChange: "transform",
248 opacity: isVisible ? 1 : 0,
249 }}
250 initial={false}
251 animate={{ opacity: isVisible ? 1 : 0 }}
252 transition={{
253 duration: 0.15,
254 }}
255 >
256 {cursor}
257 </motion.div>
258 )
259}
260