-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathkeyHandler.js
More file actions
280 lines (257 loc) · 8.45 KB
/
Copy pathkeyHandler.js
File metadata and controls
280 lines (257 loc) · 8.45 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* Swap keys and values of a plain object.
* Used to build reverse lookup maps (value → key).
* @param {object} map - The object to invert
* @returns {object} A new object with keys and values swapped
*/
function invertMap (map) {
return Object.fromEntries(Object.entries(map).map(([k, v]) => [v, k]));
}
/**
*** Extending your module to work with MMM-KeyBindings *****
*
* Use the code below in your module to accept key press
* events generated by the MMM-KeyBindings module.
*
* These is a basic implementation, expand as needed.
*
*/
class KeyHandler {
/**
* init()
* Is called when the module is instantiated.
* @param {string} name - Module name
* @param {object} config - Module configuration
*/
init (name, config) {
this.name = name;
this.config = {
...this.defaults,
...config
};
// Give each instance its own key map so handlers never share state.
this.config.map = {...this.config.map};
this.currentMode = "DEFAULT";
// Build reverse lookup: MMM-KeyBindings key name → local name
this.reverseMap = invertMap(this.config.map);
}
/**
* validate
*
* Add function below to your moduleName.js
* Add `if (this.validate(notification, payload)) { return; }`
* to the first line of module's 'notificationReceived' function.
*
* If your module does not already override the function, use the snippet below
* notificationReceived: function(notification, payload, sender) {
* if (this.validate(notification, payload)) { return; }
* },
*
* @param {string} notification - Notification name
* @param {object} payload - Notification payload
* @returns {boolean} - Whether the notification was handled
*/
validate (notification, payload) {
// Handle KEYPRESS mode change events from the MMM-KeyBindings Module
if (notification === "KEYPRESS_MODE_CHANGED") {
this.currentMode = payload;
return true;
}
// Uncomment line below for diagnostics & to confirm keypresses are being received
if (notification === "KEYPRESS" && this.debug) {
Log.debug("[KeyHandler]", payload);
}
// Validate Keypresses
if (notification === "KEYPRESS" && this.currentMode === this.config.mode) {
if (this.config.multiInstance && payload.sender !== payload.instance) {
return false; // Wrong Instance
}
if (!(payload.keyName in this.reverseMap)) {
return false; // Not a key we listen for
}
this.validKeyPress(payload);
return true;
}
// Test for focus key pressed and need to take focus:
if (notification === "KEYPRESS" && "takeFocus" in this.config) {
if (this.currentMode === this.config.mode) {
return false; // Already have focus.
}
if (this.config.multiInstance && payload.sender !== payload.instance) {
return false; // Wrong Instance
}
if (typeof this.config.takeFocus === "object") {
if (
this.config.takeFocus.keyPress !== payload.keyPress ||
this.config.takeFocus.keyState !== payload.keyState
) {
return false; // Wrong keyName/KeyPress Combo
}
} else if (
typeof this.config.takeFocus === "string" &&
payload.keyName !== this.config.takeFocus
) {
return false; // Wrong Key;
}
this.focusReceived();
return true;
}
return false;
}
/**
* focusReceived
*
* Function is called when a valid take focus key press
* has been received and is ready for action
*
*/
focusReceived () {
Log.info(`${this.name} HAS FOCUS!`);
this.sendNotification("KEYPRESS_MODE_CHANGED", this.config.mode);
this.currentMode = this.config.mode;
this.onFocus();
}
/**
* releaseFocus
*
* Call this function when ready to release focus
*
* Modify this function to do what you need in your module
* whenever you're ready to give up focus.
*
*/
releaseFocus () {
Log.info(`${this.name} HAS RELEASED FOCUS!`);
this.sendNotification("KEYPRESS_MODE_CHANGED", "DEFAULT");
this.currentMode = "DEFAULT";
this.onFocusReleased();
}
/** ************** SUBCLASSABLE FUNCTIONS ****************/
/** * Pass your functions in the KeyHandler definition ***/
/**
* validKeyPress
*
* Add function below to your moduleName.js
* Function is called when a valid key press for your module
* has been received and is ready for action
* Modify this function to do what you need in your module
* whenever a valid key is pressed.
*
* @param {object} kp - Key press payload
*/
validKeyPress (kp) {
Log.debug("[KeyHandler] Key pressed:", kp.keyName);
// Example for responding to "Left" and "Right" arrow
if (kp.keyName === this.config.map.Right) {
Log.debug("[KeyHandler] RIGHT KEY WAS PRESSED!");
} else if (kp.keyName === this.config.map.Left) {
Log.debug("[KeyHandler] LEFT KEY WAS PRESSED!");
}
}
/**
* onFocus
* Subclass this method in your KeyHandler definition to do something
* when focus has been received.
* Modify this function to do what you need in your module
* whenever focus is received.
*/
onFocus () {
// Override in subclass
Object.hasOwn(this, "name");
}
/**
* onFocusReleased
* Subclass this method in your KeyHandler definition to do something
* when focus has been released.
* Modify this function to do what you need in your module
* whenever focus is released.
*/
onFocusReleased () {
// Override in subclass
Object.hasOwn(this, "name");
}
/**
* sendNotification
* Subclassed to provide reference to module's send function.
*/
sendNotification () {
// Override in subclass
Object.hasOwn(this, "name");
}
}
/**
* Default key binding configuration shared by all handlers.
* A registered definition may override any of these; each created handler
* gets its own `config` in init(), so instances never share state.
*/
KeyHandler.prototype.defaults = {
// The "mode" this handler responds to.
mode: "DEFAULT",
// Map your local key names to MMM-KeyBindings key names.
map: {
Right: "ArrowRight",
Left: "ArrowLeft"
},
/*
* multiInstance: true -> bluetooth device controls only the local server instance.
* multiInstance: false -> bluetooth device controls all instances of this module.
*/
multiInstance: true,
/*
* Set "takeFocus" to a key (string) or { keyName, keyState } to grab focus so
* other modules stop reacting to key presses until releaseFocus() is called.
*/
takeFocus: "Enter",
debug: false
};
KeyHandler.definitions = {};
KeyHandler.legacyRegistrationWarned = false;
/**
* Register a key handler definition.
* Accepts either a KeyHandler subclass (modern) or a plain-object mixin
* (legacy). Mixins are normalized into a subclass so their methods live on
* the prototype and every created handler is an isolated instance.
* @param {string} name - Handler name
* @param {Function|object} definition - KeyHandler subclass or mixin object
*/
KeyHandler.register = function register (name, definition) {
if (typeof definition === "function") {
// Modern: a KeyHandler subclass / constructor.
KeyHandler.definitions[name] = definition;
return;
}
if (!KeyHandler.legacyRegistrationWarned && typeof Log !== "undefined" && typeof Log.warn === "function") {
Log.warn("MMM-KeyBindings: registering KeyHandler definitions as plain objects is deprecated. Please migrate to a KeyHandler subclass.");
KeyHandler.legacyRegistrationWarned = true;
}
/*
* Legacy: a plain-object mixin. Build a prototype (once) that inherits from
* KeyHandler and carries the definition's methods, so every created handler
* is a fresh, isolated instance without cloning.
*/
KeyHandler.definitions[name] = Object.assign(
Object.create(KeyHandler.prototype),
definition
);
};
/**
* Create a new key handler instance.
* @param {string} name - Handler name
* @param {object} config - Handler configuration
* @returns {KeyHandler|undefined} New instance, or undefined if unregistered
*/
KeyHandler.create = function create (name, config) {
const definition = KeyHandler.definitions[name];
if (!definition) {
return undefined;
}
let handler;
if (typeof definition === "function") {
const Handler = definition;
handler = new Handler();
} else {
handler = Object.create(definition);
}
handler.init(name, config);
return handler;
};