Skip to content

Instantly share code, notes, and snippets.

@SHND
Created December 10, 2019 17:24
Show Gist options
  • Save SHND/01e7626f65e7c7ee54ebe5fc1653fca2 to your computer and use it in GitHub Desktop.
Save SHND/01e7626f65e7c7ee54ebe5fc1653fca2 to your computer and use it in GitHub Desktop.
Assign keyboard shortkeys to document.
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