A utility for matching keyboard events against Electron accelerator strings.
npm install keymatch
# or
pnpm add keymatch
# or
yarn add keymatchUse "CmdOrCtrl" to adapt your modifier key to "Command" (MacOS) or "Ctrl" depending on the platform. This can be combined with other modifiers like "Alt" or "Shift" using +:
import { keymatch } from 'keymatch';
document.addEventListener('keydown', (event) => {
if (keymatch(event, 'CmdOrCtrl+Shift+N')) {
event.preventDefault();
createNewFile();
}
});You can also handle single-letter matches that explicitly don't have modifiers. For example, this matches when "A" is pressed, but not when "Cmd+A" is pressed:
document.addEventListener('keydown', (event) => {
if (keymatch(event, 'A')) {
event.preventDefault();
selectAll();
}
});You can also create platform-specific matches by combining with the isMac() utility. This example uses Cmd for a MacOS shortcut, and Ctrl+Shift for other platforms:
import { keymatch, isMac } from 'keymatch';
document.addEventListener('keydown', (event) => {
if (keymatch(event, isMac() ? 'Cmd+K' : 'Ctrl+Shift+K')) {
event.preventDefault();
openCommandPalette();
}
});keymatch also supports Electron accelerator shorthands, like "Up" to represent "ArrowUp":
document.addEventListener('keydown', (event) => {
if (keymatch(event, 'CmdOrCtrl+Up')) {
event.preventDefault();
moveSelectionToTop();
}
});The library supports Electron-style accelerator strings:
CmdorCommand- Maps to metaKey (⌘ on Mac)CtrlorControl- Maps to ctrlKeyCmdOrCtrlorCommandOrControl- Uses Cmd on MacOS, Ctrl on other platformsAlt- Uses Option on MacOS, Alt on other platformsShift- Maps to shiftKeyMetaorSuper- Maps to metaKeyOption- Maps to Option on MacOS. Note this modifier will only match on MacOS! UseAltfor a platform-agnostic match.
Any key that can be captured by a KeyboardEvent, including:
- Letter keys:
A,B,C, etc. - Number keys:
1,2,3, etc. - Function keys:
F1,F2,F3, etc. - Special keys:
Space,Enter,Escape,Tab,Delete, etc. - Arrow keys:
Up,Down,Left,Right(also acceptsArrowUp,ArrowDown, etc.)
Checks if a KeyboardEvent matches the given accelerator string.
Parameters:
event- The web-standard KeyboardEvent to testaccelerator- The Electron-style accelerator string
Returns:
boolean- True if the event matches the accelerator
Utility function to detect if the current platform is MacOS.
Returns:
boolean- True if running on MacOS, false otherwise
MIT