Skip to content

Instantly share code, notes, and snippets.

@ilhamgusti
Created August 6, 2022 00:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilhamgusti/6bef19c445579fa5a5f9ed8449f6ad51 to your computer and use it in GitHub Desktop.
Save ilhamgusti/6bef19c445579fa5a5f9ed8449f6ad51 to your computer and use it in GitHub Desktop.
utility to handle hotkeys
export function parseHotkey(hotkey) {
const keys = hotkey
.toLowerCase()
.split('+')
.map((part) => part.trim());
const modifiers = {
alt: keys.includes('alt'),
ctrl: keys.includes('ctrl'),
meta: keys.includes('meta'),
mod: keys.includes('mod'),
shift: keys.includes('shift'),
};
const restrictedKeys = ['alt', 'ctrl', 'meta', 'shift', 'mod'];
const freeKey = keys.find((key) => !restrictedKeys.includes(key));
return {
...modifiers,
key: freeKey,
};
}
function isExactHotkey(hotkey, event) {
const { alt, ctrl, key, meta, mod, shift } = hotkey;
const { altKey, ctrlKey, key: pressedKey, metaKey, shiftKey } = event;
if (alt !== altKey) {
return false;
}
if (mod) {
if (!ctrlKey && !metaKey) {
return false;
}
} else {
if (ctrl !== ctrlKey) {
return false;
}
if (meta !== metaKey) {
return false;
}
}
if (shift !== shiftKey) {
return false;
}
if (
key &&
(pressedKey.toLowerCase() === key.toLowerCase() ||
event.code.replace('Key', '').toLowerCase() === key.toLowerCase())
) {
return true;
}
return false;
}
export function getHotkeyMatcher(hotkey) {
return (event) => isExactHotkey(parseHotkey(hotkey), event);
}
export function getHotkeyHandler(hotkeys) {
return (event) => {
hotkeys.forEach(([hotkey, handler]) => {
if (getHotkeyMatcher(hotkey)(event.nativeEvent)) {
event.preventDefault();
handler(event);
}
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment