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

const queue = new KeyQueue();

const keyDownHandle = (request, sender, sendResponse) => {
  let action = queue.push({
    code: request.code,
    shift: request.shift,
    ctrl: request.ctrl,
    alt: request.alt,
    meta: request.meta
  });
  if (!action) {
    return;
  }

  if (actions.isBackgroundAction(action[0])) {
    doBackgroundAction(sender, action);
  } else if (actions.isContentAction(action[0])) {
    sendResponse(action);
  }
};

const doBackgroundAction = (sender, action) => {
  switch(action[0]) {
  case actions.TABS_CLOSE:
    tabs.closeTab(sender.tab.id);
    break;
  case actions.TABS_REOPEN:
    tabs.reopenTab();
    break;
  case actions.TABS_PREV:
    tabs.selectPrevTab(sender.tab.index, actions[1] || 1);
    break;
  case actions.TABS_NEXT:
    tabs.selectNextTab(sender.tab.index, actions[1] || 1);
    break;
  }
}

const normalizeUrl = (string) => {
  try {
    return new URL(string).href
  } catch (e) {
    return 'http://' + string;
  }
}

const cmdEnterHandle = (request, sender) => {
  let words = request.text.split(' ').filter((s) => s.length > 0);
  switch (words[0]) {
  case commands.OPEN:
    browser.tabs.update(sender.tab.id, { url: normalizeUrl(words[1]) });
    return;
  case commands.TABOPEN:
    browser.tabs.create({ url: normalizeUrl(words[1]) });
    return;
  }
};

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.type) {
  case 'event.keydown':
    keyDownHandle(request, sender, sendResponse);
    break;
  case 'event.cmd.enter':
    cmdEnterHandle(request, sender, sendResponse);
    break;
  case 'event.cmd.suggest':
    // TODO make suggestion and return via sendResponse
    break;
  }
});