UNPKG

phx-react

Version:

PHX REACT

43 lines 1.97 kB
import React, { useEffect, useRef, useState } from 'react'; import PHXTooltip from '../../ToolTip/ToolTip'; import { classNames } from '../../types'; /** * Renders plain truncated text, and wraps it with PHXTooltip only when the text overflows. * * @param children - Text content to render and measure. * @param className - Optional class names for the measured text element. * @param content - Optional custom tooltip content. * @returns Text content with tooltip behavior only when truncated. */ function TruncatedTooltip({ children, className, content }) { const contentRef = useRef(null); const [isTruncated, setIsTruncated] = useState(false); const tooltipContent = content !== null && content !== void 0 ? content : (typeof children === 'string' || typeof children === 'number' ? String(children) : null); /** * Updates whether the rendered text is visually truncated. * * @returns void. */ const updateTruncatedState = () => { const element = contentRef.current; if (!element) return; setIsTruncated(element.scrollWidth > element.clientWidth); }; useEffect(() => { updateTruncatedState(); const element = contentRef.current; if (!element || typeof ResizeObserver === 'undefined') return; const resizeObserver = new ResizeObserver(updateTruncatedState); resizeObserver.observe(element); return () => resizeObserver.disconnect(); }, [children]); const textElement = (React.createElement("span", { ref: contentRef, className: classNames('block min-w-0 overflow-hidden text-ellipsis', className) }, children)); if (!tooltipContent || !isTruncated) { return textElement; } return (React.createElement(PHXTooltip, { className: 'block w-full min-w-0 text-gray-900', content: tooltipContent }, textElement)); } export default TruncatedTooltip; //# sourceMappingURL=TruncatedTooltip.js.map