aboutsummaryrefslogtreecommitdiff
path: root/src/shared/settings/values.js
blob: 4482fbb0c4c2dfd064d6ecd0235cc229d88bdd62 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import DefaultSettings from './default';

const operationFromFormName = (name) => {
  let [type, argStr] = name.split('?');
  let args = {};
  if (argStr) {
    args = JSON.parse(argStr);
  }
  return Object.assign({ type }, args);
};

const operationToFormName = (op) => {
  let type = op.type;
  let args = Object.assign({}, op);
  delete args.type;

  if (Object.keys(args).length === 0) {
    return type;
  }
  return op.type + '?' + JSON.stringify(args);
};

const valueFromJson = (json) => {
  return JSON.parse(json);
};

const valueFromForm = (form) => {
  let keymaps = undefined;
  if (form.keymaps) {
    keymaps = {};
    for (let name of Object.keys(form.keymaps)) {
      let keys = form.keymaps[name];
      keymaps[keys] = operationFromFormName(name);
    }
  }

  let search = undefined;
  if (form.search) {
    search = { default: form.search.default };

    if (form.search.engines) {
      search.engines = {};
      for (let [name, url] of form.search.engines) {
        search.engines[name] = url;
      }
    }
  }

  let blacklist = form.blacklist;

  return { keymaps, search, blacklist };
};

const jsonFromValue = (value) => {
  return JSON.stringify(value, undefined, 2);
};

const formFromValue = (value) => {

  let keymaps = undefined;
  if (value.keymaps) {
    let allowedOps = new Set(Object.keys(DefaultSettings.form.keymaps));

    keymaps = {};
    for (let keys of Object.keys(value.keymaps)) {
      let op = operationToFormName(value.keymaps[keys]);
      if (allowedOps.has(op)) {
        keymaps[op] = keys;
      }
    }
  }

  let search = undefined;
  if (value.search) {
    search = { default: value.search.default };
    if (value.search.engines) {
      search.engines = Object.keys(value.search.engines).map((name) => {
        return [name, value.search.engines[name]];
      });
    }
  }

  let blacklist = value.blacklist;

  return { keymaps, search, blacklist };
};

const jsonFromForm = (form) => {
  return jsonFromValue(valueFromForm(form));
};

const formFromJson = (json) => {
  let value = valueFromJson(json);
  return formFromValue(value);
};

export {
  valueFromJson, valueFromForm, jsonFromValue, formFromValue,
  jsonFromForm, formFromJson
};