"use client"; import { useLayoutEffect, useRef, useState, type RefObject, } from "react"; import { createPortal } from "react-dom"; import { shortcutKeys, type Shortcut } from "@/lib/shortcuts"; import { placeTooltip, type TooltipPosition, type TooltipSide, } from "./tooltip-position"; export default function TooltipLayer({ anchorRef, id, label, description, shortcut, side, onMount, }: { anchorRef: RefObject; id: string; label: string; description?: string; shortcut?: Shortcut; side: TooltipSide; onMount: () => void; }) { const tooltipRef = useRef(null); const [position, setPosition] = useState(null); useLayoutEffect(() => { onMount(); const update = () => { if (!anchorRef.current || !tooltipRef.current) return; setPosition( placeTooltip( anchorRef.current.getBoundingClientRect(), tooltipRef.current.getBoundingClientRect(), side, window.innerWidth, window.innerHeight, ), ); }; update(); window.addEventListener("resize", update); window.addEventListener("scroll", update, true); return () => { window.removeEventListener("resize", update); window.removeEventListener("scroll", update, true); }; }, [anchorRef, onMount, side]); return createPortal( {shortcut ? ( {label} {shortcutKeys(shortcut).map((key) => ( {key} ))} ) : ( {label} )} {description ? ( {description} ) : null} , document.body, ); }