-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
skribbltypo.user.js
9376 lines (8571 loc) · 508 KB
/
skribbltypo.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 skribbltypo
// @website https://www.typo.rip
// @author tobeh#7437
// @description Userscript version of skribbltypo - the most advanced toolbox for skribbl.io
// @icon64 https://rawcdn.githack.com/toobeeh/skribbltypo/master/res/icon/128MaxFit.png
// @version 26.3.11.173080256
// @updateURL https://raw.githubusercontent.com/toobeeh/skribbltypo/master/skribbltypo.user.js
// @grant none
// @match https://skribbl.io/*
// @run-at document-start
// ==/UserScript==
/* polyfill */
const chrome = {
extension: {
getURL: (url) => {
return "https://rawcdn.githack.com/toobeeh/skribbltypo/master/" + url;
}
},
runtime: {
getURL: (url) => {
return "https://rawcdn.githack.com/toobeeh/skribbltypo/master/" + url;
},
getManifest: () => {
return {version: "26.3.11 usrsc"};
},
onMessage: {
addListener: (callback) => {
window.addEventListener("message",msg => {
if(msg.origin.includes("//skribbl.io")) callback(msg.data, {tab:{id:0}});
});
}
},
sendMessage: undefined
}
}
/* async typo setup for same-context of differently timed executions */
const execTypo = async () => {
/* dom content load promise */
const loaded = new Promise((resolve, reject) => {
document.addEventListener("DOMContentLoaded", () => {
setTimeout(() =>resolve(), 2000);
});
setTimeout(() =>resolve(), 2000);
});
/* wait until dom loaded */
/* await loaded; */
console.clear();
/* bundle pre dom exec */
// #content picker/colr_pickr.min.js
/*! Pickr 1.8.1 MIT | https://github.com/Simonwep/pickr */
!function (t, e) { "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.Pickr = e() : t.Pickr = e() }(window, (function () {
return function (t) { var e = {}; function o(n) { if (e[n]) return e[n].exports; var i = e[n] = { i: n, l: !1, exports: {} }; return t[n].call(i.exports, i, i.exports, o), i.l = !0, i.exports } return o.m = t, o.c = e, o.d = function (t, e, n) { o.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: n }) }, o.r = function (t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, o.t = function (t, e) { if (1 & e && (t = o(t)), 8 & e) return t; if (4 & e && "object" == typeof t && t && t.__esModule) return t; var n = Object.create(null); if (o.r(n), Object.defineProperty(n, "default", { enumerable: !0, value: t }), 2 & e && "string" != typeof t) for (var i in t) o.d(n, i, function (e) { return t[e] }.bind(null, i)); return n }, o.n = function (t) { var e = t && t.__esModule ? function () { return t.default } : function () { return t }; return o.d(e, "a", e), e }, o.o = function (t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, o.p = "", o(o.s = 0) }([function (t, e, o) {
"use strict"; o.r(e); var n = {}; function i(t, e, o, n, i = {}) { e instanceof HTMLCollection || e instanceof NodeList ? e = Array.from(e) : Array.isArray(e) || (e = [e]), Array.isArray(o) || (o = [o]); for (const r of e) for (const e of o) r[t](e, n, { capture: !1, ...i }); return Array.prototype.slice.call(arguments, 1) } o.r(n), o.d(n, "on", (function () { return r })), o.d(n, "off", (function () { return s })), o.d(n, "createElementFromString", (function () { return a })), o.d(n, "createFromTemplate", (function () { return l })), o.d(n, "eventPath", (function () { return c })), o.d(n, "resolveElement", (function () { return p })), o.d(n, "adjustableInputNumbers", (function () { return u })); const r = i.bind(null, "addEventListener"), s = i.bind(null, "removeEventListener"); function a(t) { const e = document.createElement("div"); return e.innerHTML = t.trim(), e.firstElementChild } function l(t) { const e = (t, e) => { const o = t.getAttribute(e); return t.removeAttribute(e), o }, o = (t, n = {}) => { const i = e(t, ":obj"), r = e(t, ":ref"), s = i ? n[i] = {} : n; r && (n[r] = t); for (const n of Array.from(t.children)) { const t = e(n, ":arr"), i = o(n, t ? {} : s); t && (s[t] || (s[t] = [])).push(Object.keys(i).length ? i : n) } return n }; return o(a(t)) } function c(t) { let e = t.path || t.composedPath && t.composedPath(); if (e) return e; let o = t.target.parentElement; for (e = [t.target, o]; o = o.parentElement;)e.push(o); return e.push(document, window), e } function p(t) { return t instanceof Element ? t : "string" == typeof t ? t.split(/>>/g).reduce((t, e, o, n) => (t = t.querySelector(e), o < n.length - 1 ? t.shadowRoot : t), document) : null } function u(t, e = (t => t)) { function o(o) { const n = [.001, .01, .1][Number(o.shiftKey || 2 * o.ctrlKey)] * (o.deltaY < 0 ? 1 : -1); let i = 0, r = t.selectionStart; t.value = t.value.replace(/[\d.]+/g, (t, o) => o <= r && o + t.length >= r ? (r = o, e(Number(t), n, i)) : (i++, t)), t.focus(), t.setSelectionRange(r, r), o.preventDefault(), t.dispatchEvent(new Event("input")) } r(t, "focus", () => r(window, "wheel", o, { passive: !1 })), r(t, "blur", () => s(window, "wheel", o)) } const { min: h, max: d, floor: f, round: m } = Math; function v(t, e, o) { e /= 100, o /= 100; const n = f(t = t / 360 * 6), i = t - n, r = o * (1 - e), s = o * (1 - i * e), a = o * (1 - (1 - i) * e), l = n % 6; return [255 * [o, s, r, r, a, o][l], 255 * [a, o, o, s, r, r][l], 255 * [r, r, a, o, o, s][l]] } function b(t, e, o) { const n = (2 - (e /= 100)) * (o /= 100) / 2; return 0 !== n && (e = 1 === n ? 0 : n < .5 ? e * o / (2 * n) : e * o / (2 - 2 * n)), [t, 100 * e, 100 * n] } function y(t, e, o) { const n = h(t /= 255, e /= 255, o /= 255), i = d(t, e, o), r = i - n; let s, a; if (0 === r) s = a = 0; else { a = r / i; const n = ((i - t) / 6 + r / 2) / r, l = ((i - e) / 6 + r / 2) / r, c = ((i - o) / 6 + r / 2) / r; t === i ? s = c - l : e === i ? s = 1 / 3 + n - c : o === i && (s = 2 / 3 + l - n), s < 0 ? s += 1 : s > 1 && (s -= 1) } return [360 * s, 100 * a, 100 * i] } function g(t, e, o, n) { e /= 100, o /= 100; return [...y(255 * (1 - h(1, (t /= 100) * (1 - (n /= 100)) + n)), 255 * (1 - h(1, e * (1 - n) + n)), 255 * (1 - h(1, o * (1 - n) + n)))] } function _(t, e, o) { e /= 100; const n = 2 * (e *= (o /= 100) < .5 ? o : 1 - o) / (o + e) * 100, i = 100 * (o + e); return [t, isNaN(n) ? 0 : n, i] } function w(t) { return y(...t.match(/.{2}/g).map(t => parseInt(t, 16))) } function A(t) { t = t.match(/^[a-zA-Z]+$/) ? function (t) { if ("black" === t.toLowerCase()) return "#000"; const e = document.createElement("canvas").getContext("2d"); return e.fillStyle = t, "#000" === e.fillStyle ? null : e.fillStyle }(t) : t; const e = { cmyk: /^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i, rgba: /^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i, hsla: /^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i, hsva: /^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i, hexa: /^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i }, o = t => t.map(t => /^(|\d+)\.\d+|\d+$/.test(t) ? Number(t) : void 0); let n; t: for (const i in e) { if (!(n = e[i].exec(t))) continue; const r = t => !!n[2] == ("number" == typeof t); switch (i) { case "cmyk": { const [, t, e, r, s] = o(n); if (t > 100 || e > 100 || r > 100 || s > 100) break t; return { values: g(t, e, r, s), type: i } } case "rgba": { const [, , , t, e, s, a] = o(n); if (t > 255 || e > 255 || s > 255 || a < 0 || a > 1 || !r(a)) break t; return { values: [...y(t, e, s), a], a: a, type: i } } case "hexa": { let [, t] = n; 4 !== t.length && 3 !== t.length || (t = t.split("").map(t => t + t).join("")); const e = t.substring(0, 6); let o = t.substring(6); return o = o ? parseInt(o, 16) / 255 : void 0, { values: [...w(e), o], a: o, type: i } } case "hsla": { const [, , , t, e, s, a] = o(n); if (t > 360 || e > 100 || s > 100 || a < 0 || a > 1 || !r(a)) break t; return { values: [..._(t, e, s), a], a: a, type: i } } case "hsva": { const [, , , t, e, s, a] = o(n); if (t > 360 || e > 100 || s > 100 || a < 0 || a > 1 || !r(a)) break t; return { values: [t, e, s, a], a: a, type: i } } } } return { values: null, type: null } } function C(t = 0, e = 0, o = 0, n = 1) { const i = (t, e) => (o = -1) => e(~o ? t.map(t => Number(t.toFixed(o))) : t), r = { h: t, s: e, v: o, a: n, toHSVA() { const t = [r.h, r.s, r.v, r.a]; return t.toString = i(t, t => `hsva(${t[0]}, ${t[1]}%, ${t[2]}%, ${r.a})`), t }, toHSLA() { const t = [...b(r.h, r.s, r.v), r.a]; return t.toString = i(t, t => `hsla(${t[0]}, ${t[1]}%, ${t[2]}%, ${r.a})`), t }, toRGBA() { const t = [...v(r.h, r.s, r.v), r.a]; return t.toString = i(t, t => `rgba(${t[0]}, ${t[1]}, ${t[2]}, ${r.a})`), t }, toCMYK() { const t = function (t, e, o) { const n = v(t, e, o), i = n[0] / 255, r = n[1] / 255, s = n[2] / 255, a = h(1 - i, 1 - r, 1 - s); return [100 * (1 === a ? 0 : (1 - i - a) / (1 - a)), 100 * (1 === a ? 0 : (1 - r - a) / (1 - a)), 100 * (1 === a ? 0 : (1 - s - a) / (1 - a)), 100 * a] }(r.h, r.s, r.v); return t.toString = i(t, t => `cmyk(${t[0]}%, ${t[1]}%, ${t[2]}%, ${t[3]}%)`), t }, toHEXA() { const t = function (t, e, o) { return v(t, e, o).map(t => m(t).toString(16).padStart(2, "0")) }(r.h, r.s, r.v), e = r.a >= 1 ? "" : Number((255 * r.a).toFixed(0)).toString(16).toUpperCase().padStart(2, "0"); return e && t.push(e), t.toString = () => "#" + t.join("").toUpperCase(), t }, clone: () => C(r.h, r.s, r.v, r.a) }; return r } const k = t => Math.max(Math.min(t, 1), 0); function $(t) { const e = { options: Object.assign({ lock: null, onchange: () => 0, onstop: () => 0 }, t), _keyboard(t) { const { options: o } = e, { type: n, key: i } = t; if (document.activeElement === o.wrapper) { const { lock: o } = e.options, r = "ArrowUp" === i, s = "ArrowRight" === i, a = "ArrowDown" === i, l = "ArrowLeft" === i; if ("keydown" === n && (r || s || a || l)) { let n = 0, i = 0; "v" === o ? n = r || s ? 1 : -1 : "h" === o ? n = r || s ? -1 : 1 : (i = r ? -1 : a ? 1 : 0, n = l ? -1 : s ? 1 : 0), e.update(k(e.cache.x + .01 * n), k(e.cache.y + .01 * i)), t.preventDefault() } else i.startsWith("Arrow") && (e.options.onstop(), t.preventDefault()) } }, _tapstart(t) { r(document, ["mouseup", "touchend", "touchcancel"], e._tapstop), r(document, ["mousemove", "touchmove"], e._tapmove), t.cancelable && t.preventDefault(), e._tapmove(t) }, _tapmove(t) { const { options: o, cache: n } = e, { lock: i, element: r, wrapper: s } = o, a = s.getBoundingClientRect(); let l = 0, c = 0; if (t) { const e = t && t.touches && t.touches[0]; l = t ? (e || t).clientX : 0, c = t ? (e || t).clientY : 0, l < a.left ? l = a.left : l > a.left + a.width && (l = a.left + a.width), c < a.top ? c = a.top : c > a.top + a.height && (c = a.top + a.height), l -= a.left, c -= a.top } else n && (l = n.x * a.width, c = n.y * a.height); "h" !== i && (r.style.left = `calc(${l / a.width * 100}% - ${r.offsetWidth / 2}px)`), "v" !== i && (r.style.top = `calc(${c / a.height * 100}% - ${r.offsetHeight / 2}px)`), e.cache = { x: l / a.width, y: c / a.height }; const p = k(l / a.width), u = k(c / a.height); switch (i) { case "v": return o.onchange(p); case "h": return o.onchange(u); default: return o.onchange(p, u) } }, _tapstop() { e.options.onstop(), s(document, ["mouseup", "touchend", "touchcancel"], e._tapstop), s(document, ["mousemove", "touchmove"], e._tapmove) }, trigger() { e._tapmove() }, update(t = 0, o = 0) { const { left: n, top: i, width: r, height: s } = e.options.wrapper.getBoundingClientRect(); "h" === e.options.lock && (o = t), e._tapmove({ clientX: n + r * t, clientY: i + s * o }) }, destroy() { const { options: t, _tapstart: o, _keyboard: n } = e; s(document, ["keydown", "keyup"], n), s([t.wrapper, t.element], "mousedown", o), s([t.wrapper, t.element], "touchstart", o, { passive: !1 }) } }, { options: o, _tapstart: n, _keyboard: i } = e; return r([o.wrapper, o.element], "mousedown", n), r([o.wrapper, o.element], "touchstart", n, { passive: !1 }), r(document, ["keydown", "keyup"], i), e } function S(t = {}) { t = Object.assign({ onchange: () => 0, className: "", elements: [] }, t); const e = r(t.elements, "click", e => { t.elements.forEach(o => o.classList[e.target === o ? "add" : "remove"](t.className)), t.onchange(e), e.stopPropagation() }); return { destroy: () => s(...e) } }
/*! NanoPop 2.1.0 MIT | https://github.com/Simonwep/nanopop */
const O = { variantFlipOrder: { start: "sme", middle: "mse", end: "ems" }, positionFlipOrder: { top: "tbrl", right: "rltb", bottom: "btrl", left: "lrbt" }, position: "bottom", margin: 8 }, E = (t, e, o) => { const n = "object" != typeof t || t instanceof HTMLElement ? { reference: t, popper: e, ...o } : t; return { update(t = n) { const { reference: e, popper: o } = Object.assign(n, t); if (!o || !e) throw new Error("Popper- or reference-element missing."); return ((t, e, o) => { const { container: n, margin: i, position: r, variantFlipOrder: s, positionFlipOrder: a } = { container: document.documentElement.getBoundingClientRect(), ...O, ...o }, { left: l, top: c } = e.style; e.style.left = "0", e.style.top = "0"; const p = t.getBoundingClientRect(), u = e.getBoundingClientRect(), h = { t: p.top - u.height - i, b: p.bottom + i, r: p.right + i, l: p.left - u.width - i }, d = { vs: p.left, vm: p.left + p.width / 2 + -u.width / 2, ve: p.left + p.width - u.width, hs: p.top, hm: p.bottom - p.height / 2 - u.height / 2, he: p.bottom - u.height }, [f, m = "middle"] = r.split("-"), v = a[f], b = s[m], { top: y, left: g, bottom: _, right: w } = n; for (const t of v) { const o = "t" === t || "b" === t, n = h[t], [i, r] = o ? ["top", "left"] : ["left", "top"], [s, a] = o ? [u.height, u.width] : [u.width, u.height], [l, c] = o ? [_, w] : [w, _], [p, f] = o ? [y, g] : [g, y]; if (!(n < p || n + s > l)) for (const s of b) { const l = d[(o ? "v" : "h") + s]; if (!(l < f || l + a > c)) return e.style[r] = l - u[r] + "px", e.style[i] = n - u[i] + "px", t + s } } return e.style.left = l, e.style.top = c, null })(e, o, n) } } }; function L(t, e, o) { return e in t ? Object.defineProperty(t, e, { value: o, enumerable: !0, configurable: !0, writable: !0 }) : t[e] = o, t } class x { constructor(t) { L(this, "_initializingActive", !0), L(this, "_recalc", !0), L(this, "_nanopop", null), L(this, "_root", null), L(this, "_color", C()), L(this, "_lastColor", C()), L(this, "_swatchColors", []), L(this, "_setupAnimationFrame", null), L(this, "_eventListener", { init: [], save: [], hide: [], show: [], clear: [], change: [], changestop: [], cancel: [], swatchselect: [] }), this.options = t = Object.assign({ ...x.DEFAULT_OPTIONS }, t); const { swatches: e, components: o, theme: n, sliders: i, lockOpacity: r, padding: s } = t;["nano", "monolith"].includes(n) && !i && (t.sliders = "h"), o.interaction || (o.interaction = {}); const { preview: a, opacity: l, hue: c, palette: p } = o; o.opacity = !r && l, o.palette = p || a || l || c, this._preBuild(), this._buildComponents(), this._bindEvents(), this._finalBuild(), e && e.length && e.forEach(t => this.addSwatch(t)); const { button: u, app: h } = this._root; this._nanopop = E(u, h, { margin: s }), u.setAttribute("role", "button"), u.setAttribute("aria-label", this._t("btn:toggle")); const d = this; this._setupAnimationFrame = requestAnimationFrame((function e() { if (!h.offsetWidth) return requestAnimationFrame(e); d.setColor(t.default), d._rePositioningPicker(), t.defaultRepresentation && (d._representation = t.defaultRepresentation, d.setColorRepresentation(d._representation)), t.showAlways && d.show(), d._initializingActive = !1, d._emit("init") })) } _preBuild() { const { options: t } = this; for (const e of ["el", "container"]) t[e] = p(t[e]); this._root = (t => { const { components: e, useAsButton: o, inline: n, appClass: i, theme: r, lockOpacity: s } = t.options, a = t => t ? "" : 'style="display:none" hidden', c = e => t._t(e), p = l(`\n <div :ref="root" class="pickr">\n\n ${o ? "" : '<button type="button" :ref="button" class="pcr-button"></button>'}\n\n <div :ref="app" class="pcr-app ${i || ""}" data-theme="${r}" ${n ? 'style="position: unset"' : ""} aria-label="${c("ui:dialog")}" role="window">\n <div class="pcr-selection" ${a(e.palette)}>\n <div :obj="preview" class="pcr-color-preview" ${a(e.preview)}>\n <button type="button" :ref="lastColor" class="pcr-last-color" aria-label="${c("btn:last-color")}"></button>\n <div :ref="currentColor" class="pcr-current-color"></div>\n </div>\n\n <div :obj="palette" class="pcr-color-palette">\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="palette" class="pcr-palette" tabindex="0" aria-label="${c("aria:palette")}" role="listbox"></div>\n </div>\n\n <div :obj="hue" class="pcr-color-chooser" ${a(e.hue)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-hue pcr-slider" tabindex="0" aria-label="${c("aria:hue")}" role="slider"></div>\n </div>\n\n <div :obj="opacity" class="pcr-color-opacity" ${a(e.opacity)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-opacity pcr-slider" tabindex="0" aria-label="${c("aria:opacity")}" role="slider"></div>\n </div>\n </div>\n\n <div class="pcr-swatches ${e.palette ? "" : "pcr-last"}" :ref="swatches"></div>\n\n <div :obj="interaction" class="pcr-interaction" ${a(Object.keys(e.interaction).length)}>\n <input :ref="result" class="pcr-result" type="text" spellcheck="false" ${a(e.interaction.input)} aria-label="${c("aria:input")}">\n\n <input :arr="options" class="pcr-type" data-type="HEXA" value="${s ? "HEX" : "HEXA"}" type="button" ${a(e.interaction.hex)}>\n <input :arr="options" class="pcr-type" data-type="RGBA" value="${s ? "RGB" : "RGBA"}" type="button" ${a(e.interaction.rgba)}>\n <input :arr="options" class="pcr-type" data-type="HSLA" value="${s ? "HSL" : "HSLA"}" type="button" ${a(e.interaction.hsla)}>\n <input :arr="options" class="pcr-type" data-type="HSVA" value="${s ? "HSV" : "HSVA"}" type="button" ${a(e.interaction.hsva)}>\n <input :arr="options" class="pcr-type" data-type="CMYK" value="CMYK" type="button" ${a(e.interaction.cmyk)}>\n\n <input :ref="save" class="pcr-save" value="${c("btn:save")}" type="button" ${a(e.interaction.save)} aria-label="${c("aria:btn:save")}">\n <input :ref="cancel" class="pcr-cancel" value="${c("btn:cancel")}" type="button" ${a(e.interaction.cancel)} aria-label="${c("aria:btn:cancel")}">\n <input :ref="clear" class="pcr-clear" value="${c("btn:clear")}" type="button" ${a(e.interaction.clear)} aria-label="${c("aria:btn:clear")}">\n </div>\n </div>\n </div>\n `), u = p.interaction; return u.options.find(t => !t.hidden && !t.classList.add("active")), u.type = () => u.options.find(t => t.classList.contains("active")), p })(this), t.useAsButton && (this._root.button = t.el), t.container.appendChild(this._root.root) } _finalBuild() { const t = this.options, e = this._root; if (t.container.removeChild(e.root), t.inline) { const o = t.el.parentElement; t.el.nextSibling ? o.insertBefore(e.app, t.el.nextSibling) : o.appendChild(e.app) } else t.container.appendChild(e.app); t.useAsButton ? t.inline && t.el.remove() : t.el.parentNode.replaceChild(e.root, t.el), t.disabled && this.disable(), t.comparison || (e.button.style.transition = "none", t.useAsButton || (e.preview.lastColor.style.transition = "none")), this.hide() } _buildComponents() { const t = this, e = this.options.components, o = (t.options.sliders || "v").repeat(2), [n, i] = o.match(/^[vh]+$/g) ? o : [], r = () => this._color || (this._color = this._lastColor.clone()), s = { palette: $({ element: t._root.palette.picker, wrapper: t._root.palette.palette, onstop: () => t._emit("changestop", "slider", t), onchange(o, n) { if (!e.palette) return; const i = r(), { _root: s, options: a } = t, { lastColor: l, currentColor: c } = s.preview; t._recalc && (i.s = 100 * o, i.v = 100 - 100 * n, i.v < 0 && (i.v = 0), t._updateOutput("slider")); const p = i.toRGBA().toString(0); this.element.style.background = p, this.wrapper.style.background = `\n linear-gradient(to top, rgba(0, 0, 0, ${i.a}), transparent),\n linear-gradient(to left, hsla(${i.h}, 100%, 50%, ${i.a}), rgba(255, 255, 255, ${i.a}))\n `, a.comparison ? a.useAsButton || t._lastColor || l.style.setProperty("--pcr-color", p) : (s.button.style.color = p, s.button.classList.remove("clear")); const u = i.toHEXA().toString(); for (const { el: e, color: o } of t._swatchColors) e.classList[u === o.toHEXA().toString() ? "add" : "remove"]("pcr-active"); c.style.setProperty("--pcr-color", p) } }), hue: $({ lock: "v" === i ? "h" : "v", element: t._root.hue.picker, wrapper: t._root.hue.slider, onstop: () => t._emit("changestop", "slider", t), onchange(o) { if (!e.hue || !e.palette) return; const n = r(); t._recalc && (n.h = 360 * o), this.element.style.backgroundColor = `hsl(${n.h}, 100%, 50%)`, s.palette.trigger() } }), opacity: $({ lock: "v" === n ? "h" : "v", element: t._root.opacity.picker, wrapper: t._root.opacity.slider, onstop: () => t._emit("changestop", "slider", t), onchange(o) { if (!e.opacity || !e.palette) return; const n = r(); t._recalc && (n.a = Math.round(100 * o) / 100), this.element.style.background = `rgba(0, 0, 0, ${n.a})`, s.palette.trigger() } }), selectable: S({ elements: t._root.interaction.options, className: "active", onchange(e) { t._representation = e.target.getAttribute("data-type").toUpperCase(), t._recalc && t._updateOutput("swatch") } }) }; this._components = s } _bindEvents() { const { _root: t, options: e } = this, o = [r(t.interaction.clear, "click", () => this._clearColor()), r([t.interaction.cancel, t.preview.lastColor], "click", () => { this.setHSVA(...(this._lastColor || this._color).toHSVA(), !0), this._emit("cancel") }), r(t.interaction.save, "click", () => { !this.applyColor() && !e.showAlways && this.hide() }), r(t.interaction.result, ["keyup", "input"], t => { this.setColor(t.target.value, !0) && !this._initializingActive && (this._emit("change", this._color, "input", this), this._emit("changestop", "input", this)), t.stopImmediatePropagation() }), r(t.interaction.result, ["focus", "blur"], t => { this._recalc = "blur" === t.type, this._recalc && this._updateOutput(null) }), r([t.palette.palette, t.palette.picker, t.hue.slider, t.hue.picker, t.opacity.slider, t.opacity.picker], ["mousedown", "touchstart"], () => this._recalc = !0, { passive: !0 })]; if (!e.showAlways) { const n = e.closeWithKey; o.push(r(t.button, "click", () => this.isOpen() ? this.hide() : this.show()), r(document, "keyup", t => this.isOpen() && (t.key === n || t.code === n) && this.hide()), r(document, ["touchstart", "mousedown"], e => { this.isOpen() && !c(e).some(e => e === t.app || e === t.button) && this.hide() }, { capture: !0 })) } if (e.adjustableNumbers) { const e = { rgba: [255, 255, 255, 1], hsva: [360, 100, 100, 1], hsla: [360, 100, 100, 1], cmyk: [100, 100, 100, 100] }; u(t.interaction.result, (t, o, n) => { const i = e[this.getColorRepresentation().toLowerCase()]; if (i) { const e = i[n], r = t + (e >= 100 ? 1e3 * o : o); return r <= 0 ? 0 : Number((r < e ? r : e).toPrecision(3)) } return t }) } if (e.autoReposition && !e.inline) { let t = null; const n = this; o.push(r(window, ["scroll", "resize"], () => { n.isOpen() && (e.closeOnScroll && n.hide(), null === t ? (t = setTimeout(() => t = null, 100), requestAnimationFrame((function e() { n._rePositioningPicker(), null !== t && requestAnimationFrame(e) }))) : (clearTimeout(t), t = setTimeout(() => t = null, 100))) }, { capture: !0 })) } this._eventBindings = o } _rePositioningPicker() { const { options: t } = this; if (!t.inline) { if (!this._nanopop.update({ container: document.body.getBoundingClientRect(), position: t.position })) { const t = this._root.app, e = t.getBoundingClientRect(); t.style.top = (window.innerHeight - e.height) / 2 + "px", t.style.left = (window.innerWidth - e.width) / 2 + "px" } } } _updateOutput(t) { const { _root: e, _color: o, options: n } = this; if (e.interaction.type()) { const t = "to" + e.interaction.type().getAttribute("data-type"); e.interaction.result.value = "function" == typeof o[t] ? o[t]().toString(n.outputPrecision) : "" } !this._initializingActive && this._recalc && this._emit("change", o, t, this) } _clearColor(t = !1) { const { _root: e, options: o } = this; o.useAsButton || (e.button.style.color = "rgba(0, 0, 0, 0.15)"), e.button.classList.add("clear"), o.showAlways || this.hide(), this._lastColor = null, this._initializingActive || t || (this._emit("save", null), this._emit("clear")) } _parseLocalColor(t) { const { values: e, type: o, a: n } = A(t), { lockOpacity: i } = this.options, r = void 0 !== n && 1 !== n; return e && 3 === e.length && (e[3] = void 0), { values: !e || i && r ? null : e, type: o } } _t(t) { return this.options.i18n[t] || x.I18N_DEFAULTS[t] } _emit(t, ...e) { this._eventListener[t].forEach(t => t(...e, this)) } on(t, e) { return this._eventListener[t].push(e), this } off(t, e) { const o = this._eventListener[t] || [], n = o.indexOf(e); return ~n && o.splice(n, 1), this } addSwatch(t) { const { values: e } = this._parseLocalColor(t); if (e) { const { _swatchColors: t, _root: o } = this, n = C(...e), i = a(`<button type="button" style="--pcr-color: ${n.toRGBA().toString(0)}" aria-label="${this._t("btn:swatch")}"/>`); return o.swatches.appendChild(i), t.push({ el: i, color: n }), this._eventBindings.push(r(i, "click", () => { this.setHSVA(...n.toHSVA(), !0), this._emit("swatchselect", n), this._emit("change", n, "swatch", this) })), !0 } return !1 } removeSwatch(t) { const e = this._swatchColors[t]; if (e) { const { el: o } = e; return this._root.swatches.removeChild(o), this._swatchColors.splice(t, 1), !0 } return !1 } applyColor(t = !1) { const { preview: e, button: o } = this._root, n = this._color.toRGBA().toString(0); return e.lastColor.style.setProperty("--pcr-color", n), this.options.useAsButton || o.style.setProperty("--pcr-color", n), o.classList.remove("clear"), this._lastColor = this._color.clone(), this._initializingActive || t || this._emit("save", this._color), this } destroy() { cancelAnimationFrame(this._setupAnimationFrame), this._eventBindings.forEach(t => s(...t)), Object.keys(this._components).forEach(t => this._components[t].destroy()) } destroyAndRemove() { this.destroy(); const { root: t, app: e } = this._root; t.parentElement && t.parentElement.removeChild(t), e.parentElement.removeChild(e), Object.keys(this).forEach(t => this[t] = null) } hide() { return !!this.isOpen() && (this._root.app.classList.remove("visible"), this._emit("hide"), !0) } show() { return !this.options.disabled && !this.isOpen() && (this._root.app.classList.add("visible"), this._rePositioningPicker(), this._emit("show", this._color), this) } isOpen() { return this._root.app.classList.contains("visible") } setHSVA(t = 360, e = 0, o = 0, n = 1, i = !1) { const r = this._recalc; if (this._recalc = !1, t < 0 || t > 360 || e < 0 || e > 100 || o < 0 || o > 100 || n < 0 || n > 1) return !1; this._color = C(t, e, o, n); const { hue: s, opacity: a, palette: l } = this._components; return s.update(t / 360), a.update(n), l.update(e / 100, 1 - o / 100), i || this.applyColor(), r && this._updateOutput(), this._recalc = r, !0 } setColor(t, e = !1) { if (null === t) return this._clearColor(e), !0; const { values: o, type: n } = this._parseLocalColor(t); if (o) { const t = n.toUpperCase(), { options: i } = this._root.interaction, r = i.find(e => e.getAttribute("data-type") === t); if (r && !r.hidden) for (const t of i) t.classList[t === r ? "add" : "remove"]("active"); return !!this.setHSVA(...o, e) && this.setColorRepresentation(t) } return !1 } setColorRepresentation(t) { return t = t.toUpperCase(), !!this._root.interaction.options.find(e => e.getAttribute("data-type").startsWith(t) && !e.click()) } getColorRepresentation() { return this._representation } getColor() { return this._color } getSelectedColor() { return this._lastColor } getRoot() { return this._root } disable() { return this.hide(), this.options.disabled = !0, this._root.button.classList.add("disabled"), this } enable() { return this.options.disabled = !1, this._root.button.classList.remove("disabled"), this } } L(x, "utils", n), L(x, "version", "1.8.1"), L(x, "I18N_DEFAULTS", { "ui:dialog": "color picker dialog", "btn:toggle": "toggle color picker dialog", "btn:swatch": "color swatch", "btn:last-color": "use previous color", "btn:save": "Save", "btn:cancel": "Cancel", "btn:clear": "Clear", "aria:btn:save": "save and close", "aria:btn:cancel": "cancel and close", "aria:btn:clear": "clear and close", "aria:input": "color input field", "aria:palette": "color selection area", "aria:hue": "hue selection slider", "aria:opacity": "selection slider" }), L(x, "DEFAULT_OPTIONS", { appClass: null, theme: "classic", useAsButton: !1, padding: 8, disabled: !1, comparison: !0, closeOnScroll: !1, outputPrecision: 0, lockOpacity: !1, autoReposition: !0, container: "body", components: { interaction: {} }, i18n: {}, swatches: null, inline: !1, sliders: null, default: "#42445a", defaultRepresentation: null, position: "bottom-middle", adjustableNumbers: !0, showAlways: !1, closeWithKey: "Escape" }), L(x, "create", t => new x(t)); e.default = x
}]).default
}));
//# sourceMappingURL=pickr.min.js.map
// #content color.js
// Only way to catch errors since: https://github.com/mknichel/javascript-errors#content-scripts. Paste in every script which should trace bugs.
window.onerror = (errorMsg, url, lineNumber, column, errorObj) => { if (!errorMsg) return; errors += "`❌` **" + (new Date()).toTimeString().substr(0, (new Date()).toTimeString().indexOf(" ")) + ": " + errorMsg + "**:\n" + ' Script: ' + url + ' \nLine: ' + lineNumber + ' \nColumn: ' + column + ' \nStackTrace: ' + errorObj + "\n\n"; }
// class to simplify color conversions
class Color {
//_r;
//_g;
//_b;
get r() { return this._r; }
get g() { return this._g; }
get b() { return this._b; }
// get the rgb string of the color
get rgb() { return "rgb(" + [this._r, this._g, this._b].join(",") + ")"; }
// get the rgb values of the color
get rgbValues() { return { r: this._r, g: this._g, b: this._b }; }
// get the hex string of the color
get hex() { return "#" + this._r.toString(16).padStart(2, "0") + this._g.toString(16).padStart(2, "0") + this._b.toString(16).padStart(2, "0"); }
get hsl() {
//source: https://gist.github.com/mjackson/5311256
let r = this.r / 255, g = this.g / 255, b = this.b / 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h*360, s * 100, l * 100];
}
constructor(color) {
if (color.h != null && color.s != null && color.l != null) {
// source: https://stackoverflow.com/questions/36721830/convert-hsl-to-rgb-and-hex
color.l /= 100;
const a = color.s * Math.min(color.l, 1 - color.l) / 100;
const f = n => {
const k = (n + color.h / 30) % 12;
const col = color.l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * col).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
color.hex = `${f(0)}${f(8)}${f(4)}`;
}
// create a color by hex val
if (color.hex) {
let hex = color.hex;
if (hex[0] == '#') hex = hex.substring(1);
this._r = parseInt("0x" + hex.substring(0, 2));
this._g = parseInt("0x" + hex.substring(2, 4));
this._b = parseInt("0x" + hex.substring(4, 6));
}
// create a color by single r, g and b values
else if (color.r != null && color.g != null && color.b != null) {
this._r = color.r;
this._g = color.g;
this._b = color.b;
}
else if (color.rgb) {
// create a color by rgb string
let rgb = color.rgb.trim().replace(" ", "").split(",");
this._r = parseInt(rgb[0].replace(/[^\d]/g, ''), 10);
this._g = parseInt(rgb[1].replace(/[^\d]/g, ''), 10);
this._b = parseInt(rgb[2].replace(/[^\d]/g, ''), 10);
}
};
}
// #content features/modal.js
// Only way to catch errors since: https://github.com/mknichel/javascript-errors#content-scripts. Paste in every script which should trace bugs.
window.onerror = (errorMsg, url, lineNumber, column, errorObj) => { if (!errorMsg) return; errors += "`❌` **" + (new Date()).toTimeString().substr(0, (new Date()).toTimeString().indexOf(" ")) + ": " + errorMsg + "**:\n" + ' Script: ' + url + ' \nLine: ' + lineNumber + ' \nColumn: ' + column + ' \nStackTrace: ' + errorObj + "\n\n"; }
const STOP_EXECUTION = localStorage.typoincompatibility == "true";
class Modal {
constructor(contentParent, onclose, title = "Modal", width = "50vw", height = "50vh") {
let modal = document.createElement("div");
modal.classList.add("modalContainer");
modal.style.cssText = `
width: ${width};
min-height: ${height};
left: calc((100vw - ${width}) / 2);
top: calc((100vh - ${height}) / 4);
`;
let blur = document.createElement("div");
blur.classList.add("modalBlur");
modal.insertAdjacentHTML("afterbegin", "<h3 style='text-align:center; font-weight: 600; font-size:1.7em;'>" + title + "</h2>");
modal.insertAdjacentHTML("afterbegin", `<div id="modalClose">🞬</div>`);
if (contentParent) {
let content = document.createElement("div");
content.style.cssText = `
width: 100%;
flex-grow: 2;
display:flex;
justify-content: center;
overflow-y:auto;
`;
modal.appendChild(content);
content.appendChild(contentParent);
this.content = content;
}
document.body.appendChild(modal);
document.body.appendChild(blur);
let esc = (e) => {
if (e.which == 27) {
e.preventDefault();
this.close();
}
}
document.addEventListener("keydown", esc);
this.modal = modal;
this.blur = blur;
this.onclose = onclose;
this.setNewContent = parentElement => {
this.content.replaceWith(parentElement);
};
this.setNewTitle = title => {
this.modal.querySelector("h2").innerText = title;
};
this.close = () => {
modal.style.transform = "translate(0,-20vh)";
modal.style.opacity = "0";
blur.style.opacity = "0";
document.body.style.height = "";
document.body.style.overflowY = "";
document.body.style.paddingRight = "";
document.removeEventListener("keydown", esc);
setTimeout(() => {
this.onclose();
this.blur.remove();
this.modal.remove();
}, 200)
};
blur.addEventListener("click", this.close);
modal.querySelector("#modalClose").addEventListener("click", this.close);
setTimeout(() => {
modal.style.transform = "translate(0)";
modal.style.opacity = "1";
blur.style.opacity = "0.5";
}, 20);
/* */
document.body.style.height = "100vh";
document.body.style.overflowY = "hidden";
document.body.style.paddingRight = "15px";
}
}
class Toast {
constructor(content, duration = 4500) {
let toast = elemFromString(`<div style= "
position: fixed;
bottom: 10vh;
font-size:2em;
border-radius:.5em;
z-index:300;
width: fit-content;
pointer-events: none;
color: black;
text-align:middle;
padding: 0.5em 1em;
background-color: white;
opacity: 0;
transition: opacity 0.5s;
box-shadow: black 1px 1px 9px -2px;
"></div>`);
toast.innerHTML = content;
toast.classList.add("toast");
document.body.appendChild(toast);
let width = toast.getBoundingClientRect().width;
toast.style.left = "calc(50vw - (" + width + "px) / 2)";
toast.style.opacity = "1";
setTimeout(() => {
toast.style.opacity = "0";
setTimeout(() => toast.remove(), 500);
}, duration);
this.toast = toast;
}
remove() {
this.toast.remove();
}
}
// #content features/search.js
const search = {
startFilterSearch: undefined,
SearchFilter: class {
constructor(inputOptions) {
// get names and define name match func
this.names = [];
this.names = inputOptions.find(e => e.id == "inputSearchName").value.trim() != "" ? inputOptions.find(e => e.id == "inputSearchName").value.trim().split(",").map(p => p.trim()) : []
const matchesNames = (players) => {
return this.names.length == 0 || players.some(lobbyplayer =>
this.names.some(searchPlayer => searchPlayer.toLowerCase() == lobbyplayer.Name.toLowerCase()));
};
// get round and round modifier + match func
this.targetRound = 0;
this.targetRoundModifier = 0;
let valRound = inputOptions.find(e => e.id == "inputSearchRound").value.trim();
this.targetRound = parseInt(valRound);
this.targetRoundModifier = valRound[valRound.indexOf(this.targetRound) + this.targetRound.toString().length];
if (this.targetRoundModifier != "+" && this.targetRoundModifier != "-" && this.targetRoundModifier != undefined
|| isNaN(this.targetRound)) this.targetRoundModifier = "+";
const matchesRound = (round) => {
return isNaN(this.targetRound) ||
(this.targetRoundModifier == "+" ? round >= this.targetRound
: this.targetRoundModifier == "-" ? round <= this.targetRound
: round == this.targetRound);
};
// get score and score modifier + match func
this.targetScore = 0;
this.targetScoreModifier = 0;
let valScore = inputOptions.find(e => e.id == "inputSearchScore").value.trim();
this.targetScore = parseInt(valScore);
this.targetScoreModifier = valScore[valScore.indexOf(this.targetScore) + this.targetScore.toString().length];
if (this.targetScoreModifier != "+" && this.targetScoreModifier != "-" && this.targetScoreModifier != undefined
|| isNaN(this.targetScore)) this.targetScoreModifier = "+";
const matchesScore = (players) => {
let avg = ((ps) => { let avg = 0; ps.forEach(p => avg += p.Score / ps.length); return avg; })(players);
return isNaN(this.targetScore)
|| (this.targetScoreModifier == "-" ? avg < this.targetScoreModifier : avg >= this.targetScore);
};
// get count and count modifier + match func
this.targetCount = 0;
this.targetCountModifier = 0;
let valCount = inputOptions.find(e => e.id == "inputSearchCount").value.trim();
this.targetCount = parseInt(valCount);
this.targetCountModifier = valCount[valCount.indexOf(this.targetCount) + this.targetCount.toString().length];
if (this.targetCountModifier != "+" && this.targetCountModifier != "-" && this.targetCountModifier != undefined
|| isNaN(this.targetCount)) this.targetCountModifier = "+";
const matchesCount = (players) => {
return isNaN(this.targetCount)
|| (this.targetCountModifier == "-" ? players.length <= this.targetCount : this.targetCountModifier == "+" ? players.length >= this.targetCount : players.length == this.targetCount);
};
// get ptr players checked + match func
this.targetPalantirPresent = inputOptions.find(e => e.id == "inputSearchPalantir").checked;
const matchesPalantir = (lobbyKey) => {
return !this.targetPalantirPresent || sprites.playerSprites.some(sprite => sprite.LobbyKey == lobbyKey);
};
//function to check if all filters match - if private, dont check filters
this.matchAll = (lobbyProperties) => {
return lobbyProperties.Private || matchesNames(lobbyProperties.Players)
&& matchesCount(lobbyProperties.Players)
&& matchesScore(lobbyProperties.Players)
&& matchesRound(lobbyProperties.Round)
&& matchesPalantir(lobbyProperties.Key)
}
}
},
setup: () => {
// get add filter button
let addFilterBtn = QS("#addFilter");
// create filter input elements
let containerFilters = elemFromString(`<div
id="containerFilters"
style="display:grid; grid-template-columns: 2fr 3fr 2fr 3fr; width:100%; place-items: center"
>
<div style="grid-column-start: span 4; text-align:center">
<details>
<summary style="cursor:pointer; user-select:none"> <b>How lobby filters work</b> </summary>
With lobby filters, you can search for lobbys with customizable search criteria.<br>
Add names (separated with a comma), a specific round, average player score or lobby player count.<br>
You can also add a + or - after numbers to accept more or less of that value.<br>
When you enable "With Palantir Player" the search will stop at lobbies with Palantir users.<br>
When you click "Play", Typo will only stop at lobbies that fulfull one of your active filters. <br>
</details>
</div>
<h3>Search Names:</h3>
<input id="inputSearchName" class="form-control" placeholder="Names seaparated by a comma: \'name\' or \'name, name1, name2\'" style="grid-column-start: span 3">
<h3 style="">In Round:</h3>
<input id="inputSearchRound" class="form-control" placeholder="\'1\' or \'2+\'" style="">
<h3 style="">Avg Score:</h3>
<input id="inputSearchScore" class="form-control" placeholder="\'500+\' or \'500-\'" style="">
<h3 style="">Player Count:</h3>
<input id="inputSearchCount" class="form-control" placeholder="\'4-\' or \'8\'" style="">
<div class="checkbox" style="grid-column-start: span 2"><label style="display:flex;"><input type="checkbox" id="inputSearchPalantir"><div style="margin-left: .5em; user-select:none"> With Palantir Player</div></label></div>
<div style="grid-column-start: span 4; display:grid; place-content:center"> <button class="flatUI green min air" id="addFilter" >✔ Add</button> </div>
</div>`)
/* let filterNamesForm = elemFromString('<div style="display:flex; width: 100%; margin-bottom:.5em;"><h5>Search Names:</h5><input id="inputSearchName" class="form-control" placeholder="\'name\' or \'name, name1, name2\'" style="flex-grow: 2; width:unset; margin-left: .5em;"></div>');
let filterDetailsForm = elemFromString('<div style="display:flex; width: 100%; margin-bottom:.5em;"><h5 style="flex:1;">In Round:</h5><input id="inputSearchRound" class="form-control" placeholder="\'1\' or \'2+\'" style="flex: 1;margin-left: .5em;"><h5 style="margin-left: .5em; flex:1;">Avg Score:</h5><input id="inputSearchScore" class="form-control" placeholder="\'500+\' or \'500-\'" style="flex: 1; margin-left: .5em;"></div>');
let filterPlayersForm = elemFromString('<div style="display:flex; width: 100%;"><h5 style="flex:1;">Player Count:</h5><input id="inputSearchCount" class="form-control" placeholder="\'4-\' or \'8\'" style="flex: 1;margin-left: .5em;"><div class="checkbox" style="margin-left: .5em; flex:2"><label><input type="checkbox" id="inputSearchPalantir"><span>With Palantir Player</span></label></div><div class="btn btn-success" id="addFilter" style="height: fit-content;">✔ Add</div></div>');
containerFilters.appendChild(filterNamesForm);
containerFilters.appendChild(filterDetailsForm);
containerFilters.appendChild(filterPlayersForm); */
// gets the current settings
const getFilterString = () => {
let values = [];
[...containerFilters.querySelectorAll("input")].forEach(elem => {
values.push({ id: elem.id, checked: elem.checked, value: elem.value });
});
return JSON.stringify(values);
};
let currentModal = null;
addFilterBtn.addEventListener("click", () => currentModal = new Modal(containerFilters, () => {}, "Add a lobby search filter"));
// function to add a filter
const addFilter = (filterstring, active, id) => {
let filter = new search.SearchFilter(JSON.parse(filterstring));
let names = (filter.targetPalantirPresent ? [...filter.names, "Palantir users"] : filter.names).join(", ");
let visual = [];
if (names != "") visual.push("🔎 " + names);
if (!isNaN(filter.targetRound)) visual.push("🔄 " + filter.targetRound + (filter.targetRoundModifier ? filter.targetRoundModifier : ""));
if (!isNaN(filter.targetScore)) visual.push("📈 " + filter.targetScore + (filter.targetScoreModifier ? filter.targetScoreModifier : ""));
if (!isNaN(filter.targetCount)) visual.push("👥 " + filter.targetCount + (filter.targetCountModifier ? filter.targetCountModifier : ""));
// func to remove filter btn and filter
let remove = () => {
let added = JSON.parse(localStorage.addedFilters);
added = added.filter(filter => filter.id != id);
localStorage.addedFilters = JSON.stringify(added);
}
// if nothing was selected
if (visual.join("") == "") {
new Toast("No filters set.");
remove();
return;
}
// create button element
let filterbutton = elemFromString('<button class="flatUI blue min air" style="margin: .5em">' + visual.join(" & ") + '</button>');
// add btn before add filter btn
addFilterBtn.insertAdjacentElement("beforebegin", filterbutton);
// set filter activation
if(!active) filterbutton.classList.add("filterDisabled");
filterbutton.addEventListener("click", () => {
filterbutton.classList.toggle("filterDisabled");
let added = JSON.parse(localStorage.addedFilters);
added.forEach(filter => { if (filter.id == id) filter.active = !filterbutton.classList.contains("filterDisabled") });
localStorage.addedFilters = JSON.stringify(added);
});
filterbutton.addEventListener("contextmenu", (e) => {
e.preventDefault();
remove();
filterbutton.remove();
});
}
// add filter when save is pressed
containerFilters.querySelector("#addFilter").addEventListener("click", () => {
let filterstring = getFilterString();
let id = Date.now();
localStorage.addedFilters = JSON.stringify([...JSON.parse(localStorage.addedFilters), { active: true, filter: filterstring, id: id }]);
addFilter(filterstring, true, id);
currentModal?.close()
});
// add saved filters
JSON.parse(localStorage.addedFilters).forEach(filter => {
addFilter(filter.filter, filter.active, filter.id);
});
// start search on play button
QS(".button-play").addEventListener("click", (e) => {
// if filters enabled
if (JSON.parse(localStorage.addedFilters).some(filter => filter.active)) search.startFilterSearch();
});
},
startFilterSearch: () => {
// load and create filters
let filters = [];
let humanCriterias = [];
JSON.parse(localStorage.addedFilters).forEach(filter => {
if (filter.active) {
let filterObj = new search.SearchFilter(JSON.parse(filter.filter));
filters.push(filterObj);
criteria = [];
if (filterObj.names.length > 0 || filterObj.targetPalantirPresent) criteria.push("<b>Names:</b> " + (filterObj.targetPalantirPresent ? [...filterObj.names, "Palantir Users"] : filterObj.names).join(", "));
if (!isNaN(filterObj.targetRound)) criteria.push("<b>Round:</b> " + filterObj.targetRound + (filterObj.targetRoundModifier ? filterObj.targetRoundModifier : ""));
if (!isNaN(filterObj.targetScore)) criteria.push("<b>Avg Score:</b> " + filterObj.targetScore + (filterObj.targetScoreModifier ? filterObj.targetScoreModifier : ""));
if (!isNaN(filterObj.targetCount)) criteria.push("<b>Players:</b> " + filterObj.targetCount + (filterObj.targetCountModifier ? filterObj.targetCountModifier : ""));
if (criteria.length > 0) humanCriterias.push(criteria.join(" & "));
}
});
// create search modal
let searchParamsHuman = (humanCriterias.join("<br>or<br>") != "" ?
"Search Criteria:<br>" + humanCriterias.join("<br>or<br>") : "<b>Whoops,</b> You didn't set any filters.");
let modalCont = elemFromString("<div style='text-align:center'><details><summary style='cursor:pointer; user-select:none''><b>Lobby Search Information</b></summary>While this popup is opened, typo jumps through lobbies and searches for one that matches you filters.<br>Due to skribbl limitations, typo can only join once in two seconds.</details><h4>" + searchParamsHuman + "</h4><span id='skippedPlayers'>Skipped players:<br></span><br><span id='jumpsSearch'></span><br><h4>Click anywhere out to cancel</h4><div>");
let modal = new Modal(modalCont, () => {
if(!search.searchData.searching) return;
search.searchData.searching = false;
QS("#searchRules")?.remove();
document.dispatchEvent(newCustomEvent("abortJoin"));
leaveLobby();
}, "Searching for filter match:", "40vw", "15em");
let skippedPlayers = [];
let jumps=0;
search.setSearch(() => {
// search rules
if(!QS("#searchRules")) {
let rules = document.body.appendChild(elemFromString`<style id="searchRules">
#home{ display:flex !important}
#game{ display:none !important}
#load{ display:none !important}
</style>`);
}
modalCont.querySelector("#jumpsSearch").textContent = "Skipped lobbies: " + ++jumps;
lobbies.lobbyProperties.Players.forEach(p => {
if (skippedPlayers.indexOf(p.Name) < 0 && p.Name != socket.clientData.playerName) {
skippedPlayers.push(p.Name);
modalCont.querySelector("#skippedPlayers").innerHTML += " [" + p.Name + "] <wbr> ";
}
});
let lobby = lobbies.lobbyProperties;
return filters.length <= 0 || filters.some(filter => filter.matchAll(lobby));
}, () => {
leaveLobby(true);
}, () => {
search.searchData= {
searching: false,
check: undefined, proceed: undefined, ended: undefined
};
modal.close();
QS("#searchRules")?.remove();
});
},
searchData: {
searching: false,
check: undefined, proceed: undefined, ended: undefined
},
setSearch: (check, proceed, ended = () => { }) => {
if (search.searchData.searching) return;
search.searchData.searching = true;
search.searchData.check = check;
search.searchData.proceed = proceed;
search.searchData.ended = ended;
}
}
// #content features/sprites.js
// Only way to catch errors since: https://github.com/mknichel/javascript-errors#content-scripts. Paste in every script which should trace bugs.
window.onerror = (errorMsg, url, lineNumber, column, errorObj) => { if (!errorMsg) return; errors += "`❌` **" + (new Date()).toTimeString().substr(0, (new Date()).toTimeString().indexOf(" ")) + ": " + errorMsg + "**:\n" + ' Script: ' + url + ' \nLine: ' + lineNumber + ' \nColumn: ' + column + ' \nStackTrace: ' + errorObj + "\n\n"; }
const sprites = {
// Object which has necessary properties to handle sprite logic
PlayerSpriteContainer: function (_lobbyKey, _lobbyPlayerID, _avatarContainer, _name) {
this.lobbyKey = _lobbyKey;
this.lobbyPlayerID = _lobbyPlayerID;
this.name = _name;
this.avatarContainer = _avatarContainer;
},
availableSprites: [], //list of all sprites
playerSprites: [], //list of all player identifications which are online and have sprites
lobbyPlayers: [], //list of the players in the players lobby
getSpriteURL: (id) => { // get the gif url from a sprite id
let url = "";
sprites.availableSprites.forEach(s => { if (s.ID == id) url = s.URL; });
return url;
},
isSpecial: (id) => { // checks if a sprite is special
let special = false;
sprites.availableSprites.forEach(s => { if (s.ID == id && s.Special) special = true; });
return special;
},
getPlayerList: () => { //get the lobby player list and store in lobbyPlayers
let players = [];
let playerContainer = QS("#game-players");
//let playerContainerLobby = QS("#containerLobbyPlayers");, ...playerContainerLobby.querySelectorAll(".lobbyPlayer")
[...playerContainer.querySelectorAll(".player")].forEach(p => {
let psc = new sprites.PlayerSpriteContainer(
lobbies.lobbyProperties.Key,
p.getAttribute("playerid"),
p.querySelector(".avatar"),
p.querySelector(".player-name").innerText.replace("(You)", "").trim()
)
players.push(psc);
});
sprites.lobbyPlayers = players;
},
updateSprites: () => { // compare lobbyplayers with onlinesprites and set sprite if matching
// get shifts for this lobby
let shifts = socket.data.publicData.onlineItems.filter(item => item.LobbyKey == socket.clientData.lobbyKey && item.ItemType == "shift");
sprites.lobbyPlayers.forEach(player => {
let playerSlots = [];
sprites.playerSprites.forEach(sprite => {
if (sprite.LobbyPlayerID.toString() == player.lobbyPlayerID && sprite.LobbyKey == player.lobbyKey) {
playerSlots.push({
sprite: sprite.Sprite,
slot: sprite.Slot,
shift: shifts.find(shift => shift.LobbyPlayerID == player.lobbyPlayerID && sprite.Slot == shift.Slot)
});
}
});
if (playerSlots.length > 0) {
player.avatarContainer.parentElement.parentElement.classList.toggle("typo", true);
// check if existent slots are set to 0
[...player.avatarContainer.querySelectorAll(".typoSpecialSlot")].forEach(existentSlot => {
if (!playerSlots.some(slot => existentSlot.classList.contains("specialSlot" + slot.slot))) existentSlot.remove();
});
// make avatar invisible if special is inluded
let state = playerSlots.some(slot => sprites.isSpecial(slot.sprite)) ? "none" : "";
[...player.avatarContainer.querySelectorAll(".color, .eyes, .mouth")].forEach(a => a.style.display = state);
// update slots
playerSlots.forEach(slot => {
let spriteUrl = sprites.getSpriteURL(slot.sprite);
if (!player.avatarContainer.querySelector(".specialSlot" + slot.slot) // if slot layer isnt existent or has old url
|| player.avatarContainer.querySelector(".specialSlot" + slot.slot).style.backgroundImage != "url(\"" + spriteUrl + "\")") {
if (player.avatarContainer.querySelector(".specialSlot" + slot.slot)) // remove slot layer
player.avatarContainer.querySelector(".specialSlot" + slot.slot).remove();
let spriteContainer = document.createElement("div"); // create new layer
spriteContainer.className = "specialSlot" + slot.slot;
spriteContainer.classList.add("special");
spriteContainer.classList.add("typoSpecialSlot");
spriteContainer.style.zIndex = slot.slot;
spriteContainer.style.backgroundImage = slot.shift ? "url(https://static.typo.rip/sprites/rainbow/modulate.php?url=" + spriteUrl + "&hue=" + slot.shift.ItemID + ")" : "url(" + spriteUrl + ")";
player.avatarContainer.appendChild(spriteContainer);
// set style depending on listing
if (spriteContainer.closest("#containerLobbyPlayers")) spriteContainer.style.backgroundSize = "contain";
else {
spriteContainer.parentElement.parentElement.parentElement.style.height = "56px";
spriteContainer.parentElement.parentElement.style.top = "3px";
}
}
});
}
// else remove all existent slots
else {
[...player.avatarContainer.querySelectorAll(".typoSpecialSlot")].forEach(existentSlot => existentSlot.remove());
player.avatarContainer.parentElement.parentElement.classList.toggle("typo", false);
}
});
},
updateAwards: () => {
const lobbyAwards = socket.data.publicData.onlineItems.filter(item => item.LobbyKey == socket.clientData.lobbyKey && item.ItemType == "award");
[...QSA("#game-players .player-icons")].forEach(icons => {
const playerId = Number(icons.closest(".player")?.getAttribute("playerid"));
if (Number.isNaN(playerId)) return;
let playerIcons = lobbyAwards.filter(a => a.LobbyPlayerID == playerId);
[...icons.querySelectorAll(".award")].forEach(existingIcon => {
const awardId = Number(existingIcon.getAttribute("awardId"));
if (!playerIcons.some(icon => icon.Slot == awardId)) existingIcon.remove();
else playerIcons = playerIcons.filter(icon => icon.Slot != awardId);
});
playerIcons.forEach(icon => {
const award = awards.all.find(a => a.id == icon.Slot);
icons.insertAdjacentHTML("beforeend", `<div class="icon typo award visible" awardId="${award.id}" style="background-image: url(${award.url})"></div>`);
});
});
},
updateScenes: () => {
const playerlist = QS("#game-players");
let scenesCSS = elemFromString("<style id='scenesRules'></style>");
// scene shifts for this lobby
let shifts = socket.data.publicData.onlineItems.filter(item => item.LobbyKey == socket.clientData.lobbyKey && item.ItemType == "sceneTheme");
sprites.onlineScenes.forEach(scene => {
if (scene.LobbyKey == socket.clientData.lobbyKey) {
let url = sprites.availableScenes.find(av => av.ID == scene.Sprite).URL;
const sceneShift = shifts.find(shift => shift.LobbyPlayerID == scene.LobbyPlayerID);
if(sceneShift) {
url = `https://static.typo.rip/sprites/rainbow/modulate.php?url=${url}&hue=${sceneShift.ItemID}`;
const rotate = ((360/200) * sceneShift.ItemID - 180) * -1;
scenesCSS.innerHTML += `
#game-players div.player:not(.guessed)[playerid='${scene.LobbyPlayerID}'] .player-info {filter: hue-rotate(${rotate}deg) !important}`;
}
scenesCSS.innerHTML += `
#game-players div.player[playerid='${scene.LobbyPlayerID}'] {
background-image: url(${url}) !important;
background-size: auto 100% !important;
background-position: center center !important;
background-repeat: no-repeat !important;
}
#game-players div.player[playerid='${scene.LobbyPlayerID}'] .player-background {opacity: 0}
#game-players div.player.guessed[playerid='${scene.LobbyPlayerID}'] *:is(.player-rank, .player-score, .player-name) {color: ${sprites.availableScenes.find(av => av.ID == scene.Sprite).GuessedColor} !important}
#game-players div.player[playerid='${scene.LobbyPlayerID}'] *:is(.player-rank, .player-score, .player-name) {color: ${sprites.availableScenes.find(av => av.ID == scene.Sprite).Color} !important}`;
}
});
if (QS("#scenesRules")?.innerHTML === scenesCSS.innerHTML) return;
QS("#scenesRules")?.remove();
playerlist.insertAdjacentElement("afterbegin", scenesCSS);
},
updateEndboardSprites: () => { // show sprites on endboard
let endboardAvatars = QSA(".overlay-content .result .rank-name");
sprites.lobbyPlayers.forEach(player => {
let avatarContainer = null;
endboardAvatars.forEach(a => { if (a.innerText == player.name) avatarContainer = a.closest(".podests") ? a.parentElement.parentElement.querySelector(".avatar") : a.parentElement.querySelector(".avatar"); });
if (avatarContainer != null) {
// remove all existent special slots on avatar
[...avatarContainer.parentElement.querySelectorAll(".typoSpecialSlot")].forEach(slot => slot.remove());
// update background depending on avatar
let state = player.avatarContainer.querySelector(".color").style.display;
[...avatarContainer.parentElement.querySelectorAll(".color, .eyes, .mouth")].forEach(elem => elem.style.display = state);
// add slots to avatar
let slotsOnSidebar = [...player.avatarContainer.querySelectorAll(".typoSpecialSlot")];
slotsOnSidebar.forEach(slot => {
let slotElem = avatarContainer.querySelector(".special").cloneNode(true);
slotElem.style.backgroundSize = "cover";
slotElem.classList.add(".typoSpecialSlot");
slotElem.style.display = "";
slotElem.style.backgroundPosition = "";
slotElem.style.backgroundImage = slot.style.backgroundImage;
slotElem.style.zIndex = slot.style.zIndex;
avatarContainer.appendChild(slotElem);
});
}
});
},
refreshCallback: async () => { // refresh all
sprites.getSprites();
sprites.getPlayerList();
sprites.updateSprites();
sprites.updateScenes();
sprites.updateAwards();
},
getSprites: () => {
sprites.availableSprites = socket.data.publicData.sprites;
sprites.playerSprites = socket.data.publicData.onlineSprites;
sprites.availableScenes = socket.data.publicData.scenes;
sprites.onlineScenes = socket.data.publicData.onlineScenes;
},
getOwnSpriteUrlShifted: (id) => {
let shifts = socket.data.user.rainbowSprites ? socket.data.user.rainbowSprites.split(",").map(s => s.split(":")) : [];
let url = sprites.getSpriteURL(id);
let shift = shifts.find(s => s[0] == id);
if (shift) url = "https://static.typo.rip/sprites/rainbow/modulate.php?url=" + url + "&hue=" + shift[1];
return url;
},
setLandingSprites: (authenticated = false) => {
QSA(".avatar-customizer .spriteSlot").forEach(elem => elem.remove());
QS(".avatar-customizer").style.backgroundImage = "";
if (authenticated) {
let ownsprites = socket.data.user.sprites.toString().split(",");
let activeSprites = ownsprites.filter(s => s.includes("."));
QSA(".avatar-customizer .color, .avatar-customizer .eyes, .avatar-customizer .mouth").forEach(n => {
n.style.opacity = activeSprites.some(spt => sprites.isSpecial(spt.replaceAll(".", ""))) ? 0 : 1;
});
activeSprites.forEach(sprite => {
let slot = sprite.split(".").length - 1;
let id = sprite.replaceAll(".", "");
let url = sprites.getOwnSpriteUrlShifted(id);
let specialContainer = QS(".avatar-customizer .special");
let clone = specialContainer.cloneNode(true);
specialContainer.parentElement.appendChild(clone);
clone.style = "background-image:url(" + url + "); background-size:contain; position: absolute; left: -33%; top: -33%; width: 166%;height: 166%;";
clone.style.zIndex = slot;
clone.classList.add("spriteSlot");
clone.classList.remove("special");
});
let container = QS(".avatar-customizer");
let scene = socket.data.user.scenes ? socket.data.user.scenes.toString().split(",").filter(s => s[0] == ".")[0] : undefined;
if (scene != undefined) {
const sceneID = scene.replace(".", "").split(":")[0];
const sceneShift = scene.split(":")[1];
console.log(sceneID, sceneShift);
let url = socket.data.publicData.scenes.find(_scene => _scene.ID == sceneID).URL;
if(sceneShift) url = "https://static.typo.rip/sprites/rainbow/modulate.php?url=" + url + "&hue=" + sceneShift;
container.style.cssText = `
background-repeat: no-repeat;
background-image: url(${url});
background-size: cover;
background-position: center;
`;
}
else container.style.cssText = ``;
}
else {
QSA(".avatar-customizer .color, .avatar-customizer .eyes, .avatar-customizer .mouth").forEach(n => {
n.style.opacity = 1;
});
}
},
resetCabin: async (authorized = false) => {
const cabin = QS("#cabinSlots");
cabin.innerHTML = `
<div id="loginRedir">
<button class="flatUI air min blue">Log in with Palantir</button>
</div>
<div>Slot 1<p></p></div>
<div>Slot 2<p></p></div>
<div>Slot 3<p></p></div>
<div>Slot 4<p></p></div>
<div>Slot 5<p></p></div>
<div>Slot 6<p></p></div>
<div>Slot 7<p></p></div>
<div>Slot 8<p></p></div>
<div>Slot 9<p></p></div>`;
if (!authorized) {
cabin.classList.add("unauth");
}
else {
// add sprite cabin stuff
let user = await socket.getUser();
const createSlot = (slot, unlocked = false, caption = false, background = false, id = 0) => {
return elemFromString(`<div draggable="true" spriteid="${id}" slotid="${slot}" class="${unlocked ? "unlocked" : ""}" style="background-image:url(${background ?
sprites.getOwnSpriteUrlShifted(id) : ""})">
Slot ${slot}${caption ? "<p>" + (id > 0 ? "Selected #" + id : "Empty") + "</p>" : ""}</div>`);
}
const getCombo = () => {
let slots = [...QSA("#cabinSlots > div:not(#loginRedir)")];
slots = slots.map(slot => { return { slot: slots.indexOf(slot) + 1, sprite: slot.getAttribute("spriteid") }; });
while (slots[slots.length - 1].sprite == 0) slots.pop();
return slots.map(slot => ".".repeat(parseInt(slot.slot)) + slot.sprite)
.join(",");
}
cabin.classList.remove("unauth");
const setSlotSprites = () => {
// clean slots
QSA("#cabinSlots > div:not(#loginRedir)").forEach(slot => slot.remove());
// loop through player slots and check if sprite set on slot
const activeSprites = user.user.sprites.toString().split(",")
.filter(spt => spt.includes("."))
.map(spt => {
return {
id: spt.replaceAll(".", ""),
slot: spt.split(".").length - 1
}
});
for (let slotIndex = 1; slotIndex <= user.slots || slotIndex < 16; slotIndex++) {
const sprite = activeSprites.find(spt => spt.slot == slotIndex);
const id = sprite ? parseInt(sprite.id) : 0;
const background = id > 0;
const unlocked = slotIndex <= user.slots;
cabin.appendChild(createSlot(slotIndex, unlocked, unlocked, background, id));
}
// make grid draggable
const drag = (e) => {
e.preventDefault();
// make preview elem
const preview = createSlot(0, true, false, false, 0);
preview.style.opacity = "0";
e.target.insertAdjacentElement("beforebegin", preview);
// lock element;
const bounds = e.target.getBoundingClientRect();
e.target.style.width = bounds.width + "px";
e.target.style.height = bounds.height + "px";
e.target.style.position = "fixed";
e.target.style.transition = "none";
e.target.style.transform = "translate(-50%, -50%)";
e.target.setAttribute("released", "false");
// move as first child to hover over all children
e.target.parentElement.insertAdjacentElement("afterbegin", e.target);
//listen for mouseup, follow mouse until then
let lastPrevX = 0;
const followMouse = (event) => {
e.target.style.top = event.pageY - document.body.scrollTop + "px";
e.target.style.left = event.pageX + "px";
let hoverDrop = QS("#cabinSlots > div:not(#loginRedir):hover");
if (hoverDrop != e.target) {
if (e.target.style.left < lastPrevX) hoverDrop.insertAdjacentElement("beforebegin", preview);
else hoverDrop.insertAdjacentElement("afterend", preview);
lastPrevX = e.target.style.left;
}
}
const reset = async () => {
document.removeEventListener("pointermove", followMouse);
e.target.style.position = "";
e.target.style.transition = "";
e.target.style.transform = "";
e.target.style.width = "";
e.target.style.height = "";
// move to dragged position
QS("#cabinSlots > div:not(#loginRedir):hover").insertAdjacentElement("afterend", e.target);
preview.remove();
setTimeout(() => {
e.target.setAttribute("released", "true");
}, 100);
let updatedmember = await socket.setSpriteCombo(getCombo());
user.user = updatedmember;
socket.data.user = updatedmember;
setSlotSprites();
sprites.setLandingSprites(true);
}
document.addEventListener("pointerup", reset, { once: true });
document.addEventListener("pointermove", followMouse);
}
QSA("#cabinSlots > div:not(#loginRedir)").forEach(slot => slot.addEventListener("dragstart", drag));
}
setSlotSprites();
cabin.addEventListener("contextmenu", async (event) => {
event.preventDefault();
if (event.target.getAttribute("released") == "false") return;
slotid = event.target.getAttribute("slotid");
if (slotid && event.target.classList.contains("unlocked")) {
const slotNo = parseInt(slotid);
let updatedmember = await socket.setSpriteSlot(slotNo, 0);
socket.data.user = updatedmember;
user.user = updatedmember;
setSlotSprites();
sprites.setLandingSprites(true);
}
});
cabin.addEventListener("click", event => {
if (event.target.getAttribute("released") == "false") return;
slotid = event.target.getAttribute("slotid");
if (slotid) {
const slotNo = parseInt(slotid);
const spriteList = elemFromString(`<div style="width:100%; display:flex; flex-wrap:wrap; justify-content:center;"></div>`);
spriteList.insertAdjacentHTML("beforeend",
"<div class='spriteChoice' sprite='0' style='margin:.5em; height:6em; aspect-ratio:1; background-image:none'></div>");
user.user.sprites.toString().split(",").forEach(spt => {
const id = spt.replaceAll(".", "");
const active = spt.includes(".");
if (!active && id > 0) {
spriteList.insertAdjacentHTML("beforeend",
"<div class='spriteChoice' sprite='" + id + "' style='order: " + id + ";margin:.5em; height:6em; aspect-ratio:1; background-image:url("
+ sprites.getOwnSpriteUrlShifted(id)
+ ")'></div>");
}
});
const picker = new Modal(spriteList, () => { }, "Choose a sprite for slot " + slotNo);
spriteList.addEventListener("click", async event => {
const spt = event.target.getAttribute("sprite");
if (spt) {
picker.close();
let updatedmember = await socket.setSpriteSlot(slotNo, spt);
user.user = updatedmember;
socket.data.user = updatedmember;
setSlotSprites();
sprites.setLandingSprites(true);
}
})
}
});
}
QS("#rightPanelContent #loginRedir").addEventListener("click", login);
},
init: async () => {
// make board behind playerlist so it doesnt hide portions of avatars
const c = QS("#game-players").style.zIndex = "1";
// polling for sprites, observer does not make sense since sprites take a few seconds to be activated
setInterval(sprites.refreshCallback, 2000);
let endboardObserver = new MutationObserver(() => { // mutation observer for game end result
sprites.updateEndboardSprites();
sprites.updateSprites();
});
endboardObserver.observe(QS(".overlay-content .result"), { childList: true, attributes: true });
sprites.getSprites();
}
};
// #content features/genericFunctions.js
// general util functions which have no dependencies
async function typoApiFetch(path, method = "GET", params = {}, body = undefined, userToken = undefined, parseResponse = true) {
const searchParams = new URLSearchParams(params);
const isFirefox = false; // chrome?.runtime?.getURL('').startsWith('moz-extension://') ?? false;
const apiBase = isFirefox ? "https://tobeh.host/newapi" : "https://api.typo.rip";
const url = apiBase + (path.startsWith("/") ? "" : "/") + path;
const request = await fetch(url, {
searchParams: searchParams,
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': userToken ? `Bearer ${userToken}` : undefined
},
body: body ? JSON.stringify(body) : undefined
});
if(parseResponse) return await request.json();
return request.text();
}
//Queryselector bindings
const QS = document.querySelector.bind(document);
const QSA = document.querySelectorAll.bind(document);
/**
* Generate a string by a key, that is hashed by its own value. Can be used to identify a public group token (the hash)
* @param {String} key The key that is hashed against itself
* @returns A hash that can be used for match check
*/
const genMatchHash = key => {
const sum = [...key].reduce((sum, char) => sum + char.charCodeAt(0), 0);
const hashed = [...key].map(char => String.fromCharCode(char.charCodeAt(0) + sum));
const newKey = hashed.join("");
return newKey;
}
/**
* Checks if the hash can be solved with a given key.
* @param {*} hash the self-hash to test against
* @param {*} key the key to solve the hash
* @returns true if the solved hash equals the key.
*/
const solveMatchHash = (hash, key) => {
const sum = [...key].reduce((sum, char) => sum + char.charCodeAt(0), 0);
const unhashed = [...hash].map(char => String.fromCharCode(char.charCodeAt(0) - sum));
const match = unhashed.join("") == key;
return match;
}
const localDateToUtc = ms => new Date(new Date(ms).toISOString().replace("Z", "")).getTime();