forked from aclist/kbin-kes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkes.user.js
1452 lines (1354 loc) · 60.9 KB
/
kes.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 KES
// @namespace https://github.com/aclist
// @license MIT
// @version PAM
// @description Kbin Enhancement Suite
// @author aclist
// @match https://kbin.social/*
// @match https://kbin.run/*
// @match https://lab2.kbin.pub/*
// @match https://lab3.kbin.pub/*
// @match https://fedia.io/*
// @match https://karab.in/*
// @match https://kbin.cafe/*
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_xmlhttpRequest
// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_getResourceText
// @grant GM_setClipboard
// @grant GM.addStyle
// @grant GM.xmlHttpRequest
// @grant GM.info
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.setClipboard
// @icon https://kbin.social/favicon.svg
// @connect raw.githubusercontent.com
// @connect github.com
// @require https://raw.githubusercontent.com//kbin-kes/tests/helpers/safegm.user.js
// @require https://raw.githubusercontent.com//kbin-kes/tests/helpers/kbin-mod-options.js
// @require https://raw.githubusercontent.com//kbin-kes/tests/helpers/funcs.js
// @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @resource kes_layout https://raw.githubusercontent.com//kbin-kes/tests/helpers/ui.json
// @resource kes_json https://raw.githubusercontent.com//kbin-kes/tests/helpers/manifest.json
// @resource kes_css https://raw.githubusercontent.com//kbin-kes/tests/helpers/kes.css
// @downloadURL https://raw.githubusercontent.com//kbin-kes/tests/kes.user.js
// @updateURL https://raw.githubusercontent.com//kbin-kes/tests/kes.user.js
// ==/UserScript==
//START AUTO MASTHEAD
const version = safeGM("info").script.version;
const tool = safeGM("info").script.name;
const repositoryURL = "https://github.com//kbin-kes/";
const rawURL = "https://raw.githubusercontent.com/aclist/kbin-kes/"
const branch = "tests"
const helpersPath = "helpers/"
const branchPath = rawURL + branch + "/"
const versionFile = branchPath + "VERSION";
const updateURL = branchPath + "kes.user.js";
const bugURL = repositoryURL + "issues"
const sponsorURL = "https://github.com/sponsors/aclist"
const changelogURL = repositoryURL + "blob/" + branch + "/CHANGELOG.md"
const magURL = "https://kbin.social/m/enhancement"
//resource URLs used by legacy GM. API
const manifest = branchPath + helpersPath + "manifest.json"
const cssURL = branchPath + helpersPath + "kes.css"
const layoutURL = branchPath + helpersPath + "ui.json"
//END AUTO MASTHEAD
async function checkUpdates (response) {
const newVersion = await response.responseText.trim();
if (newVersion && newVersion != version) {
// Change version link into a button for updating
versionElement.innerText = 'Install update: ' + newVersion;
versionElement.setAttribute('href', updateURL);
versionElement.className = 'new';
await safeGM("setValue", "isnew", "yes");
} else {
await safeGM("setValue", "isnew", "no");
}
preparePayloads();
}
async function makeArr (response) {
const resp = await response.response;
await safeGM("setValue", "json", resp);
}
async function setRemoteCSS (response) {
const resp = await response.responseText.trim();
await safeGM("setValue", "kes-css", resp)
}
async function setRemoteUI (response) {
const resp = await response.response;
await safeGM("setValue", "layout", resp)
await safeGM("getValue", "json")
}
async function preparePayloads () {
let json
let css
let kes_layout
let isNew
if (gmPrefix === "GM_") {
json = safeGM("getResourceText", "kes_json");
css = safeGM("getResourceText", "kes_css");
kes_layout = safeGM("getResourceText", "kes_layout");
isNew = safeGM("getValue", "isnew")
validateData(css, json, kes_layout, isNew)
} else {
genericXMLRequest(layoutURL, setRemoteUI);
genericXMLRequest(manifest, makeArr);
genericXMLRequest(cssURL, setRemoteCSS);
unwrapPayloads()
}
}
async function unwrapPayloads () {
const storedJSON = safeGM("getValue", "json")
const storedCSS = safeGM("getValue", "kes-css")
const storedUI = safeGM("getValue", "layout")
const storedNew = safeGM("getValue", "isnew")
let payload = Promise.all([storedCSS, storedJSON, storedUI, storedNew]);
payload.then((items) => {
let p0 = items[0]
let p1 = items[1]
let p2 = items[2]
let p3 = items[3]
validateData(p0, p1, p2, p3)
});
}
function validateData (rawCSS, rawJSON, rawLayout, isNew) {
if (![rawCSS, rawJSON, rawLayout].every(Boolean)) {
//if any of the remote resources are missing, block execution of the
//rest of the script and print warning header; style data must be hardcoded here
//as an emergency logic
const warning = document.createElement('p')
warning.style.cssText = "top:0;left:0;position:absolute;z-index: 9999;text-align: center;color: white;" +
"font-size: 12px; height: 20px;background-color:#5e0909;width: 100%";
warning.innerText = "[kbin Enhancement Suite] Failed to fetch the remote resources. Reload or try again later."
document.body.insertAdjacentHTML("beforebegin", warning.outerHTML);
} else {
safeGM("addStyle", rawCSS);
const j = JSON.parse(rawJSON);
const json = j.sort( function ( a, b ) {
a = a.label.toLowerCase();
b = b.label.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
});
const layoutArr = JSON.parse(rawLayout);
constructMenu(json, layoutArr, isNew);
}
}
function constructMenu (json, layoutArr, isNew) {
//instantiate kes modal and button
const sidebarPages = layoutArr.pages;
const headerTitle = layoutArr.header.title;
function injectSettingsButton (layoutArr, isNew) {
if (document.querySelector('#kes-settings')) {
return
}
let kbinContainer
if (window.innerWidth > 576) {
kbinContainer = document.querySelector('.kbin-container > menu');
} else {
kbinContainer = document.querySelector('.sidebar-options > .section > menu > ul')
}
const kesPanel = document.createElement('li');
kesPanel.id = 'kes-settings';
kesPanel.title = layoutArr.header.open.tooltip;
kbinContainer.appendChild(kesPanel);
const wrenchOuter = document.createElement('a')
const settingsButton = document.createElement('i');
wrenchOuter.appendChild(settingsButton)
settingsButton.id = 'kes-settings-button';
settingsButton.classList = layoutArr.header.open.icon;
settingsButton.style.verticalAlign = 'middle';
if (isNew === "yes") {
const stackSpan = document.createElement('span');
stackSpan.classList = 'kes-update';
let stackStrong = document.createElement('i');
stackStrong.classList = 'fa-solid fa-circle-up fa-sm kes-update-available';
stackSpan.appendChild(stackStrong);
settingsButton.appendChild(stackSpan);
}
kesPanel.addEventListener('click', () => {
showSettingsModal();
});
kesPanel.appendChild(wrenchOuter);
return kesPanel
}
injectSettingsButton(layoutArr, isNew)
var keyPressed = {};
document.addEventListener('keydown', function (e) {
let modal = document.querySelector('.kes-settings-modal')
keyPressed[e.key] = true;
if (keyPressed.Shift == true && keyPressed.Control == true && keyPressed["?"] == true) {
e.preventDefault();
if (!modal) {
showSettingsModal();
} else {
modal.remove();
}
keyPressed = {};
}
if (keyPressed.Escape == true) {
if (modal) {
modal.remove();
}
keyPressed = {};
}
}, false);
document.addEventListener('keyup', function (e) {
keyPressed[e.key + e.location] = false;
keyPressed = {};
}, false);
function cleanNamespaces () {
const kesSettings = "kes-settings"
for (let i = 0; i < json.length; ++i) {
let foundNs = json[i].namespace;
if (foundNs) {
localStorage.removeItem(foundNs);
}
}
localStorage.removeItem(kesSettings);
}
function resetAll () {
const deleteMsg = "This will delete and reset all KES settings to the default and toggle off all options. Really proceed?";
const deleteConfirm = confirm(deleteMsg);
if (deleteConfirm) {
cleanNamespaces();
window.location.reload();
}
}
function transparentMode (modal) {
modal.remove();
const transparentModal = document.createElement("div");
transparentModal.className = "kes-transparent-mode-modal";
document.body.appendChild(transparentModal);
transparentModal.addEventListener('click', ()=> {
transparentModal.remove();
showSettingsModal();
});
}
function activeModCount () {
const set = JSON.parse(localStorage["kes-settings"])
const totalMods = Object.keys(funcObj).length
let activeMods = 0
let c
let key
for (key in set) {
c = set[key]
if (c === true) {
++activeMods
}
}
let modsHR = " (" + activeMods + "/" + totalMods + ")"
return modsHR
}
function getComputedFontSize (string) {
if (typeof string === 'number') return string
if (isNaN(parseFloat(string)) === false) {
return parseFloat(string)
}
const el = document.querySelector(string)
if (!el) {
return null
}
const fontsize = document.defaultView.getComputedStyle(el).fontSize
let px = fontsize.split('px')[0]
px = parseFloat(px)
return px
}
function showSettingsModal () {
const settings = getSettings();
const modal = document.createElement("div");
modal.className = "kes-settings-modal";
const modalContent = document.createElement("div");
modalContent.className = "kes-settings-modal-content";
const header = document.createElement("div");
header.className = "kes-settings-modal-header";
const crumbs = document.createElement("div");
crumbs.className = 'kes-crumbs';
crumbs.innerText = 'Settings'
const headerCloseButton = document.createElement('span')
headerCloseButton.className = 'kes-close'
const headerCloseIcon = document.createElement('i');
headerCloseIcon.className = layoutArr.header.close.icon;
headerCloseIcon.title = layoutArr.header.close.tooltip;
headerCloseButton.appendChild(headerCloseIcon);
const headerDockButton = document.createElement('span')
headerDockButton.className = 'kes-dock'
const headerDockIcon = document.createElement('i')
headerDockIcon.className = layoutArr.header.dock_down.icon;
headerDockIcon.title = layoutArr.header.dock_down.tooltip;
headerDockButton.appendChild(headerDockIcon)
const headerEyeButton = document.createElement('span')
headerEyeButton.className = 'kes-transparent-mode'
const headerEyeIcon = document.createElement('i')
headerEyeIcon.className = layoutArr.header.transparent.icon
headerEyeIcon.title = layoutArr.header.transparent.tooltip
headerEyeButton.appendChild(headerEyeIcon)
const headerChangelogButton = document.createElement('span')
headerChangelogButton.className = 'kes-changelog'
const headerChangelogIcon = document.createElement('i')
const headerChangelogLink = document.createElement('a')
headerChangelogLink.href = changelogURL
headerChangelogLink.setAttribute('target', '_blank')
headerChangelogLink.appendChild(headerChangelogIcon)
headerChangelogIcon.className = layoutArr.header.changelog.icon
headerChangelogIcon.title = layoutArr.header.changelog.tooltip
headerChangelogButton.appendChild(headerChangelogLink)
const headerSearchButton = document.createElement('span')
headerSearchButton.className = 'kes-changelog'
const headerSearchIcon = document.createElement('i')
headerSearchIcon.className = layoutArr.header.search.icon
headerSearchIcon.title = layoutArr.header.search.tooltip
headerSearchButton.appendChild(headerSearchIcon)
headerSearchButton.addEventListener('click', () => {
const searchDialog = document.querySelector('#kes-search-dialog');
searchDialog.showModal();
document.querySelector('.kes-search-field').focus();
});
const headerVersionButton = document.createElement('span');
headerVersionButton.className = 'kes-version'
headerVersionButton.appendChild(versionElement);
const headerHr = document.createElement('hr');
headerHr.className = 'kes-header-hr'
header.appendChild(headerCloseButton)
header.appendChild(headerDockButton)
header.appendChild(headerEyeButton)
header.appendChild(headerChangelogButton)
header.appendChild(headerSearchButton)
if (window.innerWidth > 576) {
header.appendChild(headerVersionButton);
header.appendChild(crumbs)
header.appendChild(headerHr);
} else {
header.appendChild(crumbs)
header.appendChild(headerHr);
header.appendChild(headerVersionButton);
}
const sidebar = document.createElement("div");
sidebar.className = "kes-settings-modal-sidebar";
let sidebarUl = document.createElement('ul');
for (let i = 0; i < sidebarPages.length; ++i) {
let pageUpper = sidebarPages[i].charAt(0).toUpperCase() + sidebarPages[i].slice(1);
let sidebarListItem = document.createElement('li');
sidebarListItem.innerHTML = `
<a class="kes-tab-link">` + pageUpper + `</a></li>`
sidebarUl.appendChild(sidebarListItem);
}
sidebar.appendChild(sidebarUl);
function kesFormatAuthorUrl (author) {
if (author.includes('@')) {
if (window.location.hostname === author.split('@')[2]) {
return 'https://' + window.location.hostname + '/u/' + author.split('@')[1];
} else {
return 'https://' + window.location.hostname + '/u/' + author;
}
} else {
if (window.location.hostname === 'kbin.social') {
return 'https://' + window.location.hostname + '/u/' + author;
} else {
return 'https://' + window.location.hostname + '/u/@' + author + '@kbin.social';
}
}
}
function openHelpBox (it) {
const settings = getSettings();
settings.lastPage = it;
saveSettings(settings);
const modInfo = document.createElement('p');
const authorP = document.createElement('p');
if (Array.isArray(json[it].author)) {
const authorLabel = document.createElement('span');
authorLabel.style.fontWeight = 'bold';
authorLabel.innerText = 'Authors: ';
authorP.appendChild(authorLabel);
json[it].author.forEach((modAuthor) => {
const authorA = document.createElement('a');
authorA.setAttribute('href', kesFormatAuthorUrl(modAuthor));
if (modAuthor.includes('@')) {
authorA.innerText = modAuthor.split('@')[1];
} else {
authorA.innerText = modAuthor;
}
authorP.appendChild(authorA);
if (typeof(json[it].author[json[it].author.indexOf(modAuthor) + 1]) !== 'undefined') {
authorP.innerHTML += ', ';
}
});
} else {
const authorLabel = document.createElement('span');
authorLabel.style.fontWeight = 'bold';
authorLabel.innerText = 'Author: ';
authorP.appendChild(authorLabel);
let author = json[it].author;
const authorA = document.createElement('a');
authorA.setAttribute('href', kesFormatAuthorUrl(author));
if (author.includes('@')) {
authorA.innerText = author.split('@')[1];
} else {
authorA.innerText = author;
}
authorP.appendChild(authorA);
}
let desc = json[it].desc;
let link = json[it].link;
let linkLabel = json[it].link_label;
let login = json[it].login;
let loginHR;
if (login) {
loginHR = "yes";
} else {
loginHR = "no";
}
let ns = json[it].namespace;
//populate static fields
let hBox = document.querySelector('.kes-settings-modal-helpbox');
hBox.style.cssText = 'display: inline; opacity: 1;'
const toggleSpan = document.createElement('span');
toggleSpan.classList = 'kes-toggle';
const toggleInput = document.createElement('input');
toggleInput.setAttribute('type', 'checkbox');
toggleInput.classList = 'tgl kes-tgl';
toggleInput.id = 'kes-checkbox';
toggleInput.setAttribute('kes-iter', it);
toggleInput.setAttribute('kes-key', 'state');
toggleSpan.appendChild(toggleInput);
const toggleLabel = document.createElement('label');
toggleLabel.classList = 'tgl-btn';
toggleLabel.setAttribute('for', 'kes-checkbox');
toggleSpan.appendChild(toggleLabel);
modInfo.appendChild(toggleSpan);
modInfo.appendChild(authorP);
if (link) {
const linkSpan = document.createElement('span');
const linkSpanLabel = document.createElement('span');
linkSpanLabel.style.fontWeight = 'bold';
linkSpanLabel.innerText = 'Link: ';
linkSpan.appendChild(linkSpanLabel);
const linkA = document.createElement('a');
linkA.setAttribute('href', link);
if (typeof(linkLabel) !== 'undefined') {
linkA.innerText = linkLabel;
} else {
linkA.innerText = link;
}
linkSpan.appendChild(linkA);
modInfo.appendChild(linkSpan);
modInfo.appendChild(document.createElement('br'));
}
const loginReqSpan = document.createElement('span');
const loginReqSpanLabel = document.createElement('span');
loginReqSpanLabel.style.fontWeight = 'bold';
loginReqSpanLabel.innerText = 'Login required: ';
loginReqSpan.appendChild(loginReqSpanLabel);
loginReqSpan.innerHTML += loginHR;
modInfo.appendChild(loginReqSpan);
modInfo.appendChild(document.createElement('br'));
modInfo.appendChild(document.createElement('br'));
const descLabel = document.createElement('span');
descLabel.style.fontWeight = 'bold';
descLabel.innerText = 'Description';
modInfo.appendChild(descLabel);
modInfo.appendChild(document.createElement('br'));
const descSpan = document.createElement('span');
descSpan.innerText = desc;
modInfo.appendChild(descSpan);
modInfo.appendChild(document.createElement('br'));
hBox.replaceChildren(modInfo);
const br = document.createElement('br');
//populate dynamic fields
if (json[it].fields) {
const settingsLabel = document.createElement('span');
settingsLabel.style.fontWeight = 'bold';
settingsLabel.innerText = 'Settings';
hBox.appendChild(settingsLabel);
const modSettings = getModSettings(ns)
for (let i = 0; i < json[it].fields.length; ++i) {
let fieldType = json[it].fields[i].type;
let initial = json[it].fields[i].initial;
let key = json[it].fields[i].key;
let ns = json[it].namespace;
if (json[it].fields[i].label) {
let label = document.createElement('p');
label.className = "kes-field-label";
label.innerText = json[it].fields[i].label;
hBox.appendChild(label);
}
if (modSettings[key] === undefined) {
modSettings[key] = initial;
saveModSettings(modSettings, ns);
}
switch (fieldType) {
case "range": {
const range = document.createElement('input');
range.setAttribute("type", fieldType);
if (modSettings[key] === undefined) {
range.setAttribute("value", initial);
} else {
range.setAttribute("value", modSettings[key])
}
range.setAttribute("kes-iter", it);
range.setAttribute("kes-key", key);
range.setAttribute('min', json[it].fields[i].min);
range.setAttribute('max', json[it].fields[i].max);
if (json[it].fields[i].step) {
range.setAttribute('step', json[it].fields[i].step);
}
if (json[it].fields[i].show_value) {
//TODO: value should always be visible
const rangeDiv = document.createElement('div');
range.setAttribute('oninput', key + '.innerText = this.value');
range.style.verticalAlign = 'middle';
rangeDiv.appendChild(range);
const rangeValue = document.createElement('label');
rangeValue.setAttribute('style', 'display: inline-block; vertical-align: middle; margin-left: 1em;');
rangeValue.id = key;
rangeValue.for = key;
if (modSettings[key] === undefined) {
rangeValue.innerText = initial;
} else {
rangeValue.innerText = modSettings[key];
}
rangeDiv.appendChild(rangeValue);
hBox.appendChild(rangeDiv);
} else {
hBox.appendChild(range);
}
hBox.appendChild(br);
break;
}
case "reset": {
const resetField = document.createElement('input');
resetField.setAttribute("type",fieldType);
resetField.addEventListener('click', ()=> {
for (let j = 0; j < json[it].catch_reset.length; ++j) {
let fieldToReset = json[it].catch_reset[j];
let resetClassName = `.kes-settings-modal-helpbox input[kes-key="${fieldToReset}"]`
let found = document.querySelector(resetClassName)
let matchKey = found.getAttribute("kes-key")
for (let k = 0 ; k < json[it].fields.length; ++k) {
if(json[it].fields[k].key === matchKey) {
let initial = json[it].fields[k].initial
if (json[it].fields[k].type === "color") {
initial = getHex(initial);
} else if (json[it].fields[k].type === "number") {
initial = getComputedFontSize(initial)
if (!initial) {
initial = 14
}
}
found.setAttribute("value",initial);
found.value = initial;
}
}
updateState(found);
}
});
hBox.appendChild(resetField)
hBox.appendChild(br)
break;
}
case "color": {
const colorField = document.createElement('input');
let realHex
if (modSettings[key] === undefined) {
realHex = getHex(initial);
} else {
realHex = getHex(modSettings[key])
}
colorField.setAttribute("value", realHex);
colorField.setAttribute("type", fieldType);
colorField.setAttribute("kes-iter", it);
colorField.setAttribute("kes-key", key);
//#220: explicit handling for labelOp mod (child inherits 75% opacity of author header)
if (json[it].entrypoint == "labelOp") {
colorField.className = "kes-dimmed-colorpicker";
}
hBox.appendChild(colorField);
hBox.appendChild(br);
break;
}
case "number": {
const numberField = document.createElement('input');
numberField.setAttribute("type", fieldType);
let val
let size
if (modSettings[key] === undefined) {
size = getComputedFontSize(initial)
if (!size) {
val = 14
} else {
val = size
}
} else {
size = getComputedFontSize(modSettings[key])
if (!size) {
val = 14
} else {
val = size
}
}
numberField.setAttribute("value", val)
numberField.setAttribute("kes-iter", it);
numberField.setAttribute("kes-key", key);
numberField.setAttribute('min', json[it].fields[i].min);
numberField.setAttribute('max', json[it].fields[i].max);
if (json[it].fields[i].step) {
numberField.setAttribute('step', json[it].fields[i].step);
}
numberField.addEventListener('change', (e)=> {
let numTarg = e.target
numTarg.setAttribute("value",numTarg.value)
});
hBox.appendChild(numberField);
hBox.appendChild(br);
break;
}
case "select": {
const selectField = document.createElement('select');
selectField.setAttribute('name', ns);
selectField.setAttribute("kes-iter", it);
selectField.setAttribute("kes-key", key);
for (let j = 0; j < json[it].fields[i].values.length; ++j) {
let opt = document.createElement('option');
opt.setAttribute('value', json[it].fields[i].values[j]);
opt.innerText = json[it].fields[i].values[j];
if (modSettings[key] == json[it].fields[i].values[j]) {
opt.selected = 'selected';
} else if (json[it].fields[i].values[j] == json[it].fields[i].initial) {
opt.selected = 'selected'
}
selectField.appendChild(opt);
}
hBox.appendChild(selectField);
hBox.appendChild(br);
break;
}
case "radio": {
const radioDiv = document.createElement('div');
for (let j = 0; j < json[it].fields[i].values.length; ++j) {
const radioField = document.createElement('input');
radioField.setAttribute("type", fieldType);
radioField.setAttribute('name', ns);
radioField.setAttribute('id', "kes-radio-" + j);
radioField.setAttribute("kes-iter", it);
radioField.setAttribute("kes-key", key);
radioField.setAttribute("value", json[it].fields[i].values[j]);
radioField.className = "kes-default-radio";
if (modSettings[key] == json[it].fields[i].values[j]) {
radioField.checked = true;
} else if (json[it].fields[i].values[j] == json[it].fields[i].initial) {
radioField.checked = true;
}
let radioLabel = document.createElement('label');
radioLabel.setAttribute('for', "kes-radio-" + j);
radioLabel.className = ("kes-radio-label");
radioLabel.innerText = json[it].fields[i].values[j];
radioDiv.appendChild(radioField);
radioDiv.appendChild(radioLabel);
let br = document.createElement('br');
radioDiv.appendChild(br);
}
hBox.appendChild(radioDiv);
hBox.appendChild(br);
break;
}
case "checkbox": {
const checkboxLabel = document.createElement('label');
const cfield = document.createElement('input');
cfield.setAttribute("type", fieldType);
if (modSettings[key] === undefined) {
cfield.checked = initial
} else {
cfield.checked = modSettings[key]
}
cfield.setAttribute("kes-iter", it);
cfield.setAttribute("kes-key", key);
cfield.className = "kes-default-checkbox";
checkboxLabel.appendChild(cfield);
let ctext = document.createElement('text')
ctext.innerText = json[it].fields[i].checkbox_label;
checkboxLabel.appendChild(ctext)
hBox.appendChild(checkboxLabel);
break;
}
default: {
const field = document.createElement('input');
field.setAttribute("type", fieldType);
if (modSettings[key] === undefined) {
field.setAttribute("value", initial);
} else {
field.setAttribute("value", modSettings[key])
}
field.setAttribute("kes-iter", it);
field.setAttribute("kes-key", key);
hBox.appendChild(field);
hBox.appendChild(br);
}
}
}
}
// reset opacity of other helpbox toggles
let helpboxToggles = document.querySelectorAll('.kes-option');
for (let i = 0; i < helpboxToggles.length; ++i) {
if (i != it) {
helpboxToggles[i].style.cssText = 'opacity: 0.5;'
} else {
helpboxToggles[i].style.cssText = 'opacity: 1;'
}
}
let func = json[it].entrypoint;
const check = document.querySelector(`.kes-settings-modal-helpbox [kes-iter="` + it + `"]`);
if (settings[func] == true) {
check.checked = true;
} else {
check.checked = false;
}
}
// Add script tag with opentab function
function openTab (tabName) {
const settings = getSettings();
if (settings.lastTab != tabName) {
settings.lastPage = null;
}
settings.lastTab = tabName
saveSettings(settings);
let pageLower = tabName.charAt(0).toLowerCase() + tabName.slice(1);
const tablinks = document.getElementsByClassName("kes-tab-link");
for (let i = 0; i < tablinks.length; i++) {
if (tablinks[i].innerText !== tabName) {
tablinks[i].style.opacity = 0.5;
} else {
tablinks[i].style.opacity = 1;
}
}
//TODO: fails on GM
//event.stopPropagation();
// Hide all options not in this tab (without this classname)
const options = document.getElementsByClassName("kes-list")[0];
const optionsChildren = options.children;
const pageToOpen = []
for (let i = 0; i < optionsChildren.length; i++) {
if (optionsChildren[i].className.indexOf(pageLower) > -1) {
optionsChildren[i].style.display = "block";
pageToOpen.push(i);
} else {
optionsChildren[i].style.display = "none";
let crumbsRoot = document.querySelector('.kes-crumbs');
crumbsRoot.innerHTML = '<h2>' + headerTitle + ' ' +
'<i class="' + layoutArr.header.separator.icon + '"></i> ' +
tabName + '</h2>';
let crumbsChild = crumbsRoot.children[0]
let modCounter = document.createElement('text');
crumbsChild.appendChild(modCounter);
modCounter.className = "kes-mod-count"
}
}
updateCrumbs();
if (pageToOpen.length > 0) {
let lp = settings["lastPage"];
if (lp) {
openHelpBox(lp)
} else {
openHelpBox(pageToOpen[0])
}
} else {
let hBox = document.querySelector('.kes-settings-modal-helpbox');
hBox.style.opacity = 0;
}
}
const bodyHolder = document.createElement("div");
bodyHolder.className = "kes-settings-modal-body";
const kesUl = document.createElement("ul")
kesUl.className = "kes-list";
const helpBox = document.createElement("div");
helpBox.className = "kes-settings-modal-helpbox";
const footer = document.createElement("div");
footer.className = "kes-settings-modal-footer";
const magLink = document.createElement("a");
magLink.className = "kes-settings-modal-magazine";
magLink.innerText = "/m/enhancement";
magLink.setAttribute('href', magURL);
magLink.setAttribute('target', '_blank');
footer.appendChild(magLink)
const backupButton = document.createElement('button');
backupButton.innerText = "SETTINGS";
backupButton.className = "kes-backup-button";
footer.appendChild(backupButton);
backupButton.addEventListener('click', () => {
const backupDialog = document.querySelector('#kes-backup-dialog');
backupDialog.showModal();
});
function parseNamespaces () {
var names = [];
for(let i = 0 ; i < json.length ; ++i) {
if(json[i].namespace) {
names.push(json[i].namespace);
}
}
return names;
}
function parseLocalStorage () {
const names = parseNamespaces();
const toExport = {};
const keys = Object.keys(localStorage);
const values = Object.values(localStorage);
for(let i = 0 ; i < keys.length ; ++i) {
if(keys[i] === "kes-settings" || names.includes(keys[i])) {
let key = keys[i];
let value = JSON.parse(values[i]);
toExport[key] = value;
}
}
return toExport
}
function parseImportedFile (contents) {
const names = parseNamespaces();
const keys = Object.keys(contents);
cleanNamespaces();
for(let i = 0 ; i < keys.length ; ++i) {
if(keys[i] === "kes-settings" || names.includes(keys[i])) {
let namespace = keys[i];
let settings = contents[namespace];
saveModSettings(settings, namespace)
}
}
}
function exportSettings () {
const exportButton = document.createElement('a')
const rawSettings = parseLocalStorage();
const pretty = JSON.stringify(rawSettings,null,2);
const textBlob = new Blob([pretty], { type: 'application/json' });
const saveDate = new Date().toLocaleString('sv').replace(' ','-').replaceAll(':','')
const filename = `KES-backup-${saveDate}.json`
exportButton.setAttribute('href',URL.createObjectURL(textBlob));
exportButton.setAttribute('download', filename);
exportButton.style = 'display:none';
document.body.appendChild(exportButton);
exportButton.click();
alert(`Saved KES settings to ${filename}`)
}
function fileImportError () {
alert('File import error. The file may be corrupted. If you believe the file is correct, please attach it alongside a bug report.')
}
const dialogTrigger = document.createElement('input')
footer.appendChild(dialogTrigger)
dialogTrigger.id = 'kes-import-dialog'
dialogTrigger.style = 'display: none'
dialogTrigger.type = 'file';
dialogTrigger.addEventListener('change', (e) => {
const reader = new FileReader();
reader.readAsText(e.target.files[0]);
reader.onerror = function () {
fileImportError();
};
reader.onload = function () {
try {
let payload = JSON.parse(reader.result)
parseImportedFile(payload)
window.location.reload();
} catch (e) {
fileImportError();
}
};
});
const resultsNativeModal = document.createElement('dialog');
resultsNativeModal.id = 'kes-results-dialog';
resultsNativeModal.innerHTML = `
<form method="dialog">
</form>
`
const searchNativeModal = document.createElement('dialog');
searchNativeModal.id = 'kes-search-dialog';
searchNativeModal.innerHTML = `
<form method="dialog">
<menu class="kes-search-menu">
<input class="kes-search-hidden" type="submit" value="submit" hidden>
<button class="kes-search-new" type="submit" value="list-new">Show add-ons new to v${getMajorMinor(version)}</button>
<input type="text" class="kes-search-field">
<span class="kes-search-text">Type enter to submit search</span>
<button class="kes-search-closebutton" type="submit" value="close">Close</button>
</menu>
</form>
`
const nativeModal = document.createElement('dialog');
nativeModal.id = 'kes-backup-dialog';
nativeModal.innerHTML = `
<form method="dialog">
<menu class="kes-backup-menu">
<button type="submit" value="export">Export</button>Export to file<br>
<button type="submit" value="import">Import</button>Import from file<br>
<button type="submit" value="reset">Reset</button>Reset all KES settings<br>
<button type="submit" value="close">Close</button>Close this dialog
</menu>
</form>
`
nativeModal.addEventListener('close', () => {
let upload
const dialog = document.querySelector('#kes-backup-dialog');
switch (dialog.returnValue) {
case "import":
upload = document.getElementById("kes-import-dialog");
upload.click();
break;
case "export":
exportSettings();
break;
case "reset":
resetAll();
break;
case "close":
break;
}
});
resultsNativeModal.addEventListener('close', () => {
const dialog = document.querySelector('#kes-results-dialog');
const ret = dialog.returnValue
if (ret === "close") {
return
}
let page = ret.split('@')[0]
const helpString = ret.split('@')[1]
const pageCaps = page.charAt(0).toUpperCase() + page.slice(1);
openTab(pageCaps);
const opts = document.querySelectorAll('.kes-option');
opts.forEach((opt)=>{
if (opt.innerHTML.trim() === helpString) {
const ind = opt.getAttribute("kes-iter");
openHelpBox(ind);
return
}
});
});
function getMajorMinor (version) {
const d = version.split('.')
const major = d[0]
const minor = d[1]
return `${major}.${minor}`
}
function generateSearchResults (resultsMenu, record, label) {
const page = record.page
const br = document.createElement('br')
const r = document.createElement('button')
r.type = "submit";
r.className = "kes-results-fullbutton";
r.value = page + "@" + label;
r.innerText = label;
resultsMenu.appendChild(r);