"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _reactDom = require("react-dom");
var _react = require("react");
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const AutoClosableContext = /*#__PURE__*/(0, _react.createContext)(null);
/**
 * This is helper component for handling outside clicks.
 * @since 0.0.42
 */
class AutoClosable extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "children", []);
    (0, _defineProperty2.default)(this, "addChild", child => {
      this.children.push(child);
    });
    (0, _defineProperty2.default)(this, "removeChild", child => {
      this.children = this.children.filter(item => item !== child);
    });
    (0, _defineProperty2.default)(this, "getIgnoreNodes", () => {
      const {
        ignoreNodes
      } = this.props;
      const nodes = typeof ignoreNodes === 'function' ? ignoreNodes() : [];
      nodes.push(this);
      this.children.forEach(child => child.getIgnoreNodes().forEach(node => nodes.push(node)));
      return nodes;
    });
    (0, _defineProperty2.default)(this, "onOutsideClick", event => {
      const el = event.target;
      const isClickOnIgnoredNode = this.getIgnoreNodes().map(node => {
        if (node instanceof AutoClosable && node.props.nodeRef && node.props.nodeRef.current) {
          return node.props.nodeRef.current;
        }
        if (node instanceof _react.Component) {
          return (0, _reactDom.findDOMNode)(node);
        }
        if (node instanceof Node) {
          return node;
        }
        if (node && node.current instanceof Node) {
          return node.current;
        }
        return null;
      }).some(node => Boolean(node && el instanceof Node && node.contains(el)));
      if (isClickOnIgnoredNode) {
        return;
      }
      if (this.props.onClose) {
        this.props.onClose();
      }
    });
  }
  componentDidMount() {
    document.body.addEventListener('click', this.onOutsideClick, {
      capture: true
    });
    if (this.context) {
      this.context.addChild(this);
    }
  }
  componentWillUnmount() {
    document.body.removeEventListener('click', this.onOutsideClick, {
      capture: true
    });
    if (this.context) {
      this.context.removeChild(this);
    }
  }
  render() {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(AutoClosableContext.Provider, {
      value: this,
      children: _react.Children.only(this.props.children)
    });
  }
}
AutoClosable.contextType = AutoClosableContext;
var _default = exports.default = AutoClosable;