Filters seem scoped, but aren't
See original GitHub issueAn example:
useHotkeys('Delete', () => {
// do something
}, { filter: ignoreInputElements });
useHotkeys('Ctrl+Shift+Delete', () => {
// do something
}, { filter: () => true });
You might want to have different filters for different shortcuts. Here, for example, ‘Delete’ is something you might press during input, so needs to be filtered to ignore input elements, but ‘Ctrl+Shift+Delete’ is not.
Unfortunately, the hotkey filter functionality is global, so the last filter that’s set always wins. In the above example, ‘Delete’ will fire everywhere, even in input elements, which is not what the author intended.
This isn’t very react-y/declarative, as different render orders/rerenderings elsewhere can produce all sorts of strange behaviours here. It’d be better to either scope the filters to the specific shortcut somehow, or to make this behaviour obvious in the useHotkeys API. Setting the filter via useHotkeys.filter = ...
would make the fact that it’s global much clearer, for example.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:8
- Comments:7 (6 by maintainers)
I implemented a custom filter logic.
Basically everything works as before, but the filter is now scoped to each hook instance instead of globally.
Since this is a behavioral breaking change, I bumped the major version to
3.0.0
I found a fairly easy fix that I implemented in my fork (https://github.com/SteffeyDev/react-hotkeys-hook/blob/feature/scope/src/useHotkeys.ts). Can’t PR though cause I made a lot of other changes in my fork that ended up not being good because of how poorly hotkeys-js handles scoping.
The idea is that you set the global
hotkeys.filter
to() => true
so that all events are allowed through. Then you do all the filtering in the hook. The default filtering that hotkeys uses is fairly simple to copy over if the user does not pass a filter in the hook, but if they do you can use their filter instead. Once again, see the version in my fork to see it implemented in a working fashion (just ignore all my scope changes that don’t work well).If someone wants to fork and implement, it should be pretty easy. Unfortunately this would be a breaking change so would probably need a new major version.