"use client"; import React, { useState, useRef, useEffect } from "react"; export const Tooltip = ({ content, children, position = "top", showIcon = true, iconClassName = "", }) => { const [isVisible, setIsVisible] = useState(false); const [tooltipStyle, setTooltipStyle] = useState({}); const tooltipRef = useRef(null); const iconRef = useRef(null); const showTooltip = () => setIsVisible(true); const hideTooltip = () => setIsVisible(false); // Position the tooltip when it becomes visible useEffect(() => { if (isVisible && iconRef.current && tooltipRef.current) { const triggerRect = iconRef.current.getBoundingClientRect(); const tooltipRect = tooltipRef.current.getBoundingClientRect(); const spacing = 8; // Space between trigger and tooltip let style = {}; switch (position) { case "top": style = { left: triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2, top: triggerRect.top - tooltipRect.height - spacing, }; break; case "bottom": style = { left: triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2, top: triggerRect.bottom + spacing, }; break; case "left": style = { left: triggerRect.left - tooltipRect.width - spacing, top: triggerRect.top + triggerRect.height / 2 - tooltipRect.height / 2, }; break; case "right": style = { left: triggerRect.right + spacing, top: triggerRect.top + triggerRect.height / 2 - tooltipRect.height / 2, }; break; } // Adjust if tooltip would go off-screen const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; if (style.left < 10) style.left = 10; if (style.left + tooltipRect.width > viewportWidth - 10) { style.left = viewportWidth - tooltipRect.width - 10; } if (style.top < 10) style.top = 10; if (style.top + tooltipRect.height > viewportHeight - 10) { style.top = viewportHeight - tooltipRect.height - 10; } // Convert to fixed position style.position = "fixed"; style.left = `${style.left}px`; style.top = `${style.top}px`; setTooltipStyle(style); } }, [isVisible, position]); return (
{children} {showIcon && (
)} {isVisible && (
{content}
)}
); };