aboutsummaryrefslogtreecommitdiff
path: root/src/content/components/common/keymapper.js
blob: 4c294b4945ba1b7a151738ab391f9e0653f55ba4 (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
import * as inputActions from 'content/actions/input';
import * as operationActions from 'content/actions/operation';
import operations from 'shared/operations';
import * as keyUtils from 'shared/utils/keys';

const mapStartsWith = (mapping, keys) => {
  if (mapping.length < keys.length) {
    return false;
  }
  for (let i = 0; i < keys.length; ++i) {
    if (!keyUtils.equals(mapping[i], keys[i])) {
      return false;
    }
  }
  return true;
};

export default class KeymapperComponent {
  constructor(store) {
    this.store = store;
  }

  // eslint-disable-next-line max-statements
  key(key) {
    this.store.dispatch(inputActions.keyPress(key));

    let state = this.store.getState();
    let input = state.input;
    let keymaps = new Map(state.setting.keymaps);

    let matched = Array.from(keymaps.keys()).filter((mapping) => {
      return mapStartsWith(mapping, input.keys);
    });
    if (!state.addon.enabled) {
      // available keymaps are only ADDON_ENABLE and ADDON_TOGGLE_ENABLED if
      // the addon disabled
      matched = matched.filter((keys) => {
        let type = keymaps.get(keys).type;
        return type === operations.ADDON_ENABLE ||
          type === operations.ADDON_TOGGLE_ENABLED;
      });
    }
    if (matched.length === 0) {
      this.store.dispatch(inputActions.clearKeys());
      return false;
    } else if (matched.length > 1 ||
      matched.length === 1 && input.keys.length < matched[0].length) {
      return true;
    }
    let operation = keymaps.get(matched[0]);
    let act = operationActions.exec(
      operation, key.repeat, state.setting, state.addon.enabled
    );
    this.store.dispatch(act);
    this.store.dispatch(inputActions.clearKeys());
    return true;
  }
}