hotkeys.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "stable"
  7. };
  8. const INVALID_HOTKEY = "Hotkey must have at least one modifier.";
  9. const { toJSON: jsonify, toString: stringify,
  10. isFunctionKey } = require("./keyboard/utils");
  11. const { register, unregister } = require("./keyboard/hotkeys");
  12. const Hotkey = exports.Hotkey = function Hotkey(options) {
  13. if (!(this instanceof Hotkey))
  14. return new Hotkey(options);
  15. // Parsing key combination string.
  16. let hotkey = jsonify(options.combo);
  17. if (!isFunctionKey(hotkey.key) && !hotkey.modifiers.length) {
  18. throw new TypeError(INVALID_HOTKEY);
  19. }
  20. this.onPress = options.onPress && options.onPress.bind(this);
  21. this.toString = stringify.bind(null, hotkey);
  22. // Registering listener on keyboard combination enclosed by this hotkey.
  23. // Please note that `this.toString()` is a normalized version of
  24. // `options.combination` where order of modifiers is sorted and `accel` is
  25. // replaced with platform specific key.
  26. register(this.toString(), this.onPress);
  27. // We freeze instance before returning it in order to make it's properties
  28. // read-only.
  29. return Object.freeze(this);
  30. };
  31. Hotkey.prototype.destroy = function destroy() {
  32. unregister(this.toString(), this.onPress);
  33. };