Keypress
Updated on September 20, 2024Source codeTests
createKeypress is a factory that returns Recognizeable effects for recognizing one or more keycombos.
A key press starts when the final key in a keycombo goes down, and is denied by the keydown event of a key that is not part of any of the given keycombos, or by a keyup or visibilitychange event.
While the keycombo is still down, createKeypress continuously recognizes the gesture at a rate of 60fps. The gesture is recognized when the keycombo has been down for a minimum duration, which is configurable.
Create keypress
Call createKeypress with these parameters to create your keydown, keyup, and visibilitychange effects:
keycomboThe keycombo or array of keycombos to recognize.
If you pass an array of keycombos, the keypress will start recognizing whenever the current keyboard state exactly matches any one of those keycombos.
optionskeydown, keyup, and visibilitychange effects. See the Options section for more guidance.Options
minDuration0preventsDefaultUnlessDeniedtrueWhether to call preventDefault on the keydown, keyup, and visibilitychange events, unless the keypress is denied.
If the keypress 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 keypress hook API as its only parameter.
onUpundefinedA function that is called when any key is released.
onUp receives the keypress hook API as its only parameter.
onVisibilityChangeundefinedA function that is called when the page visibility changes.
onVisibilityChange receives the keypress 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 keypress effects store data in the Recognizeable instance's metadata property.
Keypress metadata includes all keyboard metadata.
Using with Listenable
The easiest way to use createKeypress with Listenable is to use the Keypress class, which is a very minimal subclass of Listenable that handles configuration for you.
Here's an example of how to use Keypress to nicely combine createKeypress with Listenable:
import { Keypress } from '@baleada/logic'
const keypress = new Keypress(keycomboOrKeycombos, [keypressOptions])
keypress.listen(() => {
console.log(keypress.metadata.duration)
})