forked from hymbz/ComicReadScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComicRead.user.js
More file actions
6327 lines (5948 loc) · 236 KB
/
ComicRead.user.js
File metadata and controls
6327 lines (5948 loc) · 236 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
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 6.5.2
// @description 为漫画站增加双页阅读模式并优化使用体验。百合会——「记录阅读历史,体验优化」、百合会新站、动漫之家——「解锁隐藏漫画」、ehentai——「匹配 nhentai 漫画」、nhentai——「彻底屏蔽漫画,自动翻页」、明日方舟泰拉记事社、禁漫天堂、拷贝漫画(copymanga)、漫画柜(manhuagui)、漫画DB(manhuadb)、漫画猫(manhuacat)、动漫屋(dm5)、绅士漫画(wnacg)、mangabz、welovemanga
// @author hymbz
// @license AGPL-3.0-or-later
// @noframes
// @match *://*/*
// @connect cdn.jsdelivr.net
// @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 self
// @connect *
// @grant GM_addElement
// @grant GM_getResourceText
// @grant GM_xmlhttpRequest
// @grant GM.addValueChangeListener
// @grant GM.removeValueChangeListener
// @grant GM.getResourceText
// @grant GM.addStyle
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.registerMenuCommand
// @grant GM.unregisterMenuCommand
// @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://unpkg.com/solid-js@1.7.3/dist/solid.cjs
// @resource solid-js/store https://unpkg.com/solid-js@1.7.3/store/dist/store.cjs
// @resource solid-js/web https://unpkg.com/solid-js@1.7.3/web/dist/web.cjs
// @resource panzoom https://unpkg.com/panzoom@9.4.3/dist/panzoom.min.js
// @resource fflate https://unpkg.com/fflate@0.7.4/umd/index.js
// @resource dmzjDecrypt https://greasyfork.org/scripts/467177-dmzjdecrypt/code/dmzjDecrypt.js?version=1207199
// @supportURL https://github.com/hymbz/ComicReadScript/issues
// @updateURL https://github.com/hymbz/ComicReadScript/raw/master/ComicRead.user.js
// @downloadURL https://github.com/hymbz/ComicReadScript/raw/master/ComicRead.user.js
// ==/UserScript==
/**
* 虽然在打包的时候已经尽可能保持代码格式不变了,但因为脚本代码比较多的缘故
* 所以真对脚本代码感兴趣的话,推荐还是直接上 github 仓库来看
* <https://github.com/hymbz/ComicReadScript>
* 对站点逻辑感兴趣的,结合 `src\index.ts` 看 `src\site` 下的对应文件即可
*/
const gmApi = {
GM,
GM_addElement,
GM_getResourceText,
GM_xmlhttpRequest,
unsafeWindow
};
const gmApiList = Object.keys(gmApi);
unsafeWindow.crsLib = {
// 有些 cjs 模块会检查这个,所以在这里声明下
process: {
env: {
NODE_ENV: 'production'
}
},
...gmApi
};
/**
* 通过 Resource 导入外部模块
* @param name \@resource 引用的资源名
*/
const selfImportSync = name => {
const code = name !== 'main' ? GM_getResourceText(name) :`
const web = require('solid-js/web');
const solidJs = require('solid-js');
const store$2 = require('solid-js/store');
const fflate = require('fflate');
const createPanZoom = require('panzoom');
const sleep = ms => new Promise(resolve => {
window.setTimeout(resolve, ms);
});
/**
* 对 document.querySelector 的封装
* 将默认返回类型改为 HTMLElement
*/
const querySelector = selector => document.querySelector(selector);
/**
* 对 document.querySelector 的封装
* 将默认返回类型改为 HTMLElement
*/
const querySelectorAll = selector => [...document.querySelectorAll(selector)];
/**
* 添加元素
* @param node 被添加元素
* @param textnode 添加元素
* @param referenceNode 参考元素,添加元素将插在参考元素前
*/
const insertNode = (node, textnode, referenceNode = null) => {
const temp = document.createElement('div');
temp.innerHTML = textnode;
const frag = document.createDocumentFragment();
while (temp.firstChild) frag.appendChild(temp.firstChild);
node.insertBefore(frag, referenceNode);
};
/** 返回 Dom 的点击函数 */
const querySelectorClick = selector => {
const dom = typeof selector === 'string' ? querySelector(selector) : selector();
if (dom) return () => dom.click();
};
/** 判断两个列表中包含的值是否相同 */
const isEqualArray = (a, b) => a.length === b.length && !a.some(t => !b.includes(t));
/** 将对象转为 URLParams 类型的字符串 */
const dataToParams = data => Object.entries(data).map(([key, val]) => \`\${key}=\${val}\`).join('&');
/** 将 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 linstenKeyup = handler => window.addEventListener('keyup', e => {
// 跳过输入框的键盘事件
switch (e.target.tagName) {
case 'INPUT':
case 'TEXTAREA':
return;
}
handler(e);
});
/** 滚动页面到指定元素的所在位置 */
const scrollIntoView = selector => querySelector(selector)?.scrollIntoView();
/**
* 限制 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);
})();
execPool.add(p);
};
});
while (doneNum !== totalNum) {
while (taskList.length && execPool.size < limit) {
taskList.shift()();
}
// eslint-disable-next-line no-await-in-loop
await Promise.race(execPool);
}
return resList;
};
/**
* 判断使用参数颜色作为默认值时是否需要切换为黑暗模式
* @param hexColor 十六进制颜色。例如 #112233
*/
const needDarkMode = hexColor => {
// by: https://24ways.org/2010/calculating-color-contrast
const r = parseInt(hexColor.substring(1, 3), 16);
const g = parseInt(hexColor.substring(3, 5), 16);
const b = parseInt(hexColor.substring(5, 7), 16);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq < 128;
};
/** 等到传入的函数返回 true */
const wait = fn => new Promise(resolve => {
const id = window.setInterval(() => {
const res = fn();
if (!res) return;
window.clearInterval(id);
resolve(res);
}, 100);
});
/** 等到指定的 dom 出现 */
const waitDom = selector => wait(() => querySelector(selector));
/** 等待指定的图片元素加载完成 */
const waitImgLoad = (img, timeout = 1000 * 10) => new Promise(resolve => {
const id = window.setTimeout(() => resolve(new ErrorEvent('超时')), timeout);
img.addEventListener('load', () => {
resolve(null);
window.clearTimeout(id);
});
img.addEventListener('error', e => {
resolve(e);
window.clearTimeout(id);
});
});
/**
* 求 a 和 b 的差集,相当于从 a 中删去和 b 相同的属性
*
* 不会修改参数对象,返回的是新对象
*/
const difference = (a, b) => {
const res = {};
const keys = Object.keys(a);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (typeof a[key] === 'object') {
const _res = difference(a[key], b[key]);
if (Object.keys(_res).length) res[key] = _res;
} else if (a[key] !== b[key]) res[key] = a[key];
}
return res;
};
/**
* Object.assign 的深拷贝版,不会导致 a 子对象属性的缺失
*
* 不会修改参数对象,返回的是新对象
*/
const assign = (a, b) => {
const res = JSON.parse(JSON.stringify(a));
const keys = Object.keys(b);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (typeof b[key] === 'object') {
const _res = assign(a[key], b[key]);
if (Object.keys(_res).length) res[key] = _res;
} else if (a[key] !== b[key]) res[key] = b[key];
}
return res;
};
/**
* 通过监视点击等会触发动态加载的事件,在触发动态加载后更新图片列表等
* @param update 动态加载后的重新加载
*/
const autoUpdate = update => {
let running = false;
const refresh = async () => {
running = true;
try {
await update();
} finally {
running = false;
}
};
['click', 'popstate'].forEach(eventName => {
window.addEventListener(eventName, () => setTimeout(() => {
if (running) return;
refresh();
}, 100));
});
refresh();
};
/** 挂载 solid-js 组件 */
const mountComponents = (id, fc) => {
const dom = document.createElement('div');
dom.id = id;
// TODO:
// 目前 solidjs 的所有事件都是在 document 上监听的
// 所以现在没法阻止脚本元素上的事件触发原网页的快捷键
// 需要等待 solidjs 更新
// https://github.com/solidjs/solid/issues/1786
//
// ['click', 'keydown', 'keypress', 'keyup'].forEach((eventName) =>
// dom.addEventListener(eventName, (e: Event) => e?.stopPropagation()),
// );
document.body.appendChild(dom);
const shadowDom = dom.attachShadow({
mode: 'open'
});
web.render(fc, shadowDom);
return dom;
};
var e=[],t=[];function n(n,r){if(n&&"undefined"!=typeof document){var a,s=!0===r.prepend?"prepend":"append",d=!0===r.singleTag,i="string"==typeof r.container?document.querySelector(r.container):document.getElementsByTagName("head")[0];if(d){var u=e.indexOf(i);-1===u&&(u=e.push(i)-1,t[u]={}),a=t[u]&&t[u][s]?t[u][s]:t[u][s]=c();}else a=c();65279===n.charCodeAt(0)&&(n=n.substring(1)),a.styleSheet?a.styleSheet.cssText+=n:a.appendChild(document.createTextNode(n));}function c(){var e=document.createElement("style");if(e.setAttribute("type","text/css"),r.attributes)for(var t=Object.keys(r.attributes),n=0;n<t.length;n++)e.setAttribute(t[n],r.attributes[t[n]]);var a="prepend"===s?"afterbegin":"beforeend";return i.insertAdjacentElement(a,e),e}}
var css$3 = ".index_module_root__e3ca723c{align-items:flex-end;bottom:0;display:flex;flex-direction:column;font-size:16px;pointer-events:none;position:fixed;right:0;z-index:9999999999}.index_module_item__e3ca723c{align-items:center;animation:index_module_bounceInRight__e3ca723c .5s 1;background:#fff;border-radius:4px;box-shadow:0 1px 10px 0 #0000001a,0 2px 15px 0 #0000000d;color:#000;cursor:pointer;display:flex;margin:1em;max-width:30vw;overflow:hidden;padding:.8em 1em;pointer-events:auto;position:relative;width:-moz-fit-content;width:fit-content}.index_module_item__e3ca723c>svg{color:var(--theme);margin-right:.5em;width:1em}.index_module_item__e3ca723c[data-exit]{animation:index_module_bounceOutRight__e3ca723c .5s 1}.index_module_schedule__e3ca723c{background-color:var(--theme);bottom:0;height:.2em;left:0;position:absolute;transform-origin:left;width:100%}.index_module_item__e3ca723c[data-schedule] .index_module_schedule__e3ca723c{transition:transform .1s}.index_module_item__e3ca723c:not([data-schedule]) .index_module_schedule__e3ca723c{animation:index_module_schedule__e3ca723c linear 1 forwards}:is(.index_module_item__e3ca723c:hover,.index_module_item__e3ca723c[data-schedule],.index_module_root__e3ca723c[data-paused]) .index_module_schedule__e3ca723c{animation-play-state:paused}.index_module_msg__e3ca723c{text-align:start;width:-moz-fit-content;width:fit-content}.index_module_msg__e3ca723c h2,.index_module_msg__e3ca723c h3{margin:.3em 0 .7em}.index_module_msg__e3ca723c ul{margin:0;text-align:left}@keyframes index_module_schedule__e3ca723c{0%{transform:scaleX(1)}to{transform:scaleX(0)}}@keyframes index_module_bounceInRight__e3ca723c{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0) scaleX(3)}60%{opacity:1;transform:translate3d(-25px,0,0) scaleX(1)}75%{transform:translate3d(10px,0,0) scaleX(.98)}90%{transform:translate3d(-5px,0,0) scaleX(.995)}to{transform:translateZ(0)}}@keyframes index_module_bounceOutRight__e3ca723c{20%{opacity:1;transform:translate3d(-20px,0,0) scaleX(.9)}to{opacity:0;transform:translate3d(2000px,0,0) scaleX(2)}}";
var modules_c21c94f2$3 = {"root":"index_module_root__e3ca723c","item":"index_module_item__e3ca723c","bounceInRight":"index_module_bounceInRight__e3ca723c","bounceOutRight":"index_module_bounceOutRight__e3ca723c","schedule":"index_module_schedule__e3ca723c","msg":"index_module_msg__e3ca723c"};
n(css$3,{});
const [_state$1, _setState] = store$2.createStore({
list: [],
map: {}
});
const setState$1 = fn => _setState(store$2.produce(fn));
// eslint-disable-next-line solid/reactivity
const store$1 = _state$1;
const creatId = () => {
let id = \`\${Date.now()}\`;
while (Reflect.has(store$1.map, id)) {
id += '_';
}
return id;
};
const _tmpl$$J = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM9.29 16.29 5.7 12.7a.996.996 0 1 1 1.41-1.41L10 14.17l6.88-6.88a.996.996 0 1 1 1.41 1.41l-7.59 7.59a.996.996 0 0 1-1.41 0z">\`);
const MdCheckCircle = ((props = {}) => (() => {
const _el$ = _tmpl$$J();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$I = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M4.47 21h15.06c1.54 0 2.5-1.67 1.73-3L13.73 4.99c-.77-1.33-2.69-1.33-3.46 0L2.74 18c-.77 1.33.19 3 1.73 3zM12 14c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1zm1 4h-2v-2h2v2z">\`);
const MdWarning = ((props = {}) => (() => {
const _el$ = _tmpl$$I();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$H = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 11c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v4c0 .55-.45 1-1 1zm1 4h-2v-2h2v2z">\`);
const MdError = ((props = {}) => (() => {
const _el$ = _tmpl$$H();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$G = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 15c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1s1 .45 1 1v4c0 .55-.45 1-1 1zm1-8h-2V7h2v2z">\`);
const MdInfo = ((props = {}) => (() => {
const _el$ = _tmpl$$G();
web.spread(_el$, props, true, true);
return _el$;
})());
const toast$1 = (msg, options) => {
if (!msg) return;
const id = options?.id ?? (typeof msg === 'string' ? msg : creatId());
setState$1(state => {
if (Reflect.has(state.map, id)) {
Object.assign(state.map[id], {
msg,
...options,
update: true
});
return;
}
state.map[id] = {
id,
type: 'info',
duration: 3000,
msg,
...options
};
state.list.push(id);
});
};
toast$1.dismiss = id => {
if (!Reflect.has(store$1.map, id)) return;
setState$1(state => {
state.map[id].exit = true;
});
};
toast$1.set = (id, options) => {
if (!Reflect.has(store$1.map, id)) return;
setState$1(state => {
Object.assign(state.map[id], options);
});
};
toast$1.success = (msg, options) => toast$1(msg, {
...options,
type: 'success'
});
toast$1.warn = (msg, options) => toast$1(msg, {
...options,
type: 'warn'
});
toast$1.error = (msg, options) => toast$1(msg, {
...options,
type: 'error'
});
const _tmpl$$F = /*#__PURE__*/web.template(\`<div>\`),
_tmpl$2$9 = /*#__PURE__*/web.template(\`<div><div>\`);
const iconMap = {
info: MdInfo,
success: MdCheckCircle,
warn: MdWarning,
error: MdError
};
const colorMap = {
info: '#3a97d7',
success: '#23bb35',
warn: '#f0c53e',
error: '#e45042',
custom: '#1f2936'
};
/** 删除 toast */
const dismissToast = id => setState$1(state => {
state.map[id].onDismiss?.({
...state.map[id]
});
const i = state.list.findIndex(t => t === id);
if (i !== -1) state.list.splice(i, 1);
Reflect.deleteProperty(state.map, id);
});
/** 重置 toast 的 update 属性 */
const resetToastUpdate = id => setState$1(state => {
Reflect.deleteProperty(state.map[id], 'update');
});
const ToastItem = props => {
/** 是否要显示进度 */
const showSchedule = solidJs.createMemo(() => props.duration === Infinity && props.schedule ? true : undefined);
const dismiss = e => {
e.stopPropagation();
if (showSchedule() && 'animationName' in e) return;
toast$1.dismiss(props.id);
};
// 在退出动画结束后才真的删除
const handleAnimationEnd = () => {
if (!props.exit) return;
dismissToast(props.id);
};
let scheduleRef;
solidJs.createEffect(() => {
if (!props.update) return;
resetToastUpdate(props.id);
scheduleRef?.getAnimations().forEach(animation => {
animation.cancel();
animation.play();
});
});
return (() => {
const _el$ = _tmpl$2$9(),
_el$2 = _el$.firstChild;
_el$.addEventListener("animationend", handleAnimationEnd);
_el$.$$click = dismiss;
web.insert(_el$, web.createComponent(web.Dynamic, {
get component() {
return iconMap[props.type];
}
}), _el$2);
web.insert(_el$2, (() => {
const _c$ = web.memo(() => typeof props.msg === 'string');
return () => _c$() ? props.msg : web.createComponent(props.msg, {});
})());
web.insert(_el$, web.createComponent(solidJs.Show, {
get when() {
return props.duration !== Infinity || props.schedule !== undefined;
},
get children() {
const _el$3 = _tmpl$$F();
_el$3.addEventListener("animationend", dismiss);
const _ref$ = scheduleRef;
typeof _ref$ === "function" ? web.use(_ref$, _el$3) : scheduleRef = _el$3;
web.effect(_p$ => {
const _v$ = modules_c21c94f2$3.schedule,
_v$2 = \`\${props.duration}ms\`,
_v$3 = showSchedule() ? \`scaleX(\${props.schedule})\` : undefined;
_v$ !== _p$._v$ && web.className(_el$3, _p$._v$ = _v$);
_v$2 !== _p$._v$2 && ((_p$._v$2 = _v$2) != null ? _el$3.style.setProperty("animation-duration", _v$2) : _el$3.style.removeProperty("animation-duration"));
_v$3 !== _p$._v$3 && ((_p$._v$3 = _v$3) != null ? _el$3.style.setProperty("transform", _v$3) : _el$3.style.removeProperty("transform"));
return _p$;
}, {
_v$: undefined,
_v$2: undefined,
_v$3: undefined
});
return _el$3;
}
}), null);
web.effect(_p$ => {
const _v$4 = modules_c21c94f2$3.item,
_v$5 = colorMap[props.type],
_v$6 = showSchedule(),
_v$7 = props.exit,
_v$8 = modules_c21c94f2$3.msg;
_v$4 !== _p$._v$4 && web.className(_el$, _p$._v$4 = _v$4);
_v$5 !== _p$._v$5 && ((_p$._v$5 = _v$5) != null ? _el$.style.setProperty("--theme", _v$5) : _el$.style.removeProperty("--theme"));
_v$6 !== _p$._v$6 && web.setAttribute(_el$, "data-schedule", _p$._v$6 = _v$6);
_v$7 !== _p$._v$7 && web.setAttribute(_el$, "data-exit", _p$._v$7 = _v$7);
_v$8 !== _p$._v$8 && web.className(_el$2, _p$._v$8 = _v$8);
return _p$;
}, {
_v$4: undefined,
_v$5: undefined,
_v$6: undefined,
_v$7: undefined,
_v$8: undefined
});
return _el$;
})();
};
web.delegateEvents(["click"]);
const _tmpl$$E = /*#__PURE__*/web.template(\`<div>\`);
const Toaster = () => {
const [visible, setVisible] = solidJs.createSignal(document.visibilityState === 'visible');
solidJs.onMount(() => {
const handleVisibilityChange = () => {
setVisible(document.visibilityState === 'visible');
};
document.addEventListener('visibilitychange', handleVisibilityChange);
solidJs.onCleanup(() => document.removeEventListener('visibilitychange', handleVisibilityChange));
});
return (() => {
const _el$ = _tmpl$$E();
web.insert(_el$, web.createComponent(solidJs.For, {
get each() {
return store$1.list;
},
children: id => web.createComponent(ToastItem, web.mergeProps(() => store$1.map[id]))
}));
web.effect(_p$ => {
const _v$ = modules_c21c94f2$3.root,
_v$2 = visible() ? undefined : '';
_v$ !== _p$._v$ && web.className(_el$, _p$._v$ = _v$);
_v$2 !== _p$._v$2 && web.setAttribute(_el$, "data-paused", _p$._v$2 = _v$2);
return _p$;
}, {
_v$: undefined,
_v$2: undefined
});
return _el$;
})();
};
const ToastStyle = css$3;
const _tmpl$$D = /*#__PURE__*/web.template(\`<style type="text/css">\`);
let dom$1;
const init = () => {
if (!dom$1) dom$1 = mountComponents('toast', () => [web.createComponent(Toaster, {}), (() => {
const _el$ = _tmpl$$D();
web.insert(_el$, ToastStyle);
return _el$;
})()]);
};
const toast = new Proxy(toast$1, {
get(target, propKey) {
init();
return target[propKey];
},
apply(target, propKey, args) {
init();
const fn = propKey ? target[propKey] : target;
return fn(...args);
}
});
// 将 xmlHttpRequest 包装为 Promise
const xmlHttpRequest = details => new Promise((resolve, reject) => {
GM_xmlhttpRequest({
...details,
onload: resolve,
onerror: reject,
ontimeout: reject
});
});
/** 发起请求 */
const request$1 = async (url, details, errorNum = 0) => {
const errorText = details?.errorText ?? '漫画加载出错';
try {
const res = await xmlHttpRequest({
method: 'GET',
url,
headers: {
Referer: window.location.href
},
...details
});
if (res.status !== 200) throw new Error(errorText);
return res;
} catch (error) {
if (errorNum >= 3) {
if (errorText && !details?.noTip) toast.error(errorText);
throw new Error(errorText);
}
console.error(errorText, error);
await sleep(1000);
return request$1(url, details, errorNum + 1);
}
};
const _tmpl$$C = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="m20.45 6 .49-1.06L22 4.45a.5.5 0 0 0 0-.91l-1.06-.49L20.45 2a.5.5 0 0 0-.91 0l-.49 1.06-1.05.49a.5.5 0 0 0 0 .91l1.06.49.49 1.05c.17.39.73.39.9 0zM8.95 6l.49-1.06 1.06-.49a.5.5 0 0 0 0-.91l-1.06-.48L8.95 2a.492.492 0 0 0-.9 0l-.49 1.06-1.06.49a.5.5 0 0 0 0 .91l1.06.49L8.05 6c.17.39.73.39.9 0zm10.6 7.5-.49 1.06-1.06.49a.5.5 0 0 0 0 .91l1.06.49.49 1.06a.5.5 0 0 0 .91 0l.49-1.06 1.05-.5a.5.5 0 0 0 0-.91l-1.06-.49-.49-1.06c-.17-.38-.73-.38-.9.01zm-1.84-4.38-2.83-2.83a.996.996 0 0 0-1.41 0L2.29 17.46a.996.996 0 0 0 0 1.41l2.83 2.83c.39.39 1.02.39 1.41 0L17.7 10.53c.4-.38.4-1.02.01-1.41zm-3.5 2.09L12.8 9.8l1.38-1.38 1.41 1.41-1.38 1.38z">\`);
const MdAutoFixHigh = ((props = {}) => (() => {
const _el$ = _tmpl$$C();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$B = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="m22 3.55-1.06-.49L20.45 2a.5.5 0 0 0-.91 0l-.49 1.06-1.05.49a.5.5 0 0 0 0 .91l1.06.49.49 1.05a.5.5 0 0 0 .91 0l.49-1.06L22 4.45c.39-.17.39-.73 0-.9zm-7.83 4.87 1.41 1.41-1.46 1.46 1.41 1.41 2.17-2.17a.996.996 0 0 0 0-1.41l-2.83-2.83a.996.996 0 0 0-1.41 0l-2.17 2.17 1.41 1.41 1.47-1.45zM2.1 4.93l6.36 6.36-6.17 6.17a.996.996 0 0 0 0 1.41l2.83 2.83c.39.39 1.02.39 1.41 0l6.17-6.17 6.36 6.36a.996.996 0 1 0 1.41-1.41L3.51 3.51a.996.996 0 0 0-1.41 0c-.39.4-.39 1.03 0 1.42z">\`);
const MdAutoFixOff = ((props = {}) => (() => {
const _el$ = _tmpl$$B();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$A = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M7 3v9c0 .55.45 1 1 1h2v7.15c0 .51.67.69.93.25l5.19-8.9a.995.995 0 0 0-.86-1.5H13l2.49-6.65A.994.994 0 0 0 14.56 2H8c-.55 0-1 .45-1 1z">\`);
const MdAutoFlashOn = ((props = {}) => (() => {
const _el$ = _tmpl$$A();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$z = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M16.12 11.5a.995.995 0 0 0-.86-1.5h-1.87l2.28 2.28.45-.78zm.16-8.05c.33-.67-.15-1.45-.9-1.45H8c-.55 0-1 .45-1 1v.61l6.13 6.13 3.15-6.29zm2.16 14.43L4.12 3.56a.996.996 0 1 0-1.41 1.41L7 9.27V12c0 .55.45 1 1 1h2v7.15c0 .51.67.69.93.25l2.65-4.55 3.44 3.44c.39.39 1.02.39 1.41 0 .4-.39.4-1.02.01-1.41z">\`);
const MdAutoFlashOff = ((props = {}) => (() => {
const _el$ = _tmpl$$z();
web.spread(_el$, props, true, true);
return _el$;
})());
var css$2 = ".index_module_iconButtonItem__9645dd99{align-items:center;display:flex;position:relative}.index_module_iconButton__9645dd99{align-items:center;background-color:initial;border-radius:9999px;border-style:none;color:var(--text,#fff);cursor:pointer;display:flex;font-size:1.5em;height:1.5em;justify-content:center;margin:.1em;outline:none;padding:0;width:1.5em}.index_module_iconButton__9645dd99:focus,.index_module_iconButton__9645dd99:hover{background-color:var(--hover_bg_color,#fff3)}.index_module_iconButton__9645dd99.index_module_enabled__9645dd99{background-color:var(--text,#fff);color:var(--text_bg,#121212)}.index_module_iconButton__9645dd99.index_module_enabled__9645dd99:focus,.index_module_iconButton__9645dd99.index_module_enabled__9645dd99:hover{background-color:var(--hover_bg_color_enable,#fffa)}.index_module_iconButton__9645dd99>svg{width:1em}.index_module_iconButtonPopper__9645dd99{align-items:center;background-color:#303030;border-radius:.3em;color:#fff;display:flex;font-size:.8em;opacity:0;padding:.4em .5em;position:absolute;top:50%;transform:translateY(-50%);user-select:none;white-space:nowrap}.index_module_iconButtonPopper__9645dd99[data-placement=right]{left:calc(100% + 1.5em)}.index_module_iconButtonPopper__9645dd99[data-placement=right]:before{border-right-color:var(--switch_bg,#6e6e6e);border-right-width:.5em;right:calc(100% + .5em)}.index_module_iconButtonPopper__9645dd99[data-placement=left]{right:calc(100% + 1.5em)}.index_module_iconButtonPopper__9645dd99[data-placement=left]:before{border-left-color:var(--switch_bg,#6e6e6e);border-left-width:.5em;left:calc(100% + .5em)}.index_module_iconButtonPopper__9645dd99:before{background-color:initial;border:.4em solid #0000;content:\\"\\";position:absolute;transition:opacity .15s}.index_module_iconButtonItem__9645dd99:focus .index_module_iconButtonPopper__9645dd99,.index_module_iconButtonItem__9645dd99:hover .index_module_iconButtonPopper__9645dd99,.index_module_iconButtonItem__9645dd99[data-show=true] .index_module_iconButtonPopper__9645dd99{opacity:1}.index_module_hidden__9645dd99{display:none}";
var modules_c21c94f2$2 = {"iconButtonItem":"index_module_iconButtonItem__9645dd99","iconButton":"index_module_iconButton__9645dd99","enabled":"index_module_enabled__9645dd99","iconButtonPopper":"index_module_iconButtonPopper__9645dd99","hidden":"index_module_hidden__9645dd99"};
n(css$2,{});
const _tmpl$$y = /*#__PURE__*/web.template(\`<div><button type="button">\`),
_tmpl$2$8 = /*#__PURE__*/web.template(\`<div>\`);
const IconButtonStyle = css$2;
/**
* 图标按钮
*/
const IconButton = _props => {
const props = solidJs.mergeProps({
placement: 'right'
}, _props);
let buttonRef;
const handleClick = e => {
// 在每次点击后取消焦点
buttonRef?.blur();
props.onClick?.(e);
};
return (() => {
const _el$ = _tmpl$$y(),
_el$2 = _el$.firstChild;
_el$2.$$click = handleClick;
const _ref$ = buttonRef;
typeof _ref$ === "function" ? web.use(_ref$, _el$2) : buttonRef = _el$2;
web.insert(_el$2, () => props.children);
web.insert(_el$, (() => {
const _c$ = web.memo(() => !!(props.popper || props.tip));
return () => _c$() ? (() => {
const _el$3 = _tmpl$2$8();
web.insert(_el$3, () => props.popper || props.tip);
web.effect(_p$ => {
const _v$6 = [modules_c21c94f2$2.iconButtonPopper, props.popperClassName].join(' '),
_v$7 = props.placement;
_v$6 !== _p$._v$6 && web.className(_el$3, _p$._v$6 = _v$6);
_v$7 !== _p$._v$7 && web.setAttribute(_el$3, "data-placement", _p$._v$7 = _v$7);
return _p$;
}, {
_v$6: undefined,
_v$7: undefined
});
return _el$3;
})() : null;
})(), null);
web.effect(_p$ => {
const _v$ = modules_c21c94f2$2.iconButtonItem,
_v$2 = props.showTip,
_v$3 = props.tip,
_v$4 = modules_c21c94f2$2.iconButton,
_v$5 = {
[modules_c21c94f2$2.hidden]: props.hidden,
[modules_c21c94f2$2.enabled]: props.enabled
};
_v$ !== _p$._v$ && web.className(_el$, _p$._v$ = _v$);
_v$2 !== _p$._v$2 && web.setAttribute(_el$, "data-show", _p$._v$2 = _v$2);
_v$3 !== _p$._v$3 && web.setAttribute(_el$2, "aria-label", _p$._v$3 = _v$3);
_v$4 !== _p$._v$4 && web.className(_el$2, _p$._v$4 = _v$4);
_p$._v$5 = web.classList(_el$2, _v$5, _p$._v$5);
return _p$;
}, {
_v$: undefined,
_v$2: undefined,
_v$3: undefined,
_v$4: undefined,
_v$5: undefined
});
return _el$;
})();
};
web.delegateEvents(["click"]);
const useSpeedDial = (options, setOptions) => {
const DefaultButton = props => {
return web.createComponent(IconButton, {
get tip() {
return props.showName ?? props.optionName;
},
placement: "left",
onClick: () => setOptions({
...options,
[props.optionName]: !options[props.optionName]
}),
get children() {
return props.children ?? (options[props.optionName] ? web.createComponent(MdAutoFixHigh, {}) : web.createComponent(MdAutoFixOff, {}));
}
});
};
const list = Object.keys(options).map(optionName => {
switch (optionName) {
case 'hiddenFAB':
case 'option':
return null;
case 'autoShow':
return () => web.createComponent(DefaultButton, {
optionName: "autoShow",
showName: "\\u81EA\\u52A8\\u8FDB\\u5165\\u9605\\u8BFB\\u6A21\\u5F0F",
get children() {
return web.memo(() => !!options.autoShow)() ? web.createComponent(MdAutoFlashOn, {}) : web.createComponent(MdAutoFlashOff, {});
}
});
default:
return () => web.createComponent(DefaultButton, {
optionName: optionName
});
}
}).filter(Boolean);
return list;
};
/* eslint-disable no-param-reassign */
const promisifyRequest = request => new Promise((resolve, reject) => {
// eslint-disable-next-line no-multi-assign
request.oncomplete = request.onsuccess = () => resolve(request.result);
// eslint-disable-next-line no-multi-assign
request.onabort = request.onerror = () => reject(request.error);
});
const useCache = (initSchema, version = 1) => {
const request = indexedDB.open('ComicReadScript', version);
request.onupgradeneeded = () => {
initSchema(request.result);
};
const dbp = promisifyRequest(request);
const useStore = (storeName, txMode, callback) => dbp.then(db => callback(db.transaction(storeName, txMode).objectStore(storeName)));
return {
/** 存入数据 */
set: (storeName, value) => useStore(storeName, 'readwrite', async store => {
store.put(value);
await promisifyRequest(store.transaction);
}),
/** 根据主键直接获取数据 */
get: (storeName, query) => useStore(storeName, 'readonly', store => promisifyRequest(store.get(query))),
/** 查找符合条件的数据 */
find: (storeName, query, index) => useStore(storeName, 'readonly', store => promisifyRequest((index ? store.index(index) : store).getAll(query))),
/** 删除符合条件的数据 */
del: (storeName, query, index) => useStore(storeName, 'readwrite', async store => {
if (index) {
store.index(index).openCursor(query).onsuccess = async function onsuccess() {
if (!this.result) return;
await promisifyRequest(this.result.delete());
this.result.continue();
};
await promisifyRequest(store.transaction);
} else {
store.delete(query);
await promisifyRequest(store.transaction);
}
})
// each: <K extends keyof Schema & string>(
// storeName: K,
// query: IDBValidKey | IDBKeyRange | null,
// callback: (cursor: IDBCursorWithValue) => void,
// ) =>
// useStore(storeName, 'readonly', (store) => {
// store.openCursor(query).onsuccess = function onsuccess() {
// if (!this.result) return;
// callback(this.result);
// this.result.continue();
// };
// return promisifyRequest(store.transaction);
// }),
};
};
const _tmpl$$x = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M16.59 9H15V4c0-.55-.45-1-1-1h-4c-.55 0-1 .45-1 1v5H7.41c-.89 0-1.34 1.08-.71 1.71l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.63-.63.19-1.71-.7-1.71zM5 19c0 .55.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1 .45-1 1z">\`);
const MdFileDownload = ((props = {}) => (() => {
const _el$ = _tmpl$$x();
web.spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$w = /*#__PURE__*/web.template(\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="currentColor" fill="currentColor" stroke-width="0"><path d="M18.3 5.71a.996.996 0 0 0-1.41 0L12 10.59 7.11 5.7A.996.996 0 1 0 5.7 7.11L10.59 12 5.7 16.89a.996.996 0 1 0 1.41 1.41L12 13.41l4.89 4.89a.996.996 0 1 0 1.41-1.41L13.41 12l4.89-4.89c.38-.38.38-1.02 0-1.4z">\`);
const MdClose = ((props = {}) => (() => {
const _el$ = _tmpl$$w();
web.spread(_el$, props, true, true);
return _el$;
})());
const useStore = initState => {
const [_state, _setState] = store$2.createStore(initState);
return {
_state,
_setState,
setState: fn => _setState(store$2.produce(fn)),
store: _state
};
};
/** 加载状态的中文描述 */
const loadTypeMap = {
error: '加载出错',
loading: '正在加载',
wait: '等待加载',
loaded: ''
};
const imgState = {
imgList: [],
pageList: [],
/** 页面填充数据 */
fillEffect: {
'-1': true
},
/** 当前页数 */
activePageIndex: 0,
/** 比例 */
proportion: {
单页比例: 0,
横幅比例: 0,
条漫比例: 0
}
};
const ScrollbarState = {
/** 滚动条 */
scrollbar: {
/** 滚动条提示文本 */
tipText: '',
/** 滚动条高度比率 */
dragHeight: 0,
/** 滚动条所处高度比率 */
dragTop: 0
},
/**
* 用于防止滚轮连续滚动导致过快触发事件的锁
*
* - 在缩放时开启,结束缩放一段时间后关闭。开启时禁止翻页。
* - 在首次触发结束页时开启,一段时间关闭。开启时禁止触发结束页的上下话切换功能。
*/
scrollLock: false
};
const defaultOption = {
dir: 'rtl',
scrollbar: {
enabled: true,
autoHidden: false,
showProgress: true
},
onePageMode: false,
scrollMode: false,
clickPage: {
enabled: 'ontouchstart' in document.documentElement,
overturn: false
},
firstPageFill: true,
disableZoom: false,
darkMode: false,
swapTurnPage: false,
flipToNext: true,
alwaysLoadAllImg: false,
scrollModeImgScale: 1,
showComment: true,
translation: {
server: '禁用',
localUrl: undefined,
forceRetry: false,
options: {
size: 'M',
detector: 'default',
translator: 'gpt3.5',
direction: 'auto',
targetLanguage: 'CHS'
}
}
};
const OptionState = {
option: JSON.parse(JSON.stringify(defaultOption))
};
const OtherState = {
panzoom: undefined,
/** 当前是否处于放大模式 */
isZoomed: false,
/** 是否强制显示侧边栏 */
showToolbar: false,
/** 是否强制显示滚动条 */
showScrollbar: false,
/** 是否显示结束页 */
showEndPage: false,
/** 是否显示点击区域 */
showTouchArea: false,
/** 结束页状态。showEndPage 更改时自动计算 */
endPageType: undefined,
/** 评论列表 */
commentList: undefined,
/** 点击结束页按钮时触发的回调 */
onExit: undefined,
/** 点击上一话按钮时触发的回调 */
onPrev: undefined,
/** 点击下一话按钮时触发的回调 */
onNext: undefined,
/** 图片加载状态发生变化时触发的回调 */
onLoading: undefined,
editButtonList: list => list,
editSettingList: list => list,
prevRef: undefined,
nextRef: undefined,
exitRef: undefined
};
const {
store,
setState,
_state
} = useStore({
...imgState,
...ScrollbarState,
...OptionState,
...OtherState,
rootRef: undefined,
mangaFlowRef: undefined,
prevAreaRef: undefined,
nextAreaRef: undefined,
menuAreaRef: undefined
});
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The \`this\` context and all arguments are passed through,
* as-is, to \`callback\` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every \`delay\` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* \`delay\` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If \`debounceMode\` is true (at begin), schedule \`clear\` to execute after \`delay\` ms. If \`debounceMode\` is
* false (at end), schedule \`callback\` to execute after \`delay\` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle (delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* \`callback\` is executed at the proper times in \`throttle\` and \`end\`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time \`callback\` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec