aboutsummaryrefslogtreecommitdiff
path: root/src/background/index.js
blob: cbd472132d8f1fa6c343be0113a31cfb53b30916 (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
import * as keys from './keys';
import * as inputActions from '../actions/input';
import * as operationActions from '../actions/operation';
import * as commandActions from '../actions/command';
import * as consoleActions from '../actions/console';
import reducers from '../reducers';
import messages from '../messages';
import * as store from '../store'

let prevInput = [];
const backgroundStore = store.createStore(reducers, (e) => {
  console.error('Vim-Vixen:', e);
});
backgroundStore.subscribe(() => {
  let currentInput = backgroundStore.getState().input
  if (JSON.stringify(prevInput) === JSON.stringify(currentInput)) {
    return
  }
  prevInput = currentInput;

  if (currentInput.keys.length === 0) {
    return;
  }

  browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
    if (tabs.length > 0) {
      return keyQueueChanged(tabs[0], backgroundStore.getState());
    }
  });
});
backgroundStore.subscribe(() => {
  browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
    if (tabs.length > 0) {
      return browser.tabs.sendMessage(tabs[0].id, {
        type: messages.STATE_UPDATE,
        state: backgroundStore.getState()
      });
    }
  });
});

const keyQueueChanged = (sendToTab, state) => {
  let prefix = keys.asKeymapChars(state.input.keys);
  let matched = Object.keys(keys.defaultKeymap).filter((keys) => {
    return keys.startsWith(prefix);
  });
  if (matched.length == 0) {
    backgroundStore.dispatch(inputActions.clearKeys());
    return Promise.resolve();
  } else if (matched.length > 1 || matched.length === 1 && prefix !== matched[0]) {
    return Promise.resolve();
  }
  let action = keys.defaultKeymap[matched];
  backgroundStore.dispatch(operationActions.exec(action, sendToTab));
  backgroundStore.dispatch(inputActions.clearKeys());
  return browser.tabs.sendMessage(sendToTab.id, action);
};

browser.runtime.onMessage.addListener((message) => {
  switch (message.type) {
  case messages.KEYDOWN:
    backgroundStore.dispatch(inputActions.keyPress(message.code, message.ctrl));
    break;
  case messages.CONSOLE_BLURRED:
    backgroundStore.dispatch(consoleActions.hide());
    break;
  case messages.CONSOLE_ENTERED:
    backgroundStore.dispatch(commandActions.exec(message.text));
    break;
  case messages.CONSOLE_CHANGEED:
    backgroundStore.dispatch(commandActions.complete(message.text));
    break;
  }
});