Allow multiple key bindings to be specified in an array

This commit is contained in:
Bryan Housel
2016-11-04 09:41:44 -04:00
parent eb7c56d310
commit 2273a6ed43
2 changed files with 37 additions and 22 deletions
+27 -22
View File
@@ -58,33 +58,37 @@ export function d3keybinding(namespace) {
return keybinding;
};
keybinding.on = function(code, callback, capture) {
var binding = {
event: {
keyCode: 0,
shiftKey: false,
ctrlKey: false,
altKey: false,
metaKey: false
},
capture: capture,
callback: callback
};
keybinding.on = function(codes, callback, capture) {
var arr = [].concat(codes);
for (var i = 0; i < arr.length; i++) {
var code = arr[i];
var binding = {
event: {
keyCode: 0,
shiftKey: false,
ctrlKey: false,
altKey: false,
metaKey: false
},
capture: capture,
callback: callback
};
code = code.toLowerCase().match(/(?:(?:[^+⇧⌃⌥⌘])+|[⇧⌃⌥⌘]|\+\+|^\+$)/g);
code = code.toLowerCase().match(/(?:(?:[^+⇧⌃⌥⌘])+|[⇧⌃⌥⌘]|\+\+|^\+$)/g);
for (var i = 0; i < code.length; i++) {
// Normalise matching errors
if (code[i] === '++') code[i] = '+';
for (var j = 0; j < code.length; j++) {
// Normalise matching errors
if (code[j] === '++') code[i] = '+';
if (code[i] in d3keybinding.modifierCodes) {
binding.event[d3keybinding.modifierProperties[d3keybinding.modifierCodes[code[i]]]] = true;
} else if (code[i] in d3keybinding.keyCodes) {
binding.event.keyCode = d3keybinding.keyCodes[code[i]];
if (code[j] in d3keybinding.modifierCodes) {
binding.event[d3keybinding.modifierProperties[d3keybinding.modifierCodes[code[j]]]] = true;
} else if (code[j] in d3keybinding.keyCodes) {
binding.event.keyCode = d3keybinding.keyCodes[code[j]];
}
}
}
bindings.push(binding);
bindings.push(binding);
}
return keybinding;
};
@@ -92,6 +96,7 @@ export function d3keybinding(namespace) {
return keybinding;
}
d3keybinding.modifierCodes = {
// Shift key, ⇧
'⇧': 16, shift: 16,
+10
View File
@@ -38,6 +38,16 @@ describe('d3.keybinding', function() {
expect(spy).to.have.been.calledOnce;
});
it('adds multiple bindings given an array of keys', function () {
d3.select(document).call(keybinding.on(['A','B'], spy));
happen.keydown(document, {keyCode: 65});
expect(spy).to.have.been.calledOnce;
happen.keydown(document, {keyCode: 66});
expect(spy).to.have.been.calledTwice;
});
it('does not dispatch when focus is in input elements by default', function () {
d3.select(document).call(keybinding.on('A', spy));