adopted-ember-addons/ember-keyboard

Avoid `keyUp` events from other tabs

Opened this issue · 1 comments

Hi, my application has a shortcut on the 'w' key on keyUp.

If I land on my application in a browser tab after using the default super+w to close another tab, the shortcut will fire without the user intending to.

So my question is, is there a way to avoid keyUp events that were started (keyDown) in another tab?

Not built into ember-keyboard itself, though you could (kind of) track this locally. For instance, something like:

registerKeyDown: Ember.on(keyDown('KeyW', function() {
  this.set('keyWPressed', true);
}),

doSomething: Ember.on(keyUp('KeyW', function() {
  if (this.get('keyWPressed') {
    this.toggleProperty('keyWPressed');
    . . . .
  }
})

The problem is, this could be painful to support if you have to do it for a lot of keys. It also still buggy. What if the user tabs away with super+w (registering the keyDown event) and then tabs back in the same way? You'd have the same problem.

You could maybe work around that by also watching for visibilitychange events. So something like:

setupVisibilityChangeObserver: Ember.on('init', function() {
  document.addEventListener('visibilitychange', () => {
    this.set('visibilityChange', true);
  });
},

registerKeyDown: Ember.on(keyDown('KeyW', function() {
  this.set('keyWPressed', true);
  this.set('visibilityChange', false);
}),

doSomething: Ember.on(keyUp('KeyW', function() {
  if (this.get('keyWPressed') && !this.get('visibilityChange')) {
    this.toggleProperty('keyWPressed');
    . . . .
  }
})