react-event-components icon indicating copy to clipboard operation
react-event-components copied to clipboard

Multiple keys pressed at once support

Open grvcoelho opened this issue 8 years ago • 4 comments

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
}

grvcoelho avatar Nov 06 '16 23:11 grvcoelho

Maybe accepting an array on the "when" parameter is a nice solution. We could make aliases for "combo" keys like ctrl, shift, alt, etc.

MarcoWorms avatar Nov 07 '16 01:11 MarcoWorms

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 avatar Nov 07 '16 18:11 MarcoWorms

@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.

anatoliyarkhipov avatar Nov 12 '16 11:11 anatoliyarkhipov

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 :)

MarcoWorms avatar Nov 12 '16 20:11 MarcoWorms