"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 _reactDom = require("react-dom");

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

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

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

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

var _Toast = _interopRequireDefault(require("../Toast"));

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

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-2020. Plesk International GmbH. All rights reserved.
let toastId = 0;

/**
 * `Toaster` is used for notifying about events happened in the system. For example, about results of performed operations.
 * @since 0.0.42
 */
class Toaster extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "state", {
      toasts: []
    });
  }

  static getDerivedStateFromProps({
    toasts,
    maxToastsNumber
  }) {
    if (toasts) {
      return {
        toasts: toasts.slice(0, maxToastsNumber)
      };
    }

    return null;
  }

  isControlled() {
    return Boolean(this.props.toasts);
  }
  /**
   * Add a new toast
   *
   * `intent` - Visual intent color to apply to component. (Type: `oneOf` 'info', 'success', 'warning', 'danger'. *Required*.)<br>
   * `accent` - Contrast (light) version of the component. (Type: `boolean`. Default: 'undefined'.)<br>
   * `icon` - Name of icon or [Icon](#!/Icon) component. (Type: `oneOfType` 'string', 'object', 'element'. Default: `undefined`.)<br>
   * `message` - Message to display in the body of the toast. (Type: `any`. Default: `undefined`.)<br>
   * `onClose` - onClose handler. (Type: `func`. Default: `undefined`.)<br>
   * `closable` - Show close control (cross mark). (Type: `boolean`. Default: `true`.)<br>
   * `autoClosable` - Whether call `onClose` after 6 seconds or not.
   * Enabled by default when the position is "top-end" and a toast has "success" intent. (Type: `boolean`. Default: 'undefined'.)<br>
   * ---
   * @param {Object} props **Toast props**:
   * @returns {string} New toast key
   * @public
   */


  add(props) {
    const key = `toast-${toastId++}`;
    this.setState(({
      toasts
    }) => ({
      toasts: [{
        key,
        ...props
      }, ...toasts].slice(0, this.props.maxToastsNumber)
    }));
    return key;
  }
  /**
   * Update toast by key
   *
   * @param {string} key
   * @param {Object} props New props
   * @returns {string} Updated toast key
   * @public
   */


  update(key, props) {
    this.setState(({
      toasts
    }) => ({
      toasts: toasts.map(toast => toast.key === key ? { ...props,
        key
      } : toast)
    }));
    return key;
  }
  /**
   * Remove toast by key
   *
   * @param {string} key
   * @public
   */


  remove(key) {
    this.setState(({
      toasts
    }) => ({
      toasts: toasts.filter(toast => toast.key !== key)
    }));
  }
  /**
   * Clear all toasts
   *
   * @public
   */


  clear() {
    this.setState({
      toasts: []
    });
  }

  render() {
    const {
      baseClassName,
      className,
      toasts,
      maxToastsNumber,
      position,
      onToastClose,
      ...props
    } = this.props;
    let stack = this.state.toasts;

    if (position === 'bottom-end') {
      stack = [...stack];
      stack.reverse();
    }

    return /*#__PURE__*/_react.default.createElement(_Layer.default, {
      level: _constants.Z_INDEX_TOASTER
    }, /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
      className: (0, _classnames.default)(baseClassName, {
        [`${baseClassName}--${position}`]: position
      }, className)
    }, props), /*#__PURE__*/_react.default.createElement(_reactTransitionGroup.TransitionGroup, {
      component: "span"
    }, stack.map(toastProps => {
      const {
        intent
      } = toastProps;
      let {
        autoClosable
      } = toastProps;

      if (autoClosable === undefined && intent === 'success' && position === 'top-end') {
        autoClosable = true;
      }

      const toastRef = /*#__PURE__*/(0, _react.createRef)();
      return /*#__PURE__*/_react.default.createElement(_reactTransitionGroup.CSSTransition, {
        key: toastProps.key,
        classNames: `${_Toast.default.defaultProps.baseClassName}-`,
        timeout: {
          enter: 300,
          exit: 300
        },
        nodeRef: toastRef
      }, /*#__PURE__*/_react.default.createElement(_Toast.default, (0, _extends2.default)({}, toastProps, {
        autoClosable: autoClosable,
        onClose: () => {
          if (!this.isControlled()) {
            this.remove(toastProps.key);
          }

          if (toastProps.onClose) {
            toastProps.onClose();
          }

          if (onToastClose) {
            onToastClose(toastProps.key);
          }
        },
        innerRef: toastRef
      })));
    }))));
  }

}

exports.default = Toaster;
(0, _defineProperty2.default)(Toaster, "defaultProps", {
  position: 'top-end',
  baseClassName: `${_constants.CLS_PREFIX}toaster`
});
(0, _defineProperty2.default)(Toaster, "create", (props = {}, container = document.body) => {
  const containerElement = document.createElement('div');
  container.appendChild(containerElement);
  return (0, _reactDom.render)( /*#__PURE__*/_react.default.createElement(Toaster, props), containerElement);
});