aboutsummaryrefslogtreecommitdiff
path: root/src/content/InputDriver.ts
blob: 0472088a24ea1a517184d20f8fd5cfcc2ffb6739 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import * as dom from '../shared/utils/dom';
import Key, * as keys from './domains/Key';

const cancelKey = (e: KeyboardEvent): boolean => {
  if (e.key === 'Escape') {
    return true;
  }
  if (e.key === '[' && e.ctrlKey) {
    return true;
  }
  return false;
};

export default class InputDriver {
  private pressed: {[key: string]: string} = {};

  private onKeyListeners: ((key: Key) => boolean)[] = [];

  constructor(target: HTMLElement) {
    this.pressed = {};
    this.onKeyListeners = [];

    target.addEventListener('keypress', this.onKeyPress.bind(this));
    target.addEventListener('keydown', this.onKeyDown.bind(this));
    target.addEventListener('keyup', this.onKeyUp.bind(this));
  }

  onKey(cb: (key: Key) => boolean) {
    this.onKeyListeners.push(cb);
  }

  private onKeyPress(e: KeyboardEvent) {
    if (this.pressed[e.key] && this.pressed[e.key] !== 'keypress') {
      return;
    }
    this.pressed[e.key] = 'keypress';
    this.capture(e);
  }

  private onKeyDown(e: KeyboardEvent) {
    if (this.pressed[e.key] && this.pressed[e.key] !== 'keydown') {
      return;
    }
    this.pressed[e.key] = 'keydown';
    this.capture(e);
  }

  private onKeyUp(e: KeyboardEvent) {
    delete this.pressed[e.key];
  }

  // eslint-disable-next-line max-statements
  private capture(e: KeyboardEvent) {
    let target = e.target;
    if (!(target instanceof HTMLElement)) {
      return;
    }
    if (this.fromInput(target)) {
      if (cancelKey(e) && target.blur) {
        target.blur();
      }
      return;
    }
    if (['Shift', 'Control', 'Alt', 'OS'].includes(e.key)) {
      // pressing only meta key is ignored
      return;
    }

    let key = keys.fromKeyboardEvent(e);
    for (let listener of this.onKeyListeners) {
      let stop = listener(key);
      if (stop) {
        e.preventDefault();
        e.stopPropagation();
        break;
      }
    }
  }

  private fromInput(e: Element) {
    return e instanceof HTMLInputElement ||
      e instanceof HTMLTextAreaElement ||
      e instanceof HTMLSelectElement ||
      dom.isContentEditable(e);
  }
}