|
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 |
|
5 "use strict"; |
|
6 |
|
7 module.metadata = { |
|
8 "stability": "stable" |
|
9 }; |
|
10 |
|
11 const INVALID_HOTKEY = "Hotkey must have at least one modifier."; |
|
12 |
|
13 const { toJSON: jsonify, toString: stringify, |
|
14 isFunctionKey } = require("./keyboard/utils"); |
|
15 const { register, unregister } = require("./keyboard/hotkeys"); |
|
16 |
|
17 const Hotkey = exports.Hotkey = function Hotkey(options) { |
|
18 if (!(this instanceof Hotkey)) |
|
19 return new Hotkey(options); |
|
20 |
|
21 // Parsing key combination string. |
|
22 let hotkey = jsonify(options.combo); |
|
23 if (!isFunctionKey(hotkey.key) && !hotkey.modifiers.length) { |
|
24 throw new TypeError(INVALID_HOTKEY); |
|
25 } |
|
26 |
|
27 this.onPress = options.onPress && options.onPress.bind(this); |
|
28 this.toString = stringify.bind(null, hotkey); |
|
29 // Registering listener on keyboard combination enclosed by this hotkey. |
|
30 // Please note that `this.toString()` is a normalized version of |
|
31 // `options.combination` where order of modifiers is sorted and `accel` is |
|
32 // replaced with platform specific key. |
|
33 register(this.toString(), this.onPress); |
|
34 // We freeze instance before returning it in order to make it's properties |
|
35 // read-only. |
|
36 return Object.freeze(this); |
|
37 }; |
|
38 Hotkey.prototype.destroy = function destroy() { |
|
39 unregister(this.toString(), this.onPress); |
|
40 }; |