-
Notifications
You must be signed in to change notification settings - Fork 3
/
options.js
233 lines (211 loc) · 6.93 KB
/
options.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"use strict";
import { RegexMatcher } from "./matcher.mjs";
const storage = browser.storage;
const sync = storage.sync;
if (!sync)
throw new Error("Storage is not available");
function debug(...args) {
//console.debug(...args);
}
function functionEntry(functionName, ...args) {
debug("Entered function: ", functionName, ...args);
}
function onError(error) {
console.error(error);
}
async function loadPatterns() {
functionEntry("loadPatterns");
let result = RegexMatcher.defaultPatterns();
if (!result)
throw new Error("No default patterns found");
const data = await sync.get("patterns");
debug("Storage now: ", data);
if (data && data.patterns) {
result = data.patterns;
}
debug("Resolved current patterns:", result);
if (!result instanceof Array)
throw new Error("Array of strings is expected");
return result;
}
async function addPattern(...patterns) {
functionEntry("addPattern", ...patterns);
for (let pattern of patterns) {
const error = RegexMatcher.validatePattern(pattern);
if (error)
throw new Error(`Pattern ${pattern} is invalid: ${error}`);
}
const stored = await loadPatterns();
debug("old pattern set: ", ...stored);
for (let pattern of patterns) {
stored.unshift(pattern);
}
if (!stored instanceof Array)
throw new Error("Array of strings is expected");
debug("new pattern set: ", ...stored);
await sync.set({
"patterns": stored
});
}
function wrapErrors(asyncFunction) {
function wrapper(...args) {
try {
Promise.resolve(asyncFunction(...args)).catch(onError);
} catch (e) {
onError(e);
}
}
return wrapper;
}
function installValidator(input, validityConsumer, validate) {
if (!input)
throw new Error("null input");
if (!validityConsumer)
throw new Error("null button");
if (!validate)
throw new Error("null validate");
const form = input.closest("form");
if (!form)
throw new Error("Can't find form");
function report(value, result) {
debug("Validating ", value, ":", result);
input.setCustomValidity(result);
validityConsumer(!result);
}
function check() {
const value = input.value;
Promise.resolve(validate(value))
.then(e => {
report(value, e);
})
.catch(e => {
report(value, e);
onError(e);
});
}
input.addEventListener("input", check);
form.addEventListener("reset", () => {
debug("Form reset");
input.setCustomValidity("");
validityConsumer(false);
});
}
function installAddingSubmitter(button, newPatternsProvider) {
const form = button.closest("form");
if (!form)
throw new Error("Can't find form");
button.addEventListener("click", wrapErrors(async () => {
const patterns = await newPatternsProvider();
await addPattern(patterns);
form.reset();
}));
}
function checkURL(string) {
try {
new URL(string)
} catch (e) {
return e.message;
}
return "";
}
{
const form = document.querySelector('form#blacklist_form');
const blacklist_text = form.querySelector("input");
const blacklist = form.querySelector("button");
installValidator(blacklist_text,
isValid => blacklist.disabled = !isValid,
value => {
return checkURL(value);
});
installAddingSubmitter(blacklist, async () => {
let choice = blacklist_text.value;
choice = choice.replace(/[.]/g, "\\.");
return [choice + "(.*)"];
});
}
{
const form = document.querySelector('form#multidomain_form');
const multidomain_text = form.querySelector("textarea");
const apply_multidomain = form.querySelector("button");
function uniq(array) {
array = array.filter(s => !!s);
array = Array.from(new Set(array));
return array;
}
installValidator(multidomain_text,
isValid => apply_multidomain.disabled = !isValid,
value => {
let array = value.split("\n");
array = uniq(array);
for (const url of array) {
const e = checkURL(url);
if (e) {
return e;
}
}
if (array.length < 2) {
return "Add another URL";
}
return "";
});
installAddingSubmitter(apply_multidomain, async () => {
let choice = multidomain_text.value.split("\n");
choice = uniq(choice);
choice = choice.join("|");
choice = choice.replace(/[.]/g, "\\.");
return [`(?:${choice}).*`];
});
}
{
const form = document.querySelector('form#patterns_form');
const matchingPatternsText = form.querySelector('textarea#regular_expressions_text');
if (!matchingPatternsText)
throw new Error("Patterns textarea is not found");
function fireInputEvent(input) {
const event = input.ownerDocument.createEvent("Event");
event.initEvent("input", true, true);
event.synthetic = true;
input.dispatchEvent(event);
}
async function setPatterns(data) {
debug("Resetting patterns", data);
if (!data)
throw new Error("Empty argument");
matchingPatternsText.value = data.join("\n");
fireInputEvent(matchingPatternsText);
}
async function restore() {
await setPatterns(await loadPatterns());
}
installValidator(matchingPatternsText, () => { }, async value => {
let result = [];
RegexMatcher.parsePatterns(value, (lineNumber, error, pattern) => {
result.push(`Line ${lineNumber}: ${pattern} : ${error.message}`);
});
return result.join("\n");
});
form.querySelector("#save").addEventListener("click", wrapErrors(async event => {
debug("Saving", event, matchingPatternsText.value);
await sync.set({
"patterns": matchingPatternsText.value.split("\n")
});
}));
form.querySelector("#default").addEventListener("click", wrapErrors(async event => {
debug("Form set to default", event, matchingPatternsText.value);
await setPatterns(RegexMatcher.defaultPatterns());
}));
form.querySelector("#restore").addEventListener("click", wrapErrors(restore));
const storageListener = wrapErrors(async (changes, areaName) => {
if (areaName !== "sync")
return;
if (changes.patterns) {
await restore();
}
});
const onChanged = storage.onChanged;
onChanged.addListener(storageListener);
// If listeners are not cleaned up, exception occurs on page refresh:
// sendRemoveListener on closed conduit [email protected]
window.addEventListener("unload", () => onChanged.removeListener(storageListener));
restore().catch(onError);
}