Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: new-options.js

Issue 29375899: Issue 4871 - Start using ESLint for adblockplusui (Closed)
Patch Set: Started addressing Sebastian's initial feedback Created Feb. 23, 2017, 11:09 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « messageResponder.js ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2016 Eyeo GmbH 3 * Copyright (C) 2006-2016 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 /* globals checkShareResource, getDocLink, i18nFormatDateTime, openSharePopup,
19 E */
20
18 "use strict"; 21 "use strict";
19 22
20 (function()
21 { 23 {
22 var subscriptionsMap = Object.create(null); 24 let subscriptionsMap = Object.create(null);
23 var filtersMap = Object.create(null); 25 let filtersMap = Object.create(null);
24 var collections = Object.create(null); 26 let collections = Object.create(null);
25 var acceptableAdsUrl = null; 27 let acceptableAdsUrl = null;
26 var getMessage = ext.i18n.getMessage; 28 let {getMessage} = ext.i18n;
27 var filterErrors = 29 let filterErrors = new Map([
28 { 30 ["synchronize_invalid_url",
29 "synchronize_invalid_url": "options_filterList_lastDownload_invalidURL", 31 "options_filterList_lastDownload_invalidURL"],
30 "synchronize_connection_error": "options_filterList_lastDownload_connectionE rror", 32 ["synchronize_connection_error",
31 "synchronize_invalid_data": "options_filterList_lastDownload_invalidData", 33 "options_filterList_lastDownload_connectionError"],
32 "synchronize_checksum_mismatch": "options_filterList_lastDownload_checksumMi smatch" 34 ["synchronize_invalid_data",
33 }; 35 "options_filterList_lastDownload_invalidData"],
36 ["synchronize_checksum_mismatch",
37 "options_filterList_lastDownload_checksumMismatch"]
38 ]);
34 39
35 function Collection(details) 40 function Collection(details)
36 { 41 {
37 this.details = details; 42 this.details = details;
38 this.items = []; 43 this.items = [];
39 } 44 }
40 45
41 Collection.prototype._setEmpty = function(table, text) 46 Collection.prototype._setEmpty = function(table, text)
42 { 47 {
43 var placeholder = table.querySelector(".empty-placeholder"); 48 let placeholder = table.querySelector(".empty-placeholder");
44 if (text && !placeholder) 49 if (text && !placeholder)
45 { 50 {
46 placeholder = document.createElement("li"); 51 placeholder = document.createElement("li");
47 placeholder.className = "empty-placeholder"; 52 placeholder.className = "empty-placeholder";
48 placeholder.textContent = getMessage(text); 53 placeholder.textContent = getMessage(text);
49 table.appendChild(placeholder); 54 table.appendChild(placeholder);
50 } 55 }
51 else if (placeholder) 56 else if (placeholder)
52 table.removeChild(placeholder); 57 table.removeChild(placeholder);
53 }; 58 };
54 59
55 Collection.prototype._createElementQuery = function(item) 60 Collection.prototype._createElementQuery = function(item)
56 { 61 {
57 var access = (item.url || item.text).replace(/'/g, "\\'"); 62 let access = (item.url || item.text).replace(/'/g, "\\'");
58 return function(container) 63 return function(container)
59 { 64 {
60 return container.querySelector("[data-access='" + access + "']"); 65 return container.querySelector("[data-access='" + access + "']");
61 }; 66 };
62 }; 67 };
63 68
64 Collection.prototype._getItemTitle = function(item, i) 69 Collection.prototype._getItemTitle = function(item, i)
65 { 70 {
66 if (item.url == acceptableAdsUrl) 71 if (item.url == acceptableAdsUrl)
67 return getMessage("options_acceptableAds_description"); 72 return getMessage("options_acceptableAds_description");
68 if (this.details[i].useOriginalTitle && item.originalTitle) 73 if (this.details[i].useOriginalTitle && item.originalTitle)
69 return item.originalTitle; 74 return item.originalTitle;
70 return item.title || item.url || item.text; 75 return item.title || item.url || item.text;
71 }; 76 };
72 77
73 Collection.prototype.addItem = function(item) 78 Collection.prototype.addItem = function(item)
74 { 79 {
75 if (this.items.indexOf(item) >= 0) 80 if (this.items.indexOf(item) >= 0)
76 return; 81 return;
77 82
78 this.items.push(item); 83 this.items.push(item);
79 this.items.sort(function(a, b) 84 this.items.sort((a, b) =>
80 { 85 {
81 // Make sure that Acceptable Ads is always last, since it cannot be 86 // Make sure that Acceptable Ads is always last, since it cannot be
82 // disabled, but only be removed. That way it's grouped together with 87 // disabled, but only be removed. That way it's grouped together with
83 // the "Own filter list" which cannot be disabled either at the bottom 88 // the "Own filter list" which cannot be disabled either at the bottom
84 // of the filter lists in the Advanced tab. 89 // of the filter lists in the Advanced tab.
85 if (a.url == acceptableAdsUrl) 90 if (a.url == acceptableAdsUrl)
86 return 1; 91 return 1;
87 if (b.url == acceptableAdsUrl) 92 if (b.url == acceptableAdsUrl)
88 return -1; 93 return -1;
89 94
90 var aTitle = this._getItemTitle(a, 0).toLowerCase(); 95 let aTitle = this._getItemTitle(a, 0).toLowerCase();
91 var bTitle = this._getItemTitle(b, 0).toLowerCase(); 96 let bTitle = this._getItemTitle(b, 0).toLowerCase();
92 return aTitle.localeCompare(bTitle); 97 return aTitle.localeCompare(bTitle);
93 }.bind(this)); 98 });
94 99
95 for (var j = 0; j < this.details.length; j++) 100 for (let j = 0; j < this.details.length; j++)
96 { 101 {
97 var table = E(this.details[j].id); 102 let table = E(this.details[j].id);
98 var template = table.querySelector("template"); 103 let template = table.querySelector("template");
99 var listItem = document.createElement("li"); 104 let listItem = document.createElement("li");
100 listItem.appendChild(document.importNode(template.content, true)); 105 listItem.appendChild(document.importNode(template.content, true));
101 listItem.setAttribute("aria-label", this._getItemTitle(item, j)); 106 listItem.setAttribute("aria-label", this._getItemTitle(item, j));
102 listItem.setAttribute("data-access", item.url || item.text); 107 listItem.setAttribute("data-access", item.url || item.text);
103 listItem.setAttribute("role", "section"); 108 listItem.setAttribute("role", "section");
104 109
105 var label = listItem.querySelector(".display"); 110 let label = listItem.querySelector(".display");
106 if (item.recommended && label.hasAttribute("data-tooltip")) 111 if (item.recommended && label.hasAttribute("data-tooltip"))
107 { 112 {
108 var tooltipId = label.getAttribute("data-tooltip"); 113 let tooltipId = label.getAttribute("data-tooltip");
109 tooltipId = tooltipId.replace("%value%", item.recommended); 114 tooltipId = tooltipId.replace("%value%", item.recommended);
110 label.setAttribute("data-tooltip", tooltipId); 115 label.setAttribute("data-tooltip", tooltipId);
111 } 116 }
112 117
113 var controls = listItem.querySelectorAll(".control"); 118 let controls = listItem.querySelectorAll(".control");
114 for (var k = 0; k < controls.length; k++) 119 for (let k = 0; k < controls.length; k++)
115 { 120 {
116 if (controls[k].hasAttribute("title")) 121 if (controls[k].hasAttribute("title"))
117 { 122 {
118 var titleValue = getMessage(controls[k].getAttribute("title")); 123 let titleValue = getMessage(controls[k].getAttribute("title"));
119 controls[k].setAttribute("title", titleValue) 124 controls[k].setAttribute("title", titleValue);
120 } 125 }
121 } 126 }
122 127
123 this._setEmpty(table, null); 128 this._setEmpty(table, null);
124 if (table.hasChildNodes()) 129 if (table.hasChildNodes())
125 { 130 {
126 table.insertBefore(listItem, 131 table.insertBefore(listItem,
127 table.childNodes[this.items.indexOf(item)]); 132 table.childNodes[this.items.indexOf(item)]);
128 } 133 }
129 else 134 else
130 table.appendChild(listItem); 135 table.appendChild(listItem);
131 this.updateItem(item); 136 this.updateItem(item);
132 } 137 }
133 return length; 138 return length;
134 }; 139 };
135 140
136 Collection.prototype.removeItem = function(item) 141 Collection.prototype.removeItem = function(item)
137 { 142 {
138 var index = this.items.indexOf(item); 143 let index = this.items.indexOf(item);
139 if (index == -1) 144 if (index == -1)
140 return; 145 return;
141 146
142 this.items.splice(index, 1); 147 this.items.splice(index, 1);
143 var getListElement = this._createElementQuery(item); 148 let getListElement = this._createElementQuery(item);
144 for (var i = 0; i < this.details.length; i++) 149 for (let i = 0; i < this.details.length; i++)
145 { 150 {
146 var table = E(this.details[i].id); 151 let table = E(this.details[i].id);
147 var element = getListElement(table); 152 let element = getListElement(table);
148 153
149 // Element gets removed so make sure to handle focus appropriately 154 // Element gets removed so make sure to handle focus appropriately
150 var control = element.querySelector(".control"); 155 let control = element.querySelector(".control");
151 if (control && control == document.activeElement) 156 if (control && control == document.activeElement)
152 { 157 {
153 if (!focusNextElement(element.parentElement, control)) 158 if (!focusNextElement(element.parentElement, control))
154 { 159 {
155 // Fall back to next focusable element within same tab or dialog 160 // Fall back to next focusable element within same tab or dialog
156 var focusableElement = element.parentElement; 161 let focusableElement = element.parentElement;
157 while (focusableElement) 162 while (focusableElement)
158 { 163 {
159 if (focusableElement.classList.contains("tab-content") 164 if (focusableElement.classList.contains("tab-content") ||
160 || focusableElement.classList.contains("dialog-content")) 165 focusableElement.classList.contains("dialog-content"))
161 break; 166 break;
162 167
163 focusableElement = focusableElement.parentElement; 168 focusableElement = focusableElement.parentElement;
164 } 169 }
165 focusNextElement(focusableElement || document, control); 170 focusNextElement(focusableElement || document, control);
166 } 171 }
167 } 172 }
168 173
169 element.parentElement.removeChild(element); 174 element.parentElement.removeChild(element);
170 if (this.items.length == 0) 175 if (this.items.length == 0)
171 this._setEmpty(table, this.details[i].emptyText); 176 this._setEmpty(table, this.details[i].emptyText);
172 } 177 }
173 }; 178 };
174 179
175 Collection.prototype.updateItem = function(item) 180 Collection.prototype.updateItem = function(item)
176 { 181 {
177 var access = (item.url || item.text).replace(/'/g, "\\'"); 182 let access = (item.url || item.text).replace(/'/g, "\\'");
178 for (var i = 0; i < this.details.length; i++) 183 for (let i = 0; i < this.details.length; i++)
179 { 184 {
180 var table = E(this.details[i].id); 185 let table = E(this.details[i].id);
181 var element = table.querySelector("[data-access='" + access + "']"); 186 let element = table.querySelector("[data-access='" + access + "']");
182 if (!element) 187 if (!element)
183 continue; 188 continue;
184 189
185 var title = this._getItemTitle(item, i); 190 let title = this._getItemTitle(item, i);
186 element.querySelector(".display").textContent = title; 191 element.querySelector(".display").textContent = title;
187 element.setAttribute("aria-label", title); 192 element.setAttribute("aria-label", title);
188 if (this.details[i].searchable) 193 if (this.details[i].searchable)
189 element.setAttribute("data-search", title.toLowerCase()); 194 element.setAttribute("data-search", title.toLowerCase());
190 var control = element.querySelector(".control[role='checkbox']"); 195 let control = element.querySelector(".control[role='checkbox']");
191 if (control) 196 if (control)
192 { 197 {
193 control.setAttribute("aria-checked", item.disabled == false); 198 control.setAttribute("aria-checked", item.disabled == false);
194 if (item.url == acceptableAdsUrl && this == collections.filterLists) 199 if (item.url == acceptableAdsUrl && this == collections.filterLists)
195 control.setAttribute("disabled", true); 200 control.setAttribute("disabled", true);
196 } 201 }
197 202
198 var dateElement = element.querySelector(".date"); 203 let dateElement = element.querySelector(".date");
199 var timeElement = element.querySelector(".time"); 204 let timeElement = element.querySelector(".time");
200 if (dateElement && timeElement) 205 if (dateElement && timeElement)
201 { 206 {
202 var message = element.querySelector(".message"); 207 let message = element.querySelector(".message");
203 if (item.isDownloading) 208 if (item.isDownloading)
204 { 209 {
205 var text = getMessage("options_filterList_lastDownload_inProgress"); 210 let text = getMessage("options_filterList_lastDownload_inProgress");
206 message.textContent = text; 211 message.textContent = text;
207 element.classList.add("show-message"); 212 element.classList.add("show-message");
208 } 213 }
209 else if (item.downloadStatus != "synchronize_ok") 214 else if (item.downloadStatus != "synchronize_ok")
210 { 215 {
211 var error = filterErrors[item.downloadStatus]; 216 let error = filterErrors.get(item.downloadStatus);
212 if (error) 217 if (error)
213 message.textContent = getMessage(error); 218 message.textContent = getMessage(error);
214 else 219 else
215 message.textContent = item.downloadStatus; 220 message.textContent = item.downloadStatus;
216 element.classList.add("show-message"); 221 element.classList.add("show-message");
217 } 222 }
218 else if (item.lastDownload > 0) 223 else if (item.lastDownload > 0)
219 { 224 {
220 var dateTime = i18n_formatDateTime(item.lastDownload * 1000); 225 let dateTime = i18nFormatDateTime(item.lastDownload * 1000);
221 dateElement.textContent = dateTime[0]; 226 dateElement.textContent = dateTime[0];
222 timeElement.textContent = dateTime[1]; 227 timeElement.textContent = dateTime[1];
223 element.classList.remove("show-message"); 228 element.classList.remove("show-message");
224 } 229 }
225 } 230 }
226 231
227 var websiteElement = element.querySelector(".context-menu .website"); 232 let websiteElement = element.querySelector(".context-menu .website");
228 if (websiteElement) 233 if (websiteElement)
229 { 234 {
230 if (item.homepage) 235 if (item.homepage)
231 websiteElement.setAttribute("href", item.homepage); 236 websiteElement.setAttribute("href", item.homepage);
232 else 237 else
233 websiteElement.setAttribute("aria-hidden", true); 238 websiteElement.setAttribute("aria-hidden", true);
234 } 239 }
235 240
236 var sourceElement = element.querySelector(".context-menu .source"); 241 let sourceElement = element.querySelector(".context-menu .source");
237 if (sourceElement) 242 if (sourceElement)
238 sourceElement.setAttribute("href", item.url); 243 sourceElement.setAttribute("href", item.url);
239 } 244 }
240 }; 245 };
241 246
242 Collection.prototype.clearAll = function() 247 Collection.prototype.clearAll = function()
243 { 248 {
244 this.items = []; 249 this.items = [];
245 for (var i = 0; i < this.details.length; i++) 250 for (let i = 0; i < this.details.length; i++)
246 { 251 {
247 var table = E(this.details[i].id); 252 let table = E(this.details[i].id);
248 var element = table.firstChild; 253 let element = table.firstChild;
249 while (element) 254 while (element)
250 { 255 {
251 if (element.tagName == "LI" && !element.classList.contains("static")) 256 if (element.tagName == "LI" && !element.classList.contains("static"))
252 table.removeChild(element); 257 table.removeChild(element);
253 element = element.nextElementSibling; 258 element = element.nextElementSibling;
254 } 259 }
255 260
256 this._setEmpty(table, this.details[i].emptyText); 261 this._setEmpty(table, this.details[i].emptyText);
257 } 262 }
258 }; 263 };
259 264
260 function focusNextElement(container, currentElement) 265 function focusNextElement(container, currentElement)
261 { 266 {
262 var focusables = container.querySelectorAll("a, button, input, .control"); 267 let focusables = container.querySelectorAll("a, button, input, .control");
263 focusables = Array.prototype.slice.call(focusables); 268 focusables = Array.prototype.slice.call(focusables);
264 var index = focusables.indexOf(currentElement); 269 let index = focusables.indexOf(currentElement);
265 index += (index == focusables.length - 1) ? -1 : 1; 270 index += (index == focusables.length - 1) ? -1 : 1;
266 271
267 var nextElement = focusables[index]; 272 let nextElement = focusables[index];
268 if (!nextElement) 273 if (!nextElement)
269 return false; 274 return false;
270 275
271 nextElement.focus(); 276 nextElement.focus();
272 return true; 277 return true;
273 } 278 }
274 279
275 collections.popular = new Collection( 280 collections.popular = new Collection([
276 [
277 { 281 {
278 id: "recommend-list-table" 282 id: "recommend-list-table"
279 } 283 }
280 ]); 284 ]);
281 collections.langs = new Collection( 285 collections.langs = new Collection([
282 [
283 { 286 {
284 id: "blocking-languages-table", 287 id: "blocking-languages-table",
285 emptyText: "options_dialog_language_added_empty" 288 emptyText: "options_dialog_language_added_empty"
286 }, 289 },
287 { 290 {
288 id: "blocking-languages-dialog-table", 291 id: "blocking-languages-dialog-table",
289 emptyText: "options_dialog_language_added_empty" 292 emptyText: "options_dialog_language_added_empty"
290 } 293 }
291 ]); 294 ]);
292 collections.allLangs = new Collection( 295 collections.allLangs = new Collection([
293 [
294 { 296 {
295 id: "all-lang-table", 297 id: "all-lang-table",
296 emptyText: "options_dialog_language_other_empty", 298 emptyText: "options_dialog_language_other_empty",
297 searchable: true 299 searchable: true
298 } 300 }
299 ]); 301 ]);
300 collections.acceptableAds = new Collection( 302 collections.acceptableAds = new Collection([
301 [
302 { 303 {
303 id: "acceptableads-table" 304 id: "acceptableads-table"
304 } 305 }
305 ]); 306 ]);
306 collections.custom = new Collection( 307 collections.custom = new Collection([
307 [
308 { 308 {
309 id: "custom-list-table" 309 id: "custom-list-table"
310 } 310 }
311 ]); 311 ]);
312 collections.whitelist = new Collection( 312 collections.whitelist = new Collection([
313 [
314 { 313 {
315 id: "whitelisting-table", 314 id: "whitelisting-table",
316 emptyText: "options_whitelisted_empty" 315 emptyText: "options_whitelisted_empty"
317 } 316 }
318 ]); 317 ]);
319 collections.customFilters = new Collection( 318 collections.customFilters = new Collection([
320 [
321 { 319 {
322 id: "custom-filters-table", 320 id: "custom-filters-table",
323 emptyText: "options_customFilters_empty" 321 emptyText: "options_customFilters_empty"
324 } 322 }
325 ]); 323 ]);
326 collections.filterLists = new Collection( 324 collections.filterLists = new Collection([
327 [
328 { 325 {
329 id: "all-filter-lists-table", 326 id: "all-filter-lists-table",
330 useOriginalTitle: true 327 useOriginalTitle: true
331 } 328 }
332 ]); 329 ]);
333 330
334 function toggleShowLanguage(subscription) 331 function toggleShowLanguage(subscription)
335 { 332 {
336 if (subscription.recommended == "ads") 333 if (subscription.recommended == "ads")
337 { 334 {
338 if (subscription.disabled) 335 if (subscription.disabled)
339 { 336 {
340 collections.allLangs.addItem(subscription); 337 collections.allLangs.addItem(subscription);
341 collections.langs.removeItem(subscription); 338 collections.langs.removeItem(subscription);
342 } 339 }
343 else 340 else
344 { 341 {
345 collections.allLangs.removeItem(subscription); 342 collections.allLangs.removeItem(subscription);
346 collections.langs.addItem(subscription); 343 collections.langs.addItem(subscription);
347 } 344 }
348 } 345 }
349 } 346 }
350 347
351 function addSubscription(subscription) 348 function addSubscription(subscription)
352 { 349 {
353 var collection; 350 let collection;
354 if (subscription.recommended) 351 if (subscription.recommended)
355 { 352 {
356 if (subscription.recommended != "ads") 353 if (subscription.recommended != "ads")
357 collection = collections.popular; 354 collection = collections.popular;
358 else if (subscription.disabled == false) 355 else if (subscription.disabled == false)
359 collection = collections.langs; 356 collection = collections.langs;
360 else 357 else
361 collection = collections.allLangs; 358 collection = collections.allLangs;
362 } 359 }
363 else if (subscription.url == acceptableAdsUrl) 360 else if (subscription.url == acceptableAdsUrl)
364 collection = collections.acceptableAds; 361 collection = collections.acceptableAds;
365 else 362 else
366 collection = collections.custom; 363 collection = collections.custom;
367 364
368 collection.addItem(subscription); 365 collection.addItem(subscription);
369 subscriptionsMap[subscription.url] = subscription; 366 subscriptionsMap[subscription.url] = subscription;
370 toggleShowLanguage(subscription); 367 toggleShowLanguage(subscription);
371 updateTooltips(); 368 updateTooltips();
372 } 369 }
373 370
374 function updateSubscription(subscription) 371 function updateSubscription(subscription)
375 { 372 {
376 for (var name in collections) 373 for (let name in collections)
377 collections[name].updateItem(subscription); 374 collections[name].updateItem(subscription);
378 375
379 toggleShowLanguage(subscription); 376 toggleShowLanguage(subscription);
380 } 377 }
381 378
382 function updateFilter(filter) 379 function updateFilter(filter)
383 { 380 {
384 var match = filter.text.match(/^@@\|\|([^\/:]+)\^\$document$/); 381 let match = filter.text.match(/^@@\|\|([^/:]+)\^\$document$/);
385 if (match && !filtersMap[filter.text]) 382 if (match && !filtersMap[filter.text])
386 { 383 {
387 filter.title = match[1]; 384 filter.title = match[1];
388 collections.whitelist.addItem(filter); 385 collections.whitelist.addItem(filter);
389 } 386 }
390 else 387 else
391 collections.customFilters.addItem(filter); 388 collections.customFilters.addItem(filter);
392 389
393 filtersMap[filter.text] = filter; 390 filtersMap[filter.text] = filter;
394 } 391 }
395 392
396 function loadRecommendations() 393 function loadRecommendations()
397 { 394 {
398 fetch("subscriptions.xml") 395 fetch("subscriptions.xml")
399 .then(function(response) 396 .then(response =>
400 { 397 {
401 return response.text(); 398 return response.text();
402 }) 399 })
403 .then(function(text) 400 .then(text =>
404 { 401 {
405 var list = document.getElementById("subscriptionSelector"); 402 let doc = new DOMParser().parseFromString(text, "application/xml");
406 var doc = new DOMParser().parseFromString(text, "application/xml"); 403 let elements = doc.documentElement.getElementsByTagName("subscription");
407 var elements = doc.documentElement.getElementsByTagName("subscription"); 404 for (let i = 0; i < elements.length; i++)
408 for (var i = 0; i < elements.length; i++)
409 { 405 {
410 var element = elements[i]; 406 let element = elements[i];
411 var type = element.getAttribute("type"); 407 let type = element.getAttribute("type");
412 var subscription = { 408 let subscription = {
413 disabled: true, 409 disabled: true,
414 downloadStatus: null, 410 downloadStatus: null,
415 homepage: null, 411 homepage: null,
416 originalTitle: element.getAttribute("title"), 412 originalTitle: element.getAttribute("title"),
417 recommended: type, 413 recommended: type,
418 url: element.getAttribute("url") 414 url: element.getAttribute("url")
419 }; 415 };
420 416
421 var prefix = element.getAttribute("prefixes"); 417 let prefix = element.getAttribute("prefixes");
422 if (prefix) 418 if (prefix)
423 { 419 {
424 prefix = prefix.replace(/\W/g, "_"); 420 prefix = prefix.replace(/\W/g, "_");
425 subscription.title = getMessage("options_language_" + prefix); 421 subscription.title = getMessage("options_language_" + prefix);
426 } 422 }
427 else 423 else
428 { 424 {
429 type = type.replace(/\W/g, "_"); 425 type = type.replace(/\W/g, "_");
430 subscription.title = getMessage("common_feature_" + type + "_title") ; 426 subscription.title = getMessage("common_feature_" +
427 type + "_title");
431 } 428 }
432 429
433 addSubscription(subscription); 430 addSubscription(subscription);
434 } 431 }
435 }); 432 });
436 } 433 }
437 434
438 function findParentData(element, dataName, returnElement) 435 function findParentData(element, dataName, returnElement)
439 { 436 {
440 while (element) 437 while (element)
441 { 438 {
442 if (element.hasAttribute("data-" + dataName)) 439 if (element.hasAttribute("data-" + dataName))
443 return returnElement ? element : element.getAttribute("data-" + dataName ); 440 {
441 if (returnElement)
442 return element;
443 return element.getAttribute("data-" + dataName);
444 }
444 445
445 element = element.parentElement; 446 element = element.parentElement;
446 } 447 }
447 return null; 448 return null;
448 } 449 }
449 450
450 function sendMessageHandleErrors(message, onSuccess) 451 function sendMessageHandleErrors(message, onSuccess)
451 { 452 {
452 ext.backgroundPage.sendMessage(message, function(errors) 453 ext.backgroundPage.sendMessage(message, errors =>
453 { 454 {
454 if (errors.length > 0) 455 if (errors.length > 0)
455 alert(errors.join("\n")); 456 alert(errors.join("\n"));
456 else if (onSuccess) 457 else if (onSuccess)
457 onSuccess(); 458 onSuccess();
458 }); 459 });
459 } 460 }
460 461
461 function openDocLink(id) 462 function openDocLink(id)
462 { 463 {
463 getDocLink(id, function(link) 464 getDocLink(id, link =>
464 { 465 {
465 if (id == "share-general") 466 if (id == "share-general")
466 openSharePopup(link); 467 openSharePopup(link);
467 else 468 else
468 location.href = link; 469 location.href = link;
469 }); 470 });
470 } 471 }
471 472
472 function switchTab(id) 473 function switchTab(id)
473 { 474 {
474 location.hash = id; 475 location.hash = id;
475 } 476 }
476 477
477 function onClick(e) 478 function onClick(e)
478 { 479 {
479 var context = document.querySelector(".show-context-menu"); 480 let context = document.querySelector(".show-context-menu");
480 if (context) 481 if (context)
481 context.classList.remove("show-context-menu"); 482 context.classList.remove("show-context-menu");
482 483
483 var element = e.target; 484 let element = e.target;
484 while (true) 485 while (element && !element.hasAttribute("data-action"))
485 { 486 element = element.parentElement;
486 if (!element)
487 return;
488 487
489 if (element.hasAttribute("data-action")) 488 element = findParentData(e.target, "action", true);
490 break; 489 let actions = element.getAttribute("data-action").split(",");
491 490 for (let i = 0; i < actions.length; i++)
492 element = element.parentElement;
493 }
494
495 var element = findParentData(e.target, "action", true);
496 var actions = element.getAttribute("data-action").split(",");
497 for (var i = 0; i < actions.length; i++)
498 { 491 {
499 switch (actions[i]) 492 switch (actions[i])
500 { 493 {
501 case "add-domain-exception": 494 case "add-domain-exception":
502 addWhitelistedDomain(); 495 addWhitelistedDomain();
503 break; 496 break;
504 case "add-predefined-subscription": 497 case "add-predefined-subscription": {
505 var dialog = E("dialog-content-predefined"); 498 let dialog = E("dialog-content-predefined");
506 var title = dialog.querySelector("h3").textContent; 499 let title = dialog.querySelector("h3").textContent;
507 var url = dialog.querySelector(".url").textContent; 500 let url = dialog.querySelector(".url").textContent;
508 addEnableSubscription(url, title); 501 addEnableSubscription(url, title);
509 closeDialog(); 502 closeDialog();
510 break; 503 break;
504 }
511 case "cancel-custom-filters": 505 case "cancel-custom-filters":
512 E("custom-filters").classList.remove("mode-edit"); 506 E("custom-filters").classList.remove("mode-edit");
513 break; 507 break;
514 case "cancel-domain-exception": 508 case "cancel-domain-exception":
515 E("whitelisting-textbox").value = ""; 509 E("whitelisting-textbox").value = "";
516 document.querySelector("#whitelisting .controls").classList.remove("mo de-edit"); 510 document.querySelector("#whitelisting .controls").classList.
511 remove("mode-edit");
517 break; 512 break;
518 case "close-dialog": 513 case "close-dialog":
519 closeDialog(); 514 closeDialog();
520 break; 515 break;
521 case "edit-custom-filters": 516 case "edit-custom-filters":
522 E("custom-filters").classList.add("mode-edit"); 517 E("custom-filters").classList.add("mode-edit");
523 editCustomFilters(); 518 editCustomFilters();
524 break; 519 break;
525 case "edit-domain-exception": 520 case "edit-domain-exception":
526 document.querySelector("#whitelisting .controls").classList.add("mode- edit"); 521 document.querySelector("#whitelisting .controls").classList.
522 add("mode-edit");
527 E("whitelisting-textbox").focus(); 523 E("whitelisting-textbox").focus();
528 break; 524 break;
529 case "import-subscription": 525 case "import-subscription": {
530 var url = E("blockingList-textbox").value; 526 let url = E("blockingList-textbox").value;
531 addEnableSubscription(url); 527 addEnableSubscription(url);
532 closeDialog(); 528 closeDialog();
533 break; 529 break;
534 case "open-dialog": 530 }
535 var dialog = findParentData(element, "dialog", false); 531 case "open-dialog": {
532 let dialog = findParentData(element, "dialog", false);
536 openDialog(dialog); 533 openDialog(dialog);
537 break; 534 break;
538 case "open-doclink": 535 }
539 var doclink = findParentData(element, "doclink", false); 536 case "open-doclink": {
537 let doclink = findParentData(element, "doclink", false);
540 openDocLink(doclink); 538 openDocLink(doclink);
541 break; 539 break;
540 }
542 case "save-custom-filters": 541 case "save-custom-filters":
543 sendMessageHandleErrors( 542 sendMessageHandleErrors({
544 {
545 type: "filters.importRaw", 543 type: "filters.importRaw",
546 text: E("custom-filters-raw").value, 544 text: E("custom-filters-raw").value,
547 removeExisting: true 545 removeExisting: true
548 }, 546 },
549 function() 547 () =>
550 { 548 {
551 E("custom-filters").classList.remove("mode-edit"); 549 E("custom-filters").classList.remove("mode-edit");
552 }); 550 });
553 break; 551 break;
554 case "switch-tab": 552 case "switch-tab": {
555 var tabId = findParentData(e.target, "tab", false); 553 let tabId = findParentData(e.target, "tab", false);
556 switchTab(tabId); 554 switchTab(tabId);
557 break; 555 break;
556 }
558 case "toggle-pref": 557 case "toggle-pref":
559 ext.backgroundPage.sendMessage( 558 ext.backgroundPage.sendMessage({
560 {
561 type: "prefs.toggle", 559 type: "prefs.toggle",
562 key: findParentData(element, "pref", false) 560 key: findParentData(element, "pref", false)
563 }); 561 });
564 break; 562 break;
565 case "update-all-subscriptions": 563 case "update-all-subscriptions":
566 ext.backgroundPage.sendMessage( 564 ext.backgroundPage.sendMessage({
567 {
568 type: "subscriptions.update" 565 type: "subscriptions.update"
569 }); 566 });
570 break; 567 break;
571 case "open-context-menu": 568 case "open-context-menu": {
572 var listItem = findParentData(element, "access", true); 569 let listItem = findParentData(element, "access", true);
573 if (listItem != context) 570 if (listItem != context)
574 listItem.classList.add("show-context-menu"); 571 listItem.classList.add("show-context-menu");
575 break; 572 break;
573 }
576 case "update-subscription": 574 case "update-subscription":
577 ext.backgroundPage.sendMessage( 575 ext.backgroundPage.sendMessage({
578 {
579 type: "subscriptions.update", 576 type: "subscriptions.update",
580 url: findParentData(element, "access", false) 577 url: findParentData(element, "access", false)
581 }); 578 });
582 break; 579 break;
583 case "remove-subscription": 580 case "remove-subscription":
584 ext.backgroundPage.sendMessage( 581 ext.backgroundPage.sendMessage({
585 {
586 type: "subscriptions.remove", 582 type: "subscriptions.remove",
587 url: findParentData(element, "access", false) 583 url: findParentData(element, "access", false)
588 }); 584 });
589 break; 585 break;
590 case "toggle-remove-subscription": 586 case "toggle-remove-subscription": {
591 var subscriptionUrl = findParentData(element, "access", false); 587 let subscriptionUrl = findParentData(element, "access", false);
592 if (element.getAttribute("aria-checked") == "true") 588 if (element.getAttribute("aria-checked") == "true")
593 { 589 {
594 ext.backgroundPage.sendMessage({ 590 ext.backgroundPage.sendMessage({
595 type: "subscriptions.remove", 591 type: "subscriptions.remove",
596 url: subscriptionUrl 592 url: subscriptionUrl
597 }); 593 });
598 } 594 }
599 else 595 else
600 addEnableSubscription(subscriptionUrl); 596 addEnableSubscription(subscriptionUrl);
601 break; 597 break;
598 }
602 case "toggle-disable-subscription": 599 case "toggle-disable-subscription":
603 ext.backgroundPage.sendMessage( 600 ext.backgroundPage.sendMessage({
604 {
605 type: "subscriptions.toggle", 601 type: "subscriptions.toggle",
606 keepInstalled: true, 602 keepInstalled: true,
607 url: findParentData(element, "access", false) 603 url: findParentData(element, "access", false)
608 }); 604 });
609 break; 605 break;
610 case "add-language-subscription": 606 case "add-language-subscription":
611 addEnableSubscription(findParentData(element, "access", false)); 607 addEnableSubscription(findParentData(element, "access", false));
612 break; 608 break;
613 case "remove-filter": 609 case "remove-filter":
614 ext.backgroundPage.sendMessage( 610 ext.backgroundPage.sendMessage({
615 {
616 type: "filters.remove", 611 type: "filters.remove",
617 text: findParentData(element, "access", false) 612 text: findParentData(element, "access", false)
618 }); 613 });
619 break; 614 break;
620 } 615 }
621 } 616 }
622 } 617 }
623 618
624 function getKey(e) 619 function getKey(e)
625 { 620 {
626 // e.keyCode has been deprecated so we attempt to use e.key 621 // e.keyCode has been deprecated so we attempt to use e.key
627 if ("key" in e) 622 if ("key" in e)
628 return e.key; 623 return e.key;
629 return getKey.keys[e.keyCode]; 624 return getKey.keys[e.keyCode];
630 } 625 }
631 getKey.keys = { 626 getKey.keys = {
632 9: "Tab", 627 9: "Tab",
633 13: "Enter", 628 13: "Enter",
634 27: "Escape", 629 27: "Escape",
635 37: "ArrowLeft", 630 37: "ArrowLeft",
636 38: "ArrowUp", 631 38: "ArrowUp",
637 39: "ArrowRight", 632 39: "ArrowRight",
638 40: "ArrowDown" 633 40: "ArrowDown"
639 }; 634 };
640 635
641 function onKeyUp(e) 636 function onKeyUp(e)
642 { 637 {
643 var key = getKey(e); 638 let key = getKey(e);
644 var element = document.activeElement; 639 let element = document.activeElement;
645 if (!key || !element) 640 if (!key || !element)
646 return; 641 return;
647 642
648 var container = findParentData(element, "action", true); 643 let container = findParentData(element, "action", true);
649 if (!container || !container.hasAttribute("data-keys")) 644 if (!container || !container.hasAttribute("data-keys"))
650 return; 645 return;
651 646
652 var keys = container.getAttribute("data-keys").split(" "); 647 let keys = container.getAttribute("data-keys").split(" ");
653 if (keys.indexOf(key) < 0) 648 if (keys.indexOf(key) < 0)
654 return; 649 return;
655 650
656 switch (container.getAttribute("data-action")) 651 switch (container.getAttribute("data-action"))
657 { 652 {
658 case "add-domain-exception": 653 case "add-domain-exception":
659 addWhitelistedDomain(); 654 addWhitelistedDomain();
660 break; 655 break;
661 case "open-doclink": 656 case "open-doclink":
662 var doclink = findParentData(element, "doclink", false); 657 let doclink = findParentData(element, "doclink", false);
663 openDocLink(doclink); 658 openDocLink(doclink);
664 break; 659 break;
665 case "switch-tab": 660 case "switch-tab":
666 if (key == "Enter") 661 if (key == "Enter")
667 { 662 {
668 var tabId = findParentData(element, "tab", false); 663 let tabId = findParentData(element, "tab", false);
669 switchTab(tabId); 664 switchTab(tabId);
670 } 665 }
671 else if (element.hasAttribute("aria-selected")) 666 else if (element.hasAttribute("aria-selected"))
672 { 667 {
673 if (key == "ArrowLeft" || key == "ArrowUp") 668 if (key == "ArrowLeft" || key == "ArrowUp")
674 { 669 {
675 element = element.previousElementSibling 670 element = element.previousElementSibling ||
676 || container.lastElementChild; 671 container.lastElementChild;
677 } 672 }
678 else if (key == "ArrowRight" || key == "ArrowDown") 673 else if (key == "ArrowRight" || key == "ArrowDown")
679 { 674 {
680 element = element.nextElementSibling 675 element = element.nextElementSibling ||
681 || container.firstElementChild; 676 container.firstElementChild;
682 } 677 }
683 678
684 var tabId = findParentData(element, "tab", false); 679 let tabId = findParentData(element, "tab", false);
685 switchTab(tabId); 680 switchTab(tabId);
686 } 681 }
687 break; 682 break;
688 } 683 }
689 } 684 }
690 685
691 function selectTabItem(tabId, container, focus) 686 function selectTabItem(tabId, container, focus)
692 { 687 {
693 // Show tab content 688 // Show tab content
694 document.body.setAttribute("data-tab", tabId); 689 document.body.setAttribute("data-tab", tabId);
695 690
696 // Select tab 691 // Select tab
697 var tabList = container.querySelector("[role='tablist']"); 692 let tabList = container.querySelector("[role='tablist']");
698 if (!tabList) 693 if (!tabList)
699 return null; 694 return null;
700 695
701 var previousTab = tabList.querySelector("[aria-selected]"); 696 let previousTab = tabList.querySelector("[aria-selected]");
702 previousTab.removeAttribute("aria-selected"); 697 previousTab.removeAttribute("aria-selected");
703 previousTab.setAttribute("tabindex", -1); 698 previousTab.setAttribute("tabindex", -1);
704 699
705 var tab = tabList.querySelector("li[data-tab='" + tabId + "']"); 700 let tab = tabList.querySelector("li[data-tab='" + tabId + "']");
706 tab.setAttribute("aria-selected", true); 701 tab.setAttribute("aria-selected", true);
707 tab.setAttribute("tabindex", 0); 702 tab.setAttribute("tabindex", 0);
708 703
709 var tabContentId = tab.getAttribute("aria-controls"); 704 let tabContentId = tab.getAttribute("aria-controls");
710 var tabContent = document.getElementById(tabContentId); 705 let tabContent = document.getElementById(tabContentId);
711 706
712 // Select sub tabs 707 // Select sub tabs
713 if (tab.hasAttribute("data-subtab")) 708 if (tab.hasAttribute("data-subtab"))
714 selectTabItem(tab.getAttribute("data-subtab"), tabContent, false); 709 selectTabItem(tab.getAttribute("data-subtab"), tabContent, false);
715 710
716 if (tab && focus) 711 if (tab && focus)
717 tab.focus(); 712 tab.focus();
718 713
719 return tabContent; 714 return tabContent;
720 } 715 }
721 716
722 function onHashChange() 717 function onHashChange()
723 { 718 {
724 var hash = location.hash.substr(1); 719 let hash = location.hash.substr(1);
725 if (!hash) 720 if (!hash)
726 return; 721 return;
727 722
728 // Select tab and parent tabs 723 // Select tab and parent tabs
729 var tabIds = hash.split("-"); 724 let tabIds = hash.split("-");
730 var tabContent = document.body; 725 let tabContent = document.body;
731 for (var i = 0; i < tabIds.length; i++) 726 for (let i = 0; i < tabIds.length; i++)
732 { 727 {
733 var tabId = tabIds.slice(0, i + 1).join("-"); 728 let tabId = tabIds.slice(0, i + 1).join("-");
734 tabContent = selectTabItem(tabId, tabContent, true); 729 tabContent = selectTabItem(tabId, tabContent, true);
735 if (!tabContent) 730 if (!tabContent)
736 break; 731 break;
737 } 732 }
738 } 733 }
739 734
740 function onDOMLoaded() 735 function onDOMLoaded()
741 { 736 {
742 populateLists(); 737 populateLists();
743 function onFindLanguageKeyUp() 738 function onFindLanguageKeyUp()
744 { 739 {
745 var searchStyle = E("search-style"); 740 let searchStyle = E("search-style");
746 if (!this.value) 741 if (!this.value)
747 searchStyle.innerHTML = ""; 742 searchStyle.innerHTML = "";
748 else 743 else
749 searchStyle.innerHTML = "#all-lang-table li:not([data-search*=\"" + this .value.toLowerCase() + "\"]) { display: none; }"; 744 {
745 searchStyle.innerHTML = "#all-lang-table li:not([data-search*=\"" +
746 this.value.toLowerCase() + "\"]) { display: none; }";
747 }
750 } 748 }
751 749
752 // Initialize navigation sidebar 750 // Initialize navigation sidebar
753 ext.backgroundPage.sendMessage( 751 ext.backgroundPage.sendMessage({
754 {
755 type: "app.get", 752 type: "app.get",
756 what: "addonVersion" 753 what: "addonVersion"
757 }, 754 },
758 function(addonVersion) 755 addonVersion =>
759 { 756 {
760 E("abp-version").textContent = addonVersion; 757 E("abp-version").textContent = addonVersion;
761 }); 758 });
762 getDocLink("releases", function(link) 759 getDocLink("releases", link =>
763 { 760 {
764 E("link-version").setAttribute("href", link); 761 E("link-version").setAttribute("href", link);
765 }); 762 });
766 763
767 updateShareLink(); 764 updateShareLink();
768 updateTooltips(); 765 updateTooltips();
769 766
770 // Initialize interactive UI elements 767 // Initialize interactive UI elements
771 document.body.addEventListener("click", onClick, false); 768 document.body.addEventListener("click", onClick, false);
772 document.body.addEventListener("keyup", onKeyUp, false); 769 document.body.addEventListener("keyup", onKeyUp, false);
773 var placeholderValue = getMessage("options_dialog_language_find"); 770 let placeholderValue = getMessage("options_dialog_language_find");
774 E("find-language").setAttribute("placeholder", placeholderValue); 771 E("find-language").setAttribute("placeholder", placeholderValue);
775 E("find-language").addEventListener("keyup", onFindLanguageKeyUp, false); 772 E("find-language").addEventListener("keyup", onFindLanguageKeyUp, false);
776 E("whitelisting-textbox").addEventListener("keypress", function(e) 773 E("whitelisting-textbox").addEventListener("keypress", e =>
777 { 774 {
778 if (getKey(e) == "Enter") 775 if (getKey(e) == "Enter")
779 addWhitelistedDomain(); 776 addWhitelistedDomain();
780 }, false); 777 }, false);
781 778
782 // Advanced tab 779 // Advanced tab
783 var tweaks = document.querySelectorAll("#tweaks li[data-pref]"); 780 let tweaks = document.querySelectorAll("#tweaks li[data-pref]");
784 tweaks = Array.prototype.map.call(tweaks, function(checkbox) 781 tweaks = Array.prototype.map.call(tweaks, checkbox =>
785 { 782 {
786 return checkbox.getAttribute("data-pref"); 783 return checkbox.getAttribute("data-pref");
787 }); 784 });
788 tweaks.forEach(function(key) 785 tweaks.forEach(key =>
789 { 786 {
790 getPref(key, function(value) 787 getPref(key, value =>
791 { 788 {
792 onPrefMessage(key, value, true); 789 onPrefMessage(key, value, true);
793 }); 790 });
794 }); 791 });
795 ext.backgroundPage.sendMessage( 792 ext.backgroundPage.sendMessage({
796 {
797 type: "app.get", 793 type: "app.get",
798 what: "features" 794 what: "features"
799 }, 795 },
800 function(features) 796 features =>
801 { 797 {
802 hidePref("show_devtools_panel", !features.devToolsPanel); 798 hidePref("show_devtools_panel", !features.devToolsPanel);
803 }); 799 });
804 800
805 var filterTextbox = document.querySelector("#custom-filters-add input"); 801 let filterTextbox = document.querySelector("#custom-filters-add input");
806 placeholderValue = getMessage("options_customFilters_textbox_placeholder"); 802 placeholderValue = getMessage("options_customFilters_textbox_placeholder");
807 filterTextbox.setAttribute("placeholder", placeholderValue); 803 filterTextbox.setAttribute("placeholder", placeholderValue);
808 function addCustomFilters() 804 function addCustomFilters()
809 { 805 {
810 var filterText = filterTextbox.value; 806 let filterText = filterTextbox.value;
811 sendMessageHandleErrors( 807 sendMessageHandleErrors({
812 {
813 type: "filters.add", 808 type: "filters.add",
814 text: filterText 809 text: filterText
815 }, 810 },
816 function() 811 () =>
817 { 812 {
818 filterTextbox.value = ""; 813 filterTextbox.value = "";
819 }); 814 });
820 } 815 }
821 E("custom-filters-add").addEventListener("submit", function(e) 816 E("custom-filters-add").addEventListener("submit", e =>
822 { 817 {
823 e.preventDefault(); 818 e.preventDefault();
824 addCustomFilters(); 819 addCustomFilters();
825 }, false); 820 }, false);
826 var customFilterEditButtons = document.querySelectorAll("#custom-filters-edi t-wrapper button");
827 821
828 E("dialog").addEventListener("keydown", function(e) 822 E("dialog").addEventListener("keydown", function(e)
829 { 823 {
830 switch (getKey(e)) 824 switch (getKey(e))
831 { 825 {
832 case "Escape": 826 case "Escape":
833 closeDialog(); 827 closeDialog();
834 break; 828 break;
835 case "Tab": 829 case "Tab":
836 if (e.shiftKey) 830 if (e.shiftKey)
837 { 831 {
838 if (e.target.classList.contains("focus-first")) 832 if (e.target.classList.contains("focus-first"))
839 { 833 {
840 e.preventDefault(); 834 e.preventDefault();
841 this.querySelector(".focus-last").focus(); 835 this.querySelector(".focus-last").focus();
842 } 836 }
843 } 837 }
844 else if (e.target.classList.contains("focus-last")) 838 else if (e.target.classList.contains("focus-last"))
845 { 839 {
846 e.preventDefault(); 840 e.preventDefault();
847 this.querySelector(".focus-first").focus(); 841 this.querySelector(".focus-first").focus();
848 } 842 }
849 break; 843 break;
850 } 844 }
851 }, false); 845 }, false);
852 846
853 onHashChange(); 847 onHashChange();
854 } 848 }
855 849
856 var focusedBeforeDialog = null; 850 let focusedBeforeDialog = null;
857 function openDialog(name) 851 function openDialog(name)
858 { 852 {
859 var dialog = E("dialog"); 853 let dialog = E("dialog");
860 dialog.setAttribute("aria-hidden", false); 854 dialog.setAttribute("aria-hidden", false);
861 dialog.setAttribute("aria-labelledby", "dialog-title-" + name); 855 dialog.setAttribute("aria-labelledby", "dialog-title-" + name);
862 document.body.setAttribute("data-dialog", name); 856 document.body.setAttribute("data-dialog", name);
863 857
864 var defaultFocus = document.querySelector("#dialog-content-" + name 858 let defaultFocus = document.querySelector(
865 + " .default-focus"); 859 "#dialog-content-" + name + " .default-focus"
860 );
866 if (!defaultFocus) 861 if (!defaultFocus)
867 defaultFocus = dialog.querySelector(".focus-first"); 862 defaultFocus = dialog.querySelector(".focus-first");
868 focusedBeforeDialog = document.activeElement; 863 focusedBeforeDialog = document.activeElement;
869 defaultFocus.focus(); 864 defaultFocus.focus();
870 } 865 }
871 866
872 function closeDialog() 867 function closeDialog()
873 { 868 {
874 var dialog = E("dialog"); 869 let dialog = E("dialog");
875 dialog.setAttribute("aria-hidden", true); 870 dialog.setAttribute("aria-hidden", true);
876 dialog.removeAttribute("aria-labelledby"); 871 dialog.removeAttribute("aria-labelledby");
877 document.body.removeAttribute("data-dialog"); 872 document.body.removeAttribute("data-dialog");
878 focusedBeforeDialog.focus(); 873 focusedBeforeDialog.focus();
879 } 874 }
880 875
881 function populateLists() 876 function populateLists()
882 { 877 {
883 subscriptionsMap = Object.create(null); 878 subscriptionsMap = Object.create(null);
884 filtersMap = Object.create(null); 879 filtersMap = Object.create(null);
885 880
886 // Empty collections and lists 881 // Empty collections and lists
887 for (var property in collections) 882 for (let property in collections)
888 collections[property].clearAll(); 883 collections[property].clearAll();
889 884
890 ext.backgroundPage.sendMessage( 885 ext.backgroundPage.sendMessage({
891 {
892 type: "subscriptions.get", 886 type: "subscriptions.get",
893 special: true 887 special: true
894 }, 888 },
895 function(subscriptions) 889 subscriptions =>
896 { 890 {
897 // Load filters 891 // Load filters
898 for (var i = 0; i < subscriptions.length; i++) 892 for (let i = 0; i < subscriptions.length; i++)
899 { 893 {
900 ext.backgroundPage.sendMessage( 894 ext.backgroundPage.sendMessage({
901 {
902 type: "filters.get", 895 type: "filters.get",
903 subscriptionUrl: subscriptions[i].url 896 subscriptionUrl: subscriptions[i].url
904 }, 897 },
905 function(filters) 898 filters =>
906 { 899 {
907 for (var i = 0; i < filters.length; i++) 900 for (let filter of filters)
908 updateFilter(filters[i]); 901 updateFilter(filter);
909 }); 902 });
910 } 903 }
911 }); 904 });
912 loadRecommendations(); 905 loadRecommendations();
913 ext.backgroundPage.sendMessage( 906 ext.backgroundPage.sendMessage({
914 {
915 type: "prefs.get", 907 type: "prefs.get",
916 key: "subscriptions_exceptionsurl" 908 key: "subscriptions_exceptionsurl"
917 }, 909 },
918 function(url) 910 url =>
919 { 911 {
920 acceptableAdsUrl = url; 912 acceptableAdsUrl = url;
921 addSubscription({ 913 addSubscription({
922 url: acceptableAdsUrl, 914 url: acceptableAdsUrl,
923 disabled: true 915 disabled: true
924 }); 916 });
925 917
926 // Load user subscriptions 918 // Load user subscriptions
927 ext.backgroundPage.sendMessage( 919 ext.backgroundPage.sendMessage({
928 {
929 type: "subscriptions.get", 920 type: "subscriptions.get",
930 downloadable: true 921 downloadable: true
931 }, 922 },
932 function(subscriptions) 923 subscriptions =>
933 { 924 {
934 for (var i = 0; i < subscriptions.length; i++) 925 for (let i = 0; i < subscriptions.length; i++)
935 onSubscriptionMessage("added", subscriptions[i]); 926 onSubscriptionMessage("added", subscriptions[i]);
936 }); 927 });
937 }); 928 });
938 } 929 }
939 930
940 function addWhitelistedDomain() 931 function addWhitelistedDomain()
941 { 932 {
942 var domain = E("whitelisting-textbox"); 933 let domain = E("whitelisting-textbox");
943 if (domain.value) 934 if (domain.value)
944 { 935 {
945 sendMessageHandleErrors( 936 sendMessageHandleErrors({
946 {
947 type: "filters.add", 937 type: "filters.add",
948 text: "@@||" + domain.value.toLowerCase() + "^$document" 938 text: "@@||" + domain.value.toLowerCase() + "^$document"
949 }); 939 });
950 } 940 }
951 941
952 domain.value = ""; 942 domain.value = "";
953 document.querySelector("#whitelisting .controls").classList.remove("mode-edi t"); 943 document.querySelector("#whitelisting .controls").
944 classList.remove("mode-edit");
954 } 945 }
955 946
956 function editCustomFilters() 947 function editCustomFilters()
957 { 948 {
958 var customFilterItems = collections.customFilters.items; 949 let customFilterItems = collections.customFilters.items;
959 var filterTexts = []; 950 let filterTexts = [];
960 for (var i = 0; i < customFilterItems.length; i++) 951 for (let i = 0; i < customFilterItems.length; i++)
961 filterTexts.push(customFilterItems[i].text); 952 filterTexts.push(customFilterItems[i].text);
962 E("custom-filters-raw").value = filterTexts.join("\n"); 953 E("custom-filters-raw").value = filterTexts.join("\n");
963 } 954 }
964 955
965 function addEnableSubscription(url, title, homepage) 956 function addEnableSubscription(url, title, homepage)
966 { 957 {
967 var messageType = null; 958 let messageType = null;
968 var knownSubscription = subscriptionsMap[url]; 959 let knownSubscription = subscriptionsMap[url];
969 if (knownSubscription && knownSubscription.disabled == true) 960 if (knownSubscription && knownSubscription.disabled == true)
970 messageType = "subscriptions.toggle"; 961 messageType = "subscriptions.toggle";
971 else 962 else
972 messageType = "subscriptions.add"; 963 messageType = "subscriptions.add";
973 964
974 var message = { 965 let message = {
975 type: messageType, 966 type: messageType,
976 url: url 967 url
977 }; 968 };
978 if (title) 969 if (title)
979 message.title = title; 970 message.title = title;
980 if (homepage) 971 if (homepage)
981 message.homepage = homepage; 972 message.homepage = homepage;
982 973
983 ext.backgroundPage.sendMessage(message); 974 ext.backgroundPage.sendMessage(message);
984 } 975 }
985 976
986 function onFilterMessage(action, filter) 977 function onFilterMessage(action, filter)
987 { 978 {
988 switch (action) 979 switch (action)
989 { 980 {
990 case "added": 981 case "added":
991 updateFilter(filter); 982 updateFilter(filter);
992 updateShareLink(); 983 updateShareLink();
993 break; 984 break;
994 case "loaded": 985 case "loaded":
995 populateLists(); 986 populateLists();
996 break; 987 break;
997 case "removed": 988 case "removed":
998 var knownFilter = filtersMap[filter.text]; 989 let knownFilter = filtersMap[filter.text];
999 collections.whitelist.removeItem(knownFilter); 990 collections.whitelist.removeItem(knownFilter);
1000 collections.customFilters.removeItem(knownFilter); 991 collections.customFilters.removeItem(knownFilter);
1001 delete filtersMap[filter.text]; 992 delete filtersMap[filter.text];
1002 updateShareLink(); 993 updateShareLink();
1003 break; 994 break;
1004 } 995 }
1005 } 996 }
1006 997
1007 function onSubscriptionMessage(action, subscription) 998 function onSubscriptionMessage(action, subscription)
1008 { 999 {
1009 if (subscription.url in subscriptionsMap) 1000 if (subscription.url in subscriptionsMap)
1010 { 1001 {
1011 var knownSubscription = subscriptionsMap[subscription.url]; 1002 let knownSubscription = subscriptionsMap[subscription.url];
1012 for (var property in subscription) 1003 for (let property in subscription)
1013 { 1004 {
1014 if (property == "title" && knownSubscription.recommended) 1005 if (property == "title" && knownSubscription.recommended)
1015 knownSubscription.originalTitle = subscription.title; 1006 knownSubscription.originalTitle = subscription.title;
1016 else 1007 else
1017 knownSubscription[property] = subscription[property]; 1008 knownSubscription[property] = subscription[property];
1018 } 1009 }
1019 subscription = knownSubscription; 1010 subscription = knownSubscription;
1020 } 1011 }
1021 switch (action) 1012 switch (action)
1022 { 1013 {
(...skipping 28 matching lines...) Expand all
1051 } 1042 }
1052 collections.filterLists.removeItem(subscription); 1043 collections.filterLists.removeItem(subscription);
1053 break; 1044 break;
1054 } 1045 }
1055 1046
1056 updateShareLink(); 1047 updateShareLink();
1057 } 1048 }
1058 1049
1059 function hidePref(key, value) 1050 function hidePref(key, value)
1060 { 1051 {
1061 var element = document.querySelector("[data-pref='" + key + "']"); 1052 let element = document.querySelector("[data-pref='" + key + "']");
1062 if (element) 1053 if (element)
1063 element.setAttribute("aria-hidden", value); 1054 element.setAttribute("aria-hidden", value);
1064 } 1055 }
1065 1056
1066 function getPref(key, callback) 1057 function getPref(key, callback)
1067 { 1058 {
1068 var checkPref = getPref.checks[key] || getPref.checkNone; 1059 let checkPref = getPref.checks[key] || getPref.checkNone;
1069 checkPref(function(isActive) 1060 checkPref(isActive =>
1070 { 1061 {
1071 if (!isActive) 1062 if (!isActive)
1072 { 1063 {
1073 hidePref(key, !isActive); 1064 hidePref(key, !isActive);
1074 return; 1065 return;
1075 } 1066 }
1076 1067
1077 ext.backgroundPage.sendMessage( 1068 ext.backgroundPage.sendMessage({
1078 {
1079 type: "prefs.get", 1069 type: "prefs.get",
1080 key: key 1070 key
1081 }, callback); 1071 }, callback);
1082 }); 1072 });
1083 } 1073 }
1084 1074
1085 getPref.checkNone = function(callback) 1075 getPref.checkNone = function(callback)
1086 { 1076 {
1087 callback(true); 1077 callback(true);
1088 }; 1078 };
1089 1079
1090 getPref.checks = 1080 getPref.checks =
1091 { 1081 {
1092 notifications_ignoredcategories: function(callback) 1082 notifications_ignoredcategories(callback)
1093 { 1083 {
1094 getPref("notifications_showui", callback); 1084 getPref("notifications_showui", callback);
1095 } 1085 }
1096 }; 1086 };
1097 1087
1098 function onPrefMessage(key, value, initial) 1088 function onPrefMessage(key, value, initial)
1099 { 1089 {
1100 switch (key) 1090 switch (key)
1101 { 1091 {
1102 case "notifications_ignoredcategories": 1092 case "notifications_ignoredcategories":
1103 value = value.indexOf("*") == -1; 1093 value = value.indexOf("*") == -1;
1104 break; 1094 break;
1105 1095
1106 case "notifications_showui": 1096 case "notifications_showui":
1107 hidePref("notifications_ignoredcategories", !value); 1097 hidePref("notifications_ignoredcategories", !value);
1108 break; 1098 break;
1109 } 1099 }
1110 1100
1111 var checkbox = document.querySelector("[data-pref='" + key + "'] button[role ='checkbox']"); 1101 let checkbox = document.querySelector(
1102 "[data-pref='" + key + "'] button[role='checkbox']"
1103 );
1112 if (checkbox) 1104 if (checkbox)
1113 checkbox.setAttribute("aria-checked", value); 1105 checkbox.setAttribute("aria-checked", value);
1114 } 1106 }
1115 1107
1116 function updateShareLink() 1108 function updateShareLink()
1117 { 1109 {
1118 var shareResources = [ 1110 let shareResources = [
1119 "https://facebook.com/plugins/like.php?", 1111 "https://facebook.com/plugins/like.php?",
1120 "https://platform.twitter.com/widgets/", 1112 "https://platform.twitter.com/widgets/",
1121 "https://apis.google.com/se/0/_/+1/fastbutton?" 1113 "https://apis.google.com/se/0/_/+1/fastbutton?"
1122 ]; 1114 ];
1123 var isAnyBlocked = false; 1115 let isAnyBlocked = false;
1124 var checksRemaining = shareResources.length; 1116 let checksRemaining = shareResources.length;
1125 1117
1126 function onResult(isBlocked) 1118 function onResult(isBlocked)
1127 { 1119 {
1128 isAnyBlocked |= isBlocked; 1120 isAnyBlocked |= isBlocked;
1129 if (!--checksRemaining) 1121 if (!--checksRemaining)
1130 { 1122 {
1131 // Hide the share tab if a script on the share page would be blocked 1123 // Hide the share tab if a script on the share page would be blocked
1132 E("tab-share").hidden = isAnyBlocked; 1124 E("tab-share").hidden = isAnyBlocked;
1133 } 1125 }
1134 } 1126 }
1135 1127
1136 for (var i = 0; i < shareResources.length; i++) 1128 for (let i = 0; i < shareResources.length; i++)
1137 checkShareResource(shareResources[i], onResult); 1129 checkShareResource(shareResources[i], onResult);
1138 } 1130 }
1139 1131
1140 function getMessages(id) 1132 function getMessages(id)
1141 { 1133 {
1142 var messages = []; 1134 let messages = [];
1143 for (var i = 1; true; i++) 1135 for (let i = 1, message = ext.i18n.getMessage(id + "_" + i); message; i++)
1144 {
1145 var message = ext.i18n.getMessage(id + "_" + i);
1146 if (!message)
1147 break;
1148
1149 messages.push(message); 1136 messages.push(message);
1150 }
1151 return messages; 1137 return messages;
1152 } 1138 }
1153 1139
1154 function updateTooltips() 1140 function updateTooltips()
1155 { 1141 {
1156 var anchors = document.querySelectorAll(":not(.tooltip) > [data-tooltip]"); 1142 let anchors = document.querySelectorAll(":not(.tooltip) > [data-tooltip]");
1157 for (var i = 0; i < anchors.length; i++) 1143 for (let i = 0; i < anchors.length; i++)
1158 { 1144 {
1159 var anchor = anchors[i]; 1145 let anchor = anchors[i];
1160 var id = anchor.getAttribute("data-tooltip"); 1146 let id = anchor.getAttribute("data-tooltip");
1161 1147
1162 var wrapper = document.createElement("div"); 1148 let wrapper = document.createElement("div");
1163 wrapper.className = "tooltip"; 1149 wrapper.className = "tooltip";
1164 anchor.parentNode.replaceChild(wrapper, anchor); 1150 anchor.parentNode.replaceChild(wrapper, anchor);
1165 wrapper.appendChild(anchor); 1151 wrapper.appendChild(anchor);
1166 1152
1167 var topTexts = getMessages(id); 1153 let topTexts = getMessages(id);
1168 var bottomTexts = getMessages(id + "_notes"); 1154 let bottomTexts = getMessages(id + "_notes");
1169 1155
1170 // We have to use native tooltips to avoid issues when attaching a tooltip 1156 // We have to use native tooltips to avoid issues when attaching a tooltip
1171 // to an element in a scrollable list or otherwise it might get cut off 1157 // to an element in a scrollable list or otherwise it might get cut off
1172 if (anchor.hasAttribute("data-tooltip-native")) 1158 if (anchor.hasAttribute("data-tooltip-native"))
1173 { 1159 {
1174 var title = topTexts.concat(bottomTexts).join("\n\n"); 1160 let title = topTexts.concat(bottomTexts).join("\n\n");
1175 anchor.setAttribute("title", title); 1161 anchor.setAttribute("title", title);
1176 continue; 1162 continue;
1177 } 1163 }
1178 1164
1179 var tooltip = document.createElement("div"); 1165 let tooltip = document.createElement("div");
1180 tooltip.setAttribute("role", "tooltip"); 1166 tooltip.setAttribute("role", "tooltip");
1181 1167
1182 var flip = anchor.getAttribute("data-tooltip-flip"); 1168 let flip = anchor.getAttribute("data-tooltip-flip");
1183 if (flip) 1169 if (flip)
1184 tooltip.className = "flip-" + flip; 1170 tooltip.className = "flip-" + flip;
1185 1171
1186 var imageSource = anchor.getAttribute("data-tooltip-image"); 1172 let imageSource = anchor.getAttribute("data-tooltip-image");
1187 if (imageSource) 1173 if (imageSource)
1188 { 1174 {
1189 var image = document.createElement("img"); 1175 let image = document.createElement("img");
1190 image.src = imageSource; 1176 image.src = imageSource;
1191 image.alt = ""; 1177 image.alt = "";
1192 tooltip.appendChild(image); 1178 tooltip.appendChild(image);
1193 } 1179 }
1194 1180
1195 for (var j = 0; j < topTexts.length; j++) 1181 for (let j = 0; j < topTexts.length; j++)
1196 { 1182 {
1197 var paragraph = document.createElement("p"); 1183 let paragraph = document.createElement("p");
1198 paragraph.innerHTML = topTexts[j]; 1184 paragraph.innerHTML = topTexts[j];
1199 tooltip.appendChild(paragraph); 1185 tooltip.appendChild(paragraph);
1200 } 1186 }
1201 if (bottomTexts.length > 0) 1187 if (bottomTexts.length > 0)
1202 { 1188 {
1203 var notes = document.createElement("div"); 1189 let notes = document.createElement("div");
1204 notes.className = "notes"; 1190 notes.className = "notes";
1205 for (var j = 0; j < bottomTexts.length; j++) 1191 for (let j = 0; j < bottomTexts.length; j++)
1206 { 1192 {
1207 var paragraph = document.createElement("p"); 1193 let paragraph = document.createElement("p");
1208 paragraph.innerHTML = bottomTexts[j]; 1194 paragraph.innerHTML = bottomTexts[j];
1209 notes.appendChild(paragraph); 1195 notes.appendChild(paragraph);
1210 } 1196 }
1211 tooltip.appendChild(notes); 1197 tooltip.appendChild(notes);
1212 } 1198 }
1213 1199
1214 wrapper.appendChild(tooltip); 1200 wrapper.appendChild(tooltip);
1215 } 1201 }
1216 } 1202 }
1217 1203
1218 ext.onMessage.addListener(function(message) 1204 ext.onMessage.addListener(message =>
1219 { 1205 {
1220 switch (message.type) 1206 switch (message.type)
1221 { 1207 {
1222 case "app.respond": 1208 case "app.respond":
1223 switch (message.action) 1209 switch (message.action)
1224 { 1210 {
1225 case "addSubscription": 1211 case "addSubscription":
1226 var subscription = message.args[0]; 1212 let subscription = message.args[0];
1227 var dialog = E("dialog-content-predefined"); 1213 let dialog = E("dialog-content-predefined");
1228 dialog.querySelector("h3").textContent = subscription.title || ""; 1214 dialog.querySelector("h3").textContent = subscription.title || "";
1229 dialog.querySelector(".url").textContent = subscription.url; 1215 dialog.querySelector(".url").textContent = subscription.url;
1230 openDialog("predefined"); 1216 openDialog("predefined");
1231 break; 1217 break;
1232 case "focusSection": 1218 case "focusSection":
1233 document.body.setAttribute("data-tab", message.args[0]); 1219 document.body.setAttribute("data-tab", message.args[0]);
1234 break; 1220 break;
1235 } 1221 }
1236 break; 1222 break;
1237 case "filters.respond": 1223 case "filters.respond":
1238 onFilterMessage(message.action, message.args[0]); 1224 onFilterMessage(message.action, message.args[0]);
1239 break; 1225 break;
1240 case "prefs.respond": 1226 case "prefs.respond":
1241 onPrefMessage(message.action, message.args[0], false); 1227 onPrefMessage(message.action, message.args[0], false);
1242 break; 1228 break;
1243 case "subscriptions.respond": 1229 case "subscriptions.respond":
1244 onSubscriptionMessage(message.action, message.args[0]); 1230 onSubscriptionMessage(message.action, message.args[0]);
1245 break; 1231 break;
1246 } 1232 }
1247 }); 1233 });
1248 1234
1249 ext.backgroundPage.sendMessage( 1235 ext.backgroundPage.sendMessage({
1250 {
1251 type: "app.listen", 1236 type: "app.listen",
1252 filter: ["addSubscription", "focusSection"] 1237 filter: ["addSubscription", "focusSection"]
1253 }); 1238 });
1254 ext.backgroundPage.sendMessage( 1239 ext.backgroundPage.sendMessage({
1255 {
1256 type: "filters.listen", 1240 type: "filters.listen",
1257 filter: ["added", "loaded", "removed"] 1241 filter: ["added", "loaded", "removed"]
1258 }); 1242 });
1259 ext.backgroundPage.sendMessage( 1243 ext.backgroundPage.sendMessage({
1260 {
1261 type: "prefs.listen", 1244 type: "prefs.listen",
1262 filter: ["notifications_ignoredcategories", "notifications_showui", 1245 filter: ["notifications_ignoredcategories", "notifications_showui",
1263 "show_devtools_panel", "shouldShowBlockElementMenu"] 1246 "show_devtools_panel", "shouldShowBlockElementMenu"]
1264 }); 1247 });
1265 ext.backgroundPage.sendMessage( 1248 ext.backgroundPage.sendMessage({
1266 {
1267 type: "subscriptions.listen", 1249 type: "subscriptions.listen",
1268 filter: ["added", "disabled", "homepage", "lastDownload", "removed", 1250 filter: ["added", "disabled", "homepage", "lastDownload", "removed",
1269 "title", "downloadStatus", "downloading"] 1251 "title", "downloadStatus", "downloading"]
1270 }); 1252 });
1271 1253
1272 window.addEventListener("DOMContentLoaded", onDOMLoaded, false); 1254 window.addEventListener("DOMContentLoaded", onDOMLoaded, false);
1273 window.addEventListener("hashchange", onHashChange, false); 1255 window.addEventListener("hashchange", onHashChange, false);
1274 })(); 1256 }
OLDNEW
« no previous file with comments | « messageResponder.js ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld