"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EventDispatcher = void 0;
exports.createDispatch = createDispatch;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var EventDispatcher = exports.EventDispatcher = /*#__PURE__*/function () {
  function EventDispatcher() {
    (0, _classCallCheck2.default)(this, EventDispatcher);
    (0, _defineProperty2.default)(this, "listeners", {});
  }
  (0, _createClass2.default)(EventDispatcher, [{
    key: "on",
    value: function on(event, cb) {
      if (!this.listeners[event]) {
        this.listeners[event] = new Set();
      }
      this.listeners[event].add(cb);
    }
  }, {
    key: "has",
    value: function has(event, cb) {
      if (!this.listeners[event]) {
        return false;
      }
      return this.listeners[event].has(cb);
    }
  }, {
    key: "off",
    value: function off(event, cb) {
      if (!this.listeners[event]) {
        return;
      }
      if (this.listeners[event].has(cb)) {
        this.listeners[event].delete(cb);
      }
    }
  }, {
    key: "emit",
    value: function emit(event, data) {
      if (!this.listeners[event]) {
        return;
      }
      this.listeners[event].forEach(function (cb) {
        return cb(data);
      });
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this.listeners = {};
    }
  }]);
  return EventDispatcher;
}();
function getEventFromEventName(eventName) {
  return typeof eventName === 'string' ? eventName : eventName.key;
}

/**
 * Creates a dispatch function that can be called inside ProseMirror Plugin
 * to notify listeners about that plugin's state change.
 */
function createDispatch(eventDispatcher) {
  return function (eventName, data) {
    if (!eventName) {
      throw new Error('event name is required!');
    }
    eventDispatcher.emit(getEventFromEventName(eventName), data);
  };
}