Declarative keyboard navigation
Encapsulate the details of handling key events in a tidy reusable component.
Summary
Power users love keyboard navigation, but it's often an overlooked feature. Keyboard nav is almost never present in designs or mockups, and the last thing UI developers want to do is juggle keyboard events.
What if there was an easy way to add keyboard navigation to your application? In this video, we'll create a declarative and composable component that makes keyboard navigation painless.
{{! use the J and K keys to navigate through the list of posts }}
{{keyboard-press
key="KeyJ"
on-press=(action (mut navigatedPost) (next navigatedPost posts))}}
{{keyboard-press
key="KeyK"
on-press=(action (mut navigatedPost) (previous navigatedPost posts))}}
{{keyboard-press
key="Enter"
on-press=(action "openPost" navigatedPost)}}
We'll first need to install ember-keyboard
in order to make this API work.
ember install ember-keyboard
Next, we can create the keyboard-press
component.
import Component from '@ember/component';
import { EKMixin, keyDown } from 'ember-keyboard';
export default Component.extend(EKMixin, {
key: null,
'on-press'() {},
didInsertElement() {
this._super(...arguments);
let key = this.get('key');
let action = this.get('on-press');
this.set('keyboardActivated', true);
this.on(keyDown(key), action);
}
});