-
Notifications
You must be signed in to change notification settings - Fork 26
/
ComicRead-AdGuard.user.js
13241 lines (12544 loc) · 499 KB
/
ComicRead-AdGuard.user.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name ComicRead
// @namespace ComicRead
// @version 10.9.1
// @description 为漫画站增加双页阅读、翻译等优化体验的增强功能。百合会(记录阅读历史、自动签到等)、百合会新站、动漫之家(解锁隐藏漫画)、E-Hentai(关联 nhentai、快捷收藏、标签染色、识别广告页等)、nhentai(彻底屏蔽漫画、无限滚动)、Yurifans(自动签到)、拷贝漫画(copymanga)(显示最后阅读记录、解锁隐藏漫画)、PonpomuYuri、再漫画、明日方舟泰拉记事社、禁漫天堂、漫画柜(manhuagui)、漫画DB(manhuadb)、动漫屋(dm5)、绅士漫画(wnacg)、mangabz、komiic、MangaDex、無限動漫、新新漫画、熱辣漫畫、hitomi、SchaleNetwork、kemono、nekohouse、welovemanga
// @description:en Add enhanced features to the comic site for optimized experience, including dual-page reading and translation. E-Hentai (Associate nhentai, Quick favorite, Colorize tags, Floating tag list, etc.) | nhentai (Totally block comics, Auto page turning) | hitomi | Anchira | kemono | nekohouse | welovemanga.
// @description:ru Добавляет расширенные функции для удобства на сайт, такие как двухстраничный режим и перевод.
// @author hymbz
// @license AGPL-3.0-or-later
// @noframes
// @match *://bbs.yamibo.com/*
// @match *://www.yamibo.com/*
// @match *://comic.idmzj.com/*
// @match *://comic.dmzj.com/*
// @match *://manhua.idmzj.com/*
// @match *://manhua.dmzj.com/*
// @match *://m.idmzj.com/*
// @match *://m.dmzj.com/*
// @match *://www.idmzj.com/*
// @match *://www.dmzj.com/*
// @match *://exhentai.org/*
// @match *://e-hentai.org/*
// @match *://nhentai.net/*
// @match *://yuri.website/*
// @match *://mangacopy.com/*
// @match *://copymanga.site/*
// @match *://copymanga.info/*
// @match *://copymanga.net/*
// @match *://copymanga.org/*
// @match *://copymanga.tv/*
// @match *://copymanga.com/*
// @match *://www.mangacopy.com/*
// @match *://www.copymanga.site/*
// @match *://www.copymanga.info/*
// @match *://www.copymanga.net/*
// @match *://www.copymanga.org/*
// @match *://www.copymanga.tv/*
// @match *://www.copymanga.com/*
// @match *://www.ponpomu.com/*
// @match *://manhua.zaimanhua.com/*
// @match *://terra-historicus.hypergryph.com/*
// @match *://18comic.org/*
// @match *://18comic.vip/*
// @match *://tw.manhuagui.com/*
// @match *://m.manhuagui.com/*
// @match *://www.mhgui.com/*
// @match *://www.manhuagui.com/*
// @match *://www.manhuadb.com/*
// @match *://www.manhuaren.com/*
// @match *://m.1kkk.com/*
// @match *://www.1kkk.com/*
// @match *://tel.dm5.com/*
// @match *://en.dm5.com/*
// @match *://www.dm5.cn/*
// @match *://www.dm5.com/*
// @match *://www.wnacg.com/*
// @match *://wnacg.com/*
// @match *://www.mangabz.com/*
// @match *://mangabz.com/*
// @match *://komiic.com/*
// @match *://mangadex.org/*
// @match *://8.twobili.com/*
// @match *://a.twobili.com/*
// @match *://articles.onemoreplace.tw/*
// @match *://www.comicabc.com/*
// @match *://m.77mh.me/*
// @match *://www.77mh.me/*
// @match *://m.77mh.xyz/*
// @match *://www.77mh.xyz/*
// @match *://m.77mh.nl/*
// @match *://www.77mh.nl/*
// @match *://relamanhua.org/*
// @match *://www.relamanhua.org/*
// @match *://www.2024manga.com/*
// @match *://hitomi.la/*
// @match *://shupogaki.moe/*
// @match *://hoshino.one/*
// @match *://niyaniya.moe/*
// @match *://kemono.su/*
// @match *://kemono.party/*
// @match *://nekohouse.su/*
// @match *://nicomanga.com/*
// @match *://weloma.art/*
// @match *://welovemanga.one/*
// @match *://comic-read.pages.dev/*
// @connect yamibo.com
// @connect dmzj.com
// @connect idmzj.com
// @connect exhentai.org
// @connect e-hentai.org
// @connect hath.network
// @connect nhentai.net
// @connect hypergryph.com
// @connect mangabz.com
// @connect copymanga.site
// @connect copymanga.info
// @connect copymanga.net
// @connect copymanga.org
// @connect copymanga.tv
// @connect mangacopy.com
// @connect xsskc.com
// @connect schale.network
// @connect self
// @connect 127.0.0.1
// @connect *
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addElement
// @grant GM_getResourceText
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM.addValueChangeListener
// @grant GM.removeValueChangeListener
// @grant GM.getResourceText
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.listValues
// @grant GM.deleteValue
// @grant unsafeWindow
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAACBUExURUxpcWB9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i2B9i////198il17idng49DY3PT297/K0MTP1M3X27rHzaCxupmstbTByK69xOfr7bfFy3WOmqi4wPz9/X+XomSBjqW1vZOmsN/l6GmFkomeqe7x8vn6+kv+1vUAAAAOdFJOUwDsAoYli9zV+lIqAZEDwV05SQAAAUZJREFUOMuFk+eWgjAUhGPBiLohjZACUqTp+z/gJkqJy4rzg3Nn+MjhwB0AANjv4BEtdITBHjhtQ4g+CIZbC4Qb9FGb0J4P0YrgCezQqgIA14EDGN8fYz+f3BGMASFkTJ+GDAYMUSONzrFL7SVvjNQIz4B9VERRmV0rbJWbrIwidnsd6ACMlEoip3uad3X2HJmqb3gCkkJELwk5DExRDxA6HnKaDEPSsBnAsZoANgJaoAkg12IJqBiPACImXQKF9IDULIHUkOk7kDpeAMykHqCEWACy8ACdSM7LGSg5F3HtAU1rrkaK9uGAshXS2lZ5QH/nVhmlD8rKlmbO3ZsZwLe8qnpdxJRnLaci1X1V5R32fjd5CndVkfYdGpy3D+htU952C/ypzPtdt3JflzZYBy7fi/O1euvl/XH1Pp+Cw3/1P1xOZwB+AWMcP/iw0AlKAAAAV3pUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHic4/IMCHFWKCjKT8vMSeVSAAMjCy5jCxMjE0uTFAMTIESANMNkAyOzVCDL2NTIxMzEHMQHy4BIoEouAOoXEXTyQjWVAAAAAElFTkSuQmCC
// @resource solid-js https://cdn.jsdelivr.net/npm/[email protected]/dist/solid.cjs
// @resource fflate https://cdn.jsdelivr.net/npm/[email protected]/umd/index.js
// @resource jsqr https://cdn.jsdelivr.net/npm/[email protected]/dist/jsQR.js
// @resource comlink https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/comlink.js
// @resource dmzjDecrypt https://greasyfork.org/scripts/467177/code/dmzjDecrypt.js?version=1207199
// @resource solid-js|store https://cdn.jsdelivr.net/npm/[email protected]/store/dist/store.cjs
// @resource solid-js|web https://cdn.jsdelivr.net/npm/[email protected]/web/dist/web.cjs
// @supportURL https://github.com/hymbz/ComicReadScript/issues
// @updateURL https://github.com/hymbz/ComicReadScript/raw/master/ComicRead-AdGuard.user.js
// @downloadURL https://github.com/hymbz/ComicReadScript/raw/master/ComicRead-AdGuard.user.js
// ==/UserScript==
let supportWorker = typeof Worker !== 'undefined';
const gmApi = {
GM,
GM_addElement: typeof GM_addElement === 'undefined' ? undefined : GM_addElement,
GM_getResourceText,
GM_xmlhttpRequest,
GM_addStyle,
unsafeWindow
};
const gmApiList = Object.keys(gmApi);
const crsLib = {
// 有些 cjs 模块会检查这个,所以在这里声明下
process: {
env: {
NODE_ENV: 'production'
}
},
...gmApi
};
const tempName = Math.random().toString(36).slice(2);
const evalCode = code => {
if (!code) return;
// 因为部分网站会对 eval 进行限制,比如推特(CSP)、hitomi(代理 window.eval 进行拦截)
// 所以优先使用最通用的 GM_addElement 来加载
if (gmApi.GM_addElement) return GM_addElement('script', {
textContent: code
})?.remove();
eval.call(unsafeWindow, code); // eslint-disable-line no-eval
};
/**
* 通过 Resource 导入外部模块
* @param name \@resource 引用的资源名
*/
const selfImportSync = name => {
let code;
// 为了方便打包、减少在无关站点上的运行损耗、顺带隔离下作用域
// 除站点逻辑外的代码会作为字符串存着,要用时再像外部模块一样导入
switch (name) {
case 'helper/languages':
code =`
const langList = ['zh', 'en', 'ru'];
/** 判断传入的字符串是否是支持的语言类型代码 */
const isLanguages = lang => Boolean(lang) && langList.includes(lang);
/** 返回浏览器偏好语言 */
const getBrowserLang = () => {
let newLang;
for (let i = 0; i < navigator.languages.length; i++) {
const language = navigator.languages[i];
const matchLang = langList.find(l => l === language || l === language.split('-')[0]);
if (matchLang) {
newLang = matchLang;
break;
}
}
return newLang;
};
const getSaveLang = async () => typeof GM === 'undefined' ? localStorage.getItem('Languages') : GM.getValue('Languages');
const setSaveLang = async val => typeof GM === 'undefined' ? localStorage.setItem('Languages', val) : GM.setValue('Languages', val);
const getInitLang = async () => {
const saveLang = await getSaveLang();
if (isLanguages(saveLang)) return saveLang;
const lang = getBrowserLang() ?? 'zh';
setSaveLang(lang);
return lang;
};
exports.getInitLang = getInitLang;
exports.isLanguages = isLanguages;
exports.langList = langList;
exports.setSaveLang = setSaveLang;
`
break;
case 'helper':
code =`
const solidJs = require('solid-js');
const web = require('solid-js/web');
const store = require('solid-js/store');
const languages = require('helper/languages');
// src/index.ts
var debounce$1 = (callback, wait) => {
if (web.isServer) {
return Object.assign(() => void 0, { clear: () => void 0 });
}
let timeoutId;
const clear = () => clearTimeout(timeoutId);
if (solidJs.getOwner())
solidJs.onCleanup(clear);
const debounced = (...args) => {
if (timeoutId !== void 0)
clear();
timeoutId = setTimeout(() => callback(...args), wait);
};
return Object.assign(debounced, { clear });
};
var throttle$1 = (callback, wait) => {
if (web.isServer) {
return Object.assign(() => void 0, { clear: () => void 0 });
}
let isThrottled = false, timeoutId, lastArgs;
const throttled = (...args) => {
lastArgs = args;
if (isThrottled)
return;
isThrottled = true;
timeoutId = setTimeout(() => {
callback(...lastArgs);
isThrottled = false;
}, wait);
};
const clear = () => {
clearTimeout(timeoutId);
isThrottled = false;
};
if (solidJs.getOwner())
solidJs.onCleanup(clear);
return Object.assign(throttled, { clear });
};
function leadingAndTrailing(schedule, callback, wait) {
if (web.isServer) {
let called = false;
const scheduled2 = (...args) => {
if (called)
return;
called = true;
callback(...args);
};
return Object.assign(scheduled2, { clear: () => void 0 });
}
let State;
((State2) => {
State2[State2["Ready"] = 0] = "Ready";
State2[State2["Leading"] = 1] = "Leading";
State2[State2["Trailing"] = 2] = "Trailing";
})(State || (State = {}));
let state = 0 /* Ready */;
const scheduled = schedule((args) => {
state === 2 /* Trailing */ && callback(...args);
state = 0 /* Ready */;
}, wait);
const fn = (...args) => {
if (state !== 2 /* Trailing */) {
if (state === 0 /* Ready */)
callback(...args);
state += 1;
}
scheduled(args);
};
const clear = () => {
state = 0 /* Ready */;
scheduled.clear();
};
if (solidJs.getOwner())
solidJs.onCleanup(clear);
return Object.assign(fn, { clear });
}
function createScheduled(schedule) {
let listeners = 0;
let isDirty = false;
const [track, dirty] = solidJs.createSignal(void 0, { equals: false });
const call = schedule(() => {
isDirty = true;
dirty();
});
return () => {
if (!isDirty)
call(), track();
if (isDirty) {
isDirty = !!listeners;
return true;
}
if (solidJs.getListener()) {
listeners++;
solidJs.onCleanup(() => listeners--);
}
return false;
};
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var es6 = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
const isEqual = /*@__PURE__*/getDefaultExportFromCjs(es6);
const throttle = (fn, wait = 100) => leadingAndTrailing(throttle$1, fn, wait);
const debounce = (fn, wait = 100) => debounce$1(fn, wait);
const sleep = ms => new Promise(resolve => {
window.setTimeout(resolve, ms);
});
const clamp = (min, val, max) => Math.max(Math.min(max, val), min);
const inRange = (min, val, max) => val >= min && val <= max;
/** 判断两个数是否在指定误差范围内相等 */
const approx = (val, target, range) => Math.abs(target - val) <= range;
function range(a, b, c) {
switch (typeof b) {
case 'undefined':
return [...Array.from({
length: a + 1
}).keys()];
case 'number':
{
const list = [];
for (let i = a; i <= b; i++) list.push(c ? c(i) : i);
return list;
}
case 'function':
return Array.from({
length: a
}, (_, i) => b(i));
}
}
/**
* 对 document.querySelector 的封装
* 将默认返回类型改为 HTMLElement
*/
const querySelector = selector => document.querySelector(selector);
/**
* 对 document.querySelector 的封装
* 将默认返回类型改为 HTMLElement
*/
const querySelectorAll = selector => [...document.querySelectorAll(selector)];
/** 返回 Dom 的点击函数 */
const querySelectorClick = (selector, textContent) => {
let getDom;
if (typeof selector === 'function') getDom = selector;else if (textContent) {
getDom = () => querySelectorAll(selector).find(e => e.textContent?.includes(textContent));
} else getDom = () => querySelector(selector);
if (getDom()) return () => getDom()?.click();
};
/** 找出数组中出现最多次的元素 */
const getMostItem = list => {
const counts = new Map();
for (const val of list) counts.set(val, (counts.get(val) ?? 0) + 1);
// eslint-disable-next-line unicorn/no-array-reduce
return [...counts.entries()].reduce((maxItem, item) => maxItem[1] > item[1] ? maxItem : item)[0];
};
/** 创建顺序数组 */
const createSequence = length => [...Array.from({
length
}).keys()];
/** 判断字符串是否为 URL */
const isUrl = text => {
// 等浏览器版本上来后可以直接使用 URL.canParse
try {
return Boolean(new URL(text));
} catch {
return false;
}
};
/** 将 blob 数据作为文件保存至本地 */
const saveAs = (blob, name = 'download') => {
const a = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
a.download = name;
a.rel = 'noopener';
a.href = URL.createObjectURL(blob);
setTimeout(() => a.dispatchEvent(new MouseEvent('click')));
};
/** 滚动页面到指定元素的所在位置 */
const scrollIntoView = (selector, behavior = 'instant') => querySelector(selector)?.scrollIntoView({
behavior
});
/** 使指定函数延迟运行期间的多次调用直到运行结束 */
const singleThreaded = (callback, defaultContinueRun = true) => {
const state = {
running: false,
continueRun: false
};
const fn = async (...args) => {
if (state.continueRun) return;
if (state.running) {
state.continueRun = defaultContinueRun;
return;
}
let res;
try {
state.running = true;
res = await callback(state, ...args);
} catch (error) {
state.continueRun = false;
await sleep(100);
throw error;
} finally {
state.running = false;
}
if (state.continueRun) {
state.continueRun = false;
setTimeout(fn, 0, ...args);
} else state.running = false;
return res;
};
return fn;
};
/**
* 限制 Promise 并发
* @param fnList 任务函数列表
* @param callBack 成功执行一个 Promise 后调用,主要用于显示进度
* @param limit 限制数
* @returns 所有 Promise 的返回值
*/
const plimit = async (fnList, callBack = undefined, limit = 10) => {
let doneNum = 0;
const totalNum = fnList.length;
const resList = [];
const execPool = new Set();
const taskList = fnList.map((fn, i) => {
let p;
return () => {
p = (async () => {
resList[i] = await fn();
doneNum += 1;
execPool.delete(p);
callBack?.(doneNum, totalNum, resList, i);
})();
execPool.add(p);
};
});
// eslint-disable-next-line no-unmodified-loop-condition
while (doneNum !== totalNum) {
while (taskList.length > 0 && execPool.size < limit) taskList.shift()();
await Promise.race(execPool);
}
return resList;
};
/**
* 判断使用参数颜色作为默认值时是否需要切换为黑暗模式
* @param hexColor 十六进制颜色。例如 #112233
*/
const needDarkMode = hexColor => {
// by: https://24ways.org/2010/calculating-color-contrast
const r = Number.parseInt(hexColor.slice(1, 3), 16);
const g = Number.parseInt(hexColor.slice(3, 5), 16);
const b = Number.parseInt(hexColor.slice(5, 7), 16);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq < 128;
};
async function wait(fn, timeout = Number.POSITIVE_INFINITY, waitTime = 100) {
let res = await fn();
let _timeout = timeout;
while (_timeout > 0 && !res) {
await sleep(waitTime);
_timeout -= waitTime;
res = await fn();
}
return res;
}
/** 等到指定的 dom 出现 */
const waitDom = selector => wait(() => querySelector(selector));
/** 等待指定的图片元素加载完成 */
const waitImgLoad = (target, timeout) => new Promise((resolve, reject) => {
const img = typeof target === 'string' ? new Image() : target;
if (img.complete && img.naturalHeight) resolve(img);
const id = timeout ? window.setTimeout(() => reject(new Error('timeout')), timeout) : undefined;
const handleError = e => {
window.clearTimeout(id);
reject(new Error(e.message));
};
const handleLoad = () => {
window.clearTimeout(id);
img.removeEventListener('error', handleError);
resolve(img);
};
img.addEventListener('load', handleLoad, {
once: true
});
img.addEventListener('error', handleError, {
once: true
});
if (typeof target === 'string') img.src = target;
});
/** 将指定的布尔值转换为字符串或未定义 */
const boolDataVal = val => val ? '' : undefined;
/** 测试图片 url 能否正确加载 */
const testImgUrl = url => new Promise(resolve => {
const img = new Image();
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = url;
});
const canvasToBlob = async (canvas, type, quality = 1) => {
if (canvas instanceof OffscreenCanvas) return canvas.convertToBlob({
type,
quality
});
return new Promise((resolve, reject) => {
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Canvas toBlob failed')), type, quality);
});
};
/**
* 求 a 和 b 的差集,相当于从 a 中删去和 b 相同的属性
*
* 不会修改参数对象,返回的是新对象
*/
const difference = (a, b) => {
const res = {};
const keys = Object.keys(a);
for (const key of keys) {
if (typeof a[key] === 'object' && typeof b[key] === 'object') {
const _res = difference(a[key], b[key]);
if (Object.keys(_res).length > 0) res[key] = _res;
} else if (a[key] !== b?.[key]) res[key] = a[key];
}
return res;
};
const _assign = (a, b) => {
const res = JSON.parse(JSON.stringify(a));
const keys = Object.keys(b);
for (const key of keys) {
if (res[key] === undefined) res[key] = b[key];else if (typeof b[key] === 'object') {
const _res = _assign(res[key], b[key]);
if (Object.keys(_res).length > 0) res[key] = _res;
} else if (res[key] !== b[key]) res[key] = b[key];
}
return res;
};
/**
* Object.assign 的深拷贝版,不会导致子对象属性的缺失
*
* 不会修改参数对象,返回的是新对象
*/
const assign = (target, ...sources) => {
let res = target;
for (const source of sources) if (typeof source === 'object') res = _assign(res, source);
return res;
};
/** 根据路径获取对象下的指定值 */
const byPath = (obj, path, handleVal) => {
const keys = path.split('.');
let target = obj;
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
// 兼容含有「.」的 key
while (!Reflect.has(target, key) && i < keys.length) {
i += 1;
if (keys[i] === undefined) break;
key += \`.\${keys[i]}\`;
}
if (handleVal && i > keys.length - 2 && Reflect.has(target, key)) {
const res = handleVal(target, key);
while (i < keys.length - 1) {
target = target[key];
i += 1;
key = keys[i];
}
if (res !== undefined) target[key] = res;
break;
}
target = target[key];
}
if (target === obj) return null;
return target;
};
const requestIdleCallback = (callback, timeout) => {
if (Reflect.has(window, 'requestIdleCallback')) return window.requestIdleCallback(callback, {
timeout
});
return window.setTimeout(callback, 16);
};
/** 获取键盘事件的编码 */
const getKeyboardCode = e => {
let {
key
} = e;
switch (key) {
case 'Shift':
case 'Control':
case 'Alt':
return key;
}
if (e.ctrlKey) key = \`Ctrl + \${key}\`;
if (e.altKey) key = \`Alt + \${key}\`;
if (e.shiftKey) key = \`Shift + \${key}\`;
return key;
};
/** 将快捷键的编码转换成更易读的形式 */
const keyboardCodeToText = code => code.replace('Control', 'Ctrl').replace('ArrowUp', '↑').replace('ArrowDown', '↓').replace('ArrowLeft', '←').replace('ArrowRight', '→').replace(/^\\s$/, 'Space');
/** 将 HTML 字符串转换为 DOM 对象 */
const domParse = html => new DOMParser().parseFromString(html, 'text/html');
/** 监听键盘事件 */
const linstenKeydown = handler => window.addEventListener('keydown', e => {
// 跳过输入框的键盘事件
switch (e.target.tagName) {
case 'INPUT':
case 'TEXTAREA':
return;
}
return handler(e);
});
/**
* 劫持修改原网页上的函数
*
* 如果传入函数的所需参数为零,将在原函数执行完后自动调用
*/
const hijackFn = (fnName, fn) => {
const rawFn = unsafeWindow[fnName];
unsafeWindow[fnName] = fn.length === 0 ? (...args) => {
const res = rawFn(...args);
fn();
return res;
} : (...args) => fn(rawFn, args);
};
async function getGmValue(name, setValueFn) {
const value = await GM.getValue(name);
if (value !== undefined) return value;
await setValueFn();
return await GM.getValue(name);
}
/** 根据范围文本提取指定范围的元素的 index */
const extractRange = (rangeText, length) => {
const list = new Set();
for (const text of rangeText.replaceAll(/[^\\d,-]/g, '').split(',')) {
if (/^\\d+$/.test(text)) list.add(Number(text) - 1);else if (/^\\d*-\\d*$/.test(text)) {
let [start, end] = text.split('-').map(Number);
end ||= length;
for (start--, end--; start <= end; start++) list.add(start);
}
}
return list;
};
/** extractRange 的逆向,按照相同的语法表述一个结果数组 */
const descRange = (list, length) => {
let text = '';
const nowRange = [];
const pushRange = newIndex => {
if (nowRange.length === 0) return;
if (text.length > 0) text += ', ';
if (nowRange.length === 1) text += nowRange[0] + 1;else {
const end = newIndex === undefined && nowRange[1] === length - 1 ? '' : nowRange[1] + 1;
text += \`\${nowRange[0] + 1}-\${end}\`;
}
nowRange.length = 0;
if (newIndex !== undefined) nowRange[0] = newIndex;
};
for (const i of list) {
switch (nowRange.length) {
case 0:
nowRange[0] = i;
break;
case 1:
if (i === nowRange[0] + 1) nowRange[1] = i;else pushRange(i);
break;
case 2:
if (i === nowRange[1] + 1) nowRange[1] = i;else pushRange(i);
break;
}
}
pushRange();
return text;
};
let publicOwner;
solidJs.createRoot(() => {
publicOwner = solidJs.getOwner();
});
/** 会自动设置 equals 的 createSignal */
const createEqualsSignal = (init, options) => solidJs.createSignal(init, {
equals: isEqual,
...options
});
/** 会自动设置 equals 和 createRoot 的 createMemo */
const createRootMemo = (fn, init, options) => {
// 如果函数已经是 createMemo 创建的,就直接使用
if (fn.name === 'bound readSignal') return fn;
const _init = init ?? fn(undefined);
// 自动为对象类型设置 equals
const _options = options?.equals === undefined && typeof _init === 'object' ? {
...options,
equals: isEqual
} : options;
return solidJs.getOwner() ? solidJs.createMemo(fn, _init, _options) : solidJs.runWithOwner(publicOwner, () => solidJs.createMemo(fn, _init, _options));
};
/** 节流的 createMemo */
const createThrottleMemo = (fn, wait = 100, init = fn(undefined), options = undefined) => {
const scheduled = createScheduled(_fn => throttle(_fn, wait));
return createRootMemo(prev => scheduled() ? fn(prev) : prev, init, options);
};
const createMemoMap = fnMap => {
const memoMap = Object.fromEntries(Object.entries(fnMap).map(([key, fn]) => [key, createRootMemo(fn)]));
const map = createRootMemo(() => {
const obj = {};
for (const key of Object.keys(memoMap)) Reflect.set(obj, key, memoMap[key]());
return obj;
});
return map;
};
const createRootEffect = (fn, val, options) => solidJs.getOwner() ? solidJs.createEffect(fn, val, options) : solidJs.runWithOwner(publicOwner, () => solidJs.createEffect(fn, val, options));
const createEffectOn = (deps, fn, options) => createRootEffect(solidJs.on(deps, fn, options));
const onAutoMount = fn => {
const owner = solidJs.getOwner();
if (!owner) return fn(owner);
solidJs.onMount(() => {
const cleanFn = fn(owner);
if (cleanFn) solidJs.onCleanup(cleanFn);
});
};
const promisifyRequest = request => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const openDb = (version, initSchema) => new Promise((resolve, reject) => {
const request = indexedDB.open('ComicReadScript', version);
request.onupgradeneeded = () => initSchema(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = error => {
console.error('数据库打开失败', error);
reject(new Error('数据库打开失败'));
};
});
const useCache = async (initSchema, version = 1) => {
const db = await openDb(version, initSchema);
return {
set: (storeName, value) => promisifyRequest(db.transaction(storeName, 'readwrite').objectStore(storeName).put(value)),
get: async (storeName, query) => promisifyRequest(db.transaction(storeName, 'readonly').objectStore(storeName).get(query)),
del: (storeName, query) => promisifyRequest(db.transaction(storeName, 'readwrite').objectStore(storeName).delete(query))
};
};
const createPointerState = (e, type = 'down') => {
const xy = [e.clientX, e.clientY];
return {
id: e.pointerId,
type,
xy,
initial: xy,
last: xy,
startTime: performance.now(),
target: e.target
};
};
const useDrag = ({
ref,
handleDrag,
easyMode,
handleClick,
skip,
touches = new Map()
}) => {
onAutoMount(() => {
const controller = new AbortController();
const options = {
capture: false,
passive: true,
signal: controller.signal
};
const handleDown = e => {
if (skip?.(e)) return;
e.stopPropagation();
if (!easyMode?.() && e.buttons !== 1) return;
ref.setPointerCapture(e.pointerId);
const state = createPointerState(e);
touches.set(e.pointerId, state);
handleDrag(state, e);
};
const handleMove = e => {
e.preventDefault();
if (!easyMode?.() && e.buttons !== 1) return;
const state = touches.get(e.pointerId);
if (!state) return;
state.type = 'move';
state.xy = [e.clientX, e.clientY];
handleDrag(state, e);
state.last = state.xy;
};
const handleUp = e => {
e.stopPropagation();
ref.releasePointerCapture(e.pointerId);
const state = touches.get(e.pointerId);
if (!state) return;
touches.delete(e.pointerId);
state.type = 'up';
state.xy = [e.clientX, e.clientY];
// 判断单击
if (handleClick && touches.size === 0 && approx(state.xy[0] - state.initial[0], 0, 5) && approx(state.xy[1] - state.initial[1], 0, 5) && performance.now() - state.startTime < 300) handleClick(e, state.target);
handleDrag(state, e);
};
ref.addEventListener('pointerdown', handleDown, options);
ref.addEventListener('pointermove', handleMove, {
...options,
passive: false
});
ref.addEventListener('pointerup', handleUp, options);
ref.addEventListener('pointercancel', e => {
e.stopPropagation();
const state = touches.get(e.pointerId);
if (!state) return;
state.type = 'cancel';
handleDrag(state, e);
touches.clear();
}, {
capture: false,
passive: true,
signal: controller.signal
});
if (easyMode) {
ref.addEventListener('pointerover', handleDown, options);
ref.addEventListener('pointerout', handleUp, options);
}
return () => controller.abort();
});
};
const useStore = initState => {
const [_state, _setState] = store.createStore(initState);
return {
_state,
_setState,
setState: fn => _setState(store.produce(fn)),
store: _state
};
};
const useStyleSheet = e => {
const styleSheet = new CSSStyleSheet();
onAutoMount(() => {
const root = e?.getRootNode() ?? document;
root.adoptedStyleSheets = [...root.adoptedStyleSheets, styleSheet];
return () => {
const index = root.adoptedStyleSheets.indexOf(styleSheet);
if (index !== -1) root.adoptedStyleSheets.splice(index, 1);
};
});
return styleSheet;
};
const useStyle = (css, e) => {
const styleSheet = useStyleSheet(e);
if (typeof css === 'string') styleSheet.replaceSync(css);else createEffectOn(createRootMemo(css), style => styleSheet.replaceSync(style));
};
/** 用 CSSStyleSheet 实现和修改 style 一样的效果 */
const useStyleMemo = (selector, styleMapArg, e) => {
const styleSheet = useStyleSheet(e);
styleSheet.insertRule(\`\${selector} { }\`);
const {
style
} = styleSheet.cssRules[0];
// 等火狐实现了 CSS Typed OM 后改用 styleMap 性能会更好,也能使用 CSS Typed OM 的 单位
const setStyle = (key, val) => {
if (val === undefined || val === '') return style.removeProperty(key);
style.setProperty(key, typeof val === 'string' ? val : \`\${val}\`);
};
const styleMapList = Array.isArray(styleMapArg) ? styleMapArg : [styleMapArg];
for (const styleMap of styleMapList) {
if (typeof styleMap === 'object') {
for (const [key, val] of Object.entries(styleMap)) {
const styleText = createRootMemo(val);
createEffectOn(styleText, newVal => setStyle(key, newVal));
}
} else {
const styleMemoMap = createRootMemo(styleMap);
createEffectOn(styleMemoMap, map => {
for (const [key, val] of Object.entries(map)) setStyle(key, val);
});
}
}
};
const zh = {
alert: {
comic_load_error: "漫画加载出错",
download_failed: "下载失败",
fetch_comic_img_failed: "获取漫画图片失败",
img_load_failed: "图片加载失败",