"use strict";

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

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

var _reactDom = _interopRequireDefault(require("react-dom"));

var _overrides = require("../helpers/overrides.js");

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

var _styledComponents = require("./styled-components.js");

var _toast = _interopRequireDefault(require("./toast.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var toasterRef = null;

var ToasterContainer =
/*#__PURE__*/
function (_React$Component) {
  _inherits(ToasterContainer, _React$Component);

  function ToasterContainer(_props) {
    var _this;

    _classCallCheck(this, ToasterContainer);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(ToasterContainer).call(this, _props));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      isMounted: false,
      toasts: []
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "dismissHandlers", {});

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "toastId", 0);

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "getToastProps", function (props) {
      var autoHideDuration = _this.props.autoHideDuration;
      var key = props.key || "toast-".concat(_this.toastId++);
      return _objectSpread({
        autoHideDuration: autoHideDuration
      }, props, {
        key: key
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "show", function () {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      var toastProps = _this.getToastProps(props);

      _this.setState(function (_ref) {
        var toasts = _ref.toasts;
        toasts.push(toastProps);
        return {
          toasts: toasts
        };
      });

      return toastProps.key;
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "update", function (key, props) {
      _this.setState(function (_ref2) {
        var toasts = _ref2.toasts;
        toasts.forEach(function (t, index, arr) {
          if (t.key === key) {
            arr[index] = _objectSpread({}, t, _this.getToastProps(props), {
              key: key
            });
          }
        });
        return {
          toasts: toasts
        };
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "dismiss", function (key) {
      if (_this.dismissHandlers[key]) {
        _this.dismissHandlers[key]();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "clearAll", function () {
      Object.keys(_this.dismissHandlers).forEach(function (key) {
        _this.dismissHandlers[key]();
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "clear", function (key) {
      key === undefined ? _this.clearAll() : _this.dismiss(key);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "internalOnClose", function (key) {
      delete _this.dismissHandlers[key];

      _this.setState(function (_ref3) {
        var toasts = _ref3.toasts;
        return {
          toasts: toasts.filter(function (t) {
            return !(t.key === key);
          })
        };
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "getOnCloseHandler", function (key, onClose) {
      return function () {
        _this.internalOnClose(key);

        typeof onClose === 'function' && onClose();
      };
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "renderToast", function (toastProps) {
      var onClose = toastProps.onClose,
          children = toastProps.children,
          key = toastProps.key,
          rest = _objectWithoutProperties(toastProps, ["onClose", "children", "key"]);

      var _this$props$overrides = _this.props.overrides,
          BodyOverride = _this$props$overrides.ToastBody,
          CloseIconOverride = _this$props$overrides.ToastCloseIcon;
      var globalToastOverrides = (0, _overrides.mergeOverrides)({
        Body: _styledComponents.Body,
        CloseIcon: _styledComponents.CloseIconSvg
      }, // $FlowFixMe
      {
        Body: BodyOverride,
        CloseIcon: CloseIconOverride
      });
      var toastOverrides = (0, _overrides.mergeOverrides)(globalToastOverrides, toastProps.overrides);
      return React.createElement(_toast.default, _extends({}, rest, {
        overrides: toastOverrides,
        key: key,
        onClose: _this.getOnCloseHandler(key, onClose)
      }), function (_ref4) {
        var dismiss = _ref4.dismiss;
        _this.dismissHandlers[key] = dismiss;
        return children;
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "getSharedProps", function () {
      var placement = _this.props.placement;
      return {
        $placement: placement
      };
    });

    toasterRef = _assertThisInitialized(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(ToasterContainer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setState({
        isMounted: true
      });
    }
  }, {
    key: "render",
    value: function render() {
      var sharedProps = this.getSharedProps();
      var RootOverride = this.props.overrides.Root;

      var _getOverrides = (0, _overrides.getOverrides)(RootOverride, _styledComponents.Root),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          Root = _getOverrides2[0],
          rootProps = _getOverrides2[1];

      var toastsLength = this.state.toasts.length;
      var toastsToRender = []; // render the toasts from the newest at the start
      // to the oldest at the end
      // eslint-disable-next-line for-direction

      for (var i = toastsLength - 1; i >= 0; i--) {
        toastsToRender.push(this.renderToast(this.state.toasts[i]));
      }

      var root = React.createElement(Root, _extends({
        "data-baseweb": "toaster"
      }, sharedProps, rootProps), toastsToRender);

      if (this.state.isMounted) {
        // Only render on the browser (portals aren't supported server-side)
        if (this.props.usePortal) {
          if (typeof document !== 'undefined') {
            return _reactDom.default.createPortal(root, // $FlowFixMe
            document.body);
          }
        } else {
          return root;
        }
      }

      return null;
    }
  }]);

  return ToasterContainer;
}(React.Component);

exports.ToasterContainer = ToasterContainer;

_defineProperty(ToasterContainer, "defaultProps", {
  placement: _constants.PLACEMENT.top,
  usePortal: true,
  overrides: {},
  autoHideDuration: 0
});

var toaster = {
  getRef: function getRef() {
    return toasterRef;
  },
  show: function show(children) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    // toasts can not be added until Toaster is mounted
    // no SSR for the `toaster.show()`
    var toasterInstance = this.getRef();

    if (toasterInstance) {
      return toasterInstance.show(_objectSpread({
        children: children
      }, props));
    } else if (process.env.NODE_ENV !== "production") {
      throw new Error('Can not add any toasts until Toaster is mounted!');
    }
  },
  info: function info(children) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.show(children, _objectSpread({}, props, {
      kind: _constants.KIND.info
    }));
  },
  positive: function positive(children) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.show(children, _objectSpread({}, props, {
      kind: _constants.KIND.positive
    }));
  },
  warning: function warning(children) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.show(children, _objectSpread({}, props, {
      kind: _constants.KIND.warning
    }));
  },
  negative: function negative(children) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.show(children, _objectSpread({}, props, {
      kind: _constants.KIND.negative
    }));
  },
  update: function update(key, props) {
    var toasterInstance = this.getRef();

    if (toasterInstance) {
      toasterInstance.update(key, props);
    } else if (process.env.NODE_ENV !== "production") {
      // eslint-disable-next-line no-console
      console.error('No ToasterContainer is mounted yet.');
    }
  },
  clear: function clear(key) {
    var toasterInstance = this.getRef();

    if (toasterInstance) {
      toasterInstance.clear(key);
    } else if (process.env.NODE_ENV !== "production") {
      // eslint-disable-next-line no-console
      console.error('No ToasterContainer is mounted yet.');
    }
  }
};
var _default = toaster;
exports.default = _default;