npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

key-controller

v2.0.7

Published

A library that abstracts handling keyboard controls in the browser

Downloads

84

Readme

key-controller

npm version Build Status Coverage Status install size

key-controller is a library that abstracts handling keydown and keyup events in the browser, making it easier to change keyboard controls dynamically.

key-controller uses KeyboardEvent.key for controller.register(...). We recommend using https://keycode.info/ for looking up .key property of specific key's event.

Installation

npm install key-controller --save-dev

If you don't use a module bundler, you can include the minified file which exports the KeyController global:

<script src="unpkg.com/key-controller/umd/key-controller.min.js" defer></script>

Concepts

Keyboard controls usually map to an abstract action, eg. Spacebar -> Jump. To make a controller, you pass in generator function and a context:

const generator = ctx => ({
  jump () {
    ctx.jump()
  }
})
const player = {
  jump () {
    console.log('jump!')
  }
}

const controller = new KeyController(generator, player)

Your generator function will be called with the contexts that were passed to KeyController and should return a JavaScript object containing abstract actions.

To map keyboard controls to the actions, you call controller.register(mycontrols):

const controls = {
  jump: ' '
}

controller.register(controls)

// Pressing Spacebar will now call player.jump()

Usage

import KeyController from 'key-controller'

const billyTheGoblin = {
  x: 0,
  isDancing: false
}

const generator = goblin => {
  moveLeft () {
    goblin.x -= 1
  },
  moveRight () {
    goblin.x += 1
  },
  toggleDance: {
    keyup () {
      goblin.isDancing = false
    },
    keydown () {
      goblin.isDancing = true
    }
  },
}
const controls = {
  moveLeft: ['ArrowLeft', 'a'],
  moveRight: ['ArrowRight', 'd'],
  toggleDance: 'alt+d'
}
const controller = new KeyController(generator, billyTheGoblin)

controller.register(controls)

API

new KeyController(generator, [...context])

Creates a "controller", an object that stores a collection of abstract actions to be trigger by the controls in controller.register(mycontrols).

generator

Type: ([...Any]) => Object

A function that takes an arbitrary number of arguments, and returns an object with abstract actions. An action name can map to a function or an object that contains a keydown and/or keyup function. If the action name maps to a function, it will be triggered on keydown.

The functions will always be passed its respective KeyboardEvent when the action is triggered. You probably won't need to use it though.

const generator = (cat, dog) => ({
  patDog (e) {
    console.log('Keyboard event:', e)
    console.log('You\'re patting the dog!')
    dog.woof()
  },
  patCat () {
    keydown () {
      console.log('You started patting the cat')
    },
    keyup () {
      console.log('You stopped patting the cat; it\'s now upset :c')
      cat.ragequit()
    }
  }
})

There is a special action name, _, which is triggered on every keypress (i.e. you don't need to specify it in your control object); it's intended for debugging purposes, such as logging the contexts.

context

Type: Any

An arbitrary number of arguments that will all be passed to the generator function (useful if you want your generator function in a separate file, which doesn't have access to the desired scope.

controller.register(controls)

Registers controls to the abstract actions defined in the generator function.

controls

Type: Object

A mapping of the abstract action names to keyboard controls, e.g.

const controls = {
  left: 'a',
  right: 'd'
}

An abstract action can map to multiple controls using arrays:

// Jump when "w" or the Spacebar is pressed
const controls = {
  jump: ['w', ' ']
}

"Modifier keys", ie. meta, ctrl, alt can be prepended using + to check whether they're being held down on keypress:

// Quit when the user press q while holding ctrl
// Note that the order and case of the modifier keys does not matter, but the "primary key" must be the last character
const controls = {
  quit: 'ctrl+q',
  rageQuit: 'cTlR+aLT+q'
}

Note that shift is NOT supported; instead, just enter the character you want to trigger the event on. For example, rather than doing shift+w, do W:

// 'W' refers to shift+w
const controls = {
  jump: 'w',
  jumpSuperHigh: 'W'
}

controller.unbind()

Unbinds the controller from the DOM. Calls document.removeEventListener(...) under the hood.

controller.bind()

Binds the controller from the DOM. Calls document.addEventListener(...) under the hood.