Description
The code captures keypress events that do not occur in a text field and dispatches on the properties of a $command
object in the application execution context. I have provided a sketch of the execution context in order to assist your review of the code of interest.
Execution Context Sketch
This is a sketch the dependencies of the code for review. The larger context is a user side script running in Firefox using Greasemonkey. The Greasemonkey script is part of a suite of user side tools. This code is not intended for review.
(function () {
// There is additional application context for making this global
window.$snatch = function ($class) {
return document.getElementsByClassName($class)[0];
};
// There is additional application context for making this global
window.$commands = {};
/* Define links */
// There is additional application context supporting defining links
// independently of the code utilizing them.
var yes = $snatch('yes');
var maybe = $snatch('rmaybe');
var no = $snatch('no');
/* Create Commands */
// There is additional application context that makes multiple
// keypresses a more practical approach than it might appear
$commands.ccc = () => { close(); };
$commands.yyy = () => { location = yes };
$commands.mmm = () => { location = maybe };
$commands.nnn = () => { location = no };
})();
JavaScript for Review
This code for handling key events originated with a copy-paste of this example on MDN. The modifications have been primarily to implement dispatch.
/* Key Event Handler */
(function () {
const commandLength = 3;
var nOffset = 0;
var keyQueue = "";
// Add a new property listing all the properties
$commands.keys = Object.keys($commands);
document.onkeypress = function (oPEvt) {
var oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase();
if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; }
if (keyQueue.length < commandLength) {
keyQueue += String.fromCharCode(nChr);
}
else if (keyQueue.length == commandLength) {
if ($commands.keys.includes(keyQueue)) {
$commands[keyQueue]();
keyQueue = "";
}
else {
keyQueue = keyQueue.slice(-2);
}
}
else { alert("too many characters!"); }
return true;
}
})();