SamSunder commited on
Commit
3cbe1cb
1 Parent(s): ef7567b

Added detailed documentation to JS functions and fixed a mistake while loading css from cookie.

Browse files
public/static/settings.js CHANGED
@@ -1,116 +1,186 @@
1
- // UI: Method for selecting all search engines
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  function selectAllHandler(elem) {
3
- let span = elem.parentElement.querySelector('span');
4
- let mainInput = document.getElementsByName('searchEng')[0];
5
- let prevStateSelectAll = span.innerText == 'Select all' ? true : false;
6
- document.querySelectorAll('.searchEng-elem').forEach(engine => {
7
- if (prevStateSelectAll) {
8
- engine.querySelector('input[type="checkbox"]').checked = true;
9
- } else {
10
- engine.querySelector('input[type="checkbox"]').checked = false;
11
- }
12
- })
13
  if (prevStateSelectAll) {
14
- let getValues = () => {
15
- let value = ""
16
- document.querySelectorAll('[data-isCheckbox]:not([data-value="all"])').forEach(elem => {
17
- value += elem.getAttribute("data-value") + ",";
18
- });
19
- return value;
20
- }
21
- mainInput.value = getValues();
22
  } else {
23
- mainInput.value = '';
24
  }
25
- span.innerText = prevStateSelectAll ? 'Deselect all' : 'Select all';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- // UI: Filter settings as per category
30
- document.querySelectorAll('.settings-sidebar .set-name').forEach(filter => {
31
- let target = filter.getAttribute('data-detailId');
32
- filter.addEventListener('click', () => {
33
- try {document.querySelector('.set-name.active').classList.remove('active');} catch(e){}
34
- filter.classList.add('active');
35
- if (target == 'all') {
36
- document.querySelectorAll('.set-item').forEach((elem) => {
37
- elem.style.display = 'block';
38
- })
39
- return;
40
- }
41
- document.querySelectorAll('.set-item[data-id="'+target+'"]').forEach((elem) => {
42
- elem.style.display = 'block'
43
- })
44
- document.querySelectorAll('.set-item:not([data-id="'+target+'"])').forEach((elem) => {
45
- elem.style.display = 'none'
46
- })
47
- })
48
- })
 
 
 
 
 
 
 
49
 
50
 
51
- // On settings form submit
 
 
 
 
 
 
 
 
52
  function submitSettings() {
53
- let form = document.settings;
54
- let stopProceeding = false;
55
- document.querySelectorAll('.errTxt').forEach(e => e.remove());
56
- for(let i = 0; i < form.elements.length; i++) {
57
- let input = form.elements[i];
58
- if (input.value == "" && input.hasAttribute('required')) {
59
- stopProceeding = true;
60
- let elem = input.parentElement.querySelector('[takeInput]')
61
- let errTxt = document.createElement('p')
62
- errTxt.classList.add('errTxt')
63
- errTxt.innerText = 'This setting can\'t be empty!!'
64
- elem.classList.add('invalid');
65
- elem.parentElement.insertBefore(errTxt, elem);
66
- let sidebarElement = input.closest('.set-item').getAttribute('data-id')
67
- document.querySelector(`.settings-sidebar .set-name[data-detailId="${sidebarElement}`).click();
68
- stopProceeding = true;
69
- }
 
 
 
70
  }
71
- if (!stopProceeding) {
72
- var expiration_date = new Date();
73
- expiration_date.setFullYear(expiration_date.getFullYear() + 1);
74
- let formData = new FormData(document.querySelector('form'));
75
- for (var [key, value] of formData.entries()) {
76
- document.cookie = `${key}=${value}; expires=${expiration_date.toUTCString()}`
77
- }
78
- } else { return false; }
79
- // On settings saved successfully
80
- alert("Settings saved succssfully!");
81
- window.location.reload();
 
 
 
82
  }
83
 
84
- // Autoload existing settings
 
 
 
 
 
 
 
 
 
 
 
85
  function loadUserSettings() {
86
- let inputs = ["searchEng", "theme", "color-sch"]
87
- var keyValuePairs = document.cookie.split(';');
88
- for(var i = 0; i < keyValuePairs.length; i++) {
89
- var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
90
- var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
91
- name = name.trim();
92
- if (!inputs.includes(name)) { return; }
93
- let input = document.getElementsByName(name)[0];
94
- input.value = value;
95
- if (name == "searchEng") {
96
- // Unload all checked engine
97
- document.querySelectorAll(".searchEng-elem input[type=checkbox]").forEach(e => {
98
- e.checked = false;
99
- })
100
- value = value.replace(" ", "");
101
- value.split(",").forEach(val => {
102
- if (!val) {return}
103
- document.querySelector(`[data-isCheckbox][data-value="${val}"]`).
104
- parentElement.querySelector('input').checked = true
105
- })
106
- } else {
107
- // Unload all selected options
108
- document.querySelector(`[data-input="${name}"] .options span[data-value="${value}"]`).
109
- removeAttribute('selected');
110
- singleSelectClickHandler(document.querySelector(`.options span[data-value="${value}"]`));
111
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  }
113
-
114
  }
115
 
 
116
  loadUserSettings();
 
1
+ /*
2
+ UI: Method for selecting all search engines
3
+
4
+ This function is called when user click on
5
+ `select all` and `deselect all` toogle element.
6
+
7
+ - If select all is pressed toggle all options and insert all value
8
+ joined with comma to input which is saved in cookie.
9
+ then changes text to `deselect all`.
10
+ eg value: 'ddg,searx,'
11
+
12
+ - If deselect all is pressed uncheck all options and insert empty
13
+ value to input which is saved in cookie.
14
+ */
15
  function selectAllHandler(elem) {
16
+ let span = elem.parentElement.querySelector("span");
17
+ let mainInput = document.getElementsByName("searchEng")[0];
18
+ let prevStateSelectAll = span.innerText == "Select all" ? true : false;
19
+ document.querySelectorAll(".searchEng-elem").forEach((engine) => {
 
 
 
 
 
 
20
  if (prevStateSelectAll) {
21
+ engine.querySelector('input[type="checkbox"]').checked = true;
 
 
 
 
 
 
 
22
  } else {
23
+ engine.querySelector('input[type="checkbox"]').checked = false;
24
  }
25
+ });
26
+ if (prevStateSelectAll) {
27
+ let getValues = () => {
28
+ let value = "";
29
+ document
30
+ .querySelectorAll('[data-isCheckbox]:not([data-value="all"])')
31
+ .forEach((elem) => {
32
+ value += elem.getAttribute("data-value") + ",";
33
+ });
34
+ return value;
35
+ };
36
+ mainInput.value = getValues();
37
+ } else {
38
+ mainInput.value = "";
39
+ }
40
+ span.innerText = prevStateSelectAll ? "Deselect all" : "Select all";
41
  }
42
 
43
+ /*
44
+ UI: Filter settings as per category
45
+
46
+ There are two elements one is `category` and `detail`.
47
+ Category contains `data-id` when a user click it
48
+ we need to show detail element having
49
+ `data-detailId` whose value is same as `data-id`.
50
+
51
+ When a user clicks on a category on sidebar, view
52
+ settings containing `data-id` of sidebar element's `data-detailId`
53
+ and hide other settings
54
 
55
+ - if `all` is clicked then show all settings.
56
+ */
57
+ document.querySelectorAll(".settings-sidebar .set-name").forEach((filter) => {
58
+ let target = filter.getAttribute("data-detailId");
59
+ filter.addEventListener("click", () => {
60
+ try {
61
+ document.querySelector(".set-name.active").classList.remove("active");
62
+ } catch (e) {}
63
+ filter.classList.add("active");
64
+ if (target == "all") {
65
+ document.querySelectorAll(".set-item").forEach((elem) => {
66
+ elem.style.display = "block";
67
+ });
68
+ return;
69
+ }
70
+ document
71
+ .querySelectorAll('.set-item[data-id="' + target + '"]')
72
+ .forEach((elem) => {
73
+ elem.style.display = "block";
74
+ });
75
+ document
76
+ .querySelectorAll('.set-item:not([data-id="' + target + '"])')
77
+ .forEach((elem) => {
78
+ elem.style.display = "none";
79
+ });
80
+ });
81
+ });
82
 
83
 
84
+ /*
85
+ This function is called when a user click on submit button
86
+ it validates all user inputs and saves to a cookie.
87
+
88
+ - if input having `required` attr and is empty it generates a
89
+ error text and insert above the setting element
90
+
91
+ - else store setttings to a cookie.
92
+ */
93
  function submitSettings() {
94
+ let form = document.settings;
95
+ let stopProceeding = false;
96
+ document.querySelectorAll(".errTxt").forEach((e) => e.remove());
97
+ for (let i = 0; i < form.elements.length; i++) {
98
+ let input = form.elements[i];
99
+ if (input.value == "" && input.hasAttribute("required")) {
100
+ stopProceeding = true;
101
+ let elem = input.parentElement.querySelector("[takeInput]");
102
+ let errTxt = document.createElement("p");
103
+ errTxt.classList.add("errTxt");
104
+ errTxt.innerText = "This setting can't be empty!!";
105
+ elem.classList.add("invalid");
106
+ elem.parentElement.insertBefore(errTxt, elem);
107
+ let sidebarElement = input.closest(".set-item").getAttribute("data-id");
108
+ document
109
+ .querySelector(
110
+ `.settings-sidebar .set-name[data-detailId="${sidebarElement}`
111
+ )
112
+ .click();
113
+ stopProceeding = true;
114
  }
115
+ }
116
+ if (!stopProceeding) {
117
+ var expiration_date = new Date();
118
+ expiration_date.setFullYear(expiration_date.getFullYear() + 1);
119
+ let formData = new FormData(document.querySelector("form"));
120
+ for (var [key, value] of formData.entries()) {
121
+ document.cookie = `${key}=${value}; expires=${expiration_date.toUTCString()}`;
122
+ }
123
+ } else {
124
+ return false;
125
+ }
126
+ // On settings saved successfully
127
+ alert("Settings saved succssfully!");
128
+ window.location.reload();
129
  }
130
 
131
+
132
+ /*
133
+ This function will be called on page ready.
134
+ it iterates over saved cookies and if cookie name is
135
+ in the list of valid cookies then load it.
136
+
137
+ - if cookie is searchEng(type=toggle/checkbox) we deselect
138
+ all checkboxes and select those which are stored in cookie.
139
+
140
+ - if cookie is of type `select` we deselect default selected
141
+ option and then select option which is stored in cookie.
142
+ */
143
  function loadUserSettings() {
144
+ let inputs = ["searchEng", "theme", "color-sch"];
145
+ var keyValuePairs = document.cookie.split(";");
146
+ for (var i = 0; i < keyValuePairs.length; i++) {
147
+ var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf("="));
148
+ var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf("=") + 1);
149
+ name = name.trim();
150
+ if (!inputs.includes(name)) {
151
+ continue;
152
+ }
153
+ let input = document.getElementsByName(name)[0];
154
+ input.value = value;
155
+ if (name == "searchEng") {
156
+ // Unload all checked engines
157
+ document
158
+ .querySelectorAll(".searchEng-elem input[type=checkbox]")
159
+ .forEach((e) => {
160
+ e.checked = false;
161
+ });
162
+ value = value.replace(" ", "");
163
+ value.split(",").forEach((val) => {
164
+ if (!val) {
165
+ return;
 
 
 
166
  }
167
+ document
168
+ .querySelector(`[data-isCheckbox][data-value="${val}"]`)
169
+ .parentElement.querySelector("input").checked = true;
170
+ });
171
+ } else {
172
+ // Unload all selected options
173
+ document
174
+ .querySelector(
175
+ `[data-input="${name}"] .options span[data-value="${value}"]`
176
+ )
177
+ .removeAttribute("selected");
178
+ singleSelectClickHandler(
179
+ document.querySelector(`.options span[data-value="${value}"]`)
180
+ );
181
  }
182
+ }
183
  }
184
 
185
+ // Code where settings are loaded from cookie.
186
  loadUserSettings();
public/templates/header.html CHANGED
@@ -24,6 +24,6 @@
24
 
25
  head.appendChild(link);
26
  }
27
- addCss('static/themes/'+ (cookies["theme"] || {{theme}}) + '.css');
28
- addCss('static/colorschemes/'+ (cookies["color-sch"] || {{colorscheme}}) + '.css');
29
  </script>
 
24
 
25
  head.appendChild(link);
26
  }
27
+ addCss('static/themes/'+ (cookies["theme"] || '{{theme}}') + '.css');
28
+ addCss('static/colorschemes/'+ (cookies["color-sch"] || '{{colorscheme}}') + '.css');
29
  </script>