-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
keyboard-commands.js
88 lines (78 loc) · 3.01 KB
/
keyboard-commands.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
(function () {
'use strict';
var KeyboardCommands = MediumEditor.Extension.extend({
name: 'keyboard-commands',
/* KeyboardCommands Options */
/* commands: [Array]
* Array of objects describing each command and the combination of keys that will trigger it
* Required for each object:
* command [String] (argument passed to editor.execAction())
* key [String] (keyboard character that triggers this command)
* meta [boolean] (whether the ctrl/meta key has to be active or inactive)
* shift [boolean] (whether the shift key has to be active or inactive)
* alt [boolean] (whether the alt key has to be active or inactive)
*/
commands: [
{
command: 'bold',
key: 'B',
meta: true,
shift: false,
alt: false
},
{
command: 'italic',
key: 'I',
meta: true,
shift: false,
alt: false
},
{
command: 'underline',
key: 'U',
meta: true,
shift: false,
alt: false
}
],
init: function () {
MediumEditor.Extension.prototype.init.apply(this, arguments);
this.subscribe('editableKeydown', this.handleKeydown.bind(this));
this.keys = {};
this.commands.forEach(function (command) {
var keyCode = command.key.charCodeAt(0);
if (!this.keys[keyCode]) {
this.keys[keyCode] = [];
}
this.keys[keyCode].push(command);
}, this);
},
handleKeydown: function (event) {
var keyCode = MediumEditor.util.getKeyCode(event);
if (!this.keys[keyCode]) {
return;
}
var isMeta = MediumEditor.util.isMetaCtrlKey(event),
isShift = !!event.shiftKey,
isAlt = !!event.altKey;
this.keys[keyCode].forEach(function (data) {
if (data.meta === isMeta &&
data.shift === isShift &&
(data.alt === isAlt ||
undefined === data.alt)) { // TODO deprecated: remove check for undefined === data.alt when jumping to 6.0.0
event.preventDefault();
event.stopPropagation();
// command can be a function to execute
if (typeof data.command === 'function') {
data.command.apply(this);
}
// command can be false so the shortcut is just disabled
else if (false !== data.command) {
this.execAction(data.command);
}
}
}, this);
}
});
MediumEditor.extensions.keyboardCommands = KeyboardCommands;
}());