aboutsummaryrefslogtreecommitdiff
path: root/src/command-line/index.js
blob: f99afa0c5dc344349388d681cd04c236afecf682 (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
import './index.scss';

const parent = window.parent;

// TODO consider object-oriented
var prevValue = "";

const blurData = () => {
  return JSON.stringify({
    type: 'vimvixen.commandline.blur'
  });
};

const keydownData = (input) => {
  return JSON.stringify({
    type: 'vimvixen.commandline.enter',
    value: input.value
  });
};

const keyupData = (input) => {
  return JSON.stringify({
    type: 'vimvixen.commandline.change',
    value: input.value
  });
};

const handleBlur = () => {
  parent.postMessage(blurData(), '*');
};

const handleKeydown = (e) => {
  switch(e.keyCode) {
  case KeyboardEvent.DOM_VK_ESCAPE:
    parent.postMessage(blurData(), '*');
    break;
  case KeyboardEvent.DOM_VK_RETURN:
    parent.postMessage(keydownData(e.target), '*');
    break;
  }
};

const handleKeyup = (e) => {
  if (e.target.value === prevValue) {
    return;
  }
  parent.postMessage(keyupData(e.target), '*');
  prevValue = e.target.value;
};

window.addEventListener('load', () => {
  let hash = window.location.hash;
  let initial = '';
  if (hash.length > 0) {
    initial = decodeURIComponent(hash.substring(1));
  }

  let input = window.document.querySelector('#vimvixen-command-line-line-input');
  input.addEventListener('blur', handleBlur);
  input.addEventListener('keydown', handleKeydown);
  input.addEventListener('keyup', handleKeyup);
  input.value = initial;
  input.focus();
});