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
minDuration
0
maxInterval
5000
The maximum millisecond interval between the end of one key release and the start of the next, in milliseconds.
preventsDefaultUnlessDenied
true
Whether 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).
onDown
undefined
A function that is called when any key is pressed down.
onDown
receives the keychord
hook API as its only parameter.
onUp
undefined
A function that is called when any key is released.
onUp
receives the keychord
hook API as its only parameter.
onVisibilityChange
undefined
A 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:
status
recognized
, denied
, or recognizing
.sequence
Metadata
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)
})