jaywcjlove / hotkeys-js

➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
https://jaywcjlove.github.io/hotkeys-js
MIT License
6.66k stars 410 forks source link

rebind keys from an unbound scope or enable / disable scopes #429

Open justin-betty opened 1 year ago

justin-betty commented 1 year ago

Hello,

Is there a way to rebind keys from an unbound scope?

for example I have set some hot keys and they are scoped. then I open a modal and I set the scope to that modal scope. But I have to unbind the other scope else both ('enter') hotkeys will be fired. after the modal is closed then the hotkeys don't work on the root element anymore because they are unbound.

Or is there a way to somehow disable and enable scopes?

rouilj commented 1 year ago

By unbound scope do you mean the "all" scope that is the default scope if the scope is not specified? AFAIK, the "all" scope is always enabled. I don't know what the scope execution order is. It could run the 'all' scope's function first or the scope set with setScope('modal') first.

Assuming the setScope('modal') function is called before the all scope, it would be nice to be able to call hotkeys.stopPropigation(). This would run only the setScope('modal') bound function and not run the 'all' scope function. I think this would handle your use case nicely. But there is no such mechanism currently.

If you have bindings that need to be disabled, they should go in a scope other than all.

If the same bindings need to be enabled in multiple scopes but need to be disabled as well, you would need to bind the keys to the function in each scope.

I am not sure what is used to disable a setScope() call. I assume setScope('') or setScope(null), setScope() or setScope('someUnusedScope') would work. Which is most correct I can't say..

ray73864 commented 9 months ago

I got around this by never assigning any hotkeys to the 'all' scope.

So what I do, is all my general purpose hotkeys get assigned to a scope called 'global', and I set that scope pretty much on page load.

Then when I load a modal, I create a new scope, set the new scope to be active, when the modal closes, I delete the new scope and set the scope back to 'global'.

I too wish that 'all' could be enabled/disabled.

I don't know what the scope execution order is. It could run the 'all' scope's function first or the scope set with setScope('modal') first.

From what I have found, the 'all' scope takes priority over the scope you just set. I found this out the hard way when weird things were happening with a modal that was open :)

Which is why I stopped using the 'all' scope.