UNPKG

@primer/react

Version:

An implementation of GitHub's Primer Design System using React

50 lines (44 loc) 1.83 kB
'use strict'; var React = require('react'); var useIsomorphicLayoutEffect = require('../utils/useIsomorphicLayoutEffect.js'); // https://gist.github.com/strothj/708afcf4f01dd04de8f49c92e88093c3 function useResizeObserver(callback, target, depsArray = []) { const [targetClientRect, setTargetClientRect] = React.useState(null); const savedCallback = React.useRef(callback); useIsomorphicLayoutEffect(() => { savedCallback.current = callback; }); useIsomorphicLayoutEffect(() => { const targetEl = target && 'current' in target ? target.current : document.documentElement; if (!targetEl) { return; } if (typeof ResizeObserver === 'function') { const observer = new ResizeObserver(entries => { savedCallback.current(entries); }); observer.observe(targetEl); return () => { observer.disconnect(); }; } else { const saveTargetDimensions = () => { const currTargetRect = targetEl.getBoundingClientRect(); if (currTargetRect.width !== (targetClientRect === null || targetClientRect === void 0 ? void 0 : targetClientRect.width) || currTargetRect.height !== targetClientRect.height) { savedCallback.current([{ contentRect: currTargetRect }]); } setTargetClientRect(currTargetRect); }; // eslint-disable-next-line github/prefer-observers window.addEventListener('resize', saveTargetDimensions); return () => { window.removeEventListener('resize', saveTargetDimensions); }; } // eslint-disable-next-line react-compiler/react-compiler // eslint-disable-next-line react-hooks/exhaustive-deps }, [target === null || target === void 0 ? void 0 : target.current, ...depsArray]); } exports.useResizeObserver = useResizeObserver;