"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
exports.preventDefault = preventDefault;
exports.stopEvent = stopEvent;
exports.stopPropagation = stopPropagation;

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

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

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

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

var _tslib = require("tslib");

var _mobx = require("mobx");

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _noop = _interopRequireDefault(require("lodash/noop"));

function on(el, eventName, handle, handles) {
  if (el.addEventListener) {
    var _handle = (0, _slicedToArray2["default"])(handle, 2),
        fn = _handle[0],
        options = _handle[1];

    el.addEventListener(eventName, fn, options);
  } else {
    var delegates = [];
    handles.forEach(function (_ref) {
      var _ref2 = (0, _slicedToArray2["default"])(_ref, 3),
          delegateFn = _ref2[2];

      if (el.detachEvent) {
        el.detachEvent("on".concat(eventName), delegateFn);
        delegates.unshift(delegateFn);
      }
    });
    delegates.forEach(function (delegateFn) {
      if (el.attachEvent) {
        el.attachEvent("on".concat(eventName), delegateFn);
      }
    });
  }
}

function off(el, eventName, handle) {
  var _handle2 = (0, _slicedToArray2["default"])(handle, 3),
      fn = _handle2[0],
      options = _handle2[1],
      delegateFn = _handle2[2];

  if (el.removeEventListener) {
    el.removeEventListener(eventName, fn, options);
  } else if (el.detachEvent) {
    el.detachEvent("on".concat(eventName), delegateFn);
  }
}

function isEventListenerOptions(options) {
  return (0, _isObject["default"])(options);
}

function isAddEventListenerOptions(options) {
  return isEventListenerOptions(options) && ('once' in options || 'passive' in options);
}

function getCapture(options) {
  return isEventListenerOptions(options) ? options.capture || false : options;
}

function isSameHandler(handle, other) {
  var _handle3 = (0, _slicedToArray2["default"])(handle, 2),
      handleFn = _handle3[0],
      handleOption = _handle3[1];

  var _other = (0, _slicedToArray2["default"])(other, 2),
      otherFn = _other[0],
      otherOption = _other[1];

  return handleFn === otherFn && getCapture(handleOption) === getCapture(otherOption);
}

function callHandler(events, handle) {
  var _handle4 = (0, _slicedToArray2["default"])(handle, 3),
      options = _handle4[1],
      delegateFn = _handle4[2];

  if (isAddEventListenerOptions(options) && options.once) {
    var index = events.indexOf(handle);

    if (index !== -1) {
      events.splice(index, 1);
    }
  }

  for (var _len = arguments.length, rest = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    rest[_key - 2] = arguments[_key];
  }

  return delegateFn.apply(void 0, rest);
}

function delegate(fn) {
  if ('handleEvent' in fn) {
    return function () {
      return fn.handleEvent.apply(fn, arguments);
    };
  }

  return function () {
    return fn.apply(void 0, arguments);
  };
}

var EventManager = /*#__PURE__*/function () {
  function EventManager(el) {
    (0, _classCallCheck2["default"])(this, EventManager);
    this.events = {};
    this.setTarget(el);
  }

  (0, _createClass2["default"])(EventManager, [{
    key: "setTarget",
    value: function setTarget(el) {
      this.el = el;
      return this;
    }
  }, {
    key: "addEventListener",
    value: function addEventListener(eventName, fn) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      eventName = eventName.toLowerCase();
      var events = this.events[eventName] || [];
      var index = events.findIndex(function (handle) {
        return isSameHandler(handle, [fn, options, _noop["default"]]);
      });

      if (index === -1) {
        var newHandle = [fn, options, delegate(fn)];

        if (getCapture(options)) {
          var captureIndex = events.findIndex(function (_ref3) {
            var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
                handleOptions = _ref4[1];

            return !getCapture(handleOptions);
          });

          if (captureIndex === -1) {
            events.push(newHandle);
          } else {
            events.splice(captureIndex, 0, newHandle);
          }
        } else {
          events.push(newHandle);
        }

        this.events[eventName] = events;
        var el = this.el;

        if (el) {
          on(el, eventName, newHandle, events);
        }
      }

      return this;
    }
  }, {
    key: "removeEventListener",
    value: function removeEventListener(eventName, fn) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      eventName = eventName.toLowerCase();
      var events = this.events[eventName];

      if (events) {
        var el = this.el;

        if (fn) {
          var index = events.findIndex(function (handle) {
            return isSameHandler(handle, [fn, options, _noop["default"]]);
          });

          if (index !== -1) {
            if (el) {
              off(el, eventName, events[index]);
            }

            events.splice(index, 1);
          }
        } else {
          this.events[eventName] = el ? (this.events[eventName] || []).filter(function (handle) {
            off(el, eventName, handle);
            return false;
          }) : [];
        }
      }

      return this;
    }
  }, {
    key: "fireEventSync",
    value: function fireEventSync(eventName) {
      for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        rest[_key2 - 1] = arguments[_key2];
      }

      var events = this.events[eventName.toLowerCase()];
      return events ? (0, _toConsumableArray2["default"])(events).every(function (handle) {
        return callHandler.apply(void 0, [events, handle].concat(rest)) !== false;
      }) : true;
    }
  }, {
    key: "fireEvent",
    value: function fireEvent(eventName) {
      for (var _len3 = arguments.length, rest = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
        rest[_key3 - 1] = arguments[_key3];
      }

      var events = this.events[eventName.toLowerCase()];
      return events ? Promise.all((0, _toConsumableArray2["default"])(events).map(function (handle) {
        return callHandler.apply(void 0, [events, handle].concat(rest));
      })).then(function (all) {
        return all.every(function (result) {
          return result !== false;
        });
      }) : Promise.resolve(true);
    }
  }, {
    key: "clear",
    value: function clear() {
      var _this = this;

      if (this.el) {
        Object.keys(this.events).forEach(function (eventName) {
          return _this.removeEventListener(eventName);
        });
      }

      this.events = {};
      return this;
    }
  }]);
  return EventManager;
}();

exports["default"] = EventManager;
(0, _tslib.__decorate)([_mobx.action], EventManager.prototype, "fireEventSync", null);
(0, _tslib.__decorate)([_mobx.action], EventManager.prototype, "fireEvent", null);

function preventDefault(e) {
  e.preventDefault();
}

function stopPropagation(e) {
  e.stopPropagation();
}

function stopEvent(e) {
  preventDefault(e);
  stopPropagation(e);
}
//# sourceMappingURL=index.js.map
