react-event-components
react-event-components copied to clipboard
Multiple keys pressed at once support
Description
Would be nice to have a behavior like this.
Scenario: I want to do something, when the user presses shitf + a.
Proposal
This is a simple and straightforward implementation. Don't know how the component interface to this might look like, though.
const keysPressed = {}
document.addEventListener('keydown', e => keysPressed[e.keyCode] = true)
document.addEventListener('keyup', e => keysPressed[e.keyCode] = false)
if (keysPressed[16] && keysPressed[65]) {
// do something
}
Maybe accepting an array on the "when" parameter is a nice solution. We could make aliases for "combo" keys like ctrl, shift, alt, etc.
Ok, so, talking to @grvcoelho we agreed on a syntax:
when="w"=> does what it does today
when={["w", "e", "r"]} => 'w', 'e', and 'r' would all trigger that action
when="shift+w" => would trigger only when 'shift' AND 'w' are pressed. You can also use this in arrays.
If anyone has a better idea lets work this through, otherwise I'll implement it this way :)
@derekstavis
edit* maybe we can find a better alternative for the array to try and keep a consistent syntax without using {}?
@MarcoWorms
maybe we can find a better alternative for the array to try and keep a consistent syntax without using {}?
It's also an option to use a comma-separated string instead of the array, like it's implemented in this library: https://github.com/madrobby/keymaster
So when={["w", "e", "r"]} may be also represented as when="w, e, r". But personally I think that both options are viable. The comma-separated version is useful when you exactly know what you want, and the array version may be used when you want to generate the keys dynamically.
I thought about the comma-separated string but I rather use the primitive types when they fit the needs, so if it's a list than it probably makes sense to use arrays :)