import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { findDOMNode } from 'react-dom';
import { Component, Children, createContext } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
const AutoClosableContext = /*#__PURE__*/createContext(null);
/**
 * This is helper component for handling outside clicks.
 * @since 0.0.42
 */
class AutoClosable extends Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "children", []);
    _defineProperty(this, "addChild", child => {
      this.children.push(child);
    });
    _defineProperty(this, "removeChild", child => {
      this.children = this.children.filter(item => item !== child);
    });
    _defineProperty(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;
    });
    _defineProperty(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 Component) {
          return 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__*/_jsx(AutoClosableContext.Provider, {
      value: this,
      children: Children.only(this.props.children)
    });
  }
}
AutoClosable.contextType = AutoClosableContext;
export default AutoClosable;