Skip to content

Instantly share code, notes, and snippets.

@lukemelia
Last active April 21, 2023 17:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukemelia/d3b3bf472eda9b983c3f45a4df1e3eaf to your computer and use it in GitHub Desktop.
Save lukemelia/d3b3bf472eda9b983c3f45a4df1e3eaf to your computer and use it in GitHub Desktop.
keyboard-shortcut element modifer

An element modifier to attach a keyboard shortcut to an element that has a click method

Example usage:

  <button {{action 'doSomethingCool'}} {{keyboard-shortcut "D"}}>
    [D]o something cool
  </button>

Requirements:

  • ember-octane preview (from blueprint)
  • ember-oo-modifiers (0.2.2)
  • ember-keyboard

Note: make sure @ember-decorators/babel-transforms is present and is at ^2.1.2 for now (this is expected to be rolled into ember-cli-babel)

// app/modifiers/keyboard-shortcut.js
import Modifier from 'ember-oo-modifiers';
import { inject as service } from '@ember/service';
import { keyDown } from 'ember-keyboard';
class KeyboardShortcutModifier extends Modifier {
@service keyboard;
keyboardActivated = true
keyboardPriority = 0
didReceiveArguments([key, action]) {
this.key = key;
this.action = action;
}
// Note: ember-keyboard is designed to be used via its mixin, however classes don't support mixins.
// So this modifier implements `has` and `trigger` to behave like it would if EKMixin was included.
// We would love to see a a better, non-mixin way of interacting with ember-keyboard be added.
didInsertElement(){
super.didInsertElement(...arguments);
this.keyboard.register(this);
}
willDestroyElement(){
super.willDestroyElement(...arguments);
this.keyboard.unregister(this);
}
has(triggerName) {
if (triggerName === `keydown:Key${this.key}`) {
return true;
}
return false;
}
trigger(listenerName) {
if (listenerName === keyDown(`Key${this.key}`)) {
this.element.click();
}
}
}
export default Modifier.modifier(KeyboardShortcutModifier);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment