UNPKG

@wordpress/widget-dashboard

Version:

Stateless rendering engine for widget dashboards: the WidgetDashboard compound component and its grid-settings kit.

54 lines (53 loc) • 1.83 kB
import { useResizeObserver } from "@wordpress/compose"; import { useCallback, useEffect, useRef, useState } from "@wordpress/element"; // packages/widget-dashboard/src/components/widget-header/use-is-truncated.ts const FIT_TOLERANCE = .05; function measure(element, slack) { const range = document.createRange(); range.selectNodeContents(element); return (typeof range.getBoundingClientRect === "function" ? range.getBoundingClientRect().width - element.getBoundingClientRect().width : element.scrollWidth - element.clientWidth) > slack + FIT_TOLERANCE; } /** * Whether a single-line element clips its text: the ref to observe, then the * answer. * * @param reclaim Width a control shown only while clipped gives back, so it * cannot keep the text clipped. */ function useIsTruncated(reclaim = 0) { const [element, setElement] = useState(null); const [isTruncated, setIsTruncated] = useState(false); const isTruncatedRef = useRef(false); const reclaimRef = useRef(reclaim); const update = useCallback((target) => { const next = measure(target, isTruncatedRef.current ? reclaimRef.current : 0); isTruncatedRef.current = next; setIsTruncated(next); }, []); const observeRef = useResizeObserver(([{ target }]) => update(target)); const measureRef = useCallback((node) => { setElement(node ?? null); observeRef(node); }, [observeRef]); useEffect(() => { reclaimRef.current = reclaim; if (element) update(element); }, [ element, reclaim, update ]); useEffect(() => { if (!element || !document.fonts) return; let isActive = true; document.fonts.ready.then(() => { if (isActive) update(element); }); return () => { isActive = false; }; }, [element, update]); return [measureRef, isTruncated]; } export { useIsTruncated }; //# sourceMappingURL=use-is-truncated.mjs.map