UNPKG

@redocly/theme

Version:

Shared UI components lib

75 lines 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useElementSize = useElementSize; const react_1 = require("react"); const getInitialSize = (ref) => { if (ref === null || ref === void 0 ? void 0 : ref.current) { return { width: ref.current.offsetWidth, height: ref.current.offsetHeight, }; } if ((ref === null || ref === void 0 ? void 0 : ref.current) === null) { return { width: 0, height: 0, }; } return { width: typeof window !== 'undefined' ? window.innerWidth : 0, height: typeof window !== 'undefined' ? window.innerHeight : 0, }; }; function useElementSize({ delay = 50, detectSizes = 'both', } = {}) { const ref = (0, react_1.useRef)(null); const previousSize = (0, react_1.useRef)(getInitialSize(ref)); const [size, setSize] = (0, react_1.useState)(getInitialSize(ref)); const isFirstUpdate = (0, react_1.useRef)(true); const updateSize = (0, react_1.useCallback)((newSize) => { const shouldUpdateWidth = detectSizes === 'both' || detectSizes === 'width'; const shouldUpdateHeight = detectSizes === 'both' || detectSizes === 'height'; const widthChanged = shouldUpdateWidth && newSize.width !== previousSize.current.width; const heightChanged = shouldUpdateHeight && newSize.height !== previousSize.current.height; if (widthChanged || heightChanged) { const updatedSize = { width: shouldUpdateWidth ? newSize.width : previousSize.current.width, height: shouldUpdateHeight ? newSize.height : previousSize.current.height, }; setSize(updatedSize); previousSize.current = updatedSize; } }, [detectSizes]); (0, react_1.useLayoutEffect)(() => { let timeoutId = null; const triggerUpdateWithThrottling = (newSize) => { if (isFirstUpdate.current) { updateSize(newSize); isFirstUpdate.current = false; return; } if (timeoutId !== null) return; timeoutId = window.setTimeout(() => { updateSize(newSize); timeoutId = null; }, delay); }; if ((ref === null || ref === void 0 ? void 0 : ref.current) && typeof ResizeObserver !== 'undefined') { const observer = new ResizeObserver((entries) => { for (const entry of entries) { const { width, height } = entry.contentRect; triggerUpdateWithThrottling({ width, height }); } }); observer.observe(ref.current); return () => { observer.disconnect(); if (timeoutId !== null) { clearTimeout(timeoutId); } }; } }, [ref, updateSize, delay]); return [size, ref]; } //# sourceMappingURL=use-element-size.js.map