@julionav/tinykeys
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

tinykeys

A tiny (~400 B) & modern library for keybindings. See Demo

Install

npm install --save tinykeys

Usage

import tinykeys from "tinykeys"

tinykeys(window, {
  "Shift+D": () => {
    alert("The 'Shift' and 'd' keys were pressed at the same time")
  },
  "y e e t": () => {
    alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
  },
  "$mod+KeyD": () => {
    alert("Either 'Control+d' or 'Meta+d' were pressed")
  },
})

Keybinding Syntax

Keybindings are made up of a sequence of presses.

A press can be as simple as a single key which matches against KeyboardEvent.code and KeyboardEvent.key (case-insensitive).

// Matches `event.key`:
"d"
// Matches: `event.code`:
"KeyD"

Presses can optionally be prefixed with modifiers which match against any valid value to KeyboardEvent.getModifierState().

"Control+d"
"Meta+d"
"Shift+D"
"Alt+KeyD"
"Meta+Shift+D"

There is also a special $mod modifier that makes it easy to support cross platform keybindings:

  • Mac: $mod = Meta (⌘)
  • Windows/Linux: $mod = Control
"$mod+D" // Meta/Control+D
"$mod+Shift+D" // Meta/Control+Shift+D

Keybinding Sequences

Keybindings can also consist of several key presses in a row:

"g i" // i.e. "Go to Inbox"
"g a" // i.e. "Go to Archive"
"ArrowUp ArrowUp ArrowDown ArrowDown ArrowLeft ArrowRight ArrowLeft ArrowRight B A"

Each press can optionally be prefixed with modifier keys:

"$mod+K $mod+1" // i.e. "Toggle Level 1"
"$mod+K $mod+2" // i.e. "Toggle Level 2"
"$mod+K $mod+3" // i.e. "Toggle Level 3"

Each press in the sequence must be pressed within 1000ms of the last.

Package Sidebar

Install

npm i @julionav/tinykeys

Weekly Downloads

0

Version

1.0.3

License

MIT

Unpacked Size

33.8 kB

Total Files

12

Last publish

Collaborators

  • julionav