Created
August 6, 2022 00:27
-
-
Save ilhamgusti/6bef19c445579fa5a5f9ed8449f6ad51 to your computer and use it in GitHub Desktop.
utility to handle hotkeys
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
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