forked from jae-jae/Userscript-Plus
-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathutil.js
More file actions
339 lines (336 loc) · 7.61 KB
/
util.js
File metadata and controls
339 lines (336 loc) · 7.61 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
'use strict';
import { webext } from './ext.js';
import { err } from './logger.js';
// #region Utilities
const userjs = {};
const getUAData = () => {
if (userjs.isMobile !== undefined) {
return userjs.isMobile;
}
try {
if (navigator) {
const { userAgent, userAgentData } = navigator;
const { platform, mobile } = userAgentData ? Object(userAgentData) : {};
userjs.isMobile =
/Mobile|Tablet/.test(userAgent ? String(userAgent) : '') ||
Boolean(mobile) ||
/Android|Apple/.test(platform ? String(platform) : '');
} else {
userjs.isMobile = false;
}
} catch (ex) {
userjs.isMobile = false;
ex.cause = 'getUAData';
err(ex);
}
return userjs.isMobile;
};
const isMobile = getUAData();
const isString = (val) => typeof val === 'string';
/**
* @type { import("../typings/types").objToStr }
*/
const objToStr = (obj) => {
return Object.prototype.toString.call(obj);
};
/**
* @template {string | URL} S
* @param {S} str
*/
const strToURL = (str) => {
let url;
try {
url = objToStr(str).includes('URL') ? str : new URL(str);
} catch (ex) {
ex.cause = 'strToURL';
err(ex);
}
if (url !== undefined) {
return url
}
return str;
};
/**
* @type { import("../typings/types").isRegExp }
*/
const isRegExp = (obj) => {
const s = objToStr(obj);
return s.includes('RegExp');
};
/**
* @type { import("../typings/types").isElem }
*/
const isElem = (obj) => {
const s = objToStr(obj);
return s.includes('Element');
};
/**
* @type { import("../typings/types").isObj }
*/
const isObj = (obj) => {
const s = objToStr(obj);
return s.includes('Object');
};
/**
* @type { import("../typings/types").isFN }
*/
const isFN = (obj) => {
const s = objToStr(obj);
return s.includes('Function');
};
/**
* @type { import("../typings/types").isNull }
*/
const isNull = (obj) => {
return Object.is(obj, null) || Object.is(obj, undefined);
};
/**
* @type { import("../typings/types").isBlank }
*/
const isBlank = (obj) => {
return (
(typeof obj === 'string' && Object.is(obj.trim(), '')) ||
((obj instanceof Set || obj instanceof Map) && Object.is(obj.size, 0)) ||
(Array.isArray(obj) && Object.is(obj.length, 0)) ||
(isObj(obj) && Object.is(Object.keys(obj).length, 0))
);
};
/**
* @type { import("../typings/types").isEmpty }
*/
const isEmpty = (obj) => {
return isNull(obj) || isBlank(obj);
};
/**
* @type { import("../typings/types").normalizeTarget }
*/
const normalizeTarget = (target, toQuery = true, root) => {
if (Object.is(target, null) || Object.is(target, undefined)) {
return [];
}
if (Array.isArray(target)) {
return target;
}
if (typeof target === 'string') {
return toQuery ? Array.from((root || document).querySelectorAll(target)) : [target];
}
if (isElem(target)) {
return [target];
}
return Array.from(target);
};
/**
* @type { import("../typings/types.d.ts").ael }
*/
const ael = (el, type, listener, options = {}) => {
try {
for (const elem of normalizeTarget(el)) {
if (!elem) {
continue;
}
if (isMobile && type === 'click') {
elem.addEventListener('touchstart', listener, options);
continue;
}
elem.addEventListener(type, listener, options);
}
} catch (ex) {
ex.cause = 'ael';
err(ex);
}
};
/**
* @type { import("../typings/types.d.ts").formAttrs }
*/
const formAttrs = (elem, attr = {}) => {
if (!elem) {
return elem;
}
for (const key in attr) {
if (typeof attr[key] === 'object') {
formAttrs(elem[key], attr[key]);
} else if (isFN(attr[key])) {
if (/^on/.test(key)) {
elem[key] = attr[key];
continue;
}
ael(elem, key, attr[key]);
} else if (key === 'class') {
elem.className = attr[key];
} else {
elem[key] = attr[key];
}
}
return elem;
};
/**
* @type { import("../typings/types.d.ts").make }
*/
const make = (tagName, cname, attrs) => {
let el;
try {
el = document.createElement(tagName);
if (!isEmpty(cname)) {
if (typeof cname === 'string') {
el.className = cname;
} else if (isObj(cname)) {
formAttrs(el, cname);
}
}
if (!isEmpty(attrs)) {
if (typeof attrs === 'string') {
el.textContent = attrs;
} else if (isObj(attrs)) {
formAttrs(el, attrs);
}
}
} catch (ex) {
ex.cause = 'make';
err(ex);
}
return el;
};
/**
* @param { string } url - URL of webpage to open
* @param { object } params - GM parameters
* @returns { Promise<chrome.tabs.Tab | browser.tabs.Tab> }
*/
const openInTab = async (url) => {
const newTab = await webext.tabs.create({ url });
return newTab;
};
const union = (...arr) => [...new Set(arr.flat())];
const loadFilters = (cfg) => {
/** @type {Map<string, import("../typings/types.d.ts").Filters >} */
const pool = new Map();
const handles = {
pool,
enabled() {
return [...pool.values()].filter((o) => o.enabled);
},
refresh() {
if (!Object.is(pool.size, 0)) pool.clear();
for (const [key, value] of Object.entries(cfg.filters)) {
if (!pool.has(key))
pool.set(key, {
...value,
reg: new RegExp(value.regExp, value.flag),
keyReg: new RegExp(key.trim().toLocaleLowerCase(), 'gi'),
valueReg: new RegExp(value.name.trim().toLocaleLowerCase(), 'gi')
});
}
return this;
},
get(str) {
return [...pool.values()].find((v) => v.keyReg.test(str) || v.valueReg.test(str));
},
/**
* @param { import("../typings/types.d.ts").GSForkQuery } param0
*/
match({ name, users }) {
const p = handles.enabled();
if (Object.is(p.length, 0)) return true;
for (const v of p) {
if ([{ name }, ...users].find((o) => o.name.match(v.reg))) return false;
}
return true;
}
};
for (const [key, value] of Object.entries(cfg.filters)) {
if (!pool.has(key))
pool.set(key, {
...value,
reg: new RegExp(value.regExp, value.flag),
keyReg: new RegExp(key.trim().toLocaleLowerCase(), 'gi'),
valueReg: new RegExp(value.name.trim().toLocaleLowerCase(), 'gi')
});
}
return handles.refresh();
};
/**
* @param {string} txt
*/
const formatURL = (txt) =>
txt
.split('.')
.splice(-2)
.join('.')
.replace(/\/|https:/g, '');
const matchesFromHostnames = (hostnames) => {
const out = [];
for (const hn of hostnames) {
if (hn === '*' || hn === 'all-urls') {
out.length = 0;
out.push('<all_urls>');
break;
}
out.push(`*://*.${hn}/*`);
}
return out;
};
/**
* @param {string[]} origins
*/
const hostnamesFromMatches = (origins) => {
const out = [];
for (const origin of origins) {
if (origin === '<all_urls>') {
out.push('all-urls');
continue;
}
const match = /^\*:\/\/(?:\*\.)?([^/]+)\/\*/.exec(origin);
if (match === null) {
continue;
}
out.push(match[1]);
}
return out;
};
/**
* @param {string} hn
*/
const normalizedHostname = (hn) => {
return hn.replace(/^www\./, '');
};
/**
* @param {string} str
*/
const decode = (str) => {
let last = str;
while (true) {
try {
const decoded = decodeURIComponent(last);
if (decoded === last) {
return last;
}
last = decoded;
} catch (e) {
return last;
}
}
};
// #endregion
export {
decode,
formatURL,
objToStr,
strToURL,
isRegExp,
isElem,
isObj,
isFN,
isNull,
isBlank,
isEmpty,
isString,
normalizeTarget,
ael,
formAttrs,
make,
openInTab,
union,
loadFilters,
matchesFromHostnames,
hostnamesFromMatches,
normalizedHostname
};