"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const index_esm$1 = require("../../../../min-dash/dist/index.esm.js");
const index_esm = require("../../../../min-dom/dist/index.esm.js");
const KeyboardUtil = require("./KeyboardUtil.js");
var r = "keyboard.keydown", l = "keyboard.keyup", d = "input-handle-modified-keys", c = 1e3;
function i(t, e) {
  var n = this;
  this._config = t || {}, this._eventBus = e, this._keydownHandler = this._keydownHandler.bind(this), this._keyupHandler = this._keyupHandler.bind(this), e.on("diagram.destroy", function() {
    n._fire("destroy"), n.unbind();
  }), e.on("diagram.init", function() {
    n._fire("init");
  }), e.on("attach", function() {
    t && t.bindTo && n.bind(t.bindTo);
  }), e.on("detach", function() {
    n.unbind();
  });
}
i.$inject = [
  "config.keyboard",
  "eventBus"
];
i.prototype._keydownHandler = function(t) {
  this._keyHandler(t, r);
};
i.prototype._keyupHandler = function(t) {
  this._keyHandler(t, l);
};
i.prototype._keyHandler = function(t, e) {
  var n;
  if (!this._isEventIgnored(t)) {
    var u = {
      keyEvent: t
    };
    n = this._eventBus.fire(e || r, u), n && t.preventDefault();
  }
};
i.prototype._isEventIgnored = function(t) {
  return k(t.target) && this._isModifiedKeyIgnored(t);
};
i.prototype._isModifiedKeyIgnored = function(t) {
  if (!KeyboardUtil.isCmd(t))
    return true;
  var e = this._getAllowedModifiers(t.target);
  return e.indexOf(t.key) === -1;
};
i.prototype._getAllowedModifiers = function(t) {
  var e = index_esm.closest(t, "[" + d + "]", true);
  return !e || this._node && !this._node.contains(e) ? [] : e.getAttribute(d).split(",");
};
i.prototype.bind = function(t) {
  this.unbind(), this._node = t, index_esm.event.bind(t, "keydown", this._keydownHandler, true), index_esm.event.bind(t, "keyup", this._keyupHandler, true), this._fire("bind");
};
i.prototype.getBinding = function() {
  return this._node;
};
i.prototype.unbind = function() {
  var t = this._node;
  t && (this._fire("unbind"), index_esm.event.unbind(t, "keydown", this._keydownHandler, true), index_esm.event.unbind(t, "keyup", this._keyupHandler, true)), this._node = null;
};
i.prototype._fire = function(t) {
  this._eventBus.fire("keyboard." + t, { node: this._node });
};
i.prototype.addListener = function(t, e, n) {
  index_esm$1.isFunction(t) && (n = e, e = t, t = c), this._eventBus.on(n || r, t, e);
};
i.prototype.removeListener = function(t, e) {
  this._eventBus.off(e || r, t);
};
i.prototype.hasModifier = KeyboardUtil.hasModifier;
i.prototype.isCmd = KeyboardUtil.isCmd;
i.prototype.isShift = KeyboardUtil.isShift;
i.prototype.isKey = KeyboardUtil.isKey;
function k(t) {
  return t && (index_esm.matches(t, "input, textarea") || t.contentEditable === "true");
}
exports.default = i;
