Small keyboard shortcut management for DOM-based applications
[![NPM version][npm-image]][npm-url]
[![NPM downloads][downloads-image]][downloads-url]
[![Build status][build-image]][build-url]
[![Build coverage][coverage-image]][coverage-url]
[![Bundle size][size-image]][size-url]
Small keyboard shortcut management for DOM-based applications.
npm install keyboard-manager --save
Keyboard Manager uses a simple queue, processed from newest to oldest, of listener functions to execute keyboard shortcuts. Keyboard event propagation stops when handled, but returning true
from the listener will continue propagation to older listeners.
import { Keyboard, stringifyKey, createShortcuts } from "keyboard-manager";
const keyboard = new Keyboard();
const shortcut1 = stringifyKey("cmd", "a"); //=> "65 91"
const shortcut2 = stringifyKey("cmd", "up"); //=> "38 91"
// Bind event listeners to all combos or specific keys using `createShortcuts`.
keyboard.addListener(
createShortcuts({
[shortcut1]: (e) => e.preventDefault(),
[shortcut2]: (e) => e.preventDefault(),
})
);
// Attach event listener to document.
window.addEventListener("keydown", keyboard.getHandler(), false);
// Mount a keyboard inside another listener.
new Keyboard().addListener(keyboard.getListener());
The stringifyKey(...keys)
function returns a consistent identity string for the keyboard shortcut. Internally, keyboardEventCombo(e)
will map keyboard events to the matching string.
The createShortcuts(map [, returnValue])
function accepts a map of keyboard shortcut functions and returns a single listener function for mounting with keyboard.addListener(callback)
.
Tip: returnValue
defaults to true
for propagation. Setting to false
will stop propagation, effectively creating a new shortcut “scope”. This is useful for features, such as full-screen modals or recording keyboard shortcuts, where key presses should not interact with the rest of the document.
Wrap any listener in filterInputEvent(callback)
to automatically ignore and propagate events originating from an input-like element (<input />
, <select ></select>
, `