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
156 stars 6 forks source link

Cancel key combo when switching to a different window #16

Closed DarkLight1337 closed 1 year ago

DarkLight1337 commented 1 year ago

When I switch to a different window via keyboard (e.g. Alt+Tab), then return to the original window without using the keyboard (e.g. via clicking on it), the active key combo becomes stuck at the state before I left the window (e.g. at Alt), until I press and release the key again. This behaviour may confuse users into thinking that the key combos have stopped working.

It would be great if the active key combo automatically cancels when the window loses focus.

Here is a temporary solution that seems to work on keyboard shortcuts for tabbing out of the active window (I only tested on Windows though):

const keystrokes = new Keystrokes({
    selfReleasingKeys: [
        'ctrl', 'meta', 'alt', 'tab',
    ],
    keyRemap: {
        control: 'ctrl',
        os: 'meta',     // For Firefox
    },
});

addEventListener('blur', () => {
    // Prevent getting stuck in a key sequence after tabbing to a different window
    // @ts-expect-error
    keystrokes._tryReleaseSelfReleasingKeys();
});
RobertWHurst commented 1 year ago

Yes, I had added this back with KeyboardJS. I'm trying to decide if this should go in the browser bindings, or in the library; I'm trying to decide if this is a platform dependent behavior or a general one. I'll try to get a solution together in the next day or so. Thanks for raising the issue @DarkLight1337

RobertWHurst commented 1 year ago

Just put out a new release with this behavior added. Let me know if you have any issues.

DarkLight1337 commented 1 year ago

I've played around a bit and it seems to work as intended. Thanks!