Add keydown_util.js module.

This is a pretty thin abstraction to prevent having to put
magic numbers in code, doing the which/keyCode hack, and remembering
to all preventDefault.

Hopefully we'll expand it to handle things like shift/alt keys
for components that want their own keyboard handlers (vs. going
through hotkey.js).
This commit is contained in:
Steve Howell 2018-04-04 10:36:49 -04:00 committed by Tim Abbott
parent c06565d909
commit bd591424e2
5 changed files with 58 additions and 10 deletions

View File

@ -33,6 +33,7 @@
"server_events": false,
"server_events_dispatch": false,
"message_scroll": false,
"keydown_util": false,
"info_overlay": false,
"ui": false,
"ui_report": false,

View File

@ -1,9 +1,12 @@
set_global('i18n', global.stub_i18n);
zrequire('keydown_util');
zrequire('components');
var LEFT_KEY = { which: 37 };
var RIGHT_KEY = { which: 39 };
var noop = function () {};
var LEFT_KEY = { which: 37, preventDefault: noop };
var RIGHT_KEY = { which: 39, preventDefault: noop };
(function test_basics() {
var keydown_f;

View File

@ -68,12 +68,14 @@ exports.toggle = (function () {
function maybe_go_left() {
if (meta.idx > 0) {
select_tab(meta.idx - 1);
return true;
}
}
function maybe_go_right() {
if (meta.idx < opts.values.length - 1) {
select_tab(meta.idx + 1);
return true;
}
}
@ -83,14 +85,12 @@ exports.toggle = (function () {
select_tab(idx);
});
meta.$ind_tab.keydown(function (e) {
var key = e.which || e.keyCode;
if (key === 37) {
maybe_go_left();
} else if (key === 39) {
maybe_go_right();
}
keydown_util.handle({
elem: meta.$ind_tab,
handlers: {
left_arrow: maybe_go_left,
right_arrow: maybe_go_right,
},
});
if (typeof opts.selected === "number") {

43
static/js/keydown_util.js Normal file
View File

@ -0,0 +1,43 @@
var keydown_util = (function () {
var exports = {};
/*
See hotkey.js for handlers that are more app-wide.
*/
var keys = {
37: 'left_arrow',
38: 'up_arrow',
39: 'right_arrow',
40: 'down_arrow',
};
exports.handle = function (opts) {
opts.elem.keydown(function (e) {
var key = e.which || e.keyCode;
var key_name = keys[key];
if (!key_name) {
return;
}
if (!opts.handlers[key_name]) {
return;
}
var handled = opts.handlers[key_name]();
if (handled) {
e.preventDefault();
}
});
};
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = keydown_util;
}

View File

@ -1023,6 +1023,7 @@ JS_SPECS = {
'js/loading.js',
'js/util.js',
'js/dynamic_text.js',
'js/keydown_util.js',
'js/lightbox_canvas.js',
'js/rtl.js',
'js/dict.js',