A utility for matching keyboard events against Electron accelerator strings.
npm install keymatch
# or
pnpm add keymatch
# or
yarn add keymatch
Use "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:
-
Cmd
orCommand
- Maps to metaKey (⌘ on Mac) -
Ctrl
orControl
- Maps to ctrlKey -
CmdOrCtrl
orCommandOrControl
- Uses Cmd on MacOS, Ctrl on other platforms -
Alt
- Uses Option on MacOS, Alt on other platforms -
Shift
- Maps to shiftKey -
Meta
orSuper
- Maps to metaKey -
Option
- Maps to Option on MacOS. Note this modifier will only match on MacOS! UseAlt
for 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 test -
accelerator
- 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