Configuration-centric keyboard shortcuts for your Angular apps.
- Define hotkeys on an entire route, automatically binding and unbinding them as you navigate
- Automatic listing of shortcuts when users hit the
- Super duper unit tests
Why I made this:
Other projects out there rely too heavily on HTML markup for keyboard shortcuts. For example:
While this is a great approach for many Angular apps, some applications do not have a 1 to 1 relationship between DOM elements and controller methods. In my case, many methods on the controller were only accessible through the keyboard.
Additionally, this only allows you to pass a function reference, you can't pass arguments to the function you intend to call. So instead of simply calling
seek(currentTime + 30) and
seek(currentTime + 60), I needed to create a ton of helper functions on the scope (such as
forward60), and litter my HTML like this:
With a few dozen shortcuts, this left the DOM really messy, and with multiple views and directive templates, it was next to impossible to remember where all the different shortcuts were. This became a maintenance nightmare.
You can either define hotkeys in your Controller, or in your Route configuration (or both). To start, though, require the lib as a dependency for your angular app:
Behind the scenes, I'm using the Mousetrap library to manage the key bindings. Check out the docs there for more information on what kind of key combinations can be used.
Binding hotkeys in controllers:
Binding hotkeys in routes:
You can also define hotkeys on an entire route, and this lib will bind and unbind them as you navigate the app.
Binding hotkeys in directives:
Lastly, even though binding hotkeys in your templates/html tends to be a bad idea, it can be super useful for simple shortcuts. Think along the lines of a modal directive where you simply want to bind to the escape key or something equally simple. Accomplishing this within a controller is too much overhead, and it may lead to code-reuse.
Example of how directive-based hotkeys works:
hotkeys.add(combo, description, callback)
combo: They keyboard combo (shortcut) you want to bind to
description: [OPTIONAL] The description for what the combo does and is only used for the Cheat Sheet. If it is not supplied, it will not show up, and in effect, allows you to have unlisted hotkeys.
callback: The function to execute when the key(s) are pressed. Passes along two arguments,
object: An object version of the above parameters.
Returns the Hotkey object
Removes and unbinds a hotkey