"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = useVisibility;

var _react = require("react");

var _lodash = _interopRequireDefault(require("lodash.throttle"));

/**
 * Check if an element is in viewport

 * @param {number} offset - Number of pixels up to the observable element from the top
 * @param {number} throttleMilliseconds - Throttle observable listener, in ms
 */
function useVisibility(offset = 0, throttleMilliseconds = 100, initialState = false) {
  const [isVisible, setIsVisible] = (0, _react.useState)(initialState);
  const currentElement = /*#__PURE__*/(0, _react.createRef)();
  const onScroll = (0, _lodash.default)(() => {
    if (!currentElement.current) {
      setIsVisible(false);
      return;
    }

    const top = currentElement.current.getBoundingClientRect().top;
    setIsVisible(top + offset >= 0 && top - offset <= window.innerHeight);
  }, throttleMilliseconds);
  (0, _react.useEffect)(() => {
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  });
  return [isVisible, currentElement];
}

module.exports = exports.default;