A small js library that converts key hits to commands and allows remapping keys
-
Bring the library into your project:
npm install github:rocket-boots/keyboard-commander(optionally add a#tagto the end, e.g.,#v0.2.0) -
Import into one of your components
import { KeyboardCommander } from 'keyboard-commander';
-
Create a mapping object between keys and a set of commands that your app or game will interpret later
const mapping = { w: 'wear/wield', e: 'eat', r: 'read', Tab: 'next target', Enter: 'action', };
Note that keys are case sensitive, and the commands can be anything - a string, function, object, etc.
-
Create a function to handle the commands
const handleCommand = (command) => { /* do something based on the command received */ };
-
Instantiate a keyboard commander object, passing in the mapping
const kbCommander = new KeyboardCommander(mapping); kbCommander.on('command', handleCommand); // Alternatively: // const kbCommander = new KeyboardCommander(mapping, { command: handleCommand });
onwill set up an observer to listen for an event (arg 1) and then run a listener function (arg 2)- There are currently four events:
command,missingCommand,mount,unmount,mapping
- There are currently four events:
offwill remove an event and listener
setMappingtakes a mapping object as an argument and sets it internally, overwriting whatever mapping currently existsmapKeymaps an individual key (arg 1) to a command (arg 2)mapUnmappedKeyonly maps a key to a command if it is not set alreadyunmapKeyremove a key mapping
triggerCommandtriggers a command eventtriggerMissingCommandtriggers a missingCommand eventtriggerKeytriggers a key hit
getKeysMappedreturns an array of the keys that are currently mappedgetCommandsreturns an array of the commands that are currently mappedisKeyDowntrue/false whether or not the key is being held downisCommandDowntrue/false whether the command is held down; can be used instead of triggers
mountadds the event listeners to the documentunmountremoves the event listeners
- Try it out: http://rocket-boots.github.io/keyboard-commander/
- Code: https://github.com/rocket-boots/keyboard-commander/blob/main/index.html
- When hitting keys fast together with Shift, there's the possibility that a key gets stuck in the key-down (
true) state.