import { forwardRef, useRef, useId, type ComponentType } from "react"; import { useCursor } from "./cursor-context"; import type { EnhancedComponentProps } from "./types"; /** * Helper function to determine the visible portion of an element within scrollable containers * @param element The DOM element we want to check visibility for * @param elementRect The original bounding client rect of the element * @returns A DOMRect representing only the visible portion of the element */ const getVisibleRect = (element: HTMLElement, elementRect: DOMRect): DOMRect => { // Find all scrollable parent containers let parent = element.parentElement; let visibleRect = { ...elementRect, left: elementRect.left, right: elementRect.right, top: elementRect.top, bottom: elementRect.bottom, width: elementRect.width, height: elementRect.height, x: elementRect.x, y: elementRect.y, }; // Traverse up through parent elements to find scrollable containers while (parent) { if (typeof window === "undefined") break; const style = window.getComputedStyle(parent); const hasOverflow = [style.overflowY, style.overflowX].some((overflow) => ["auto", "scroll", "hidden"].includes(overflow), ); if (hasOverflow) { const parentRect = parent.getBoundingClientRect(); // Calculate the intersection between the element and its scrollable parent const newLeft = Math.max(visibleRect.left, parentRect.left); const newTop = Math.max(visibleRect.top, parentRect.top); const newRight = Math.min(visibleRect.right, parentRect.right); const newBottom = Math.min(visibleRect.bottom, parentRect.bottom); // Update the visible rect dimensions visibleRect = { ...visibleRect, left: newLeft, top: newTop, right: newRight, bottom: newBottom, width: Math.max(0, newRight - newLeft), height: Math.max(0, newBottom - newTop), x: newLeft, y: newTop, }; // If element is completely outside the viewport of the parent, return empty rect if (visibleRect.width <= 0 || visibleRect.height <= 0) { return new DOMRect(0, 0, 0, 0); } } parent = parent.parentElement; } return DOMRect.fromRect(visibleRect); }; export function withCursor
(Component: ComponentType
) {
// Create a display name for the enhanced component
const displayName = Component.displayName || Component.name || "Component";
const EnhancedComponent = forwardRef