-
Notifications
You must be signed in to change notification settings - Fork 4
/
NM trade enhancement.user.js
2701 lines (2519 loc) · 102 KB
/
NM trade enhancement.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 NM trade enhancement
// @namespace 7nik
// @version 2.9.9
// @description Adds enhancements to the trading window
// @author 7nik
// @icon https://github.com/7nik/nm-trade-enhancements/raw/master/app/images/icon.svg
// @homepageURL https://github.com/7nik/nm-trade-enhancements
// @supportURL https://github.com/7nik/nm-trade-enhancements/issues
// @updateURL https://github.com/7nik/nm-trade-enhancements/releases/latest/download/userscript.meta.js
// @downloadURL https://github.com/7nik/nm-trade-enhancements/releases/latest/download/userscript.user.js
// @match https://www.neonmob.com/*
// @grant GM_addStyle
// @grant GM_getValue
// @run-at document-start
// @require https://github.com/rafaelw/mutation-summary/raw/master/src/mutation-summary.js
// @require https://unpkg.com/@popperjs/core@2
// @require https://unpkg.com/tippy.js@6
// ==/UserScript==
/* globals MutationSummary NM angular io tippy */
/* eslint-disable
max-classes-per-file,
sonarjs/cognitive-complexity,
sonarjs/no-duplicate-string,
unicorn/no-fn-reference-in-iterator
*/
"use strict";
const RESET_BUTTON_ICON = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAQAAAD8x0bcAAABNU\
lEQVQoz2NgwAsamFxsQpnxq2FwMnP77CyMV4kDj9t3lyAC5rjnuD+35MRvlbz7GzdjAua4zXDbhkc6lDmU01Hb/Ye7JB7nup91/\
+j+1rUDpxJPPve17s/c/wPhA3dtrEpcpdzWuQe7lrmfcf/s/t/NF8MdHurOAe7PPRxcorwk3Fzd4t0uObCgG8LorOT2zFnLLdpJ\
2bXcQcJF0205irwxq4s70MvtriZARU7uRs56rhPd41y3uIV7BHpY+vFCXOLs/liLzcPSfYfbektOtyQ/Xpcod3+PdI90tyR3b3D\
ceQuCwsNT1F2/gcmtxu2Ea6SzmoOM+363g25tiBi64/7Xjdstz/0UxGr3RW43XPjdot0TQdBSCGKZn1sWA5MDiwMPVBeTq6rbet\
dAD3UQ9OViIA4AAM0mVgxU9d2NAAAAAElFTkSuQmCC`;
const CORE_GEM_ICON = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAMCAYAAAC9QufkAAACTUlEQV\
QoU3VRW0iTYRh+3m/7928rt9LNZaZzSzecCzNqDDWEKAqFyEpZrMPwVDCCIOh610HSTRB0oAPdBNkBlKLb8CK6KDqAGUROiqw12\
8G5/fv/r2/LiV303Hx87/s+PM/7vIQVDNznusJ8sjfgMl5yO6TIsU5putI7fjPV6XdIt4JO4/mFD5gaHCS11KPKwJHLif2qyq52\
e2Snv1F+m8iop8Jdhtfn7mW2L2n8ttcubevYIn8R82f2+OnZCpnT0fFkd1HDpChUdXmN6GiSUVTxc+ZHPjr3S73CCTZ3tQSfQy5\
x0oyhr8eHF9Q/nuzhGq4BvMViZvA1GtBWZ4DJQIgn1dzcomIq2ZP1BK/dAItRV7I7y/UYpYGz0w+UbK5fp2fUGvTAVl8NsyA6q/\
VIZDUspMvrlSFrGtbnFUEmDkYPaWjosTe9uHSnqKiBKpsVO/oCsNqtMAglSUfI5rUyURWv8j0LFMSf4SXXs5MEzilyesqfS2buF\
paVdovNgu5DQdRs2gAS/jgX8zkVv+ez0PIqiOENSdKJsfDGd6tpj45OeBYT+QnhoM3RUIPe8G6Y1xlRFEl+/ZRCPquCMfaeTDg8\
FrJ//OdUXDgYiTzpTGdyN5RC0bvZacPeg7uQSgJLmSKYnmZ0Oj48HK6dJhI7r71zJZRodNKz8C31VDhwtfia4fK4hCJ9tpqMB0I\
hS1mxglXblULJwXDk0b50avm6s7mpodm3NS5JfGQoXPu8ovhfcqkRi8VYPN6+01FXf9Hd6r4wP1vzKhajv7GvwR8AsNgcRdQufw\
AAAABJRU5ErkJggg==`;
const SEARCH_ICON = `'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 \
20 20"><path fill="%239f96a8" d="M 7 0 A 7 7 0 1 0 11 13 L 16 19 A 2 2 0 1 0 19 16 L 13 11 A 7 7 0 \
0 0 7 0 L 7 2 A 5 5 0 0 1 7 12 A 5 5 0 0 1 7 2"/></svg>'`;
GM_addStyle(`
#freebies-nav-btn {
width: 70px;
}
.trade--side--items--loading:empty {
display: none;
}
.pack-tier--pack .pack {
height: 120px;
}
.trade--add-items--filters {
display: flex;
flex-wrap: wrap;
justify-content: stretch;
align-content: space-between;
height: 89px;
}
.trade--add-items--filters input.small.search {
font-size: 12px;
height: auto;
padding: 0.5em 0.6em;
width: 20px;
}
.trade--add-items--filters .filter-sets {
width: calc(49% - 50px);
flex-grow: 1;
}
.trade--add-items--filters input.search:focus {
width: calc(50% - 30px);
margin: 0;
flex-grow: 1;
}
.trade--add-items--filters input.search:focus + .filter-sets {
display: none;
}
.trade--add-items--filters .icon-button {
align-self: flex-end;
padding: 13px 0 0 5px;
font-size: inherit;
width: 30px;
display: none;
cursor: pointer;
}
.trade--add-items--filters .icon-button:hover {
color: #085b85;
}
.trade--add-items--filters span.reset {
font-size: inherit;
text-align: right;
align-self: flex-end;
width: 30px;
cursor: pointer;
}
.trade--add-items--filters span.reset .reset-sett {
display: inline-block;
vertical-align: middle;
width: 18px;
height: 18px;
opacity: 0.8;
background-image: url(${RESET_BUTTON_ICON});
background-size: contain;
background-position: bottom;
background-repeat: no-repeat;
}
.trade--add-items--filters .filter-sets:hover + .icon-button,
.trade--add-items--filters .filter-sets + .icon-button:hover {
display: initial;
}
.trade--add-items--filters .filter-sets:hover + .icon-button + .reset,
.trade--add-items--filters .filter-sets + .icon-button:hover + .reset {
display: none;
}
.trade--add-items--filters select.series{
flex-grow: 1;
}
#print-list .hiddenSeries {
padding: 5px 20px;
border-bottom: 1px solid rgba(0,0,0,.1);
white-space: normal;
}
#print-list .hiddenSeries > span {
font-size: 10px;
color: #9f96a8;
}
#print-list .hiddenSeries span span {
white-space: nowrap;
}
#print-list .hiddenSeries a {
cursor: pointer;
color: #9f96a8;
position: relative;
bottom: -1px;
}
#print-list .hiddenSeries a:hover {
color: #085b85;
}
#print-list .hidden-item {
display: none;
}
.trade--item .icon-button {
margin-left: 0.5ch;
position: relative;
bottom: 1px;
opacity: 0;
color: #9f96a8;
cursor: pointer;
}
.trade--item .search-series-button {
width: 10px;
height: 10px;
background-image: url(${SEARCH_ICON});
}
.trade--item:hover .icon-button {
opacity: 1;
}
.trade--item .card-trading {
font-size: 13px;
position: absolute;
top: 15px;
right: 20px;
}
.trade--item .print-chooser {
border: none;
background: none;
color: #5f5668;
cursor: pointer;
}
#trade--search--empty {
animation: fadeIn 0s 0.15s backwards;
}
* ~ #trade--search--empty {
opacity: 0;
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
.tippy-box[data-theme~='trade'] {
background: #efefef;
border-radius: 5px;
filter: drop-shadow(0 1px 4px rgb(0, 0, 0, 0.35));
width: 280px;
max-width: 280px;
}
.tippy-box[data-theme~='trade'] .tippy-arrow {
color: #efefef;
}
.tippy-box[data-theme~='trade'] header {
padding: 7px;
border-bottom: 1px solid rgba(0,0,0,.1);
text-align: center;
user-select: none;
}
.tippy-box[data-theme~='trade'] header a {
cursor: pointer;
font-weight: 500;
padding: 1px 4px;
border-radius: 7px;
}
.tippy-box[data-theme~='trade'] header a.off {
color: #888;
cursor: initial;
}
.tippy-box[data-theme~='trade'] header a:not(.off):hover {
background: rgba(0,0,0,.15);
}
.tippy-box[data-theme~='trade'][data-theme~='sidebar'] {
box-shadow: 1px 1px 7px rgba(0, 0, 0, .15);
}
.tippy-box[data-theme~='trade'][data-theme~='sidebar'] .btn {
display: none;
}
.tippy-box[data-theme~='tooltip'] {
max-width: 250px;
background: #FBF8CF;
color: #2c2830;
box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
}
.tippy-box[data-theme~='tooltip'] .tippy-arrow {
color: #FBF8CF;
}
.tippy-box[data-theme~='tooltip'] .i {
width: 18px;
height: 15px;
margin: 0 0 3px 2px;
}
.tippy-box[data-theme~='tooltip'] .i.core {
background-image: url(${CORE_GEM_ICON});
background-size: auto;
width: 15px;
}
.tippy-box[data-theme~='tooltip'] .pipe {
margin-bottom: 4px;
}
#messages {
display: flex;
flex-direction: column;
height: 100vh;
}
#messages .last-action {
font-size: 9pt;
color: #857a90;
}
#messages > :last-child {
overflow: auto;
flex-grow: 1;
}
#messages .comments {
height: 100%;
display: flex;
flex-direction: column;
}
#messages .comments--list--container {
flex-shrink: 1;
flex-grow: 1;
position: initial;
}
#messages .comments--field:not(:only-child) {
position: initial;
}
.btn.wislist-btn {
padding: 14px 18px;
}
#wishlist--animate {
position: fixed;
top: 0;
height: 100vh;
width: 100vw;
background: rgba(37,26,48,.9);
z-index: 5;
color: silver;
}
#wishlist--animate > i {
position: absolute;
font-size: 20pt;
animation-name: flyout;
animation-duration: var(--time);
animation-fill-mode: forwards;
}
@keyframes flyout {
from {
top: var(--startY);
left: var(--startX);
}
to {
top: var(--endY);
left: var(--endX);
}
}
div.set-header--collect-it + div.set-header--collect-it {
display: none;
}
.gray-card img {
filter: grayscale(1);
}
/* block showing of video context menu */
.piece-video.original::after {
content: "";
display: block;
width: 100%;
height: 100%;
position: absolute;
top: 0;
}
.collection--prints .card-trading-icon {
position: absolute;
left: 3%;
top: 3%;
}
.collection--prints .card-trading-icon:not([data-length="0"]) {
cursor: pointer;
z-index: 4;
color: white;
box-shadow: 1.5px -1.5px white, -1.5px 1.5px white, 1.5px 1.5px white, -1.5px -1.5px white;
font-size: 9pt;
background: black;
padding: 2px;
margin: 5px;
opacity: 0.85;
transform: rotate(45deg);
line-height: 1;
}
.card-trading-icon:not([data-length="0"])::before {
display: inline-block;
font-family: 'glyphter nm icon font';
content: '\\0053';
}
.collection--prints .card-trading-icon:not([data-length="0"])::before {
vertical-align: top;
transform: rotate(-45deg);
}
.set-checklist .card-trading-icon:not([data-length="0"])::before {
vertical-align: text-top;
font-size: 12px;
color: #857a90;
}
.collection--prints [ng-if="!piece.own_count"] ~ .card-trading-icon {
opacity: 0.5;
}
.trade-preview--print.highlight-card {
border-radius: 5px;
box-shadow: 0 2px 5px #8400ff;
}
`);
const cardsInTrades = (() => {
let res;
return {
lastUpdate: -1,
receive: {},
give: {},
loading: new Promise((resolve) => { res = resolve; }),
ready () {
cardsInTrades.loading = false;
res();
},
/**
* Returns list of trades where the given card is involved
* @param {object} print - the involved card
* @param {("give"|"receive"|"both")} dir - how the card should be involved in a trade
* @param {("print"|"card")} level - look for a certain print or all prints
* @return {Promise<number[]>} - list of trade IDs
*/
getTrades: async (print, dir = "both", level = "print") => {
if (cardsInTrades.loading) await cardsInTrades.loading;
const tradeIds = [];
if (!print) return tradeIds;
if (level === "print") {
if (dir === "give" || dir === "both") {
tradeIds.push(...cardsInTrades.give[print.id]?.[print.print_id] ?? []);
}
if (dir === "receive" || dir === "both") {
tradeIds.push(...cardsInTrades.receive[print.id]?.[print.print_id] ?? []);
}
} else {
if (cardsInTrades.give[print.id] && (dir === "give" || dir === "both")) {
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (const pid in cardsInTrades.give[print.id]) {
tradeIds.push(...cardsInTrades.give[print.id][pid]);
}
}
if (cardsInTrades.receive[print.id] && (dir === "receive" || dir === "both")) {
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (const pid in cardsInTrades.receive[print.id]) {
tradeIds.push(...cardsInTrades.receive[print.id][pid]);
}
}
}
return tradeIds;
},
/**
* Updates usage in trades for the given print
* @param {number} tradeId - the trade ID with the print
* @param {("give"|"receive")} side - how the print is involved in the trade
* @param {number} cid - card ID
* @param {number} pid - print ID
* @param {(-1,+1)} change - remove or add the print
*/
updatePrint: (tradeId, side, cid, pid, change) => {
if (!(cid in cardsInTrades[side])) cardsInTrades[side][cid] = {};
if (!(pid in cardsInTrades[side][cid])) cardsInTrades[side][cid][pid] = [];
if (change > 0) {
cardsInTrades[side][cid][pid].push(tradeId);
} else {
cardsInTrades[side][cid][pid] = cardsInTrades[side][cid][pid]
.filter((id) => id !== tradeId);
}
cardsInTrades.lastUpdate = Date.now();
},
};
})();
const templatePatches = [];
const debug = (...args) => console.debug("[NM trade enhancement]", ...args);
/**
* Wrapper of trade object
*/
class Trade {
/**
* Wrapper for trade info object
* @param {Object} trade - Trade info object
*/
constructor (trade) {
this.id = trade.id;
this.state = trade.state;
const youAreBidder = trade.bidder.id === NM.you.attributes.id;
this.you = youAreBidder ? trade.bidder : trade.responder;
this.yourOffer = youAreBidder ? trade.bidder_offer.prints : trade.responder_offer.prints;
this.yourOffer.reverse().sort((a, b) => b.rarity.rarity - a.rarity.rarity);
this.partner = youAreBidder ? trade.responder : trade.bidder;
this.parnerOffer = youAreBidder ? trade.responder_offer.prints : trade.bidder_offer.prints;
this.parnerOffer.reverse().sort((a, b) => b.rarity.rarity - a.rarity.rarity);
}
/**
* Creates the trade preview
* @return {HTMLElement} Element with trade preview
*/
makeTradePreview (highlightCardId) {
const a = document.createElement("a");
a.className = "trade-preview";
a.href = `?view-trade=${this.id}`;
a.innerHTML = `
<div class="trade-preview--give">
<div class="trade-preview--heading small-caps">You will give</div>
${this.yourOffer.map(Trade.makeThumb).join("")}
</div>
<div class="trade-preview--get">
<div class="trade-preview--heading small-caps">${this.partner.name} will give</div>
${this.parnerOffer.map(Trade.makeThumb).join("")}
</div>
<div class="btn small trade-preview--action">View Trade</div>`;
// eslint-disable-next-line no-underscore-dangle
a.addEventListener("click", () => a._tippy?.hide());
if (highlightCardId) {
const card = a.querySelector(`[data-print-id="${highlightCardId}"`);
if (card) card.classList.add("highlight-card");
}
return a;
}
/**
* Creates small thumbnail of a print
* @param {Object} print - Print for thumbnailing
* @return {string} HTML code of the thumbnail
*/
static makeThumb (print) {
return `
<span class="trade-preview--print" data-print-id="${print.id}">
<div class="piece small fluid">
<figure class="front">
<img class="asset" src="${print.piece_assets.image.small.url}">
<span class="piece-info">
<i class="i tip ${print.rarity.class}"></i>
</span>
</figure>
</div>
</span>`;
}
/**
* Gets and caches info about a trade by its id
* @param {number|string} tradeId - Trade id
* @param {boolean} [useCache=true] - May use cache or forcely do request
* @return {Promise<Trade>} trade info
*/
static async get (tradeId, useCache = true) {
if (!Trade.cache[tradeId] || !useCache) {
Trade.cache[tradeId] = await api("api", `/trades/${tradeId}/`);
saveValue("tradesCache", Trade.cache);
}
return new Trade(Trade.cache[tradeId]);
}
static cache = (() => {
const trades = loadValue("tradesCache", { minDate: 0 });
// remove outdated trades
Reflect.ownKeys(trades).forEach((id) => {
if (new Date(trades[id].expire_date) < trades.minDate) {
delete trades[id];
}
});
return trades;
})()
}
/**
* A collection of items with property id
*/
class Collection {
/**
* Constructor.
* @param {string} name - Name loading and saving the collection
* @param {?object[]} items - The collection.
* If not provided, will be loaded from `localStoreage`.
*/
constructor (name, items) {
this.name = name;
if (items) {
this.items = items;
this.save();
} else {
this.items = loadValue(name, []);
}
}
/**
* Save the collection to `localStorage` if name provided.
*/
save () { if (this.name) saveValue(this.name, this.items); }
/**
* Adds items to the collection with overwriting existing one and saves the collection.
* @param {object|object[]|Collection} items - Item(s) to add.
*/
add (items) {
if (items.trades) items = items.trades;
if (!Array.isArray(items)) items = [items];
this.items = this.items.filter((item) => !items.find(({ id }) => id === item.id));
this.items.unshift(...items);
this.save();
}
/**
* Removes given items from the collection or, if provided function, filters them and saves.
* @param {object|object[]|Collection|function} items - Items to remove or, if it's function,
* uses it find items for removing.
*/
remove (items) {
if (typeof items === "function") {
this.items = this.items.filter((item) => !items(item));
} else {
if (items.trades) items = items.trades;
if (!Array.isArray(items)) items = [items];
items.forEach((item) => {
const index = this.items.findIndex(({ id }) => id === item.id);
if (index >= 0) this.items.splice(index, 1);
});
}
this.save();
}
/**
* Applies given function to every item.
* @param {function} fn - Function to apply to a item.
*/
forEach (fn) {
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
this.items.forEach(fn);
}
/**
* Applies given function to every item and returns arrays of results.
* @param {function} fn - Function to apply to a item.
* @return {any[]} Array of results.
*/
map (fn) {
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
return this.items.map(fn);
}
/**
* Get number of items in the collection.
* @return {number} - Number of items in the collection.
*/
get count () { return this.items.length; }
/**
* Make the collection iterable
*/
* [Symbol.iterator] () {
yield* this.items;
}
}
/**
* Reads a saved value from `localStorage` if presented, otherwise - default value
* @param {string} name - Name of the value
* @param {?any} defValue - Default value of the value
* @return {any} Saved or default value
*/
function loadValue (name, defValue) {
const fullName = "NM_trade_enhancements_".concat(name);
if (fullName in localStorage) {
return JSON.parse(localStorage[fullName]);
}
// TODO: rid of GM_getValue
const value = GM_getValue(name, defValue);
if (value !== defValue) saveValue(name, value);
return value;
}
/**
* Saves a value to `localStorage`
* @param {string} name - Name of the value
* @param {any} value - Value to save
*/
function saveValue (name, value) {
const fullName = "NM_trade_enhancements_".concat(name);
localStorage[fullName] = JSON.stringify(value);
}
/**
* Converts string to The Camel Case
* @param {string} str - String for converting
* @return {string} String in the camel case
*/
function toPascalCase (str) {
return str
.trim()
.replace(/\s+/g, " ")
.split(" ")
.map((s) => s[0].toUpperCase().concat(s.slice(1).toLowerCase()))
.join(" ");
}
/**
* Returns a scope binded to the element
* @param {HTMLElement} element - Element
* @return {Object} Binded scope
*/
function getScope (element) {
return angular.element(element).scope();
}
/**
* API call to server
* @param {("api"|"napi"|"root")} type - Which API scheme use
* @param {string} url - Relative URL to API
* @param {object} [body] - Body (params) of the request
* @return {Promise<Object>} Parsed JSON response
*/
function api (type, url, body) {
let fullUrl;
switch (type) {
case "api": fullUrl = `https://www.neonmob.com/api${url}`; break;
case "napi": fullUrl = `https://napi.neonmob.com${url}`; break;
case "root": fullUrl = `https://www.neonmob.com${url}`; break;
default: fullUrl = url;
}
// forbid parallel requests
this.lastRequest = (this.lastRequest ?? Promise.resolve())
.then(() => fetch(fullUrl, body), () => fetch(fullUrl, body))
.then((res) => res.json());
return this.lastRequest;
}
/**
* Will call the callback for existing and added elements which match the selector
* @param {HTMLElement} rootNode - In whose subtree wait for the elements
* @param {string} selector - Selector of the target elements
* @param {function(HTMLElement): undefined} callback - Callback applied to the elements
*/
function forAllElements (rootNode, selector, callback) {
rootNode.querySelectorAll(selector).forEach((elem) => callback(elem));
new MutationSummary({
rootNode,
queries: [{ element: selector }],
callback: (summaries) => summaries[0].added.forEach((elem) => callback(elem)),
});
}
/**
* Returns a promise which will be resolved when the element appears
* @param {HTMLElement} rootNode - In whose subtree wait for the element
* @param {string} selector - Selector of the target element
* @return {Promise<HTMLElement>} The added element
*/
function waitForElement (rootNode, selector) {
const element = rootNode.querySelector(selector);
if (element) return Promise.resolve(element);
return new Promise((resolve) => {
const observer = new MutationSummary({
rootNode,
queries: [{ element: selector }],
callback: (summaries) => {
observer.disconnect();
resolve(summaries[0].added[0]);
},
});
});
}
/**
* Adds listeners to creating and finishing trades
* @param {function(trades[])} onloaded - Handler for currently pending trades
* @param {function(trade)} onadded - Handler for new trades
* @param {function(trade)} onremoved - Handler for trades finished in any way
*/
function onTradeChange (onloaded, onadded, onremoved) {
if (!unsafeWindow.io) {
setTimeout(onTradeChange, 100, onloaded, onadded, onremoved);
return;
}
const socketTrades = io.connect(
"https://napi.neonmob.com/trades",
{ transports: ["websocket"] },
);
if (onloaded) socketTrades.on("loadInitial", ({ results }) => onloaded(results));
if (onadded) socketTrades.on("addItem", (result) => onadded(result));
if (onremoved) socketTrades.on("removeItem", (result) => onremoved(result));
}
/**
* Gets and caches info about a series by its id
* @param {(number|string)} settId - Series id
* @return {Promise<Object>} series info
*/
function getSeriesInfo (settId) {
if (!getSeriesInfo[settId]) {
getSeriesInfo[settId] = api("api", `/setts/${settId}/`);
getSeriesInfo[settId].then((data) => {
getSeriesInfo[settId] = data;
});
}
return getSeriesInfo[settId];
}
/**
* Keep data in the variable `cardsInTrades` syncronized with pending
*/
async function updateCardsInTrade () {
const updateTrade = async ({ object: { id } }, change) => {
const trade = await Trade.get(id);
trade.yourOffer.forEach(({ id: cid, print_id: pid }) => {
cardsInTrades.updatePrint(id, "give", cid, pid, change);
});
trade.parnerOffer.forEach(({ id: cid, print_id: pid }) => {
cardsInTrades.updatePrint(id, "receive", cid, pid, change);
});
};
onTradeChange(
(initialTrades) => {
Promise.all(initialTrades.map((trade) => updateTrade(trade, +1)))
.then(cardsInTrades.ready);
},
(addedTrade) => {
updateTrade(addedTrade, +1);
},
(removedTrade) => {
updateTrade(removedTrade, -1);
},
);
}
/**
* Add notifications of auto-withdrawn trades
*/
function fixAutoWithdrawnTrade () {
if (!unsafeWindow.io) {
setTimeout(fixAutoWithdrawnTrade, 100);
return;
}
let pendingTrades = new Collection("pendingTrades");
const hiddenTrades = new Collection("hiddenTrades");
const socketNotif = io.connect(
"https://napi.neonmob.com/notifications",
{ transports: ["websocket"] },
);
/**
* Show trade in notification if it was auto-withdrawn
* @param {object} trade - Trade info
*/
function addAutoWithdrawnNotification (trade) {
if (trade.verb_phrase !== "auto-withdrew") return;
trade.read = false;
hiddenTrades.add(trade);
// add the trade to notifications
socketNotif.listeners("addItem")[0]?.(trade);
}
socketNotif.on("loadInitial", ({ results: notifications }) => {
const minTime = new Date(notifications[notifications.length - 1].actor.time).getTime();
Trade.cache.minDate = minTime;
hiddenTrades.remove((trade) => new Date(trade.actor.time) < minTime);
if (hiddenTrades.count > 0) {
const [addItem] = socketNotif.listeners("addItem");
if (addItem) {
hiddenTrades.forEach((trade) => addItem(trade));
} else {
notifications.push(...hiddenTrades);
}
}
});
onTradeChange(
(initialTrades) => {
pendingTrades.remove(initialTrades);
pendingTrades.forEach(async (trade) => {
trade.verb_phrase = (await Trade.get(trade.object.id, false)).state;
addAutoWithdrawnNotification(trade);
});
pendingTrades = new Collection("pendingTrades", initialTrades);
},
(addedTrade) => {
pendingTrades.add(addedTrade);
},
(removedTrade) => {
pendingTrades.remove(removedTrade);
addAutoWithdrawnNotification(removedTrade);
},
);
// synchronize added notification status when they get read
window.addEventListener("click", ({ target }) => {
// when clicked the notification
const notifElem = target.closest("li.nm-notifications-feed--item");
if (notifElem) {
const { notification } = getScope(notifElem);
if (notification.verb_phrase === "auto-withdrew") {
if (notification.read) return;
// replace trade with read copy to avoid side-effect and save
hiddenTrades.add({ ...notification, read: true });
}
// when clicked "Mark all read"
} else if (target.matches("a.text-link")) {
// replace trades with read copies to avoid side-effect and save
hiddenTrades.forEach((trade) => {
if (!trade.read) hiddenTrades.add({ ...trade, read: true });
});
}
}, true);
}
/**
* Fixes the Open Pack button color for series with additional freebie packs
* @param {HTMLElement} button - <span.collect-it-button>
*/
async function fixFreebieCount (button) {
const { sett } = getScope(button);
// skip discontinued, unreleased, limited
if (sett.discontinued
|| new Date(sett.released) > Date.now()
|| sett.edition_size === "limited"
) {
return;
}
// assume all series with extra freebies packs have the same number of them
// use value from the previous visit
let realFreebiesNumber = loadValue("realFreebiesNumber", 3);
if (realFreebiesNumber !== 3) {
sett.daily_freebies = realFreebiesNumber;
}
// get the current number of freebies
const numberUpdated = fixFreebieCount.numberUpdated
?? (fixFreebieCount.numberUpdated = api("api", `/pack-tiers/?sett_id=${sett.id}`)
.then((packs) => packs
.filter((pack) => pack.currency === "freebie")
// eslint-disable-next-line unicorn/no-reduce
.reduce((num, pack) => num + pack.count, 0))
.then((freebieNumber) => {
if (realFreebiesNumber !== freebieNumber) {
realFreebiesNumber = freebieNumber;
saveValue("realFreebiesNumber", freebieNumber);
return true;
}
return false;
}));
if (await numberUpdated) {
sett.daily_freebies = realFreebiesNumber;
}
}
/**
* Adds how ago was last action of the user
* @param {HTMLElement} header - <div.nm-conversation--header>
*/
async function addLastActionAgo (header, watchForChanges = true) {
const userId = getScope(header).recipient.id;
const lastActionAgo = await api("napi", `/activityfeed/user/${userId}/?amount=5&page=1`)
.then((data) => data[0]?.created ?? "one eternity ago");
const div = document.createElement("div");
div.className = "last-action";
div.innerHTML = `last action: <i>${lastActionAgo}</i>`;
header.querySelector(".nm-conversation--header h3").append(div);
if (watchForChanges === false) return;
new MutationSummary({
rootNode: header.querySelector(".nm-conversation--header h3 a"),
queries: [{ characterData: true }],
callback: (summaries) => {
header.querySelector(".last-action")?.remove();
addLastActionAgo(header, false);
},
});
}
/**
* Adds to pending trades in the sidebar priviews
* @param {HTMLElement} notification - <li.nm-notification> or <li.nm-notifications-feed--item>
*/
async function addTradePreview (notification) {
const scope = getScope(notification);
if (scope.notification && scope.notification.object.type !== "trade-event") return;
const tradeId = (scope.notification ?? scope.trade).object.id;
const tip = tippy(notification, {
onTrigger: async (instance) => {
if (instance.props.content) return;
addTradePreview.currentTradeId = tradeId;
const preview = (await Trade.get(tradeId)).makeTradePreview();
// set only if it still actuall
if (addTradePreview.currentTradeId === tradeId) {
instance.setContent(preview);
}
},
onShow: (instance) => document.body.contains(notification),
});
const tips = addTradePreview.tips ?? (addTradePreview.tips = {});
tips[tradeId] = tip;
const singleton = addTradePreview.singleton
?? (addTradePreview.singleton = tippy.createSingleton([tip], {
delay: [600, 200],
placement: "left",
theme: "trade sidebar",
overrides: ["onTrigger", "onShow"],
}));
singleton.setInstances(Object.values(tips));
}
/**
* Allows you to confirm/decline a confirm message and close a trade by keyboard.
* @param {Event} ev - keyup event
*/
function addHotkeys (ev) {
if (["Enter", "NumpadEnter", "Space"].includes(ev.code)
&& document.querySelector("#message.show #confirm-btn, #alert.show #alert-btn")
) {
document.querySelector("#message.show #confirm-btn, #alert.show #alert-btn").click();
ev.preventDefault();
ev.stopPropagation();
}
if (ev.code === "Escape") {
// if a confirm message is shown
if (document.querySelector("#message.show #cancel-btn")) {
document.querySelector("#message.show #cancel-btn").click();
ev.stopPropagation();
// if a trade window is open
} else if (document.querySelector(".nm-modal--actionbar--left")) {
document.querySelector(".nm-modal--actionbar--left").click();
ev.stopPropagation();
}