"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = require("react");

var _utils = require("../utils");

var _getTargetElement = require("../utils/dom/getTargetElement");

function isInViewPort(el) {
  if (!el) {
    return undefined;
  }

  var viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  var rect = el.getBoundingClientRect();

  if (rect) {
    var top = rect.top,
        bottom = rect.bottom,
        left = rect.left,
        right = rect.right;
    return bottom > 0 && top <= viewPortHeight && left <= viewPortWidth && right > 0;
  }

  return false;
}

function useInViewport(target) {
  var _useState = (0, _react.useState)(function () {
    if (!_utils.inBrowser || !window.IntersectionObserver) return true;
    var el = (0, _getTargetElement.getTargetElement)(target);
    return isInViewPort(el);
  }),
      inViewPort = _useState[0],
      setInViewport = _useState[1];

  (0, _react.useEffect)(function () {
    var el = (0, _getTargetElement.getTargetElement)(target); // compatibility: https://caniuse.com/#feat=intersectionobserver

    if (!el || !_utils.inBrowser || !window.IntersectionObserver) {
      return function () {};
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.some(function (entry) {
        if (entry.intersectionRatio > 0) {
          setInViewport(true);
          observer.disconnect();
          return true;
        }

        return false;
      });
    }, {
      threshold: [0.0001]
    });
    observer.observe(el);
    return function () {
      observer.disconnect();
    };
  }, [target]);
  return inViewPort;
}

var _default = useInViewport;
exports.default = _default;