RobertWHurst / Keystrokes

Keystrokes as an easy to use library for binding functions to keys and key combos. It can be used with any TypeScript or JavaScript project, even in non-browser environments.
MIT License
158 stars 6 forks source link

`keyup` listener #18

Closed silverwind closed 1 year ago

silverwind commented 1 year ago

Is your feature request related to a problem? Please describe.

I'd like to track the "down" state of the shift key, and for that a way to define a keyUp listener would be necessary. With keyboardjs I do:

let shiftDown = false;
keyboardjs.bind("shift", () => {shiftDown = true});
keyboardjs.bind("shift", null, () => {shiftDown = false});

Describe the solution you'd like

Some way to define for which event to listen, for example with an options argument:

bindKey("shift", () => {}, {event: "keydown"});
bindKey("shift", () => {}, {event: "keyup"});
RobertWHurst commented 1 year ago

Hi @silverwind. Indeed this is important functionality. It is actually already possible to do this. There is a section on this in the readme. The gist is that you can pass an object as a handler instead of a function. The object has three optional properties. onPressed is essentially keydown, onPressedWithRepeat is the same thing, but calls the handler repeatedly (just like the browser), and onReleased is essentially keyup.

Here is an example:

bindKey('shift', {
  onPressed: () => console.log('keydown'),
  onReleased: () => console.log('keyup'),
})

bindKeyCombo('shift > b', {
  onPressed: () => console.log('keydown'),
  onReleased: () => console.log('keyup'),
})

Does that solve you're problem?

RobertWHurst commented 1 year ago

Going to close for now, but we can reopen if need be.

silverwind commented 1 year ago

Yes, that should be suitable, I CTRL-F'ed for keyup in the README which gave no matches, sorry for not looking more closely.

RobertWHurst commented 1 year ago

No problem at all, glad to help. 😁