Created
December 10, 2019 17:24
-
-
Save SHND/01e7626f65e7c7ee54ebe5fc1653fca2 to your computer and use it in GitHub Desktop.
Assign keyboard shortkeys to document.
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
function noop(){}; | |
function createKeydownListener(key: string, modifiers: string[] = [], cb: Function = noop) { | |
const shouldHaveAlt: Boolean = modifiers.includes(keymap.ALT); | |
const shouldHaveCtrl: Boolean = modifiers.includes(keymap.CTRL); | |
const shouldHaveMeta: Boolean = modifiers.includes(keymap.META); | |
const shouldHaveShift: Boolean = modifiers.includes(keymap.SHIFT); | |
return function (event: KeyboardEvent) { | |
if (event.keyCode !== key.toUpperCase().charCodeAt(0)) | |
return; | |
if (shouldHaveAlt === event.altKey && | |
shouldHaveCtrl === event.ctrlKey && | |
shouldHaveMeta === event.metaKey && | |
shouldHaveShift === event.shiftKey) | |
{ | |
cb({key: key.toUpperCase(), modifiers, event}); | |
} | |
} | |
} | |
function keymap(key: string, modifiers: string[] = [], cb: Function = noop) { | |
if (key.length !== 1) | |
throw new Error('key parameter should be a string of length 1'); | |
modifiers.forEach((modifier) => { | |
if (! [keymap.ALT, keymap.CTRL, keymap.META, keymap.SHIFT].includes(modifier)) | |
throw new Error(`modifiers elements should be one of values '${keymap.ALT}', '${keymap.CTRL}', '${keymap.META}', '${keymap.SHIFT}'`) | |
}) | |
document.body.addEventListener('keydown', createKeydownListener(key, modifiers, cb)); | |
} | |
keymap.ALT = 'alt'; | |
keymap.CTRL = 'ctrl' | |
keymap.META = 'meta'; | |
keymap.SHIFT = 'shift'; | |
keymap('a', ['ctrl', 'shift'], (x: Object) => { | |
console.log(x) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment