imbhargav5 / rooks

Essential React custom hooks ⚓ to super charge your components!
https://rooks.vercel.app
MIT License
3.2k stars 215 forks source link

useKeys – key map not cleared if window loses focus #1730

Closed CiaranMn closed 12 months ago

CiaranMn commented 1 year ago

Description

If the window loses focus, the keyup handler is not called and therefore any keys that were held while the window loses focus are still thought to be held when it regains focus.

I believe this is the issue underlying https://github.com/imbhargav5/rooks/pull/1210 which fixed it for specific cases of focus being lost, but there are many more, e.g.:

  1. User presses CTRL + F: when re-focusing the window, CTRL + F are still tracked as pressed (codesandbox)
  2. Users holds a key and clicks another tab
  3. Various other browser hot keys which cause the window to lose focus, e.g. for downloads in Chrome ⌘ + Shift + j or ctrl + j

Solution The simplest solution is to have a blur handler on the window which wipes the PressedKeyMapping.

I believe the code for overwriting alert etc can then be removed (but have not tested it).

coycoylaniba commented 1 year ago

what's the status for this?

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

CiaranMn commented 11 months ago

Since the above I've discovered that there are some other actions which can take focus from the window and prevent the keyup handler from firing, for example the screen capture shortcut on MacOS (cmd + shift + 5).

Since manually maintaining a map of held keys seems unreliable, we've switched to just using the information available on KeyboardEvent, which is fine if you just need a combination of ctrl/shift/meta/alt + some other single key, and don't care about the difference between CtrlLeft/CtrlRight, or need to handle multiple non-modifier keys. Example implementation.