Created
December 10, 2019 17:27
-
-
Save SHND/52815400bc8c8aaaa0ed0faa7faf5b0f to your computer and use it in GitHub Desktop.
Assign keyboard shortcuts 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
"use strict"; | |
function noop() { } | |
; | |
function createKeydownListener(key, modifiers = [], cb = noop) { | |
const shouldHaveAlt = modifiers.includes(keymap.ALT); | |
const shouldHaveCtrl = modifiers.includes(keymap.CTRL); | |
const shouldHaveMeta = modifiers.includes(keymap.META); | |
const shouldHaveShift = modifiers.includes(keymap.SHIFT); | |
return function (event) { | |
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, modifiers = [], cb = 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) => { | |
console.log(x); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment