"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useElementsSize = useElementsSize;
var _react = require("react");
var _debounce = _interopRequireDefault(require("lodash-es/debounce"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const DEBOUNCE_TIME = 300;

/**
 * Easily gets the width and height of referenced component
 * Example:
 *
 ```
   const buttonWrapperEl = useRef(null);
   const [width, height] = useElementsSize(buttonWrapperEl);
   <button ref={ref}></button>
   <div style={width}></div>
 ```
 * @param {object} ref - The `ref` to measure
 */
function useElementsSize(ref, checkOnRerender = false) {
  const [size, setSize] = (0, _react.useState)({});
  const sizeRef = (0, _react.useRef)({});
  const setSizeDebouncedRef = (0, _react.useRef)((0, _debounce.default)(setSize, DEBOUNCE_TIME, {
    leading: true
  }));
  sizeRef.current = size;
  (0, _react.useEffect)(() => {
    const handleResize = () => {
      if (ref.current) {
        const {
          width,
          height
        } = ref.current.getBoundingClientRect();
        setSize({
          width,
          height
        });
      }
    };
    handleResize();
    const debouncedResize = (0, _debounce.default)(handleResize, DEBOUNCE_TIME);
    window.addEventListener('resize', debouncedResize);
    return () => {
      window.removeEventListener('resize', debouncedResize);
      debouncedResize.cancel();
      setSizeDebouncedRef.current?.cancel?.();
    };
  }, []);
  (0, _react.useEffect)(() => {
    if (checkOnRerender && ref.current) {
      const {
        width,
        height
      } = ref.current.getBoundingClientRect();
      if (width !== sizeRef.current.width || height !== sizeRef.current.height) {
        setSizeDebouncedRef.current({
          width,
          height
        });
      }
    }
  });
  return [size.width, size.height];
}