Keychord
Updated on September 20, 2024Source codeTests
createKeychord is a factory that returns Recognizeable effects for recognizing a keychord, i.e. multiple keycombos pressed and released in a specific order.
A key chord is a sequence of keyreleases that are "played" in a specific order.
Each keyrelease in the sequence must be played for a minimum duration, and the time between the end of one keyrelease and the start of the next cannot exceed a maximum interval. Both the duration and the interval are configureable.
Create keychord
Call createKeychord with these parameters to create your keydown, keyup, and visibilitychange effects:
Options
minDuration0maxInterval5000The maximum millisecond interval between the end of one key release and the start of the next, in milliseconds.
preventsDefaultUnlessDeniedtrueWhether to call preventDefault on the keydown, keyup, and visibilitychange events, unless the keychord is denied.
If the keychord has been denied, the default will never be prevented (although you can still prevent it via the hooks listed below).
onDownundefinedA function that is called when any key is pressed down.
onDown receives the keychord hook API as its only parameter.
onUpundefinedA function that is called when any key is released.
onUp receives the keychord hook API as its only parameter.
onVisibilityChangeundefinedA function that is called when the page visibility changes.
onVisibilityChange receives the keychord hook API as its only parameter.
Hook API
The hook API is an object that is passed to the onDown, onUp, and onVisibilityChange options as their only parameter. It contains the following properties:
statusrecognized, denied, or recognizing.sequenceMetadata
Your created keychord effects store data in the Recognizeable instance's metadata property.
Keychord metadata has one property: played, an array of keyboard metadata objects that describe each individual keycombo in the chord.
Using with Listenable
The easiest way to use createKeychord with Listenable is to use the Keychord class, which is a very minimal subclass of Listenable that handles configuration for you.
Here's an example of how to use Keychord to nicely combine createKeychord with Listenable:
import { Keychord } from '@baleada/logic'
const keychord = new Keychord(keycombos, [keychordOptions])
keychord.listen(() => {
console.log(keychord.metadata.played[0].duration)
})