"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

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

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

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

var _react = _interopRequireWildcard(require("react"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _constants = require("../../constants");

var _reactTransitionGroup = require("react-transition-group");

var _Backdrop = _interopRequireDefault(require("./Backdrop"));

var _Layer = _interopRequireDefault(require("../Layer"));

var _FocusTrap = _interopRequireDefault(require("../FocusTrap"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

// Copyright 1999-2021. Plesk International GmbH. All rights reserved.

/**
 * `Overlay` component.
 */
const overlays = [];
/**
 * @since 0.0.65
 */

class Overlay extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "state", {
      isOpened: false,
      isExist: false
    });
    (0, _defineProperty2.default)(this, "prevFocusElement", null);
    (0, _defineProperty2.default)(this, "contentRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "backdropRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "handleBackdropClick", () => {
      const {
        onClose,
        canCloseOnBackdropClick
      } = this.props;

      if (canCloseOnBackdropClick) {
        (0, _utils2.safeInvoke)(onClose);
      } else {
        this.focus();
      }
    });
    (0, _defineProperty2.default)(this, "handleContentKeyUp", e => {
      const {
        onClose
      } = this.props;

      if (!e.isDefaultPrevented() && e.key === 'Escape') {
        (0, _utils2.safeInvoke)(onClose);
        e.preventDefault();
      }
    });
  }

  componentDidMount() {
    if (this.props.isOpen) {
      this.overlayWillOpen();
    }
  }

  componentDidUpdate(prevProps) {
    if (!this.props.isOpen && prevProps.isOpen) {
      this.overlayWillClose();
    } else if (this.props.isOpen && !prevProps.isOpen) {
      this.overlayWillOpen();
    }
  }

  componentWillUnmount() {
    if (this.props.isOpen) {
      this.overlayWillClose();
    }
  }

  overlayWillOpen() {
    (0, _utils.disableDocumentScroll)();
    overlays.push(this);
    this.setState({
      isExist: true
    }, () => {
      this.prevFocusElement = document.activeElement;
    });
    setTimeout(() => {
      this.setState({
        isOpened: true
      }, () => {
        this.focus();
      });
    });
  }

  overlayWillClose() {
    overlays.pop();

    if (overlays.length === 0) {
      (0, _utils.enableDocumentScroll)();
    }

    this.setState({
      isOpened: false
    }, () => {
      if (this.prevFocusElement) {
        this.prevFocusElement.focus();
        this.prevFocusElement = null;
      }
    });
  }

  focus() {
    if (this.contentRef.current === null || document.activeElement === null || !this.props.isOpen) {
      return;
    }

    const isFocusOutside = !this.contentRef.current.contains(document.activeElement);

    if (isFocusOutside) {
      const autofocusElement = this.contentRef.current.querySelector('[autofocus]');

      if (autofocusElement) {
        autofocusElement.focus();
      } else {
        this.contentRef.current.focus();
      }
    }
  }

  renderContent({
    baseClassName,
    children,
    canCloseOnEscapePress,
    sideBanner
  }) {
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactTransitionGroup.CSSTransition, {
      in: this.state.isOpened,
      classNames: `${baseClassName}-`,
      timeout: 300,
      onExited: () => {
        this.setState({
          isExist: false
        });
      },
      nodeRef: this.contentRef
    }, /*#__PURE__*/_react.default.createElement(_FocusTrap.default, {
      className: `${baseClassName}__content`,
      onKeyUp: canCloseOnEscapePress ? this.handleContentKeyUp : null,
      ref: this.contentRef,
      role: "dialog",
      "aria-modal": "true"
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: `${baseClassName}__body`
    }, children), this.renderImage({
      baseClassName,
      image: sideBanner
    }))));
  }

  renderBackdrop({
    baseClassName
  }) {
    return /*#__PURE__*/_react.default.createElement(_reactTransitionGroup.CSSTransition, {
      in: this.state.isOpened,
      classNames: `${baseClassName}-`,
      timeout: 300,
      nodeRef: this.backdropRef
    }, /*#__PURE__*/_react.default.createElement(_Backdrop.default, {
      onClick: () => this.handleBackdropClick(),
      innerRef: this.backdropRef
    }));
  }

  renderImage({
    baseClassName,
    image
  }) {
    const classPrefix = `${baseClassName}__side`;

    if (!image) {
      return null;
    }

    if ( /*#__PURE__*/(0, _react.isValidElement)(image)) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: `${classPrefix}`
      }, image);
    }

    if (typeof image === 'string') {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: classPrefix
      }, /*#__PURE__*/_react.default.createElement("img", {
        className: `${classPrefix}-image`,
        src: image
      }));
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: classPrefix
    }, /*#__PURE__*/_react.default.createElement("img", (0, _extends2.default)({
      className: `${classPrefix}-image`
    }, image)));
  }

  render() {
    const {
      baseClassName,
      className,
      children,
      isOpen,
      placement,
      size,
      sideBanner,
      sideBannerContainer,
      onClose,
      canCloseOnBackdropClick,
      canCloseOnEscapePress,
      style,
      ...props
    } = this.props;
    const {
      isExist
    } = this.state;

    if (!isExist) {
      return null;
    }

    return /*#__PURE__*/_react.default.createElement(_Layer.default, {
      level: _constants.Z_INDEX_OVERLAY
    }, /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
      className: (0, _classnames.default)(baseClassName, `${baseClassName}--${placement}`, `${baseClassName}--${size}`, sideBanner && `${baseClassName}--side`, className),
      style: {
        '--sideBannerBackground': sideBannerContainer === null || sideBannerContainer === void 0 ? void 0 : sideBannerContainer.background,
        '--sideBannerAlign': sideBannerContainer === null || sideBannerContainer === void 0 ? void 0 : sideBannerContainer.align,
        ...style
      }
    }, props), this.renderBackdrop({
      baseClassName
    }), this.renderContent({
      baseClassName,
      children,
      canCloseOnEscapePress,
      sideBanner
    })));
  }

}

exports.default = Overlay;
(0, _defineProperty2.default)(Overlay, "propTypes", {
  /**
   * Toggles visibility.
   */
  isOpen: _propTypes.default.bool,

  /**
   * Overlay placement.
   */
  placement: _propTypes.default.oneOf(['center', 'left', 'right']),

  /**
   * Overlay size.
   */
  size: _propTypes.default.oneOf(['xs', 'sm', 'md', 'lg']),

  /**
   * onClose handler.
   */
  onClose: _propTypes.default.func,

  /**
   * Indicating if clicking the backdrop should close the overlay.
   */
  canCloseOnBackdropClick: _propTypes.default.bool,

  /**
   * Indicating if pressing the escape key should close the overlay.
   */
  canCloseOnEscapePress: _propTypes.default.bool,

  /**
   * Block with an image, placed at the side of the component
   * @since 3.25.0
   */
  sideBanner: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object, _propTypes.default.element]),

  /**
   * Additional properties for the sideBanner
   * @since 3.25.0
   */
  sideBannerContainer: _propTypes.default.shape({
    /**
     * Values for css background property
     */
    background: _propTypes.default.string,

    /**
     * One of: center, flex-start, flex-end
     */
    align: _propTypes.default.oneOf(['center', 'flex-start', 'flex-end'])
  }),

  /**
   * @ignore
   */
  style: _propTypes.default.object,

  /**
   * Content of the `Overlay`.
   */
  children: _propTypes.default.node,

  /**
   * @ignore
   */
  className: _propTypes.default.string,

  /**
   * @ignore
   */
  baseClassName: _propTypes.default.string
});
(0, _defineProperty2.default)(Overlay, "defaultProps", {
  isOpen: false,
  placement: 'center',
  size: 'md',
  onClose: null,
  canCloseOnBackdropClick: true,
  canCloseOnEscapePress: true,
  sideBanner: undefined,
  sideBannerContainer: undefined,
  style: undefined,
  children: null,
  className: null,
  baseClassName: `${_constants.CLS_PREFIX}overlay`
});