import { isFunction as F } from "../../../../min-dash/dist/index.esm.mjs";
import { closest as D, event as m, matches as y } from "../../../../min-dom/dist/index.esm.mjs";
import { isCmd as f, hasModifier as s, isShift as a, isKey as i$1 } from "./KeyboardUtil.mjs";
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 (!f(t))
    return true;
  var e = this._getAllowedModifiers(t.target);
  return e.indexOf(t.key) === -1;
};
i.prototype._getAllowedModifiers = function(t) {
  var e = D(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, m.bind(t, "keydown", this._keydownHandler, true), m.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"), m.unbind(t, "keydown", this._keydownHandler, true), m.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) {
  F(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 = s;
i.prototype.isCmd = f;
i.prototype.isShift = a;
i.prototype.isKey = i$1;
function k(t) {
  return t && (y(t, "input, textarea") || t.contentEditable === "true");
}
export {
  i as default
};
