"use strict";

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

var _react = require("react");

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

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

/* eslint-disable no-param-reassign */
var overflowScrollReg = /scroll|auto/i;
var defaultRoot = _utils.inBrowser ? window : undefined;

function isElement(node) {
  var ELEMENT_NODE_TYPE = 1;
  return node.tagName !== 'HTML' && node.tagName !== 'BODY' && node.nodeType === ELEMENT_NODE_TYPE;
}

function getScrollParent(el, root) {
  if (root === void 0) {
    root = defaultRoot;
  }

  if (root === undefined) {
    root = window;
  }

  var node = el;

  while (node && node !== root && isElement(node)) {
    var _window$getComputedSt = window.getComputedStyle(node),
        overflowY = _window$getComputedSt.overflowY;

    if (overflowScrollReg.test(overflowY)) {
      if (node.tagName !== 'BODY') {
        return node;
      }

      var htmlOverflowY = window.getComputedStyle(node.parentNode).overflowY;

      if (overflowScrollReg.test(htmlOverflowY)) {
        return node;
      }
    }

    node = node.parentNode;
  }

  return root;
}

function useScrollParent(el) {
  var _useState = (0, _react.useState)(),
      scrollParent = _useState[0],
      setScrollParent = _useState[1];

  (0, _react.useEffect)(function () {
    if (el) {
      var element = (0, _getTargetElement.getTargetElement)(el);
      setScrollParent(getScrollParent(element));
    }
  }, []);
  return scrollParent;
}

var _default = useScrollParent;
exports.default = _default;