Skip to content

Instantly share code, notes, and snippets.

@ieda
Created February 26, 2018 13:03
Show Gist options
  • Save ieda/7c47876d9fb42c63d6e3f33716714b73 to your computer and use it in GitHub Desktop.
Save ieda/7c47876d9fb42c63d6e3f33716714b73 to your computer and use it in GitHub Desktop.
KeyboardJSでキーシーケンスに対応してみる実験。Mousetrapで本来の目的が果たせることが分かったため中断。
// sequenceStr: "a >> b" for press A(, release A), press B, onKeyDownCallback.
// TODO: Support onKeyUpCallback.
// INFO: Timeout is only to break sequence. Wrong key press does NOT break sequence.
function bindSequence(sequenceStr, onKeyDownCallback, onKeyUpCallback=null, timeoutToNextKey=500) {
var sequenceDelimiter = ">>";
var keys = sequenceStr
.split(sequenceDelimiter)
.map(el => el.trim());
//console.log("bindSequence", keys);
var baseContext = keyboardJS.getContext();
keys.reduceRight(function (prev, key, index, target) {
return function (_seqStr) {
// Only for first sequence key.
var sequenceStarted = false;
var f = function (e) {
e.preventRepeat();
// Avoid multi call with repeating first sequence key pressing
if (sequenceStarted) return;
sequenceStarted = true;
prev(sequenceStr);
if (index == 0) {
setTimeout(function () {
sequenceStarted = false;
}, timeoutToNextKey);
}
else {
keyboardJS.withContext(baseContext, function () {
keyboardJS.unbind(key, f, null);
});
}
};
// Without onKeyUpCallback, preventRepeat will not be unlocked.
// So only once call next per pressing sequence first key.
keyboardJS.withContext(baseContext, function () {
keyboardJS.bind(key, f, index == 0 ? function (e) {} : null);
});
// timeout then unbind
if (index != 0) {
setTimeout(function () {
keyboardJS.withContext(baseContext, function () {
keyboardJS.unbind(key, f, null);
});
}, timeoutToNextKey);
}
}
}, onKeyDownCallback ? onKeyDownCallback : () => null)();
}
bindSequence('w >> t >> f', function(seqStr) {
console.log(seqStr);
keyboardJS.setContext('wtf');
});
keyboardJS.withContext('wtf', function() {
bindSequence('w >> w >> e >> w >> w >> e', seqStr => console.log(seqStr, "っうぇっうぇ"));
});
bindSequence('e >> e', null, seqStr => alert(seqStr));
keyboardJS.bind('v > c', function (e) {
console.log('v > c is pressed');
e.preventRepeat();
}, function (e) {
console.log('v > c is released');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment