aboutsummaryrefslogtreecommitdiff
path: root/src/components/background-input.js
blob: 4735d5af413bf3d604aa89eb2cc03a5a7c76dc23 (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
import * as inputActions from '../actions/input';
import * as operationActions from '../actions/operation';

export default class BackgroundInputComponent {
  constructor(store) {
    this.store = store;
    this.keymaps = {};
    this.prevInputs = [];
  }

  update(sender) {
    let state = this.store.getState();
    this.reloadSettings(state.setting);
    this.handleKeyInputs(sender, state.input);
  }

  reloadSettings(setting) {
    if (!setting.settings.json) {
      return;
    }
    this.keymaps = JSON.parse(setting.settings.json).keymaps;
  }

  handleKeyInputs(sender, input) {
    if (JSON.stringify(this.prevInputs) === JSON.stringify(input)) {
      return;
    }
    this.prevInputs = input;

    if (input.keys.length === 0) {
      return;
    }
    if (sender) {
      return this.handleKeysChanged(sender, input);
    }
  }

  handleKeysChanged(sender, input) {
    let matched = Object.keys(this.keymaps).filter((keyStr) => {
      return keyStr.startsWith(input.keys);
    });
    if (matched.length === 0) {
      this.store.dispatch(inputActions.clearKeys(), sender);
      return Promise.resolve();
    } else if (matched.length > 1 ||
      matched.length === 1 && input.keys !== matched[0]) {
      return Promise.resolve();
    }
    let operation = this.keymaps[matched];
    this.store.dispatch(operationActions.exec(operation, sender.tab), sender);
    this.store.dispatch(inputActions.clearKeys(), sender);
  }
}