aboutsummaryrefslogtreecommitdiff
path: root/src/background/index.js
blob: e72cab00a3726fb014d67dcbee321d88c45152f9 (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
import * as keys from './keys';
import * as inputActions from '../actions/input';
import backgroundReducers from '../reducers/background';
import commandReducer from '../reducers/command';
import inputReducers from '../reducers/input';

let inputState = inputReducers(undefined, {});

const keyQueueChanged = (sender, prevState, state) => {
  if (state.keys.length === 0) {
    return Promise.resolve();
  }

  let prefix = keys.asKeymapChars(state.keys);
  let matched = Object.keys(keys.defaultKeymap).filter((keys) => {
    return keys.startsWith(prefix);
  });
  if (matched.length == 0) {
    return handleMessage(inputActions.clearKeys(), sender);
  } else if (matched.length > 1 || matched.length === 1 && prefix !== matched[0]) {
    return Promise.resolve();
  }
  let action = keys.defaultKeymap[matched];
  return handleMessage(inputActions.clearKeys(), sender).then(() => {
    return backgroundReducers(undefined, action, sender).then(() => {
      return browser.tabs.sendMessage(sender.tab.id, action);
    });
  });
};

const handleMessage = (action, sender) => {
  let nextInputState = inputReducers(inputState, action);
  if (JSON.stringify(nextInputState) !== JSON.stringify(inputState)) {
    let prevState = inputState;
    inputState = nextInputState;
    return keyQueueChanged(sender, prevState, inputState);
  }
  return backgroundReducers(undefined, action, sender).then(() => {
    return commandReducer(undefined, action, sender).then(() => {
      return browser.tabs.sendMessage(sender.tab.id, action);
    });
  });
};

browser.runtime.onMessage.addListener(handleMessage);