-
Notifications
You must be signed in to change notification settings - Fork 0
/
mousehunt-utils.js
3244 lines (2810 loc) · 94.5 KB
/
mousehunt-utils.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 🐭️ MouseHunt Utils
// @author bradp
// @version 1.11.0
// @description MouseHunt Utils is a library of functions that can be used to make other MouseHunt userscripts easily.
// @license MIT
// @namespace bradp
// @match https://www.mousehuntgame.com/*
// @icon https://i.mouse.rip/mouse.png
// @grant none
// ==/UserScript==
/* eslint-disable no-unused-vars */
/**
* Add styles to the page.
*
* @author bradp
* @since 1.0.0
*
* @example <caption>Basic usage</caption>
* addStyles(`.my-class {
* color: red;
* }`);
*
* @example <caption>With an identifier</caption>
* addStyles(`.my-class {
* display: none;
* }`, 'my-identifier');
*
* @example <caption>With an identifier, but will only add the styles once</caption>
* addStyles(`.my-other-class {
* color: blue;
* }`, 'my-identifier', true);
*
* @param {string} styles The styles to add.
* @param {string} identifier The identifier to use for the style element.
* @param {boolean} once Only add the styles once for the identifier.
*
* @return {Element} The style element.
*/
const addStyles = (styles, identifier = 'mh-utils-custom-styles', once = false) => {
identifier = `mh-utils-${identifier}`;
// Check to see if the existing element exists.
const existingStyles = document.getElementById(identifier);
// If so, append our new styles to the existing element.
if (existingStyles) {
if (once) {
return existingStyles;
}
existingStyles.innerHTML += styles;
return existingStyles;
}
// Otherwise, create a new element and append it to the head.
const style = document.createElement('style');
style.id = identifier;
style.innerHTML = styles;
document.head.appendChild(style);
return style;
};
/**
* Do something when ajax requests are completed.
*
* @author bradp
* @since 1.0.0
*
* @example <caption>Basic usage</caption>
* onRequest((response) => {
* console.log(response);
* }, 'managers/ajax/turns/activeturn.php');
*
* @example <caption>Basic usage, but skip the success check</caption>
* onRequest((response) => {
* console.log(response);
* }, 'managers/ajax/turns/activeturn.php', true);
*
* @example <caption>Basic usage, running for all ajax requests</caption>
* onRequest((response) => {
* console.log(response);
* });
*
* @param {Function} callback The callback to call when an ajax request is completed.
* @param {string} url The url to match. If not provided, all ajax requests will be matched.
* @param {boolean} skipSuccess Skip the success check.
*/
const onRequest = (callback, url = null, skipSuccess = false) => {
const req = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
this.addEventListener('load', function () {
if (this.responseText) {
let response = {};
try {
response = JSON.parse(this.responseText);
} catch (e) {
return;
}
if (response.success || skipSuccess) {
if (! url) {
callback(response);
return;
}
if (this.responseURL.indexOf(url) !== -1) {
callback(response);
}
}
}
});
req.apply(this, arguments);
};
};
const onAjaxRequest = onRequest;
/**
* Run the callbacks depending on visibility.
*
* @author bradp
* @since 1.0.0
*
* @ignore
*
* @param {Object} settings Settings object.
* @param {Node} parentNode The parent node.
* @param {Object} callbacks The callbacks to run.
*
* @return {Object} The settings.
*/
const runCallbacks = (settings, parentNode, callbacks) => {
// Loop through the keys on our settings object.
Object.keys(settings).forEach((key) => {
// If the parentNode that's passed in contains the selector for the key.
if (parentNode && parentNode.classList && parentNode.classList.contains(settings[key].selector)) {
// Set as visible.
settings[key].isVisible = true;
// If there is a show callback, run it.
if (callbacks[key] && callbacks[key].show) {
callbacks[key].show();
}
} else if (settings[key].isVisible) {
// Mark as not visible.
settings[key].isVisible = false;
// If there is a hide callback, run it.
if (callbacks[key] && callbacks[key].hide) {
callbacks[key].hide();
}
}
});
return settings;
};
/**
* Do something when the overlay is shown or hidden.
*
* @param {Object} callbacks
* @param {Function} callbacks.show The callback to call when the overlay is shown.
* @param {Function} callbacks.hide The callback to call when the overlay is hidden.
* @param {Function} callbacks.change The callback to call when the overlay is changed.
*/
const onOverlayChange = (callbacks) => {
// Track the different overlay states.
let overlayData = {
map: {
isVisible: false,
selector: 'treasureMapPopup'
},
item: {
isVisible: false,
selector: 'itemViewPopup'
},
mouse: {
isVisible: false,
selector: 'mouseViewPopup'
},
image: {
isVisible: false,
selector: 'largerImage'
},
convertible: {
isVisible: false,
selector: 'convertibleOpenViewPopup'
},
adventureBook: {
isVisible: false,
selector: 'adventureBookPopup'
},
marketplace: {
isVisible: false,
selector: 'marketplaceViewPopup'
},
gifts: {
isVisible: false,
selector: 'giftSelectorViewPopup'
},
support: {
isVisible: false,
selector: 'supportPageContactUsForm'
},
premiumShop: {
isVisible: false,
selector: 'MHCheckout'
}
};
// Observe the overlayPopup element for changes.
const observer = new MutationObserver(() => {
if (callbacks.change) {
callbacks.change();
}
// Grab the overlayPopup element and make sure it has classes on it.
const overlayType = document.getElementById('overlayPopup');
if (overlayType && overlayType.classList.length <= 0) {
return;
}
// Grab the overlayBg and check if it is visible or not.
const overlayBg = document.getElementById('overlayBg');
if (overlayBg && overlayBg.classList.length > 0) {
// If there's a show callback, run it.
if (callbacks.show) {
callbacks.show();
}
} else if (callbacks.hide) {
// If there's a hide callback, run it.
callbacks.hide();
}
// Run all the specific callbacks.
overlayData = runCallbacks(overlayData, overlayType, callbacks);
});
// Observe the overlayPopup element for changes.
const observeTarget = document.getElementById('overlayPopup');
if (observeTarget) {
observer.observe(observeTarget, {
attributes: true,
attributeFilter: ['class']
});
}
};
/**
* TODO: update this docblock.
*
* @param {*} callback
*/
const onOverlayClose = (callback) => {
eventRegistry.addEventListener('js_dialog_hide', callback);
};
/**
* TODO: update this docblock.
*/
const getDialogMapping = () => {
return {
treasureMapPopup: 'map',
itemViewPopup: 'item',
mouseViewPopup: 'mouse',
largerImage: 'image',
convertibleOpenViewPopup: 'convertible',
adventureBookPopup: 'adventureBook',
marketplaceViewPopup: 'marketplace',
giftSelectorViewPopup: 'gifts',
supportPageContactUsForm: 'support',
MHCheckout: 'premiumShop',
};
};
/**
* TODO: update this docblock.
*
* @param {*} callback
* @param {*} overlay
* @param {*} once
*/
const onDialogShow = (callback, overlay = null, once = false) => {
eventRegistry.addEventListener('js_dialog_show', () => {
if (! activejsDialog) {
return;
}
// Get all the tokens and check the content.
const tokens = activejsDialog.getAllTokens();
// Make sure we have the 'content' key.
// For item and mouse views, the entire event fires twice, once while loading and
// once when the content is loaded. We only want to run this once, so we check if
// the content is empty in a weird way.
if (
! tokens ||
! tokens['{*content*}'] ||
! tokens['{*content*}'].value ||
tokens['{*content*}'].value === '' ||
tokens['{*content*}'].value.indexOf('data-item-type=""') > -1 || // Item view.
tokens['{*content*}'].value.indexOf('data-mouse-id=""') > -1 // Mouse view.
) {
return;
}
// Grab the attributes of the dialog to determine the type.
const atts = activejsDialog.getAttributes();
const dialogType = atts.className
.replace('jsDialogFixed', '')
.replace('wide', '')
.replace('default', '')
.replaceAll(' ', ' ')
.replaceAll(' ', '.')
.trim();
// Make sure this only ran once within the last 100ms for the same overlay.
if (window.mhutils?.lastDialog?.overlay === dialogType && (Date.now() - window.mhutils.lastDialog.timestamp) < 250) {
return;
}
const lastDialog = {
overlay: dialogType,
timestamp: Date.now(),
};
window.mhutils = window.mhutils ? { ...window.mhutils, ...lastDialog } : lastDialog;
if (! overlay && 'function' === typeof callback) {
return callback();
}
const dialogMapping = getDialogMapping();
if ('function' === typeof callback && (overlay === dialogType || overlay === dialogMapping[dialogType])) {
return callback();
}
}, null, once);
};
/**
* TODO: update this docblock.
*
* @param {*} callback
* @param {*} overlay
* @param {*} once
*/
const onDialogHide = (callback, overlay = null, once = false) => {
eventRegistry.addEventListener('js_dialog_hide', () => {
const dialogType = window?.mhutils?.lastDialog?.overlay || null;
window.mhutils.lastDialog = {};
if (! overlay) {
return callback();
}
const dialogMapping = getDialogMapping();
if (overlay === dialogType || overlay === dialogMapping[dialogType]) {
return callback();
}
}, null, once);
};
/**
* Do something when the page or tab changes.
*
* @param {Object} callbacks
* @param {Function} callbacks.show The callback to call when the page is navigated to.
* @param {Function} callbacks.hide The callback to call when the page is navigated away from.
* @param {Function} callbacks.change The callback to call when the page is changed.
*/
const onPageChange = (callbacks) => {
// Track our page tab states.
let tabData = {
blueprint: { isVisible: null, selector: 'showBlueprint' },
tem: { isVisible: false, selector: 'showTrapEffectiveness' },
trap: { isVisible: false, selector: 'editTrap' },
camp: { isVisible: false, selector: 'PageCamp' },
travel: { isVisible: false, selector: 'PageTravel' },
inventory: { isVisible: false, selector: 'PageInventory' },
shop: { isVisible: false, selector: 'PageShops' },
mice: { isVisible: false, selector: 'PageAdversaries' },
friends: { isVisible: false, selector: 'PageFriends' },
sendSupplies: { isVisible: false, selector: 'PageSupplyTransfer' },
team: { isVisible: false, selector: 'PageTeam' },
tournament: { isVisible: false, selector: 'PageTournament' },
news: { isVisible: false, selector: 'PageNews' },
scoreboards: { isVisible: false, selector: 'PageScoreboards' },
discord: { isVisible: false, selector: 'PageJoinDiscord' },
preferences: { isVisible: false, selector: 'PagePreferences' },
profile: { isVisible: false, selector: 'HunterProfile' },
};
// Observe the mousehuntContainer element for changes.
const observer = new MutationObserver(() => {
// If there's a change callback, run it.
if (callbacks.change) {
callbacks.change();
}
// Grab the container element and make sure it has classes on it.
const mhContainer = document.getElementById('mousehuntContainer');
if (mhContainer && mhContainer.classList.length > 0) {
// Run the callbacks.
tabData = runCallbacks(tabData, mhContainer, callbacks);
}
});
// Observe the mousehuntContainer element for changes.
const observeTarget = document.getElementById('mousehuntContainer');
if (observeTarget) {
observer.observe(observeTarget, {
attributes: true,
attributeFilter: ['class']
});
}
};
/**
* Do something when the trap tab is changed.
*
* @param {Object} callbacks
*/
const onTrapChange = (callbacks) => {
// Track our trap states.
let trapData = {
bait: {
isVisible: false,
selector: 'bait'
},
base: {
isVisible: false,
selector: 'base'
},
weapon: {
isVisible: false,
selector: 'weapon'
},
charm: {
isVisible: false,
selector: 'trinket'
},
skin: {
isVisible: false,
selector: 'skin'
}
};
// Observe the trapTabContainer element for changes.
const observer = new MutationObserver(() => {
// Fire the change callback.
if (callbacks.change) {
callbacks.change();
}
// If we're not viewing a blueprint tab, bail.
const mhContainer = document.getElementById('mousehuntContainer');
if (mhContainer.classList.length <= 0 || ! mhContainer.classList.contains('showBlueprint')) {
return;
}
// If we don't have the container, bail.
const trapContainerParent = document.querySelector('.campPage-trap-blueprintContainer');
if (! trapContainerParent || ! trapContainerParent.children || ! trapContainerParent.children.length > 0) {
return;
}
// If we're not in the itembrowser, bail.
const trapContainer = trapContainerParent.children[0];
if (! trapContainer || trapContainer.classList.length <= 0 || ! trapContainer.classList.contains('campPage-trap-itemBrowser')) {
return;
}
// Run the callbacks.
trapData = runCallbacks(trapData, trapContainer, callbacks);
});
// Grab the campPage-trap-blueprintContainer element and make sure it has children on it.
const observeTargetParent = document.querySelector('.campPage-trap-blueprintContainer');
if (! observeTargetParent || ! observeTargetParent.children || ! observeTargetParent.children.length > 0) {
return;
}
// Observe the first child of the campPage-trap-blueprintContainer element for changes.
const observeTarget = observeTargetParent.children[0];
if (observeTarget) {
observer.observe(observeTarget, {
attributes: true,
attributeFilter: ['class']
});
}
};
/**
* Add something to the event registry.
*
* @param {string} event The event name.
* @param {Function} callback The callback to run when the event is fired.
* @param {boolean} remove Whether or not to remove the event listener after it's fired.
*/
const onEvent = (event, callback, remove = false) => {
eventRegistry.addEventListener(event, callback, null, remove);
};
/**
* Do something when the user travels to a location.
*
* @param {string} location The location traveled to.
* @param {Object} options The options
* @param {string} options.shouldAddReminder Whether or not to add a reminder.
* @param {string} options.title The title of the reminder.
* @param {string} options.text The text of the reminder.
* @param {string} options.button The button text of the reminder.
* @param {string} options.action The action to take when the button is clicked.
* @param {string} options.callback The callback to run when the user is at the location.
*/
const onTravel = (location, options) => {
eventRegistry.addEventListener('travel_complete', () => onTravelCallback(location, options));
};
/**
* Do something when the user travels to a location.
* This is a callback for the onTravel function.
*
* @param {string} location The location traveled to.
* @param {Object} options The options
* @param {string} options.shouldAddReminder Whether or not to add a reminder.
* @param {string} options.title The title of the reminder.
* @param {string} options.text The text of the reminder.
* @param {string} options.button The button text of the reminder.
* @param {string} options.action The action to take when the button is clicked.
* @param {string} options.callback The callback to run when the user is at the location.
*/
const onTravelCallback = (location, options) => {
if (location && location !== getCurrentLocation()) {
return;
}
if (options?.shouldAddReminder) {
showHornMessage({
title: options.title || '',
text: options.text || '',
button: options.button || 'Dismiss',
action: options.action || null,
});
}
if (options.callback) {
options.callback();
}
};
/**
* TODO: update this docblock.
*
* @param {string} targetPage The target page.
* @param {string} targetTab The target tab.
* @param {string} targetSubtab The target subtab.
* @param {string} forceCurrentPage The current page.
* @param {string} forceCurrentTab The current tab.
* @param {string} forceCurrentSubtab The current subtab.
*/
const matchesCurrentPage = (targetPage = null, targetTab = null, targetSubtab = null, forceCurrentPage = null, forceCurrentTab = null, forceCurrentSubtab = null) => {
if (! targetPage) {
return false;
}
// Only targetPage is being checked.
const currentPage = forceCurrentPage || getCurrentPage();
if (! targetTab) {
return currentPage === targetPage;
}
// Only targetTab is being checked.
const currentTab = forceCurrentTab || getCurrentTab();
if (! targetSubtab) {
return currentPage === targetPage && currentTab === targetTab;
}
// Only targetSubtab is being checked.
const currentSubtab = forceCurrentSubtab || getCurrentSubtab();
if (currentSubtab === currentTab) {
return currentPage === targetPage && currentTab === targetTab;
}
return currentPage === targetPage && currentTab === targetTab && currentSubtab === targetSubtab;
};
/*
onNavigation(() => console.log('mouse stats by location'),
{
page: 'adversaries',
tab: 'your_stats',
subtab: 'location'
}
);
onNavigation(() => console.log('friend request page'),
{
page:'friends',
tab: 'requests'
}
);
onNavigation(() => console.log('hunter profile, but not when refreshing the page'),
{
page: 'hunterprofile',
onLoad: true
}
);
*/
/**
* TODO: update this docblock
*
* @param {Function} callback The callback to run when the user navigates to the page.
* @param {Object} options The options
* @param {string} options.page The page to watch for.
* @param {string} options.tab The tab to watch for.
* @param {string} options.subtab The subtab to watch for.
* @param {boolean} options.onLoad Whether or not to run the callback on load.
*/
const onNavigation = (callback, options = {}) => {
const defaults = {
page: false,
tab: false,
subtab: false,
onLoad: true,
};
// merge the defaults with the options
const { page, tab, subtab, onLoad } = Object.assign(defaults, options);
// If we don't pass in a page, then we want to run the callback on every page.
let bypassMatch = false;
if (! page) {
bypassMatch = true;
}
// We do this once on load in case we are starting on the page we want to watch for.
if (onLoad) {
if (bypassMatch || matchesCurrentPage(page, tab, subtab)) {
callback();
}
}
eventRegistry.addEventListener('set_page', (e) => {
const tabs = e?.data?.tabs || {};
const currentTab = Object.keys(tabs).find((key) => tabs[key].is_active_tab);
const forceCurrentTab = currentTab?.type;
if (! subtab) {
if (matchesCurrentPage(page, tab, false, getCurrentPage(), forceCurrentTab)) {
callback();
}
return;
}
if (currentTab?.subtabs && currentTab?.subtabs.length > 0) {
const forceSubtab = currentTab.subtabs.find((searchTab) => searchTab.is_active_subtab).subtab_type;
if (matchesCurrentPage(page, tab, subtab, getCurrentPage(), forceCurrentTab, forceSubtab)) {
callback();
}
}
});
eventRegistry.addEventListener('set_tab', (e) => {
const forceCurrentTab = e.page_arguments.tab;
const forceCurrentSubtab = e.page_arguments.sub_tab;
if (matchesCurrentPage(page, tab, subtab, getCurrentPage(), forceCurrentTab, forceCurrentSubtab)) {
callback();
}
});
};
const onNavigate = onNavigation;
/**
* Get the current page slug.
*
* @return {string} The page slug.
*/
const getCurrentPage = () => {
return hg.utils.PageUtil.getCurrentPage().toLowerCase(); // eslint-disable-line no-undef
};
/**
* Get the current page tab, defaulting to the current page if no tab is found.
*
* @return {string} The page tab.
*/
const getCurrentTab = () => {
const tab = hg.utils.PageUtil.getCurrentPageTab().toLowerCase(); // eslint-disable-line no-undef
if (tab.length <= 0) {
return getCurrentPage();
}
return tab;
};
/**
* Get the current page sub tab, defaulting to the current tab if no sub tab is found.
*
* @return {string} The page tab.
*/
const getCurrentSubtab = () => {
const subtab = hg.utils.PageUtil.getCurrentPageSubTab();
if (! subtab || subtab.length <= 0) {
return getCurrentTab();
}
return subtab.toLowerCase();
};
// Backwards compatibility.
const getCurrentSubTab = getCurrentSubtab;
/**
* Check if the overlay is visible.
*
* @return {boolean} True if the overlay is visible, false otherwise.
*/
const isOverlayVisible = () => {
return activejsDialog && activejsDialog.isVisible();
};
/**
* Get the current overlay.
*
* @return {string} The current overlay.
*/
const getCurrentOverlay = () => {
const overlay = document.getElementById('overlayPopup');
if (overlay && overlay.classList.length <= 0) {
return null;
}
let overlayType = overlay.classList.value;
overlayType = overlayType.replace('jsDialogFixed', '');
overlayType = overlayType.replace('default', '');
overlayType = overlayType.replace('wide', '');
overlayType = overlayType.replace('ajax', '');
overlayType = overlayType.replace('overlay', '');
// Replace some overlay types with more readable names.
overlayType = overlayType.replace('treasureMapPopup', 'map');
overlayType = overlayType.replace('itemViewPopup', 'item');
overlayType = overlayType.replace('mouseViewPopup', 'mouse');
overlayType = overlayType.replace('largerImage', 'image');
overlayType = overlayType.replace('convertibleOpenViewPopup', 'convertible');
overlayType = overlayType.replace('adventureBookPopup', 'adventureBook');
overlayType = overlayType.replace('marketplaceViewPopup', 'marketplace');
overlayType = overlayType.replace('giftSelectorViewPopup', 'gifts');
overlayType = overlayType.replace('supportPageContactUsForm', 'support');
overlayType = overlayType.replace('MHCheckout', 'premiumShop');
return overlayType.trim();
};
/**
* Get the current location.
*
* @return {string} The current location.
*/
const getCurrentLocation = () => {
const location = user?.environment_type || '';
return location.toLowerCase();
};
/**
* Check if the user is logged in.
*
* @return {boolean} True if the user is logged in, false otherwise.
*/
const isLoggedIn = () => {
return user.length > 0 && 'login' !== getCurrentPage();
};
/**
* Get the saved settings.
*
* @param {string} key The key to get.
* @param {boolean} defaultValue The default value.
* @param {string} identifier The identifier for the settings.
*
* @return {Object} The saved settings.
*/
const getSetting = (key = null, defaultValue = null, identifier = 'mh-utils-settings') => {
// Grab the local storage data.
const settings = JSON.parse(localStorage.getItem(identifier)) || {};
// If we didn't get a key passed in, we want all the settings.
if (! key) {
return settings;
}
// If the setting doesn't exist, return the default value.
if (Object.prototype.hasOwnProperty.call(settings, key)) {
return settings[key];
}
return defaultValue;
};
/**
* Save a setting.
*
* @param {string} key The setting key.
* @param {boolean} value The setting value.
* @param {string} identifier The identifier for the settings.
*/
const saveSetting = (key, value, identifier = 'mh-utils-settings') => {
// Grab all the settings, set the new one, and save them.
const settings = getSetting(null, {}, identifier);
settings[key] = value;
localStorage.setItem(identifier, JSON.stringify(settings));
};
/**
* Save a setting and toggle the class in the settings UI.
*
* @ignore
*
* @param {Node} node The setting node to animate.
* @param {string} key The setting key.
* @param {boolean} value The setting value.
*/
const saveSettingAndToggleClass = (node, key, value, identifier = 'mh-utils-settings') => {
node.parentNode.parentNode.classList.add('busy');
// Toggle the state of the checkbox.
node.classList.toggle('active');
// Save the setting.
saveSetting(key, value, identifier);
// Add the completed class & remove it in a second.
node.parentNode.parentNode.classList.remove('busy');
node.parentNode.parentNode.classList.add('completed');
setTimeout(() => {
node.parentNode.parentNode.classList.remove('completed');
}, 1000);
addSettingRefreshReminder();
};
/**
* Make the settings tab.
*
* @param {string} identifier The identifier for the settings.
* @param {string} name The name of the settings tab.
*/
const addSettingsTab = (identifier = 'userscript-settings', name = 'Userscript Settings') => {
addSettingsTabOnce(identifier, name);
onPageChange({ preferences: { show: () => addSettingsTabOnce(identifier, name) } });
return identifier;
};
/**
* Make the settings tab once.
*
* @ignore
*
* @param {string} identifier The identifier for the settings.
* @param {string} name The name of the settings tab.
*/
const addSettingsTabOnce = (identifier = 'userscript-settings', name = 'Userscript Settings') => {
if ('preferences' !== getCurrentPage()) {
return;
}
const existingSettings = document.querySelector(`#${identifier}`);
if (existingSettings) {
return;
}
const tabsContainer = document.querySelector('.mousehuntHud-page-tabHeader-container');
if (! tabsContainer) {
return;
}
const tabsContentContainer = document.querySelector('.mousehuntHud-page-tabContentContainer');
if (! tabsContentContainer) {
return;
}
// make sure the identifier is unique and safe to use as a class.
identifier = identifier.replace(/[^a-z0-9-_]/gi, '');
const settingsTab = document.createElement('a');
settingsTab.id = identifier;
settingsTab.href = '#';
settingsTab.classList.add('mousehuntHud-page-tabHeader', identifier);
settingsTab.setAttribute('data-tab', identifier);
settingsTab.setAttribute('onclick', 'hg.utils.PageUtil.onclickPageTabHandler(this); return false;');
const settingsTabText = document.createElement('span');
settingsTabText.innerText = name;
settingsTab.appendChild(settingsTabText);
tabsContainer.appendChild(settingsTab);
const settingsTabContent = document.createElement('div');
settingsTabContent.classList.add('mousehuntHud-page-tabContent', 'game_settings', identifier);
settingsTabContent.setAttribute('data-tab', identifier);
tabsContentContainer.appendChild(settingsTabContent);
if (identifier === getCurrentTab()) {
const tab = document.getElementById(identifier);
if (tab) {
tab.click();
}
}
};
/**
* Add a setting to the preferences page, both on page load and when the page changes.
*
* @param {string} name The setting name.
* @param {string} key The setting key.
* @param {boolean} defaultValue The default value.
* @param {string} description The setting description.
* @param {Object} section The section settings.
* @param {string} tab The tab to add the settings to.
* @param {Object} settings The settings for the settings.
*/
const addSetting = (name, key, defaultValue = true, description = '', section = {}, tab = 'userscript-settings', settings = null) => {
onPageChange({ preferences: { show: () => addSettingOnce(name, key, defaultValue, description, section, tab, settings) } });
addSettingOnce(name, key, defaultValue, description, section, tab, settings);
addSettingRefreshReminder();
onPageChange({ preferences: { show: addSettingRefreshReminder } });
};
/**
* Add a setting to the preferences page.
*
* @ignore
*
* @param {string} name The setting name.
* @param {string} key The setting key.
* @param {boolean} defaultValue The default value.
* @param {string} description The setting description.
* @param {Object} section The section settings.
* @param {string} tab The tab to add the settings to.
* @param {Object} settingSettings The settings for the settings.
*/
const addSettingOnce = (name, key, defaultValue = true, description = '', section = {}, tab = 'userscript-settings', settingSettings = null) => {
// Make sure we have the container for our settings.
const container = document.querySelector(`.mousehuntHud-page-tabContent.${tab}`);
if (! container) {
return;
}
section = {
id: section.id || 'settings',
name: section.name || 'Userscript Settings',
description: section.description || '',
};
let tabId = 'mh-utils-settings';
if (tab !== 'userscript-settings') {
tabId = tab;
}
section.id = `${tabId}-${section.id.replace(/[^a-z0-9-_]/gi, '')}`;
// If we don't have our custom settings section, then create it.
let sectionExists = document.querySelector(`#${section.id}`);
if (! sectionExists) {
// Make the element, add the ID and class.
const title = document.createElement('div');
title.id = section.id;
title.classList.add('PagePreferences__title');
// Set the title of our section.
const titleText = document.createElement('h3');
titleText.classList.add('PagePreferences__titleText');
titleText.textContent = section.name;
// Append the title.
title.appendChild(titleText);
// Add a separator.
const seperator = document.createElement('div');
seperator.classList.add('PagePreferences__separator');
// Append the separator.
title.appendChild(seperator);