-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
2823 lines (2507 loc) · 101 KB
/
script.js
File metadata and controls
2823 lines (2507 loc) · 101 KB
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
let onAuth = {}; loggedOut
let inventory = [];
let hideMarkerTimer;
let emptyItem = {
name: "empty",
damage: 0,
armor: 0,
crystalLevel: 0,
kind: "empty",
sprite: 0,
}
let loadLoop;
let uiLoop;
let mouseReleaseTimer;
let isLeftMouseButtonPressed = false;
let autoSellList = [];
let stashPutTracker = { from: null, to: null };
let currentTooltipText = "";
var freeBlessings = 0;
var nextBlessingCost = 1;
var blessings = {};
let totalBlessings = 0;
var currentGold = 0;
var tooltips = {
inventory: {},
stash: {},
selectedItems: {},
blessings: {}
};
var loadedImages = [];
var totalPages = 1;
var oldTotalPages = 0;
var currentPage = 1;
const itemsPerPage = 50;
let previousInventoryState = {};
let previousStashState = {};
let previousSelectedItemsState = {};
let meterRunning = false;
var xpMeter = {
cumulativeXpCache: 0,
lastLevelChecked: 0,
xp: 0,
startingXp: 0,
startingXpPerMinute: 0,
minuteCount: 0,
startingLevelsMinute: 0,
startingLevelsTotal: 0
}
var meterMinuteTimer;
var updateMeterInfo = false;
var unsavedChanges = false;
var isWindowActive = true;
class RequestQueue {
constructor() {
this.queue = [];
this.pendingPromise = false;
this.currentAbortController = null;
this.currentRequestType = null; // Store the type of the current request
}
// Add a new request to the queue
enqueue(promiseFunction) {
const functionName = promiseFunction.name || 'anonymous';
return new Promise((resolve, reject) => {
this.queue.push({
promiseFunction,
resolve,
reject,
type: functionName // Use the function name as the type
});
this.dequeue(); // Try processing the queue
});
}
// Process the queue items
dequeue() {
if (this.pendingPromise || this.queue.length === 0) {
return false;
}
const item = this.queue.shift();
this.pendingPromise = true;
this.currentAbortController = new AbortController(); // Create a new AbortController for this request
this.currentRequestType = item.type; // Set the current request type
const { signal } = this.currentAbortController;
item.promiseFunction(signal)
.then(value => {
this.pendingPromise = false;
this.currentAbortController = null; // Clear the abort controller after completion
this.currentRequestType = null; // Clear the current request type
item.resolve(value);
this.dequeue(); // Process next item in the queue
})
.catch(err => {
this.pendingPromise = false;
this.currentAbortController = null; // Clear the abort controller after failure
this.currentRequestType = null; // Clear the current request type
item.reject(err);
this.dequeue(); // Process next item in the queue
});
}
// Clear the queue and abort requests of a specific type
clear(type = null) {
if (type) {
// Clear specific type requests
this.queue = this.queue.filter(item => item.type !== type);
if (this.currentRequestType === type && this.currentAbortController) {
this.currentAbortController.abort(); // Abort the current request if it matches the type
this.pendingPromise = false;
this.currentRequestType = null;
this.currentAbortController = null; // Clear the current request details
this.dequeue(); // Process the next item in the queue
}
} else {
// Clear all requests
if (this.currentAbortController) {
this.currentAbortController.abort(); // Abort the current request
}
this.queue = [];
this.pendingPromise = false;
this.currentRequestType = null;
this.currentAbortController = null; // Clear all current request details
}
}
}
const requestQueue = new RequestQueue();
var settingInventory = false;
//get json from server
let recipes;
fetch(myServer + '/recipes', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(response.statusText);
}
}
)
.then(data => {
recipes = data;
})
.catch(error => {
console.error(error);
});
var accessToken;
var connected = false;
if (localStorage.getItem('accessToken')) {
connected = true;
accessToken = localStorage.getItem('accessToken');
removeLoggedOutElement();
initExtension();
} else {
connectToExtension();
}
//inventory fix
async function checkImageExists(imagePath) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = imagePath;
});
}
//inventory fix
function scheduleNextInventoryCheck() {
setTimeout(() => {
getInventory().then(() => {
scheduleNextInventoryCheck(); // Schedule the next check after the promise resolves
}).catch(error => {
console.error('Error retrieving inventory:', error);
scheduleNextInventoryCheck(); // Even if there is an error, schedule the next check
});
}, 2000);
}
function formatItemAmount(amount) {
if (amount <= 999) {
return `${amount}`; // Return the amount as is if it's 999 or less
} else {
const thousands = Math.floor(amount / 1000);
const remainder = amount % 1000;
return `<span style="color : #FFD700;">${thousands}</span>\n${remainder.toString().padStart(3, '0')}`; // Pad the remainder with zeros
}
}
function formatMoney(number) {
return String(new Intl.NumberFormat('en-US', { maximumFractionDigits: 1, notation: "compact", compactDisplay: "short" }).format(number));
}
function formatTime(minutes) {
// If the input is less than an hour, just return the minutes
if (minutes < 60) {
return `${Math.floor(minutes)} minutes`;
}
// Calculate hours and remaining minutes
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
// Format hours and remaining minutes
const formattedMinutes = remainingMinutes < 10 ? `0${remainingMinutes}` : remainingMinutes;
// Return the formatted time
return `${hours}:${formattedMinutes} hours`;
}
function formatNumber(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function descriptionWithStats(item) {
if (item.description === undefined)
item.description = "none";
var statsDescription = item.description;
var reqLevel = false;
if (item.levelRequirement !== undefined) {
statsDescription += `<br><br>[REQUIRES LEVEL ${item.levelRequirement}]<br>`;
reqLevel = true;
}
if (!reqLevel)
statsDescription += '<br>';
if (item.armorBonus >= 1.0) { //FORBIDDEN ARMOR
statsDescription += '<br>FORBIDDEN ARMOR';
} else if (item.armorBonus >= 0.8) { //LEGENDARY ARMOR
statsDescription += '<br>LEGENDARY ARMOR';
} else if (item.armorBonus >= 0.6) { //EPIC ARMOR
statsDescription += '<br>EPIC ARMOR';
} else if (item.armorBonus >= 0.4) { //EXTRAORDINARY ARMOR
statsDescription += '<br>EXTRAORDINARY ARMOR';
}
if (item.damageBonus >= 1.0) { //FORBIDDEN DAMAGE
statsDescription += '<br>FORBIDDEN DAMAGE';
} else if (item.damageBonus >= 0.8) { //LEGENDARY DAMAGE
statsDescription += '<br>LEGENDARY DAMAGE';
} else if (item.damageBonus >= 0.6) { //EPIC DAMAGE
statsDescription += '<br>EPIC DAMAGE';
} else if (item.damageBonus >= 0.4) { //EXTRAORDINARY DAMAGE
statsDescription += '<br>EXTRAORDINARY DAMAGE';
}
return statsDescription;
}
function formatDescription(item) {
// Define the words and their corresponding colors, ensuring longer phrases come first
const wordsToColor = [
{ word: 'extraordinary', color: '#2270AF' },
{ word: 'epic', color: '#7C337B' },
{ word: 'legendary', color: '#CCB333' },
{ word: 'forbidden', color: '#4B4A56' },
{ word: 'mana', color: 'lightblue' },
{ word: 'health', color: 'red' },
{ word: 'damage', color: '#ec8d34' },
{ word: 'damages', color: '#ec8d34' },
{ word: 'armor', color: '#20985d' },
{ word: 'one-hit', color: '#5C4033' }
];
var description = descriptionWithStats(item);
// Iterate over the words to color and replace them in the description
wordsToColor.forEach(({ word, color }) => {
const regex = new RegExp(word, 'gi'); // Create a case-insensitive regex
description = description.replace(regex, match => `<span style="color: ${color};">${match}</span>`);
});
return description;
}
function formatGem(gem) {
if (gem !== undefined) {
try {
const gemPercentage = parseInt(gem.description.match(/\d+/)[0]);
return gem.name + " (+" + gemPercentage + "%)";
} catch (error) {
return gem.description;
}
} else {
return "";
}
}
function generateBlessingTooltip(blessing, total) {
var blessingName;
var image;
var description;
switch (blessing) {
case "dex":
blessingName = "Dexterity";
image = 'images/attackSpeed.png';
description = 'Increases your attack speed.';
break;
case "str":
blessingName = "Strength";
image = 'images/damage.png';
description = 'Increases your physical damage.';
break;
case "def":
blessingName = "Defense";
image = 'images/armor.png';
description = 'Increases your armor.';
break;
case "luck":
blessingName = "Luck";
image = 'images/luck.png';
description = 'Increases your drop rate when killing monsters.';
break;
case "xp":
blessingName = "XP Gain";
image = 'images/xp.png';
description = 'Increases your experience rate when killing monsters.';
break;
}
blessingTooltip =
`<div class="item-image" style='background-image: url("${image}");'></div>` +
`<span style="font-size: 0.47vw;">${blessingName}</span><br>` +
`<div style="margin-top:0.26vw;"/>`;
blessingTooltip +=
`${description}<br>` +
`Current Blessings: ${total}<br>` +
`Next Blessing Cost: ${abbreviateNumber(nextBlessingCost)}<br><br>` +
`Click to buy/assign 1 ${blessingName} blessing.<br>` +
`<span style="color: green;">CTRL</span> + <span style="color: lightblue;">Click</span> to buy/assign 100 ${blessingName} blessing.<br>` +
`<span style="color: purple;">SHIFT</span> + <span style="color: lightblue;">Click</span> to assign all free blessings to ${blessingName} blessing.<br><span style="color: red;">WARNING</span> If you don't have free blessings all your money will be used.`;
return blessingTooltip;
}
function generateItemTooltip(item, image) {
itemTooltip =
`<div class="item-image" style='background-image: ${image};'></div>` +
`<span style="font-size: 0.47vw;">${item.name}</span><br>` +
`<div style="margin-top:0.26vw;"/>`;
if (item.damage > 0) {
if (item.gem !== undefined) {
itemTooltip += `Base Damage: ${formatNumber(item.damage)}<br>`;
itemTooltip += `Damage: ${formatNumber(Math.round(item.damage * (1 + (item.gem?.gemRank ?? 0) * 0.08)))}<br>`;
}
else
itemTooltip += `Damage: ${formatNumber(Math.round(item.damage * (1 + (item.gem?.gemRank ?? 0) * 0.08)))}<br>`;
}
if (item.armor > 0) {
if (item.gem !== undefined) {
itemTooltip += `Base Armor: ${formatNumber(item.armor)}<br>`;
itemTooltip += `Armor: ${formatNumber(Math.round(item.armor * (1 + (item.gem?.gemRank ?? 0) * 0.08)))}<br>`;
}
else
itemTooltip += `Armor: ${formatNumber(Math.round(item.armor * (1 + (item.gem?.gemRank ?? 0) * 0.08)))}<br>`;
}
itemTooltip +=
`Kind: ${item.kind}<br>` +
`Gold Value: ${formatMoney(item.goldValue)}<br>` +
`${item.critChance ? `Crit Chance: ${item.critChance}%<br>` : ''}` +
`${item.critEffectiveness ? `Crit Effectiveness: ${item.critEffectiveness}%<br>` : ''}` +
`${formatDescription(item)}<br>` +
`${item.gem ? `Gem: ${formatGem(item.gem)}` : ''}`;
return itemTooltip;
}
function addItemModifiers(item, itemElement) {
let backgrounds = [];
if (item.lock == true && (item.tradable == false || item.gem != undefined)) {
backgrounds.push("url('images/inventory_background/locknon-tradable.png')");
} else {
if (item.lock == true) {
backgrounds.push("url('images/inventory_background/lock.png')");
}
if (item.tradable == false || item.gem != undefined) {
backgrounds.push("url('images/inventory_background/non-tradable.png')");
}
}
if (item.armorBonus >= 1.0) { // FORBIDDEN ARMOR
backgrounds.push("url('images/inventory_background/forbidden-armor.png')");
} else if (item.armorBonus >= 0.8) { // LEGENDARY ARMOR
backgrounds.push("url('images/inventory_background/legendary-armor.png')");
} else if (item.armorBonus >= 0.6) { // EPIC ARMOR
backgrounds.push("url('images/inventory_background/epic-armor.png')");
} else if (item.armorBonus >= 0.4) { // EXTRAORDINARY ARMOR
backgrounds.push("url('images/inventory_background/extraordinary-armor.png')");
}
if (item.damageBonus >= 1.0) { // FORBIDDEN DAMAGE
backgrounds.push("url('images/inventory_background/forbidden-damage.png')");
} else if (item.damageBonus >= 0.8) { // LEGENDARY DAMAGE
backgrounds.push("url('images/inventory_background/legendary-damage.png')");
} else if (item.damageBonus >= 0.6) { // EPIC DAMAGE
backgrounds.push("url('images/inventory_background/epic-damage.png')");
} else if (item.damageBonus >= 0.4) { // EXTRAORDINARY DAMAGE
backgrounds.push("url('images/inventory_background/extraordinary-damage.png')");
}
if (item.shimmering === 1) { // SHINY ITEM
backgrounds.push("url('images/inventory_background/shimmering.png')");
}
// If there are any backgrounds to apply, set them
if (backgrounds.length > 0) {
itemElement.style.backgroundImage = backgrounds.join(', ') + ', ' + itemElement.style.backgroundImage;
}
}
function getImageName(item) {
if (item.shimmering === 1) {
return item.name.replace(/\s+/g, '') + "_shimmering";
} else {
return item.name.replace(/\s+/g, '');
}
}
function animateAmount(element, oldValue, newValue, duration = 1800) {
const start = oldValue;
const range = newValue - start;
let current = start;
const stepTime = 10; // Interval in milliseconds
const steps = duration / stepTime;
const increment = range / steps;
if (element.animationTimer) {
clearInterval(element.animationTimer);
}
element.animationTimer = setInterval(() => {
current += increment;
element.innerHTML = formatItemAmount(Math.floor(current));
if ((increment > 0 && current >= newValue) || (increment < 0 && current <= newValue)) {
element.innerHTML = formatItemAmount(newValue);
clearInterval(element.animationTimer);
element.animationTimer = null;
}
}, stepTime);
}
function styleItem(item, itemElement, isDefault = false, swapped = false) {
// Check if itemElement already has a .item-amount element
let amountDisplay = itemElement.querySelector('.item-amount');
if (item.amount > 0) {
if (!amountDisplay) {
amountDisplay = document.createElement('div');
amountDisplay.classList.add('item-amount');
itemElement.appendChild(amountDisplay);
}
// Stop any ongoing animation
clearInterval(amountDisplay.animationTimer);
amountDisplay.animationTimer = null;
if (!swapped) {
amountDisplay.classList.remove('item-amount-changed-up');
amountDisplay.classList.remove('item-amount-changed-down');
void amountDisplay.offsetWidth;
if (item.amount !== item.previousAmount && item.amount > item.previousAmount && item.previousAmount !== undefined) {
amountDisplay.classList.add('item-amount-changed-up');
setTimeout(() => {
amountDisplay.classList.remove('item-amount-changed-up');
}, 2000);
animateAmount(amountDisplay, item.previousAmount, item.amount, 1800);
} else if (item.amount !== item.previousAmount && item.amount < item.previousAmount && item.previousAmount !== undefined) {
amountDisplay.classList.add('item-amount-changed-down');
setTimeout(() => {
amountDisplay.classList.remove('item-amount-changed-down');
}, 2000);
animateAmount(amountDisplay, item.previousAmount, item.amount, 1800);
} else {
amountDisplay.innerHTML = formatItemAmount(item.amount);
}
} else {
amountDisplay.innerHTML = formatItemAmount(item.amount);
}
} else {
if (amountDisplay) {
itemElement.removeChild(amountDisplay);
}
}
var imageName = getImageName(item);
var _itemImagePath = "images/items/" + imageName + ".png";
if (isDefault || loadedImages[imageName] === false) {
_itemImagePath = "images/items/default.png";
}
if (item.gem != undefined) {
let _gemImagePath = "images/items/" + item.gem.name.replace(/\s+/g, '') + ".gif";
itemElement.style.backgroundImage = "url('" + _itemImagePath + "'), url('" + _gemImagePath + "')";
} else {
if (item.kind == "gem") {
_itemImagePath = "images/items/" + item.name.replace(/\s+/g, '') + ".gif";
itemElement.style.backgroundImage = "url('" + _itemImagePath + "')";
} else {
itemElement.style.backgroundImage = "url('" + _itemImagePath + "')";
}
}
addItemModifiers(item, itemElement);
itemElement.style.backgroundPosition = "center center, center center"; // Positions for each image
itemElement.style.backgroundRepeat = "no-repeat, repeat"; // Repeat settings for each image
// Size settings for each image (e.g., cover, contain, or explicit dimensions)
itemElement.style.backgroundSize = "cover, contain";
}
function connectToExtension() {
window.Twitch.ext.onAuthorized(function (auth) {
try {
if (window.Twitch.ext.viewer.isLinked) {
removeLoggedOutElement(); // Call the new function to remove the element
} else {
fullInventoryDivs.forEach(function (div) {
div.style.display = "none";
});
}
initExtension();
} catch (error) {
initExtension();
}
});
}
// New function to remove the 'loggedOut' element
function removeLoggedOutElement() {
let fullInventoryDivs = document.querySelectorAll(".hud");
let element = document.getElementById('loggedOut');
if (element) {
element.remove();
}
fullInventoryDivs.forEach(function (div) {
div.style.display = "block";
});
}
function abbreviateNumber(value) {
let newValue = value;
if (value >= 1000) {
const suffixes = ["", "k", "M", "B", "T"];
const suffixNum = Math.floor(Math.log10(value) / 3);
let shortValue = (value / Math.pow(1000, suffixNum));
// Round to three significant figures
shortValue = Number(shortValue.toPrecision(3));
newValue = shortValue + suffixes[suffixNum];
}
return newValue;
}
function updatePaginationControls() {
const stashInventoryContainer = document.getElementById('stashInventory');
// Check if pagination controls already exist
let paginationControls = document.querySelector('.stash-pagination');
if (!paginationControls) {
// Create a div for pagination controls if it doesn't exist
paginationControls = document.createElement('div');
paginationControls.classList.add('stash-pagination');
stashInventoryContainer.appendChild(paginationControls);
}
// Loop through 10 pages
for (let page = 1; page <= 10; page++) {
let pageButton = document.querySelector(`.page-button[data-page='${page}']`);
if (!pageButton) {
// Create page button if it doesn't exist
pageButton = document.createElement('div');
pageButton.classList.add('page-button');
pageButton.dataset.page = page;
pageButton.innerText = page; // Set the initial text when creating the button
paginationControls.appendChild(pageButton);
}
// Update button properties
if (page <= totalPages) {
if (page === currentPage) {
pageButton.disabled = true;
pageButton.classList.add('active');
} else {
pageButton.disabled = false;
pageButton.classList.remove('active');
pageButton.onclick = () => changePage(page);
}
// Update or create pageImage
let pageImage = pageButton.querySelector('.page-image');
var firstCell = $('#stash-inventory-' + page + ' .inventory-row:first .inventory-cell:first');
var firstInventoryItem = firstCell.find('.inventory-item:first');
if (firstInventoryItem.length > 0) {
var backgroundImage = firstInventoryItem.css('background-image');
const urls = backgroundImage.match(/url\(["']?([^"']*)["']?\)/g);
if (urls && urls.length > 0) {
const lastUrl = urls[urls.length - 1].replace(/url\(["']?([^"']*)["']?\)/, '$1');
if (!pageImage) {
pageImage = document.createElement('div');
pageImage.classList.add('page-image');
pageButton.innerText = ""; // Clear the text when adding an image
pageButton.appendChild(pageImage);
}
pageImage.style.backgroundImage = `url(${lastUrl})`;
} else if (pageImage) {
pageImage.remove();
pageButton.innerText = page; // Restore the text if no image
}
} else if (pageImage) {
pageImage.remove();
pageButton.innerText = page; // Restore the text if no image
}
} else {
pageButton.classList.add('disabled');
pageButton.disabled = true;
pageButton.onclick = null;
pageButton.title = "Buy more stash pages on the shop.";
// Remove the pageImage if it exists for pages that exceed totalPages
let pageImage = pageButton.querySelector('.page-image');
if (pageImage) {
pageImage.remove();
pageButton.innerText = page; // Restore the text if no image
}
}
}
}
function initTooltips(){
$(document).tooltip({
items: ".inventory-item, .bless-button",
track: true,
content: function () {
if ($(this).hasClass('bless-button')) { //Bless tooltip
blessingType = $(this).attr('data-type');
return tooltips['blessings'][blessingType] || '';
}
// Get location and position from data attributes
if ($(this).attr('data-inventory-position') !== undefined) {
type = 'inventory';
position = $(this).attr('data-inventory-position');
}
else if ($(this).attr('data-stashposition') !== undefined) {
type = 'stash';
position = $(this).attr('data-stashposition');
}
else {
type = 'selectedItems';
position = $(this).attr('data-item-type');
}
// Fetch the tooltip content from the global tooltips object
return tooltips[type][position] || '';
},
open: function (event, ui) {
// Get the new tooltip text
var newTooltipText = $(event.target).attr('data-ui-tooltip-content') || $(event.target).attr('title');
// Compare with the current tooltip text
if (newTooltipText === currentTooltipText) {
// Prevent the new tooltip from opening if the text is the same
event.preventDefault();
//$('.ui-tooltip').not(ui.tooltip).remove();
} else {
// Update the current tooltip text
currentTooltipText = newTooltipText;
$('.ui-tooltip').not(ui.tooltip).remove();
}
contextMenu = $('.context-menu-list').length > 0;
beingMoved = $(event.target).attr('moving');
if (contextMenu || beingMoved) {
event.preventDefault();
$('.ui-tooltip').remove();
}
if (beingMoved) {
currentTooltipText = "";
}
},
close: function (event, ui) {
// Clear the current tooltip text on close
currentTooltipText = "";
}
});
}
function isTabActive() {
if (document.hidden) {
return false;
} else {
return true;
}
}
function initExtension() {
initTooltips();
getInventory().then(() => {
loadLoop = setInterval(() => {
getInventory().catch(err => console.error('Failed to get inventory:', err));
}, 2000);
uiLoop = setInterval(() => {
if (settingInventory){
getUIInfo().catch(err => console.error('Failed to get UI Info:', err));
}
}, 2000);
initializeContextMenu();
$('#settings-tabs').tabs();
}).catch(error => {
console.error('Initial inventory retrieval failed:', error);
// Optionally start the interval even if the initial call fails
loadLoop = setInterval(() => {
getInventory().catch(err => console.error('Failed to get inventory:', err));
}, 2000);
});
}
function stopInventoryCheck() {
clearInterval(loadLoop);
}
function restartInventoryCheck() {
stopInventoryCheck(); // Ensure no duplicates
loadLoop = setInterval(() => {
getInventory().catch(err => console.error('Failed to get inventory:', err));
}, 2000);
}
try {
document.getElementById('share').addEventListener('click', (e) => {
e.preventDefault();
event.stopPropagation();
window.Twitch.ext.actions.requestIdShare();
});
}
catch (error) {
console.log("Share button not found")
}
let tooltipTimeout;
$(document).on('mouseover', '.inventory-item', function () {
clearTimeout(tooltipTimeout);
});
$(document).on('mouseout', '.inventory-item', function () {
tooltipTimeout = setTimeout(() => {
$('.ui-tooltip').remove();
}, 2000);
});
document.addEventListener('mousedown', function (event) {
// Check if the left mouse button is pressed
if (event.button === 0) {
isLeftMouseButtonPressed = true;
clearTimeout(mouseReleaseTimer);
}
});
document.addEventListener('mouseup', function (event) {
// Check if the left mouse button is released
if (event.button === 0) {
clearTimeout(mouseReleaseTimer);
mouseReleaseTimer = setTimeout(setIsLeftMouseButtonPressedToFalse, 200)
}
});
document.querySelectorAll('.rpgui-tab').forEach(tab => {
tab.addEventListener('click', function() {
document.querySelectorAll('.rpgui-tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.rpgui-tab-content').forEach(content => content.style.display = 'none');
this.classList.add('active');
document.getElementById(this.getAttribute('data-tab')).style.display = 'block';
});
});
function setIsLeftMouseButtonPressedToFalse() {
isLeftMouseButtonPressed = false;
}
// we need to do this because otherwise there are issues with html
window.addEventListener("DOMContentLoaded", function () {
let craftInventoryDivs = document.querySelectorAll(".crafting");
craftInventoryDivs.forEach(function (div) {
div.style.display = "none";
});
let stashInventoryDivs = document.querySelectorAll("#stashInventory");
stashInventoryDivs.forEach(function (div) {
div.style.display = "none";
});
// Restore the state from localStorage or default to visible
$('.collapsible').each(function (index) {
var collapsibleElement = $(this);
var state = localStorage.getItem('collapsible_' + index);
var buttonElement = $(this).prev('.expandable').children().find('.action-button.collapse');
if (state === 'hidden') {
collapsibleElement.hide();
buttonElement.text('+');
}
var closeState = localStorage.getItem('close_' + index);
if (closeState === 'closed') {
if (index == 4)
collapsibleElement.parent().parent().hide(); // Hide the entire section including expandable button
else
collapsibleElement.parent().hide(); // Hide the entire section including expandable button
}
});
$('.action-button.collapse').click(function () {
var collapsibleElement = $(this).parent().parent().next('.collapsible');
var isCurrentlyVisible = collapsibleElement.is(":visible");
var buttonElement = $(this);
// Log the action based on current visibility
if (isCurrentlyVisible) {
buttonElement.text('+');
// Check if the container is expanded, if so, trigger the expand button
var parentContainer = $(this).closest('.hud-container');
if (parentContainer.hasClass('expanded')) {
buttonElement.prev('.expand').trigger('click');
}
} else {
buttonElement.text('-');
}
// Toggle the visibility
var collapsibleIndex = $('.collapsible').index(collapsibleElement);
if (!$(collapsibleElement).hasClass('special')) {
if (isCurrentlyVisible) {
localStorage.setItem('collapsible_' + collapsibleIndex, 'hidden');
} else {
localStorage.setItem('collapsible_' + collapsibleIndex, 'visible');
}
if ($(collapsibleElement).attr('id') == 'statsBars'){
$('.main-tabs').fadeToggle();
}
collapsibleElement.slideToggle();
} else {
if (isCurrentlyVisible) {
localStorage.setItem('collapsible_' + collapsibleIndex, 'hidden');
// If the element is visible, slide up
collapsibleElement.animate({
height: 'toggle'
}, 400, function () {
// Ensure the margin-top is reapplied after animation
collapsibleElement.css('margin-top', '-0.2vw');
});
} else {
localStorage.setItem('collapsible_' + collapsibleIndex, 'visible');
// If the element is hidden, slide down
collapsibleElement.css('margin-top', '-0.2vw'); // Set the margin before animation
collapsibleElement.animate({
height: 'toggle'
}, 400);
}
}
});
$('.action-button.expand').click(function () {
var buttonElement = $(this);
var collapsibleElement = $(this).parent().parent().next('.collapsible');
var isCurrentlyVisible = collapsibleElement.is(":visible");
if ($(this).parent().parent().parent().hasClass('expanded')) {
$('.stats-meter .meter.stopped').hide();
$('.stats-meter .meter.running').hide();
$('.stats').removeClass('full');
$(this).parent().parent().parent().removeClass('expanded');
buttonElement.text('→');
} else {
$('.stats-meter .meter' + (meterRunning ? '.running' : '.stopped')).show();
$('.stats').addClass('full');
$(this).parent().parent().parent().addClass('expanded');
buttonElement.text('←');
// Check if the container is not showing, if so, trigger the collapse button
if (!isCurrentlyVisible) {
buttonElement.next('.collapse').trigger('click');
}
}
});
// Add click event for the close button
$('.action-button.close:not(.dry)').click(function (event) {
event.stopPropagation();
var parentElement = $(this).closest('.expandable').parent();
var collapsibleIndex = $('.collapsible').index(parentElement.find('.collapsible'));
// Hide the element and save the state
parentElement.hide();
localStorage.setItem('close_' + collapsibleIndex, 'closed');
$('#chk-' + parentElement.attr('data-id')).prop('checked', false);
});
$('.action-button.close.dry').click(function (event) {
event.stopPropagation();
$(this).parent().parent().parent().hide();
$('.side-tab').removeClass('active');
});
$('#stashInventory .action-button.close.dry,#craftInventory .action-button.close.dry').click(function (event) {
event.stopPropagation();
$('.side-tab').removeClass('active');
});
// Make .movable elements sortable
$("#main-hud-container").sortable({
handle: ".header.draggable",
items: ".movable",
start: function(event, ui) {
$('.side-tabs.main').hide();
},
stop: function(event, ui) {
$('.side-tabs.main').show();
},
update: function(event, ui) {
saveOrder();
}
});
// Restore the saved order
restoreOrder();
function saveOrder() {
var order = $(".movable").map(function() {
return $(this).data("id");
}).get();
localStorage.setItem('sortableOrder', JSON.stringify(order));
}
function restoreOrder() {
var order = JSON.parse(localStorage.getItem('sortableOrder'));
var defaultOrder = ["health", "stats", "mission", "blessings", "inventory"];
if (!order || order.length === 0 || order == defaultOrder) {
order = defaultOrder;
}
if (order != defaultOrder){
var container = $("#main-hud-container");
$.each(order, function(index, value) {
var item = $('[data-id="' + value + '"]');
container.append(item);
});
}
}
// Restore the checkbox states
function restoreCheckboxStates() {
$('.hud-settings .rpgui-checkbox').each(function () {
var containerId = $(this).attr('id');
var value = $(this).val();
var state = localStorage.getItem(value);
if (state === 'closed') {
$(this).prop('checked', false);
} else {
$(this).prop('checked', true);
}
});
}
restoreCheckboxStates();
// Add event listeners to hud checkboxes
$('.hud-settings .rpgui-checkbox').change(function () {
var containerId = $(this).attr('id');
containerId = containerId.replace('chk-', '');
var value = $(this).val();
var isChecked = $(this).is(':checked');
const hudContainer = $(`.movable[data-id='${containerId}']`);