import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React from "react";
import shortid from "shortid";
import isHotkey from "is-hotkey";
import { characterShortId } from "../utils";
var keyStack = {};
var listener = false;
var filter = ["TEXTAREA", "INPUT"];

var setupListener = function setupListener() {
  if (!listener && document.body) {
    document.body.addEventListener("keydown", function (e) {
      // We ignore all keyboard events coming from within `slateEditor` element and inputs.
      // @ts-ignore
      if (e.srcElement.dataset.slateEditor || filter.includes(e.srcElement.nodeName) || e.srcElement.getAttribute('contenteditable') === 'true') {
        return;
      }

      var matchedKey = Object.keys(keyStack).find(function (key) {
        return isHotkey(key, e);
      });

      if (matchedKey && keyStack[matchedKey].length > 0) {
        var item = keyStack[matchedKey][0];
        item.handler(e);
        e.stopPropagation();
      }
    });
    listener = true;
  }
};

var _addKeyHandler = function addKeyHandler(id, key, handler) {
  setupListener();
  keyStack[key] = keyStack[key] || [];

  if (!keyStack[key].find(function (item) {
    return item.id === id;
  })) {
    keyStack[key].unshift({
      id: id,
      handler: handler
    });
  }
};

var _removeKeyHandler = function removeKeyHandler(id, key) {
  if (!keyStack[key]) {
    return;
  }

  var index = keyStack[key].findIndex(function (item) {
    return item.id === id;
  });

  if (index >= 0) {
    keyStack[key].splice(index, 1);
  }
};

export function useKeyHandler() {
  characterShortId(shortid);

  var _React$useState = React.useState(shortid.generate()),
      _React$useState2 = _slicedToArray(_React$useState, 1),
      id = _React$useState2[0];

  return React.useMemo(function () {
    return {
      addKeyHandler: function addKeyHandler(key, handler) {
        _addKeyHandler(id, key, handler);
      },
      removeKeyHandler: function removeKeyHandler(key) {
        _removeKeyHandler(id, key);
      }
    };
  }, []);
}
//# sourceMappingURL=useKeyHandler.js.map