Last active
April 1, 2021 01:33
-
-
Save izelnakri/80d33d1e75ee23d9e055075216a26db4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let stdin = process.stdin; | |
| stdin.setRawMode(true); | |
| stdin.resume(); | |
| stdin.setEncoding('utf8'); | |
| let targetInputs = {}; | |
| let inputs = []; | |
| stdin.on('data', function(key){ | |
| if (key === '\u0003') { | |
| process.exit(); // so node process doesnt trap Control-C | |
| } | |
| inputs.shift(); | |
| inputs.push(key); | |
| let inputString = inputs.join(''); | |
| let targetListener = targetInputs[inputString.toUpperCase()]; | |
| if (targetListener && targetListenerConformsToCase(targetListener, inputString)) { | |
| targetListener.closure(inputString); | |
| inputs.fill(undefined); | |
| } | |
| }); | |
| export default function listenToKeyboardKey(inputString, closure, options = { caseSensitive: false }) { | |
| if (inputString.length > inputs.length) { | |
| inputs.length = inputString.length; | |
| } | |
| targetInputs[inputString.toUpperCase()] = Object.assign(options, { closure }); | |
| } | |
| function targetListenerConformsToCase(targetListener, inputString) { | |
| if (targetListener.caseSensitive) { | |
| return inputString === inputString.toUpperCase(); | |
| } | |
| return true; | |
| } | |
| // USAGE: | |
| // import listenToKeyboardKey from './lib/utils/listen-to-keyboard-key.js'; | |
| // listenToKeyboardKey('ql', (matchedKey) => console.log('ql called!')); | |
| // listenToKeyboardKey('qx', (matchedKey) => console.log('qx CALLED!')); | |
| // listenToKeyboardKey('QA', (matchedKey) => console.log('qa CALLED!'), { caseSensitive: true }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment