import { arrow as arrowMiddleware, autoUpdate, flip, offset, useFloating, } from '@floating-ui/react'; import { clsx } from 'clsx'; import { AriaAttributes, CSSProperties, PropsWithChildren, ReactElement, ReactNode, cloneElement, useId, useRef, useState, } from 'react'; import { CommonProps, Position } from '../common'; import useDirection from '../common/hooks/useDirection'; import { PositionBottom, PositionLeft, PositionRight, PositionTop, } from '../common/PropsValues/position'; export type TooltipProps = PropsWithChildren<{ position?: PositionTop | PositionRight | PositionBottom | PositionLeft; label: ReactNode; id?: string; }> & CommonProps; const Tooltip = ({ position = Position.TOP, children = undefined, label, id, className, }: TooltipProps) => { const [open, setOpen] = useState(false); const arrowRef = useRef(null); const { isRTL } = useDirection(); const resolvedPosition = isRTL ? position === 'left' ? 'right' : position === 'right' ? 'left' : position : position; const fallbackId = useId(); const tooltipId = id ?? fallbackId; const { refs, floatingStyles, placement, middlewareData } = useFloating({ placement: resolvedPosition, middleware: [ offset(16), flip({ fallbackPlacements: [Position.TOP] }), // eslint-disable-next-line react-hooks/refs -- arrowRef is passed to floating-ui middleware, legitimate API usage arrowMiddleware({ element: arrowRef, padding: 8 }), ], whileElementsMounted: open ? autoUpdate : undefined, open, }); const arrowStyle: CSSProperties = { ...(middlewareData.arrow?.x != null ? { left: middlewareData.arrow.x } : {}), ...(middlewareData.arrow?.y != null ? { top: middlewareData.arrow.y } : {}), }; return ( /* eslint-disable react-hooks/refs -- setReference and setFloating are callback refs from floating-ui, safe to pass during render */ setOpen(true)} onFocus={() => setOpen(true)} onMouseOut={() => setOpen(false)} onBlur={() => setOpen(false)} > {children ? cloneElement(children as ReactElement>, { 'aria-describedby': `${tooltipId}-tooltip`, }) : null}