Hotkeyz
A small (3.2kB min / 1.5kB gzip) dev-friendly keyboard event callback helper.
Installation
npm install hotkeyz
Building the listener
The hotkeyz
function expects a config object as parameter and will return a function that you can use as a callback for keyboard events.
The config object lists the different combos you'd like to react to, they should use valid combos as keys and event callbacks as value.
Combos are composed of modifiers and actual keys and should respect the following rules:
- simple key:
{key}
- modifier:
{modifier} - {key}
- many modifiers:
{modifier} + {modifier} [+ ...] - {key}
- many combos:
{combo}, {combo} [, ...]
- combo sequence (waits up to 1s between each combo):
{combo} {combo} [...]
Valid modifiers are:
meta
ctrl
alt
shift
const callback =
Using the callback
Hotkeyz only creates a function that acts as a switch for key events, it doesn't do anything DOM related so it'll be your job to add/remove it as an event listener.
Every key event that has a matching hotkey will be captured by the callback: it won't bubble up and its default action will be prevented. For any other key stroke, the browser will behave as it normally would.
Vanilla
const callback = document
React
Component state = counter: 0 { this } handleKey = { return <div tabIndex="0" onKeyDown=thishandleKey> thisstatecounter </div> }
Key detection
Hotkeys relies on two methods to match your hotkeys with the emitted keyboard event, providing you two ways of describing your hotkeys:
- based on
event.key
: use the actual character you want your listener to react to - based on
event.keyCode
: use the regular name of the key on your keyboard
keyCode
detection is based on keycode so you can name your keys using strings that could be generated by this lib.
Note that both methods can react to a same key stroke. If you create 2 hotkeys that do that, both their callbacks will be invoked.
If you use the key
method, remember that some characters already imply a combination of modifiers. Due to that combination being quite specific to the client, the key
method will simply ignore modifiers for them. If you really want to specify a complex combination, you can still rely on the keyCode
method.
When describing a sequence, you should stick to one of the two methods, hotkeyz won't react to a rule with mixed syntaxes.
As the characters ,
, +
and -
are reserved by the hotkey syntax, you may not use them directly as keys. If you want to do so, you should use their aliases comma
, plus
and minus