michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: module.metadata = { michael@0: "stability": "stable" michael@0: }; michael@0: michael@0: const INVALID_HOTKEY = "Hotkey must have at least one modifier."; michael@0: michael@0: const { toJSON: jsonify, toString: stringify, michael@0: isFunctionKey } = require("./keyboard/utils"); michael@0: const { register, unregister } = require("./keyboard/hotkeys"); michael@0: michael@0: const Hotkey = exports.Hotkey = function Hotkey(options) { michael@0: if (!(this instanceof Hotkey)) michael@0: return new Hotkey(options); michael@0: michael@0: // Parsing key combination string. michael@0: let hotkey = jsonify(options.combo); michael@0: if (!isFunctionKey(hotkey.key) && !hotkey.modifiers.length) { michael@0: throw new TypeError(INVALID_HOTKEY); michael@0: } michael@0: michael@0: this.onPress = options.onPress && options.onPress.bind(this); michael@0: this.toString = stringify.bind(null, hotkey); michael@0: // Registering listener on keyboard combination enclosed by this hotkey. michael@0: // Please note that `this.toString()` is a normalized version of michael@0: // `options.combination` where order of modifiers is sorted and `accel` is michael@0: // replaced with platform specific key. michael@0: register(this.toString(), this.onPress); michael@0: // We freeze instance before returning it in order to make it's properties michael@0: // read-only. michael@0: return Object.freeze(this); michael@0: }; michael@0: Hotkey.prototype.destroy = function destroy() { michael@0: unregister(this.toString(), this.onPress); michael@0: };