function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/**
 * Plugin for adding `$bvToast` property to all Vue instances
 */

import { NAME_TOAST, NAME_TOASTER, NAME_TOAST_POP } from '../../../constants/components';
import { EVENT_NAME_DESTROYED, EVENT_NAME_HIDDEN, EVENT_NAME_HIDE, EVENT_NAME_SHOW, HOOK_EVENT_NAME_DESTROYED } from '../../../constants/events';
import { useParentMixin } from '../../../mixins/use-parent';
import { concat } from '../../../utils/array';
import { getComponentConfig } from '../../../utils/config';
import { requestAF } from '../../../utils/dom';
import { getRootEventName, getRootActionEventName } from '../../../utils/events';
import { isUndefined, isString } from '../../../utils/inspect';
import { assign, defineProperties, defineProperty, hasOwnProperty, keys, omit, readonlyDescriptor } from '../../../utils/object';
import { pluginFactory } from '../../../utils/plugins';
import { warn, warnNotClient } from '../../../utils/warn';
import { createNewChildComponent } from '../../../utils/create-new-child-component';
import { getEventRoot } from '../../../utils/get-event-root';
import { BToast, props as toastProps } from '../toast';

// --- Constants ---

var PROP_NAME = '$bvToast';
var PROP_NAME_PRIV = '_bv__toast';

// Base toast props that are allowed
// Some may be ignored or overridden on some message boxes
// Prop ID is allowed, but really only should be used for testing
// We need to add it in explicitly as it comes from the `idMixin`
var BASE_PROPS = ['id'].concat(_toConsumableArray(keys(omit(toastProps, ['static', 'visible']))));

// Map prop names to toast slot names
var propsToSlots = {
  toastContent: 'default',
  title: 'toast-title'
};

// --- Helper methods ---

// Method to filter only recognized props that are not undefined
var filterOptions = function filterOptions(options) {
  return BASE_PROPS.reduce(function (memo, key) {
    if (!isUndefined(options[key])) {
      memo[key] = options[key];
    }
    return memo;
  }, {});
};

// Method to install `$bvToast` VM injection
var plugin = function plugin(Vue) {
  // Create a private sub-component constructor that
  // extends BToast and self-destructs after hidden
  // @vue/component
  var BVToastPop = Vue.extend({
    name: NAME_TOAST_POP,
    extends: BToast,
    mixins: [useParentMixin],
    destroyed: function destroyed() {
      // Make sure we not in document any more
      var $el = this.$el;
      if ($el && $el.parentNode) {
        $el.parentNode.removeChild($el);
      }
    },
    mounted: function mounted() {
      var _this = this;
      // Self destruct handler
      var handleDestroy = function handleDestroy() {
        // Ensure the toast has been force hidden
        _this.localShow = false;
        _this.doRender = false;
        _this.$nextTick(function () {
          _this.$nextTick(function () {
            // In a `requestAF()` to release control back to application
            // and to allow the portal-target time to remove the content
            requestAF(function () {
              _this.$destroy();
            });
          });
        });
      };
      // Self destruct if parent destroyed
      this.bvParent.$once(HOOK_EVENT_NAME_DESTROYED, handleDestroy);
      // Self destruct after hidden
      this.$once(EVENT_NAME_HIDDEN, handleDestroy);
      // Self destruct when toaster is destroyed
      this.listenOnRoot(getRootEventName(NAME_TOASTER, EVENT_NAME_DESTROYED), function (toaster) {
        /* istanbul ignore next: hard to test */
        if (toaster === _this.toaster) {
          handleDestroy();
        }
      });
    }
  });

  // Private method to generate the on-demand toast
  var makeToast = function makeToast(props, parent) {
    if (warnNotClient(PROP_NAME)) {
      /* istanbul ignore next */
      return;
    }
    // Create an instance of `BVToastPop` component
    var toast = createNewChildComponent(parent, BVToastPop, {
      // We set parent as the local VM so these toasts can emit events on the
      // app `$root`, and it ensures `BToast` is destroyed when parent is destroyed
      propsData: _objectSpread(_objectSpread(_objectSpread({}, filterOptions(getComponentConfig(NAME_TOAST))), omit(props, keys(propsToSlots))), {}, {
        // Props that can't be overridden
        static: false,
        visible: true
      })
    });
    // Convert certain props to slots
    keys(propsToSlots).forEach(function (prop) {
      var value = props[prop];
      if (!isUndefined(value)) {
        // Can be a string, or array of VNodes
        if (prop === 'title' && isString(value)) {
          // Special case for title if it is a string, we wrap in a <strong>
          value = [parent.$createElement('strong', {
            class: 'mr-2'
          }, value)];
        }
        toast.$slots[propsToSlots[prop]] = concat(value);
      }
    });
    // Create a mount point (a DIV) and mount it (which triggers the show)
    var div = document.createElement('div');
    document.body.appendChild(div);
    toast.$mount(div);
  };

  // Declare BvToast instance property class
  var BvToast = /*#__PURE__*/function () {
    function BvToast(vm) {
      _classCallCheck(this, BvToast);
      // Assign the new properties to this instance
      assign(this, {
        _vm: vm,
        _root: getEventRoot(vm)
      });
      // Set these properties as read-only and non-enumerable
      defineProperties(this, {
        _vm: readonlyDescriptor(),
        _root: readonlyDescriptor()
      });
    }

    // --- Public Instance methods ---

    // Opens a user defined toast and returns immediately
    return _createClass(BvToast, [{
      key: "toast",
      value: function toast(content) {
        var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
        if (!content || warnNotClient(PROP_NAME)) {
          /* istanbul ignore next */
          return;
        }
        makeToast(_objectSpread(_objectSpread({}, filterOptions(options)), {}, {
          toastContent: content
        }), this._vm);
      }

      // shows a `<b-toast>` component with the specified ID
    }, {
      key: "show",
      value: function show(id) {
        if (id) {
          this._root.$emit(getRootActionEventName(NAME_TOAST, EVENT_NAME_SHOW), id);
        }
      }

      // Hide a toast with specified ID, or if not ID all toasts
    }, {
      key: "hide",
      value: function hide() {
        var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
        this._root.$emit(getRootActionEventName(NAME_TOAST, EVENT_NAME_HIDE), id);
      }
    }]);
  }(); // Add our instance mixin
  Vue.mixin({
    beforeCreate: function beforeCreate() {
      // Because we need access to `$root` for `$emits`, and VM for parenting,
      // we have to create a fresh instance of `BvToast` for each VM
      this[PROP_NAME_PRIV] = new BvToast(this);
    }
  });

  // Define our read-only `$bvToast` instance property
  // Placed in an if just in case in HMR mode
  if (!hasOwnProperty(Vue.prototype, PROP_NAME)) {
    defineProperty(Vue.prototype, PROP_NAME, {
      get: function get() {
        /* istanbul ignore next */
        if (!this || !this[PROP_NAME_PRIV]) {
          warn("\"".concat(PROP_NAME, "\" must be accessed from a Vue instance \"this\" context."), NAME_TOAST);
        }
        return this[PROP_NAME_PRIV];
      }
    });
  }
};
export var BVToastPlugin = /*#__PURE__*/pluginFactory({
  plugins: {
    plugin: plugin
  }
});