UNPKG

opendash

Version:

open.DASH data visualization framework

53 lines 1.86 kB
import { useState, useCallback, useLayoutEffect } from "react"; import throttle from "lodash.throttle"; function getSize(ref) { if (!ref || !ref.current) { return { width: 0, height: 0, }; } return { width: ref.current.offsetWidth, height: ref.current.offsetHeight, }; } export function useElementSize(ref, throttleDuration) { if (throttleDuration === void 0) { throttleDuration = 0; } var _a = useState(getSize(ref)), state = _a[0], setState = _a[1]; function _handleResize() { var nextState = getSize(ref); var shouldUpdate = nextState.width !== state.width || nextState.height !== state.height; if (shouldUpdate) { setState(nextState); } } var handleResize = useCallback(throttleDuration ? throttle(_handleResize, throttleDuration) : _handleResize, [ref, throttleDuration]); useLayoutEffect(function () { if (!ref || !ref.current) { return; } handleResize(); // @ts-ignore // TS doesn't know about ResizeObserver yet if (typeof ResizeObserver === "function") { // @ts-ignore // TS doesn't know about ResizeObserver yet var resizeObserver_1 = new ResizeObserver(function () { handleResize(); }); resizeObserver_1.observe(ref.current); return function () { resizeObserver_1.disconnect(ref.current); }; } else { window.addEventListener("resize", handleResize); return function () { window.removeEventListener("resize", handleResize); }; } }, [ref.current]); return state; } //# sourceMappingURL=useElementSize.js.map