import { useCallback, useEffect, useMemo, useState, useRef } from "react"; import { createPortal } from "react-dom"; import { CursorContext } from "./cursor-context"; import type { CursorProviderProps } from "./types"; import { cn } from "../hooks/cn"; // Spring physics configuration const SPRING_CONFIG = { stiffness: 0.15, // How snappy (higher = faster) damping: 0.75, // How bouncy (lower = more bounce, 1 = no bounce) mass: 1, }; // Squish configuration const SQUISH_CONFIG = { maxSquish: 0.15, // Maximum squish amount (0.15 = 15% squish) velocityScale: 0.008, // How much velocity affects squish recovery: 0.15, // How fast squish recovers }; interface SpringState { x: number; y: number; width: number; height: number; velocityX: number; velocityY: number; velocityW: number; velocityH: number; scaleX: number; scaleY: number; } export const CursorProvider = ({ children, maxOffsetX = 5, maxOffsetY = 20, cursorSize = 20, boundaryThreshold = 4, outerThreshold = 8, cursorClassName, className, as: Component = "div", ...props }: CursorProviderProps) => { const [isClient, setIsClient] = useState(false); const [isMouseInside, setIsMouseInside] = useState(false); // Refs for high-frequency updates const cursorRef = useRef(null); const cursorInnerRef = useRef(null); const mousePositionRef = useRef({ x: 0, y: 0 }); const prevMousePositionRef = useRef({ x: 0, y: 0 }); const hoveredElementIdRef = useRef(null); const hoveredElementRef = useRef(null); const elementDimensionsRef = useRef({ width: 0, height: 0, x: 0, y: 0, right: 0, bottom: 0 }); const elementBorderRadiusRef = useRef("9999px"); const animationFrameRef = useRef(null); // Spring animation state const springRef = useRef({ x: 0, y: 0, width: cursorSize, height: cursorSize, velocityX: 0, velocityY: 0, velocityW: 0, velocityH: 0, scaleX: 1, scaleY: 1, }); // Target state (where we want the cursor to be) const targetRef = useRef({ x: 0, y: 0, width: cursorSize, height: cursorSize, }); const [hoveredElementId, setHoveredElementId] = useState(null); useEffect(() => { setIsClient(true); }, []); // Calculate target position and size based on current state const updateTarget = useCallback(() => { const mouse = mousePositionRef.current; const dims = elementDimensionsRef.current; const isHovering = hoveredElementIdRef.current !== null; if (isHovering && dims.width > 0) { // Calculate distance from each edge (negative = outside) const distFromLeft = mouse.x - dims.x; const distFromRight = dims.x + dims.width - mouse.x; const distFromTop = mouse.y - dims.y; const distFromBottom = dims.y + dims.height - mouse.y; // Total threshold zone = inner boundary + outer threshold const totalThreshold = boundaryThreshold + outerThreshold; let offsetX = 0; let offsetY = 0; // Left side: inside near edge or outside within threshold if (distFromLeft < boundaryThreshold) { // Map from boundaryThreshold (inside) to -outerThreshold (outside) -> 0 to maxOffset const progress = Math.min(1, (boundaryThreshold - distFromLeft) / totalThreshold); offsetX = -maxOffsetX * progress; } // Right side else if (distFromRight < boundaryThreshold) { const progress = Math.min(1, (boundaryThreshold - distFromRight) / totalThreshold); offsetX = maxOffsetX * progress; } // Top side if (distFromTop < boundaryThreshold) { const progress = Math.min(1, (boundaryThreshold - distFromTop) / totalThreshold); offsetY = -maxOffsetY * progress; } // Bottom side else if (distFromBottom < boundaryThreshold) { const progress = Math.min(1, (boundaryThreshold - distFromBottom) / totalThreshold); offsetY = maxOffsetY * progress; } targetRef.current = { x: dims.x + offsetX, y: dims.y + offsetY, width: dims.width, height: dims.height, }; } else { // Follow mouse as a dot targetRef.current = { x: mouse.x - cursorSize / 2, y: mouse.y - cursorSize / 2, width: cursorSize, height: cursorSize, }; } }, [cursorSize, maxOffsetX, maxOffsetY, boundaryThreshold, outerThreshold]); // Animation loop with spring physics const animate = useCallback(() => { const cursor = cursorRef.current; const cursorInner = cursorInnerRef.current; if (!cursor || !cursorInner) { animationFrameRef.current = requestAnimationFrame(animate); return; } const spring = springRef.current; const target = targetRef.current; const { stiffness, damping } = SPRING_CONFIG; // Calculate mouse velocity for squish effect const mouse = mousePositionRef.current; const prevMouse = prevMousePositionRef.current; const mouseVelocityX = mouse.x - prevMouse.x; const mouseVelocityY = mouse.y - prevMouse.y; prevMousePositionRef.current = { ...mouse }; // Spring physics for position const forceX = (target.x - spring.x) * stiffness; const forceY = (target.y - spring.y) * stiffness; spring.velocityX = (spring.velocityX + forceX) * damping; spring.velocityY = (spring.velocityY + forceY) * damping; spring.x += spring.velocityX; spring.y += spring.velocityY; // Spring physics for size const forceW = (target.width - spring.width) * stiffness; const forceH = (target.height - spring.height) * stiffness; spring.velocityW = (spring.velocityW + forceW) * damping; spring.velocityH = (spring.velocityH + forceH) * damping; spring.width += spring.velocityW; spring.height += spring.velocityH; // Squish effect based on velocity // Moving horizontally -> squish vertically (and vice versa) const targetScaleX = 1 - Math.abs(mouseVelocityY) * SQUISH_CONFIG.velocityScale; const targetScaleY = 1 - Math.abs(mouseVelocityX) * SQUISH_CONFIG.velocityScale; // Clamp squish and smoothly interpolate const clampedTargetScaleX = Math.max(1 - SQUISH_CONFIG.maxSquish, Math.min(1, targetScaleX)); const clampedTargetScaleY = Math.max(1 - SQUISH_CONFIG.maxSquish, Math.min(1, targetScaleY)); spring.scaleX += (clampedTargetScaleX - spring.scaleX) * SQUISH_CONFIG.recovery; spring.scaleY += (clampedTargetScaleY - spring.scaleY) * SQUISH_CONFIG.recovery; // Also add squish from spring velocity (bouncing) const bounceSquishX = 1 - Math.abs(spring.velocityY) * 0.02; const bounceSquishY = 1 - Math.abs(spring.velocityX) * 0.02; const finalScaleX = Math.max(0.85, spring.scaleX * bounceSquishX); const finalScaleY = Math.max(0.85, spring.scaleY * bounceSquishY); // Apply to DOM cursor.style.transform = `translate3d(${spring.x}px, ${spring.y}px, 0)`; cursor.style.width = `${spring.width}px`; cursor.style.height = `${spring.height}px`; // Apply squish to inner element cursorInner.style.transform = `scale(${finalScaleX}, ${finalScaleY})`; // Update border radius based on hover state - use target element's radius const isHovering = hoveredElementIdRef.current !== null; if (isHovering) { cursorInner.style.borderRadius = elementBorderRadiusRef.current; } else { cursorInner.style.borderRadius = "9999px"; } animationFrameRef.current = requestAnimationFrame(animate); }, []); // Start animation loop useEffect(() => { if (!isClient) return; animationFrameRef.current = requestAnimationFrame(animate); return () => { if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current); } }; }, [isClient, animate]); // Handle mouse movement useEffect(() => { if (!isClient) return; const handleMouseMove = (e: MouseEvent) => { mousePositionRef.current = { x: e.clientX, y: e.clientY }; updateTarget(); }; document.addEventListener("mousemove", handleMouseMove, { passive: true }); return () => document.removeEventListener("mousemove", handleMouseMove); }, [isClient, updateTarget]); const handleMouseEnter = useCallback(() => { setIsMouseInside(true); // Initialize spring position to current mouse position const mouse = mousePositionRef.current; springRef.current.x = mouse.x - cursorSize / 2; springRef.current.y = mouse.y - cursorSize / 2; updateTarget(); }, [cursorSize, updateTarget]); const handleMouseLeave = useCallback(() => { setIsMouseInside(false); hoveredElementIdRef.current = null; hoveredElementRef.current = null; setHoveredElementId(null); updateTarget(); }, [updateTarget]); const checkMouseInElement = useCallback(() => { if (!hoveredElementRef.current || !hoveredElementIdRef.current) return; const rect = hoveredElementRef.current.getBoundingClientRect(); const mouse = mousePositionRef.current; elementDimensionsRef.current = { width: rect.width, height: rect.height, x: rect.left, y: rect.top, right: rect.right, bottom: rect.bottom, }; const isInside = mouse.x >= rect.left && mouse.x <= rect.right && mouse.y >= rect.top && mouse.y <= rect.bottom; if (!isInside) { hoveredElementIdRef.current = null; hoveredElementRef.current = null; setHoveredElementId(null); } updateTarget(); }, [updateTarget]); useEffect(() => { if (!isClient) return; const handleScroll = () => checkMouseInElement(); document.addEventListener("scroll", handleScroll, { passive: true, capture: true }); return () => document.removeEventListener("scroll", handleScroll, { capture: true }); }, [checkMouseInElement, isClient]); const registerHoveredElement = useCallback( (id: string, dimensions: DOMRect, element?: HTMLElement) => { hoveredElementIdRef.current = id; elementDimensionsRef.current = { width: dimensions.width, height: dimensions.height, x: dimensions.left, y: dimensions.top, right: dimensions.right, bottom: dimensions.bottom, }; if (element) { hoveredElementRef.current = element; // Get computed border-radius from the target element const computedStyle = window.getComputedStyle(element); elementBorderRadiusRef.current = computedStyle.borderRadius || "8px"; } setHoveredElementId(id); updateTarget(); }, [updateTarget], ); const unregisterHoveredElement = useCallback(() => { hoveredElementIdRef.current = null; hoveredElementRef.current = null; elementBorderRadiusRef.current = "9999px"; setHoveredElementId(null); updateTarget(); }, [updateTarget]); const updateElementDimensions = useCallback( (dimensions: DOMRect) => { if (hoveredElementIdRef.current) { elementDimensionsRef.current = { width: dimensions.width, height: dimensions.height, x: dimensions.left, y: dimensions.top, right: dimensions.right, bottom: dimensions.bottom, }; updateTarget(); } }, [updateTarget], ); const contextValue = useMemo( () => ({ mousePosition: mousePositionRef.current, hoveredElementId, elementDimensions: elementDimensionsRef.current, registerHoveredElement, unregisterHoveredElement, updateElementDimensions, }), [hoveredElementId, registerHoveredElement, unregisterHoveredElement, updateElementDimensions], ); // Cursor with halo/glow effect from original design const cursorElement = isClient && (
); return ( <> {isClient && typeof document !== "undefined" && document.body && createPortal(cursorElement, document.body)} {children} ); };