'use client'; import { useRef, useState, ReactNode } from 'react'; type TooltipProps = { children: ReactNode; content: ReactNode; delay?: number; mobileDelay?: number; offsetX?: number; offsetY?: number; edgeBuffer?: number; className?: string; }; export default function Tooltip({ children, content, delay = 250, mobileDelay = 250, offsetX = 20, offsetY = 20, edgeBuffer = 10, className, }: TooltipProps) { const ttRef = useRef(null); const [show, setShow] = useState(false); const [pos, setPos] = useState({ x: 0, y: 0 }); const delayTimeout = useRef(null); const longPressTimeout = useRef(null); const handleMouseEnter = () => { delayTimeout.current = setTimeout(() => setShow(true), delay); }; const handleMouseLeave = () => { if (delayTimeout.current) clearTimeout(delayTimeout.current); setShow(false); }; const handleMouseMove = (e: React.MouseEvent) => { const { clientX: x, clientY: y } = e; const ttWidth = ttRef.current?.offsetWidth || 0; const ttHeight = ttRef.current?.offsetHeight || 0; const viewportWidth = window.innerWidth - edgeBuffer; const viewportHeight = window.innerHeight - edgeBuffer; const ttRight = ttWidth + offsetX + x; const ttBottom = ttHeight + offsetY + y; const adjustX = ttRight > viewportWidth ? ttRight - viewportWidth : 0; const adjustY = ttBottom > viewportHeight ? ttBottom - viewportHeight : 0; setPos({ x: x - adjustX, y: y - adjustY }); }; const handleTouchStart = () => { longPressTimeout.current = setTimeout(() => setShow(true), mobileDelay); }; const handleTouchEnd = () => { if (longPressTimeout.current) clearTimeout(longPressTimeout.current); setShow(false); }; return ( <>
{children}
{content}
); }