-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsidedish.user.js
2213 lines (2011 loc) · 74.1 KB
/
sidedish.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 ss21 sidedish
// @version 2.4.5
// @description A companion userscript for the ss21 userstyle.
// @author saxamaphone69
// @namespace https://github.com/saxamaphone69/ss21
// @match *://boards.4chan.org/*
// @match *://find.4chan.org/*
// @match *://www.4chan.org/*
// @connect 4chan.org
// @connect a.4cdn.org
// @connect 4cdn.org
// @grant GM.xmlHttpRequest
// @grant GM.setValue
// @grant GM.getValue
// @run-at document-start
// @icon data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 96 960 960'%3E%3Cpath d='M70 622q0-15 11-29.5t29-23.5q22-9 44-22.5t54-13.5q48 0 72.5 28.5T343 590q37 0 64-28.5t74-28.5q47 0 72.5 28.5T618 590q36 0 62-28.5t73-28.5q33 0 54.5 14t43.5 23q18 9 29 23t11 29q0 13-9 21.5t-21 6.5q-36-8-56.5-26T753 606q-37 0-63.5 28.5T617 663q-48 0-74-28.5T481 606q-36 0-63.5 28.5T342 663q-47 0-72-28.5T208 606q-31 0-51.5 18T101 650q-13 2-22-6.5T70 622Zm0 185q0-14 10.5-28.5T110 756q22-9 44-23t54-14q47 0 72 28.5t63 28.5q37 0 64-28.5t74-28.5q47 0 72.5 28.5T617 776q36 0 62.5-28.5T753 719q32 0 54 14t45 23q18 8 28.5 22t10.5 29q0 14-9 22t-21 6q-36-8-56.5-25.5T753 792q-37 0-63.5 28.5T617 849q-48 0-74-28.5T481 792q-36 0-63.5 28.5T343 849q-47 0-73-28.5T208 792q-31 0-51.5 17.5T100 835q-12 2-21-6t-9-22Zm0-371q0-15 11-29.5t29-23.5q22-9 44-22.5t54-13.5q48 0 72.5 28.5T343 404q37 0 64-28.5t74-28.5q47 0 72.5 28.5T618 404q36 0 62-28.5t73-28.5q33 0 54.5 14t43.5 23q18 9 29 23t11 29q0 13-9 21.5t-21 6.5q-36-8-56.5-26T753 420q-37 0-63.5 28.5T617 477q-48 0-74-28.5T481 420q-36 0-64 28.5T342 477q-47 0-72-28.5T208 420q-31 0-51.5 18T101 464q-13 2-22-6.5T70 436Z'/%3E%3C/svg%3E
// @noframes
// @updateURL https://github.com/saxamaphone69/ss21/raw/main/sidedish.user.js
// @downloadURL https://github.com/saxamaphone69/ss21/raw/main/sidedish.user.js
// ==/UserScript==
(async () => {
"use strict";
//console.group("Initialising ss21 sidedish...");
/*! @ryanmorr/ready v1.4.0 | https://github.com/ryanmorr/ready */
function _typeof(a){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},_typeof(a)}(function(a,b){"object"===("undefined"==typeof exports?"undefined":_typeof(exports))&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):(a=a||self,a.ready=b())})(this,function(){'use strict';function a(a){for(var b,c=a.selector,d=a.callback,e=g.querySelectorAll(c),f=0,j=e.length;f<j;f++)b=e[f],b[h]||(b[h]=!0,d.call(b,b))}function b(){f.forEach(a)}function c(a){var b=f.indexOf(a);-1!==b&&f.splice(b,1),0===f.length&&null!=e&&(e.disconnect(),e=null)}function d(d,h){if("function"==typeof d&&(h=d,d=g,j))return h.call(g,g),function(){return null};e||(e=new MutationObserver(b),e.observe(g.documentElement,{childList:!0,subtree:!0}));var i={selector:d,callback:h};return f.push(i),a(i),function(){return c(i)}}var e=null,f=[],g=window.document,h=Symbol("ready"),j=/complete|loaded|interactive/.test(g.readyState);return j||g.addEventListener("DOMContentLoaded",function(){j=!0;for(var a,b=0,c=f.length;b<c;b++)a=f[b],a.selector===g&&(a.callback.call(g,g),f.splice(b--,1))}),d});
const d = document,
doc = d.documentElement,
currentBoard = location.pathname.split("/")[1],
config = (() => {
switch (location.pathname.split("/")[2]) {
case "thread":
return "thread";
case "catalog":
return "catalog";
case "archive":
return "archive";
default:
return "index";
}
})();
// add `.site-loading` to `html` so css can hide the page loading
doc.classList.add("site-loading");
if (window.location.host.split('.')[0] === 'find') {
doc.classList.remove("site-loading");
doc.classList.add("is-search");
}
const ss21Settings = {
scrollProgress: {
value: true,
name: 'Scrolling Progress Bar',
desc: 'Adds a fixed scrolling progress bar to the Header to indicate how much of the page has been scrolled.'
},
resizeQuotePreviews: {
value: false,
name: 'Resize Quote Previews',
desc: 'When hovering over a quote, if the post is larger than the viewport height, resizes it all to fit.'
},
removeStyles: {
value: false,
name: 'Remove 4chan X CSS',
desc: 'Remove the default 4chan X CSS inserted into the page for styling.'
},
reorganiseElements: {
value: false,
name: 'Reorganise Elements',
desc: 'Change the original location of HTML elements on the page to suit a Material layout.'
},
};
async function get(option) {
return await GM.getValue(option);
}
async function set(option, value) {
// val = items[key];
// results.push(GM.setValue(g.NAMESPACE + key, JSON.stringify(val)));
//
//if (typeof GM.setValue !== "undefined") {
//
// await GM.setValue("data", JSON.stringify(reset ? defaults : data));
GM.setValue(option, JSON.stringify(value));
//}
}
/*
async function showOff() {
for (let setting in ss21Settings) {
await set('ss21' + setting, ss21Settings[setting]);
}
}
showOff();
async function grabEm() {
let values = await GM.listValues();
for (let item in values) {
let setting = values[item];
let details = await get(setting);
//console.log(setting, JSON.parse(details).value);
//console.log(values[item], await JSON.parse(get(values[item])));
//console.log(await get(values[item]));
}
}
grabEm();
*/
//console.log(await get('ss21resizeQuotePreviews'));
//console.log(get('ss21resizeQuotePreviews'));
/*
async function getStoredValues(init) {
data = await GM.getValue("data", defaults);
try {
data = JSON.parse(data);
if (!Object.keys(data).length || ({}).toString.call(data) !== "[object Object]") {
throw new Error();
}
} catch (err) { // compat
data = await GM.getValue("data", defaults);
}
}
async function setStoredValues(reset) {
data.processedCss = $style.textContent;
await GM.setValue("data", JSON.stringify(reset ? defaults : data));
}
for(let key in settings){
GM_setValue(key, settings[key]);
}
*/
function $(sel, root) {
return (root || d).querySelector(sel);
}
function $$(sel, root) {
return [...(root || d).querySelectorAll(sel)];
}
function on(sel, events, cb) {
sel = Array.isArray(sel) ? sel : [sel];
let event = events.split(/\s+/);
sel.forEach((sel) => {
event.forEach((ev) => {
sel.addEventListener(ev, cb, {
passive: true,
});
});
});
return this;
}
function make(obj) {
let key,
el = d.createElement(obj.el);
if (obj.cl4ss) {
el.className = obj.cl4ss;
}
if (obj.html) {
el.innerHTML = obj.html;
}
if (obj.attr) {
for (key in obj.attr) {
if (obj.attr.hasOwnProperty(key)) {
el.setAttribute(key, obj.attr[key]);
}
}
}
if (obj.appendTo) {
let parent = obj.appendTo;
if (typeof parent === "string") {
$(parent).appendChild(el);
} else {
parent.appendChild(el);
}
}
if (obj.prepend) {
let parent = obj.prepend;
if (typeof parent === "string") {
$(parent).prepend(el);
} else {
parent.prepend(el);
}
}
return el;
}
function removeStyle(sel) {
if (sel) {
console.log(
"%css21 sidedish is removing this stylesheet: ",
"color:green;",
sel
);
sel.remove();
return true;
} else {
console.log("%css21 sidedish was unable to find: ", "color:red;", sel);
return false;
}
}
function sendNotification(type, content) {
d.dispatchEvent(
new CustomEvent("CreateNotification", {
detail: {
type: type, // success, info, warning, error
content: content,
lifetime: 0,
},
})
);
}
function removeStyles() {
//removeStyle($("link[rel='stylesheet']", d.head));
removeStyle($("style[type]", d.head)); // this removes the inline mobile css
removeStyle($("#fourchanx-css", d.head)); // this removes the css required by 4chan x
removeStyle($("#custom-css", d.head)); // this removes extra, custom css by 4chan x
//removeStyle($("#sound-player-css", d.head)); // sounds player
}
function init() {
on(d, "IndexBuild", doc.classList.remove("site-loading"));
const isChanX = doc && doc.classList.contains('fourchan-x');
if (!isChanX) {
doc.classList.remove("site-loading");
doc.classList.add("is-ext");
}
on(d, "OpenSettings", function () {
const settingDescriptions = $$(".description");
for (let settingDescription of settingDescriptions) {
const content = settingDescription.textContent.slice(2);
settingDescription.textContent = content;
}
});
removeStyles();
function getBoardType() {
let type = style_group;
type = type.slice(0, -6);
doc.classList.add(type);
}
getBoardType();
function toggleFooter() {
const navBot = $("#boardNavDesktopFoot");
on(navBot, "click", function (e) {
if (e.target === this) {
this.classList.toggle("is-active");
}
});
}
toggleFooter();
// this should return the `#header-bar` element
const headerBar = $("#header-bar") || $('#boardNavDesktop');
const scrollProgress = make({
//el: "progress",
el: "div",
attr: {
id: "scroll-progress"//,
//value: 0,
//max: 100,
},
appendTo: headerBar,
});
/*
const hero = $(".boardBanner"),
heroHeight = 480,
boardTitle = $(".boardTitle"),
mVal = 300;
//boardTitle.style.setProperty("--length", boardTitle.innerText.length);
let ticking = false;
function rAF(args) {
if (!ticking) {
window.requestAnimationFrame(function () {
ticking = false;
});
}
ticking = true;
}*/
/*
//https://github.com/adactio/FitText.js/blob/master/fittext.js
//https://github.com/rikschennink/fitty/blob/gh-pages/src/fitty.js
function fitText(el) {
el.style.fontSize = Math.max(Math.min(el.clientWidth / 10, parseFloat(1/0)), parseFloat(-1/0)) + 'px';
}
fitText(hero);
*/
// https://codepen.io/shshaw/pen/LYVBVve
/*
[...document.querySelectorAll("[data-fit-text]")].forEach(el => {
// We just need the length of the string as a CSS variable...
el.style.setProperty("--length", el.innerText.length);
});
*/
/*
[data-fit-text] {
// Sized via the viewport, but the --width variable could be set by JS based on the element or parent's width.
--width: 100vw;
// Adjust scale depending on your exact font.
--scale: 0.9;
font-size: calc(var(--width) / (var(--length, 1) * 0.5) * var(--scale, 1));
font-family: "Poppins", sans-serif;
font-weight: 600;
line-height: 1;
margin: 1rem 0;
}
*/
/*
function fancyShadow(el) {
let oVal = window.scrollY,
nVal = (oVal / 2.5) * 0.1;
if (oVal >= heroHeight) {
headerBar.classList.add("scrolled");
el.style.textShadow = "0 0 var(--primary-500)";
} else {
headerBar.classList.remove("scrolled");
el.style.textShadow =
16 + -nVal + "px " + (16 + -nVal) + "px var(--primary-500)";
}
}
function parallaxHero(el) {
let oVal, cVal;
oVal = Math.round(window.scrollY / 3);
if (oVal < mVal) {
cVal = oVal;
} else {
cVal = mVal;
}
el.style.transform = "translate3d(0, " + cVal + "px, 0)";
}
function progressScroll(el) {
let dHeight = d.body.clientHeight,
wHeight = window.innerHeight,
scrollPercent = (window.scrollY / (dHeight - wHeight)) * 100;
el.value = scrollPercent.toFixed(2);
}
on(window, "scroll", function (e) {
rAF(parallaxHero(hero));
rAF(fancyShadow(boardTitle));
rAF(progressScroll(scrollProgress));
});
*/
function countBacks() {
//console.log("Counting backlinks");
let posts = $$(".post");
for (let post of posts) {
let backlinks = $$(".backlink", post);
post.setAttribute("data-backlinks-length", backlinks.length);
if (backlinks.length > 8) {
post.parentNode.classList.add("post--hot");
}
}
}
function convertSummaries() {
//console.log("Converting summaries");
let summaries = $$(".summary:not(.summary-bottom, .preview-summary)");
for (let summary of summaries) {
summary.classList.add('summary--converted');
let oldText, newText;
oldText = summary.innerHTML;
newText = oldText.replace(/(\d+(?=\ ))/g, "<b>$1</b>");
summary.innerHTML = newText;
//summary.innerHTML = `<a class="material-symbols-outlined" target="blank" href="` + summary.getAttribute('href') + `">open_in_new</a>` + newText + `<span hidden>` + oldText + `</span>`;
}
}
async function checkSetting(setting) {
let val = await GM.getValue(setting);
return JSON.parse(val).value;
}
async function progressScrollOrNot() {
if (await checkSetting("ss21scrollProgress")) {
doc.classList.add('ss21-scrollprogress--on');
} else {
doc.classList.add('ss21-scrollprogress--off');
}
}
progressScrollOrNot();
function checkers() {
let obs = $$('.thread');
[...obs].forEach((ob) => {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == 'childList') {
convertSummaries()
}
});
});
observer.observe(ob, {childList: true});
})/*
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.removedNodes);
});
});
observer.observe(ob, {childList: true});
}*/
}
if (config === "index") {
on(d, "IndexRefresh", checkers);
}
/*
function watchElForDeletion(elToWatch, callback, parent = document.querySelector('body')){
const observer = new MutationObserver(function (mutations) {
// loop through all mutations
mutations.forEach(function (mutation) {
// check for changes to the child list
if (mutation.type === 'childList') {
// check if anything was removed and if the specific element we were looking for was removed
if (mutation.removedNodes.length > 0 && mutation.removedNodes[0] === elToWatch) {
callback();
}
}
});
});
// start observing the parent - defaults to document body
observer.observe(parent, { childList: true });
};
const target = $(".board");
const config = {
childList: true,
};
function subscriber(mutations) {
convertSummaries();
swapInfo();
disabledPrevAndNext();
}
const observer = new MutationObserver(subscriber);
observer.observe(target, config);
*/
/*
function watchThreadForSummary() {
let threads = $$('.thread');
for (let thread of threads) {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
console.log(mutation.target);
if (mutation.target.classList.contains('summary')) {
let summary = mutation.target;
console.log(summary);
//let oldText, newText;
//oldText = summary.innerHTML;
//newText = oldText.replace(/(\d+(?=\ ))/g, "<b>$1</b>");
//summary.innerHTML = `<a class="material-symbols-outlined" target="blank" href="` + summary.getAttribute('href') + `">open_in_new</a>` + newText + `<span hidden>` + oldText + `</span>`;
//summary.innerHTML = `<a class="material-symbols-outlined" target="blank" href="">open_in_new</a>` + newText + `<span hidden>` + oldText + `</span>`;
}
}
});
});
observer.observe(thread, {childList:true});
}
}
*/
/*
function getSumms() {
console.log('RUNNING GETSUMMS');
ready('.summary:not(.summary-bottom)', (element) => {
let summary = element;
let oldText, newText;
oldText = summary.innerHTML;
newText = oldText.replace(/(\d+(?=\ ))/g, "<b>$1</b>");
console.log('old: ' + oldText + ', new: ' + newText);
summary.innerHTML = `<a class="material-symbols-outlined" target="blank" href="` + summary.getAttribute('href') + `">open_in_new</a>` + newText + `<span hidden>` + oldText + `</span>`;
});
convertSummaries();
}
*/
//getSumms();
function swapInfo() {
//console.log("Switching OP's post info");
let ops = $$(".op");
for (let op of ops) {
let opPostInfo = $(".postInfo", op);
op.prepend(opPostInfo);
op.classList.add("post--file-swapped");
}
}
function stripPageBrackets() {
//console.log("Switching OP's post info");
let pagenums = $$(".page-num:not(.page-num--converted)");
for (let pagenum of pagenums) {
let oldText, newText;
oldText = pagenum.innerText;
newText = oldText.match(/\d+/)[0];
pagenum.innerHTML = `<span class="page-num--icon"><span class="page-num--number">${newText}</span></span>`;
pagenum.classList.add('page-num--converted');
}
}
// if a thumbnail has a tall aspect ratio, allow for greater styling control
function checkHeights() {
let thumbs = $$(".fileThumb");
for (let thumb of thumbs) {
let thumbSize = $("img", thumb);
let thumbHeight = thumbSize.style.height;
let thumbWidth = thumbSize.style.width;
if (thumbHeight.slice(0, -2) > thumbWidth.slice(0, -2)) {
// adds it to the `.thread` container
thumb.parentNode.parentNode.parentNode.parentNode.classList.add("file--tall");
}
}
}
function checkAspect() {
// https://stackoverflow.com/a/61544600
let ERROR_ALLOWED = 0.05
let STANDARD_ASPECT_RATIOS = [
[1, '1'],
[4/3, '43'],
[5/4, '54'],
[3/2, '32'],
[16/10, '1610'],
[16/9, '169'],
[21/9, '219'],
[32/9, '329'],
]
let RATIOS = STANDARD_ASPECT_RATIOS.map(function(tpl){return tpl[0]}).sort()
let LOOKUP = Object()
for (let i=0; i < STANDARD_ASPECT_RATIOS.length; i++){
LOOKUP[STANDARD_ASPECT_RATIOS[i][0]] = STANDARD_ASPECT_RATIOS[i][1]
}
/*
Find the closest value in a sorted array
*/
function findClosest(arrSorted, value){
var closest = arrSorted[0]
var closestDiff = Math.abs(arrSorted[0] - value)
for (let i=1; i<arrSorted.length; i++){
let diff = Math.abs(arrSorted[i] - value)
if (diff < closestDiff){
closestDiff = diff
closest = arrSorted[i]
} else {
return closest
}
}
return arrSorted[arrSorted.length-1]
}
/*
Estimate the aspect ratio based on width x height (order doesn't matter)
*/
function estimateAspectRatio(dim1, dim2){
let ratio = Math.max(dim1, dim2) / Math.min(dim1, dim2)
if (ratio in LOOKUP){
return LOOKUP[ratio]
}
// Look by approximation
var closest = findClosest(RATIOS, ratio)
if (Math.abs(closest - ratio) <= ERROR_ALLOWED){
// was: return '~' + LOOKUP[closest]
return LOOKUP[closest]
}
return 'non-standard-ratio' + Math.round(ratio * 100) / 100 + '1'
}
let thumbs = $$(".fileThumb");
for (let thumb of thumbs) {
let thumbSize = $("img", thumb);
let thumbHeight = thumbSize.style.height;
let thumbWidth = thumbSize.style.width;
let NthumbHeight = thumbHeight.slice(0, -2);
let NthumbWidth = thumbWidth.slice(0, -2);
thumb.parentNode.parentNode.parentNode.parentNode.setAttribute("data-aspect-ratio", estimateAspectRatio(NthumbWidth, NthumbHeight));
}
}
function countThreads() {
let delform = $('.board');
let threads = $$('.thread');
delform.setAttribute('data-thread-count', threads.length);
}
/*
function disabledPrevAndNext() {
let prevBut = document.querySelector('.pagelist .prev button');
if (prevBut.disabled) {
document.querySelector('.pagelist .prev').dataset.clickable = 'false';
} else {
document.querySelector('.pagelist .prev').dataset.clickable = 'true';
}
let nextBut = document.querySelector('.pagelist .next button');
if (nextBut.disabled) {
document.querySelector('.pagelist .next').dataset.clickable = 'false';
} else {
document.querySelector('.pagelist .next').dataset.clickable = 'true';
}
}
*/
if (config === "index") {
const target = $(".board");
const config = {
childList: true,
};
function subscriber(mutations) {
convertSummaries();
swapInfo();
//disabledPrevAndNext();
countThreads();
stripPageBrackets();
//newTabber();
}
const observer = new MutationObserver(subscriber);
observer.observe(target, config);
}
if (config === "index") {
on(d, "IndexRefresh", convertSummaries);
on(d, "IndexRefresh", swapInfo);
on(d, "IndexRefresh", checkHeights);
on(d, "IndexRefresh", checkAspect);
on(d, "IndexRefresh", countThreads);
on(d, "IndexRefresh", stripPageBrackets);
//on(d, "IndexRefresh", newTabber);
}
if (config === "thread") {
countBacks();
swapInfo();
}
// two from https://github.com/duanemoody
// javascript:let p=$$("a.download-button"), i=0, v=setInterval(() => {p[i++].click(); (i>p.length) && clearInterval(v);}, 1000);
// javascript:var pics=document.querySelectorAll("a.download-button"), counter=0, interval=setInterval(function() {pics[counter].click(); counter++; if (counter > pics.length) {clearInterval(interval);}}, 1000);
// https://stackoverflow.com/questions/30088897/trying-to-download-all-of-the-images-on-the-website-using-javascript
// https://gist.github.com/sfrdmn/8834747
// https://gist.github.com/lucidBrot/432d2c6184a188a060e58dbb36bd2084
function downloadMedia() {
ready('#shortcuts', (element) => {
let _this = element;
make({
el: 'a',
cl4ss: 'material-icons shortcut ss21--download-all',
attr: {
title: 'Download all media in thread'
},
prepend: _this,
html: `download_for_offline`
});
});
let imgToggle = $('.ss21--download-all');
imgToggle.addEventListener('click', function() {
let allMedia = [].slice.call($$('.download-button'));
let i = 0;
try {
allMedia.forEach(function(media) {
downloadThem(media, i++);
})
} catch(e) {
console.log('Something went wrong...', e);
}
function downloadThem(media) {
setTimeout(() => {
media.click();
}, i * 500)
}
});
}
downloadMedia();
/*
function addTransition() {
ready('#fourchanx-settings', (element) => {
//console.log('hey im here');
let _this = element;
//function $(sel, root) {
//function on(sel, events, cb) {
//el.classList.add("lol");
//el.addEventListener("transitionend", function () {
//return el.remove();
//},true)
let close = $('.close', _this);
console.log(close);
close.addEventListener('click', function(e) {
console.log('closing it');
e.preventDefault();
//d.addEventListener("animationend", function () {
// _this.classList.add('active');
// _this.parentNode.remove();
//}, true);
}, { passive: false });
on(close, 'click', (e) => {
e.preventDefault();
_this.addEventListener("transitionend", function () {
_this.parentNode.remove();
}, true);
});
//});
}
on(d, "OpenSettings", function () {
addTransition();
});
*/
function addTransition() {
ready('#fourchanx-settings', (element) => {
let _this = element;
_this.style.viewTransitionName = 'settings';
function handleClick(event) {
console.log('Button clicked!');
}
_this.querySelector('.close').removeEventListener('click', handleClick);
});
}
on(d, "OpenSettings", function () {
d.startViewTransition(() => addTransition());
});
function addSettings() {
ready('#fourchanx-settings', (element) => {
let _this = element;
let tabs = $('.sections-list');
let sections = $('.section-container section');
let ss21Tab = make({
el: 'a',
cl4ss: 'tab-ss21',
attr: {
href: 'javascript:;'
},
appendTo: tabs
});
ss21Tab.textContent = 'ss21';
let ss21Section = `<fieldset><legend>ss21</legend>`;
for (let setting in ss21Settings) {
/*
let getVal = async () => {
let val = await get(`ss21${setting}`);
return val;
};
console.log(getVal);
get(`ss21${setting}`)
.then((response) => response);
ss21Section += `<div class="ss21-option">` +
get(`ss21${setting}`)
.then((response) => response) +
`</div>`;
*/
/*
const printAddress = async () => {
const a = await address;
console.log(a);
};
printAddress();
*//*
let getVal = async () => {
let val = await get(`ss21${setting}`);
};
console.log(getVal());
console.log(`ss21${setting} is ${getVal()}`);
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// below is original
*/
//let valy = true;
/*
let val2 = (async () => {
console.log(await GM.listValues());
console.log(ss21Settings[setting]);
console.log('inside poo', await get(ss21Settings[setting]));
await get(ss21Settings[setting]).then((value) => {
console.log('then: ', value);
});
})();
//valy = poo();
console.log('val2: ', val2);
get(ss21Settings[setting]).then((loo) => {
console.log('loo: ', loo);
});
*/
//(async => valy = get(ss21Settings[setting]))();
//console.log(valy);
(async () => {
let valy = await GM.getValue('ss21' + setting);
valy = JSON.parse(valy).value;
//console.log(setting, JSON.parse(valy).value);
ss21Section += `<div class="ss21-option">
<input type="checkbox" id="ss21-option--${setting}" ${valy ? "checked" : ""} data-settingname="ss21${setting}" data-val="${valy}">
<label class="ss21-label" for="ss21-option--${setting}">${ss21Settings[setting].name}</label>
<span class="ss21-description">${ss21Settings[setting].desc}</span>
</div>`;
})();
/*
ss21Section += `<div class="ss21-option">
<input type="checkbox" id="ss21-option--${setting}" ${valy ? "checked" : ""} data-settingname="ss21${setting}" data-val="${valy}">
<label class="ss21-label" for="ss21-option--${setting}">${ss21Settings[setting].name}</label>
<span class="ss21-description">${ss21Settings[setting].desc}</span>
</div>`;
*/
}
ss21Section += `</fieldset>`;
on(ss21Tab, 'click', function() {
let tabLinks = $$('.sections-list a');
for (let tab of tabLinks) {
tab.classList.remove('tab-selected');
}
ss21Tab.classList.add('tab-selected');
sections.className = '';
sections.classList.add('section-ss21');
sections.innerHTML = ss21Section;
});
ready('.section-ss21', (element) => {
let _this = element;
let checkboxes = $$('.ss21-option input');
for (let checkbox of checkboxes) {
checkbox.addEventListener('click', async function(e) {
//console.log(checkbox.checked);//, JSON.parse(checkbox.getAttribute('data-val').toLowerCase()), !checkbox.getAttribute('data-val'));
let setting = checkbox.getAttribute('data-settingname');
let checkSetting = checkbox.checked;
let key = await GM.getValue(setting);
//console.log(key);
let keyParse = JSON.parse(key);
//console.log('parse: ', keyParse);
keyParse.value = checkSetting;
keyParse = JSON.stringify(keyParse);
checkbox.toggleAttribute('checked');
checkbox.setAttribute('data-val', checkSetting);
//console.log(`setting ${setting} to ${checkSetting}`);
await GM.setValue(setting, keyParse);
}, false);
}
});
});
}
//on(d, "OpenSettings", addSettings);
function boardDrawer() {
let boardDrawer = make({
el: "aside",
cl4ss: "ss21--board-drawer-background",
appendTo: "body",
html: `<nav class="ss21--board-drawer"></nav>`,
});
ready("#board-list", (element) => {
let _this = element;
make({
el: "a",
cl4ss: "material-icons ss21--board-drawer-toggle",
prepend: headerBar,
attr: {
title: "Open board list drawer",
},
html: `menu`,
});
});
let boardNavToggle = $(".ss21--board-drawer-toggle");
let url = "https://a.4cdn.org/boards.json";
function createNode(element) {
return d.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
boardDrawer.addEventListener("click", function (e) {
if (e.target === boardDrawer) {
boardDrawer.classList.remove("drawer-open");
}
});
on(boardNavToggle, "click", function () {
boardDrawer.classList.add("drawer-open");
fetch(url)
.then((resp) => resp.json())
.then(function (data) {
let boards = data.boards;
return boards.map(function (board) {
let anchor = createNode("a");
anchor.classList.add("board-list-entry");
anchor.textContent = `/${board.board}/ - ${board.title}`;
if (board.ws_board === 0) {
anchor.classList.add("board--nws");
anchor.href = `https://boards.4chan.org/${board.board}/`;
} else {
anchor.classList.add("board--ws");
anchor.href = `https://boards.4chan.org/${board.board}/`;
}
append($(".ss21--board-drawer"), anchor);
});
});
});
}
boardDrawer();
/*
function getBoardInfo() {
let cbBoard, cbTitle, cbMetad;
fetch("https://a.4cdn.org/boards.json")
.then(resp => resp.json())
.then(data => {
let foundBoard = data.boards.find(board => board.board === currentBoard);
cbBoard = foundBoard.board;
cbTitle = foundBoard.title;
cbMetad = foundBoard.meta_description.replace(/"/g, '"').replace(/&/g, '&');
});
}
getBoardInfo();
*/
function changeFileName(observer) {
// Temporarily disconnect the observer to avoid a loop
if (observer) observer.disconnect();
$('#qr-file-button').value = 'upload';
$('#file-n-submit input[type="submit"]').value = 'send';
// Reconnect the observer after the change with inline config
if (observer) {
observer.observe($('#qr'), {
attributes: true,// Watch for attribute changes
attributeFilter: ['value'], // Only watch the 'value' attribute
subtree: true,// Monitor changes within child elements of #qr
});
}
}
on(d, 'QRDialogCreation', function() {
const captchaContainer = document.querySelector(".captcha-root");
let tBgObserver = null;
const observeTBgStyle = (tBg) => {
// Disconnect any existing observer to avoid duplicate listeners
if (tBgObserver) {
tBgObserver.disconnect();
tBgObserver = null;
}
// If tBg exists, observe its style attribute
if (tBg) {
tBgObserver = new MutationObserver(() => {
const bgImage = window.getComputedStyle(tBg).backgroundImage;
if (bgImage && bgImage !== "none") {
captchaContainer.classList.add("captcha-loaded");
} else {
captchaContainer.classList.remove("captcha-loaded");
}
});
tBgObserver.observe(tBg, {
attributes: true,
attributeFilter: ["style"], // Only watch the style attribute
});
// Run the check immediately to handle cases where the background-image is already set
const bgImage = window.getComputedStyle(tBg).backgroundImage;
if (bgImage && bgImage !== "none") {
captchaContainer.classList.add("captcha-loaded");
} else {