aboutsummaryrefslogtreecommitdiff
path: root/src/background/key-queue.js
blob: d9362339253bc72e89330e449f185fcf334653de (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
import * as actions from '../shared/actions';

const DEFAULT_KEYMAP = {
  ':': [ actions.CMD_OPEN ],
  'o': [ actions.CMD_TABS_OPEN, false ],
  'O': [ actions.CMD_TABS_OPEN, true ],
  'k': [ actions.SCROLL_LINES, -1 ],
  'j': [ actions.SCROLL_LINES, 1 ],
  '<C-E>': [ actions.SCROLL_LINES, -1 ],
  '<C-Y>': [ actions.SCROLL_LINES, 1 ],
  '<C-U>': [ actions.SCROLL_PAGES, -0.5 ],
  '<C-D>': [ actions.SCROLL_PAGES, 0.5 ],
  '<C-B>': [ actions.SCROLL_PAGES, -1 ],
  '<C-F>': [ actions.SCROLL_PAGES, 1 ],
  'gg': [ actions.SCROLL_TOP ],
  'G': [ actions.SCROLL_BOTTOM ],
  'd': [ actions.TABS_CLOSE ],
  'u': [ actions.TABS_REOPEN],
  'h': [ actions.TABS_PREV, 1 ],
  'l': [ actions.TABS_NEXT, 1 ],
  'r': [ actions.TABS_RELOAD, false ],
  'R': [ actions.TABS_RELOAD, true ],
  'zi': [ actions.ZOOM_IN ],
  'zo': [ actions.ZOOM_OUT ],
  'zz': [ actions.ZOOM_NEUTRAL],
  'f': [ actions.FOLLOW_START, false ],
  'F': [ actions.FOLLOW_START, true ],
  'H': [ actions.HISTORY_PREV ],
  'L': [ actions.HISTORY_NEXT ],
}

export default class KeyQueue {

  constructor(keymap = DEFAULT_KEYMAP) {
    this.data = [];
    this.keymap = keymap;
  }

  push(key) {
    this.data.push(key);

    let current = this.asKeymapChars();
    let filtered = Object.keys(this.keymap).filter((keys) => {
      return keys.startsWith(current);
    });

    if (filtered.length == 0) {
      this.data = [];
      return null;
    } else if (filtered.length === 1 && current === filtered[0]) {
      let action = this.keymap[filtered[0]];
      this.data = [];
      return action;
    }
    return null;
  }

  asKeymapChars() {
    return this.data.map((k) => {
      let c = String.fromCharCode(k.code);
      if (k.ctrl) {
        return '<C-' + c.toUpperCase() + '>';
      } else {
        return c
      }
    }).join('');
  }

  asCaretChars() {
    return this.data.map((k) => {
      let c = String.fromCharCode(k.code);
      if (k.ctrl) {
        return '^' + c.toUpperCase();
      } else {
        return c;
      }
    }).join('');
  }
}