-
Notifications
You must be signed in to change notification settings - Fork 6
/
script.js
2510 lines (2030 loc) · 126 KB
/
script.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
/* -------- scripts/Utility.js -------- */
function convertToTitleSnakeCase(phrase)
{
if(!phrase.length)
return phrase;
phrase = phrase.replaceAll("_", " ");
let words = phrase.split(" ");
let titleCaseWords = [];
for(let word of words)
titleCaseWords.push(word[0].toUpperCase() + word.slice(1).toLowerCase());
return titleCaseWords.join("_");
}
// gotten from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios
const iOSPlatformList = new Set(["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"]);
function isRunningIOS()
{
return iOSPlatformList.has(navigator.platform) ||
// iPad on iOS 13 detection
(navigator.userAgent.includes("Mac") && "ontouchend" in document);
}
function getLocaleString(num)
{
// since this is an internal function with an optional parameter, I am worried that this might cause weird behavior, as in toLocaleString(undefined) behaving differently from toLocaleString()
// return num.toLocaleString(shouldIgnoreLocale ? "en-US" : undefined);
return shouldIgnoreLocale ? num.toLocaleString("en-US") : num.toLocaleString();
}
/* -------- scripts/Globals.js -------- */
let itemsPerRow = 8;
let textListSeparatorSelectedRadio = 0;
let itemsPerRowSlider, itemsPerRowLabel, itemNameInput, itemQuantityInput, itemPriceOrMultiplierInput, itemTable;
let bottomText, screenshotRegion, screenshotPriceHolder;
let settingsOverlay, importFileInput, itemListDropdown, deleteItemListButton, createItemListInput, createItemListButton, includeSettingsInItemListCheckBox, copyCurrentItemsFromItemListCheckBox, abbreviationMappingTable, bottomTextSettingInput, textListSeparatorRadios, textListCustomSeparatorInput, textListSeparatorCustomRadio, textListFormatInput, priceCalculationItemInput, showPriceInScreenshotCheckBox, showTotalInNormalModeCheckBox, hidePriceOrMultiplierCheckBox, defaultQuantityInput, defaultPriceOrMultiplierInput, refocusNameOnSubmitCheckBox, focusQuantityOnAutocompleteCheckBox, ignoreLocaleCheckBox/*, reduceAnimationsCheckBox*/;
let priceCalculationModeStateSpan;
let disableInPriceCalculationModeElems, disableOutsidePriceCalculationModeElems;
let equationVisibilityStateSpan, unselectedItemsVisibilityStateSpan;
let shouldHideUnselectedItems = false;
let totalSelectedPriceArea, totalSelectedPriceHolder, totalSelectedPriceMessageHolder, totalSelectedPriceEquationHolder;
let coinImageUrl;
let priceCalculationItem;
let priceCalculationModeSelectionInfo;
let changelogOverlay, failedCopyOverlay, contactOverlay;
let copyImageLoadingWheel;
let activeItemList;
let shouldIncludeSettingsInItemList, shouldCopyCurrentItemsFromItemList;
let shouldShowTotalInNormalMode; // FIXME -- I'm starting to think more and more that this shouldn't be a variable, since the state is already completely coupled with the checkbox; adding this variable just prevents a get...() call that queries the checkbox with jquery to check if it's checked
let shouldHidePriceOrMultiplier;
let defaultQuantity, defaultPriceOrMultiplier;
let shouldRefocusNameOnSubmit, shouldFocusQuantityOnAutocomplete, shouldIgnoreLocale;
let itemNameFuzzyMatchesHolder, priceCalculationItemFuzzyMatchesHolder;
let preparedItemNames;
let items = new Map();
let itemLists = new Map();
let abbreviationMapping = new Map([
["tnt", "tnt barrel"],
["dyn", "dynamite"],
["wsugar", "white sugar"],
["bsugar", "brown sugar"],
["bpop", "buttered popcorn"],
["cpop", "cherry popsicle"],
["bmuff", "blackberry muffin"],
["rmuff", "raspberry muffin"],
["vice", "vanilla ice cream"],
["sice", "strawberry ice cream"],
["gbar", "gold bar"],
["sbar", "silver bar"],
["pbar", "platinum bar"],
["rcoal", "refined coal"],
["gcheese", "goat cheese"]
]);
let isActivelyCopyingImage = false;
/* -------- scripts/Init.js -------- */
$(document).ready(() =>
{
// Since there are risks that people will lose their item listings and/or settings with update v3.0, I am creating this backup at the very start as a countermeasure for the worst-case scenario (in which case I can roll back the update).
if(localStorage.getItem("v2.14_backup") === null)
localStorage.setItem("v2.14_backup", JSON.stringify(localStorage));
setUpCustomItems();
itemsPerRowSlider = $("#itemsPerRowSlider");
itemsPerRowLabel = $("#itemsPerRowLabel");
itemNameInput = $("#itemNameInput");
itemQuantityInput = $("#itemQuantityInput");
itemPriceOrMultiplierInput = $("#itemPriceOrMultiplierInput");
itemTable = $("#itemTable");
bottomText = $("#bottomText");
screenshotRegion = $("#screenshotRegion");
screenshotPriceHolder = $("#screenshotPriceHolder");
settingsOverlay = new Overlay("settingsOverlay", "showButton");
importFileInput = $("#importFileInput");
itemListDropdown = $("#itemListDropdown");
deleteItemListButton = $("#deleteItemListButton");
createItemListInput = $("#createItemListInput");
createItemListButton = $("#createItemListButton");
includeSettingsInItemListCheckBox = $("#includeSettingsInItemListCheckBox");
copyCurrentItemsFromItemListCheckBox = $("#copyCurrentItemsFromItemListCheckBox");
abbreviationMappingTable = $("#abbreviationMappingTable");
bottomTextSettingInput = $("#bottomTextSettingInput");
textListSeparatorRadios = $("input[name='textListSeparatorGroup']");
textListCustomSeparatorInput = $("#textListCustomSeparatorInput");
textListSeparatorCustomRadio = $("#textListSeparatorCustomRadio");
textListFormatInput = $("#textListFormatInput");
priceCalculationItemInput = $("#priceCalculationItemInput");
showPriceInScreenshotCheckBox = $("#showPriceInScreenshotCheckBox");
showTotalInNormalModeCheckBox = $("#showTotalInNormalModeCheckBox");
hidePriceOrMultiplierCheckBox = $("#hidePriceOrMultiplierCheckBox");
defaultQuantityInput = $("#defaultQuantityInput");
defaultPriceOrMultiplierInput = $("#defaultPriceOrMultiplierInput");
refocusNameOnSubmitCheckBox = $("#refocusNameOnSubmitCheckBox");
focusQuantityOnAutocompleteCheckBox = $("#focusQuantityOnAutocompleteCheckBox");
ignoreLocaleCheckBox = $("#ignoreLocaleCheckBox");
// reduceAnimationsCheckBox = $("#reduceAnimationsCheckBox");
priceCalculationModeStateSpan = $("#priceCalculationModeStateSpan");
disableInPriceCalculationModeElems = $(".disableInPriceCalculationMode");
disableOutsidePriceCalculationModeElems = $(".disableOutsidePriceCalculationMode");
equationVisibilityStateSpan = $("#equationVisibilityStateSpan");
unselectedItemsVisibilityStateSpan = $("#unselectedItemsVisibilityStateSpan");
totalSelectedPriceArea = $("#totalSelectedPriceArea");
totalSelectedPriceHolder = $("#totalSelectedPriceHolder");
totalSelectedPriceMessageHolder = $("#totalSelectedPriceMessageHolder");
totalSelectedPriceEquationHolder = $("#totalSelectedPriceEquationHolder");
priceCalculationModeSelectionInfo = $("#priceCalculationModeSelectionInfo");
changelogOverlay = new Overlay("changelogOverlay", "showButton");
failedCopyOverlay = new Overlay("failedCopyOverlay", "imageHolder");
/* TODO -- should this be called contactUsOverlay instead? */
contactOverlay = new Overlay("contactOverlay", "showButton");
copyImageLoadingWheel = $("#copyImageLoadingWheel");
itemNameFuzzyMatchesHolder = $("#itemNameFuzzyMatchesHolder");
priceCalculationItemFuzzyMatchesHolder = $("#priceCalculationItemFuzzyMatchesHolder");
itemsPerRowSlider.on("input", (event) =>
{
itemsPerRow = parseInt(event.target.value); // must convert to integer/number (since I do + calculations with it and don't want it to concat like a string)
itemsPerRowLabel.text(itemsPerRow);
updateItemLayout();
rescaleScreenshotRegion();
});
itemNameInput.on("focus", () =>
{
updateFuzzyMatches(itemNameInput, itemNameFuzzyMatchesHolder);
});
itemNameInput.on("blur", () =>
{
itemNameFuzzyMatchesHolder.empty();
});
itemNameInput.on("keydown", (e) =>
{
// should use key to get the value representation of the input, allowing numpad numbers to show up like normal numbers ( https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key and https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code )
if(e.key.length !== 1 || e.key < '0' || e.key > '9')
return;
let selection = e.key - '0';
if(selection === 0)
selection = 10;
const buttons = itemNameFuzzyMatchesHolder.find("button");
if(buttons.length < selection)
return;
buttons.eq(selection - 1).trigger("mousedown", {usedKeyboard: true});
event.preventDefault();
});
itemNameInput.on("keyup", (e) =>
{
handleAddingItem(e);
// this should be done AFTER handling adding the item, since we want this to show no results if enter was pressed and the name input got wiped
updateFuzzyMatches(itemNameInput, itemNameFuzzyMatchesHolder);
});
itemQuantityInput.on("keyup", handleAddingItem);
itemPriceOrMultiplierInput.on("keyup", handleAddingItem);
$("#itemSubmitButton").on("click", (e) => handleAddingItem(e, true));
$("#itemDeleteButton").on("click", (e) =>
{
// want to return early if there was no item name (otherwise, the item quantity input's value would stay at 0 because handleAddingItem() would return early without doing anything)
if(!formatItemName(itemNameInput.val()).length)
{
// done to be consistent with Submit; clicking Submit reselects the name field even when it is empty (when this setting is enabled)
if(shouldRefocusNameOnSubmit)
itemNameInput.trigger("select");
return;
}
//items.delete();
itemQuantityInput.val("0");
handleAddingItem(e, true);
});
const coinImagePromise = getImageUrl("Coin")
.then(imageUrl => coinImageUrl = imageUrl)
.catch(e => console.log("Failed to get coin image url --", e));
$("#copyImageToClipboardButton").on("click", copyImageToClipboard);
// TODO -- all of this event stuff seems to be identical for both the settings and changelog popups (and probably for potential future ones as well); I should probably turn at least part of this into some function with parameters for the corresponding jquery objects/selectors (for show button, hide button, background, etc.)
// TODO -- I might want to eventually move this css stuff to a class, then use classList to add/remove these classes from the respective elements? https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
settingsOverlay.showButton.on("click", () =>
{
settingsOverlay.overlay.prop("hidden", false);
// disables scrolling the main page and removes the scrollbar from the side while the settings button is focused ( https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling )
// have to set both due to how I'm hiding overflow-x via css (this might not actually be required; TODO -- see if the css file actually needs html and body to both have overflow set; it seems like both should be set to prevent running into issues though: https://stackoverflow.com/questions/41506456/why-body-overflow-not-working )
$("html, body").css("overflow-y", "hidden");
// prevents the screenshot region from shifting over to the right due to the scrollbar now missing ( https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page and https://css-tricks.com/elegant-fix-jumping-scrollbar-issue/ and https://aykevl.nl/2014/09/fix-jumping-scrollbar )
screenshotRegion.css("margin-right", "calc(100vw - 100%)");
});
settingsOverlay.hideButton.on("click", () =>
{
settingsOverlay.overlay.prop("hidden", true);
$("html, body").css("overflow-y", "visible");
screenshotRegion.css("margin-right", "unset");
});
settingsOverlay.background.on("click", () =>
{
settingsOverlay.hideButton.trigger("click");
});
loadAllFromLocalStorage();
// want to keep this synchronous
ensureItemsHaveMaxPriceSet();
// I could make total price update only once at the end when in price calc mode, but I've decided to update it with every new price loaded in ensureItemsHaveMaxPriceSet(); this way, the user can see the price/errors update in real time (it's more responsive).
/*
.then(() => {
if(getIsInPriceCalculationMode())
updateTotalPrice();
});
*/
// want to update the layout after loading from local storage, but only after the coin image has loaded
coinImagePromise.then(() =>
{
updateItemLayout();
});
// these must all be after local storage is loaded (since their initial values change depending on what the user's settings had saved)
$("#ExportButton").on("click", exportAll);
$("#ImportButton").on("click", () =>
{
importFileInput.trigger("click");
});
importFileInput.on("change", async (event) =>
{
const files = event.target.files;
if(files.length)
importAll(await files[0].text());
event.target.value = null; // reset it to not have any file selected (so that if the user reselects the same file, it will trigger the "change" event to load/import it again)
});
itemListDropdown.on("change", (event) =>
{
deleteItemListButton.prop("disabled", event.target.value === "Default");
storeItemList();
activeItemList = event.target.value;
loadItemList();
});
deleteItemListButton.on("click", () =>
{
if(activeItemList === "Default")
{
console.log("Attempted to delete Default item list! This shouldn't be possible; please contact JJCUBER.");
return;
}
itemLists.delete(activeItemList);
activeItemList = "Default";
loadItemList();
});
createItemListInput.on("input", (event) =>
{
createItemListButton.prop("disabled", itemLists.has(event.target.value));
});
createItemListInput.on("keyup", (event) =>
{
// create item list with current name upon clicking enter key (if it is a valid name)
if(event.code === "Enter" && !createItemListButton.prop("disabled"))
createItemListButton.trigger("click");
});
createItemListButton.on("click", () =>
{
if(itemLists.has(createItemListInput.val()))
{
console.log("Attempted to create an existing item list! This shouldn't be possible; please contact JJCUBER.");
return;
}
storeItemList();
createNewItemList(createItemListInput.val());
createItemListInput.val("");
loadItemList();
});
includeSettingsInItemListCheckBox.on("click", () =>
{
shouldIncludeSettingsInItemList = !shouldIncludeSettingsInItemList;
saveAllToLocalStorage();
});
copyCurrentItemsFromItemListCheckBox.on("click", () =>
{
shouldCopyCurrentItemsFromItemList = !shouldCopyCurrentItemsFromItemList;
saveAllToLocalStorage();
});
// TODO -- make sure nothing related to this (including the stuff in Persist.js) needs to be called before the stuff above (for a while, this was the first section of the settings overlay, but I have since added multiple settings above it).
setUpAbbreviationMappingTable();
// on input for showing live modifications in the background (behind the settings popup)
bottomTextSettingInput.on("input", event =>
{
bottomText[0].innerText = event.target.value;
});
// on change for when focus is lost to the input area, which "commits" the changes to local storage as well
bottomTextSettingInput.on("change", event =>
{
bottomText[0].innerText = event.target.value;
saveAllToLocalStorage();
// I only do this on change and not on input because I fear that it would cause too much lag/input delay from processing this
rescaleScreenshotRegion();
});
bottomText.on("click", () =>
{
settingsOverlay.showButton.trigger("click");
// bottomTextSettingInput[0].scrollIntoView(false); // ensures that the textarea is visible/on screen (and puts it at the bottom so that it won't overlap with the x/close button)
bottomTextSettingInput[0].scrollIntoView(); // ensures that the textarea is visible/on screen (and puts it at the top; for some reason, iOS doesn't do the normal behavior of shifting the page up when showing the keyboard after doing it this way)
// TODO -- maybe this should be .focus() instead?
bottomTextSettingInput.trigger("select");
});
// (only fires once the slider is released)
itemsPerRowSlider.on("change", () =>
{
saveAllToLocalStorage();
});
// be careful; checked is a property, NOT an attribute (I originally was using .attr() -- https://api.jquery.com/attr/ )
textListSeparatorRadios.eq(textListSeparatorSelectedRadio).prop("checked", true);
textListCustomSeparatorInput[0].disabled = textListSeparatorRadios[textListSeparatorSelectedRadio].id !== "textListSeparatorCustomRadio";
textListSeparatorRadios.each((i, elem) =>
{
$(elem).on("click", i, (event) =>
{
textListSeparatorSelectedRadio = event.data;
// textListCustomSeparatorInput[0].disabled = event.target.id !== "textListSeparatorCustomRadio";
textListCustomSeparatorInput[0].disabled = event.target !== textListSeparatorCustomRadio[0];
saveAllToLocalStorage();
});
});
textListCustomSeparatorInput.on("change", (event) =>
{
textListSeparatorCustomRadio.val(event.target.value);
saveAllToLocalStorage();
});
textListFormatInput.on("change", () =>
{
saveAllToLocalStorage();
});
priceCalculationItemInput.on("focus", () =>
{
updateFuzzyMatches(priceCalculationItemInput, priceCalculationItemFuzzyMatchesHolder);
});
priceCalculationItemInput.on("blur", () =>
{
priceCalculationItemFuzzyMatchesHolder.empty();
});
priceCalculationItemInput.on("keydown", (e) =>
{
// should use key to get the value representation of the input, allowing numpad numbers to show up like normal numbers ( https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key and https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code )
if(e.key.length !== 1 || e.key < '0' || e.key > '9')
return;
let selection = e.key - '0';
if(selection === 0)
selection = 10;
const buttons = priceCalculationItemFuzzyMatchesHolder.find("button");
if(buttons.length < selection)
return;
buttons.eq(selection - 1).trigger("mousedown", {usedKeyboard: true});
event.preventDefault();
});
priceCalculationItemInput.on("keyup", (e) =>
{
updateFuzzyMatches(priceCalculationItemInput, priceCalculationItemFuzzyMatchesHolder);
});
priceCalculationItemInput.on("change", async (event) =>
{
let itemNameFormatted = formatItemName(event.target.value);
let itemUrl, itemMaxPrice;
try
{
itemUrl = await getImageUrl(itemNameFormatted);
itemMaxPrice = await getMaxPrice(itemNameFormatted);
}
catch
{
// default to diamond ring for invalid item names
itemNameFormatted = "Diamond_Ring";
itemUrl = await getImageUrl(itemNameFormatted);
itemMaxPrice = await getMaxPrice(itemNameFormatted);
}
priceCalculationItem = new Item(itemNameFormatted, undefined, itemUrl, undefined, itemMaxPrice);
// TODO -- it might be better to just always make sure price gets immediately updated tbh (although, enabling price calc mode or showing of the price in screenshot will run update total price themselves)
if(getIsInPriceCalculationMode() || getIsPriceShownInScreenshot())
updateTotalPrice();
saveAllToLocalStorage();
});
// want to make it fire immediately the first time; I couldn't do this inside the load all function since this must be set after the load all and after the coin image url is fetched
priceCalculationItemInput.trigger("change");
// TODO -- should I be using change event instead of click event for checkboxes (along with any input element variants)? Resources such as https://stackoverflow.com/questions/3442322/jquery-checkbox-event-handling make it sound like click doesn't work for certain things, but they do seem to (which is likely due to how old this so question is). This resource seems to better explain; in my use case, they are pretty much identical, though there is a potential distinction: https://stackoverflow.com/questions/11205957/jquery-difference-between-change-and-click-event-of-checkbox
showPriceInScreenshotCheckBox.on("click", () =>
{
let wasShowing = getIsPriceShownInScreenshot();
screenshotPriceHolder.prop("hidden", wasShowing);
showTotalInNormalModeCheckBox.prop("disabled", wasShowing);
if(!wasShowing)
updateTotalPrice();
saveAllToLocalStorage();
});
showTotalInNormalModeCheckBox.on("click", () =>
{
shouldShowTotalInNormalMode = !shouldShowTotalInNormalMode;
updateTotalPrice();
saveAllToLocalStorage();
});
hidePriceOrMultiplierCheckBox.on("click", () =>
{
shouldHidePriceOrMultiplier = !shouldHidePriceOrMultiplier;
updateItemLayout();
saveAllToLocalStorage();
});
defaultQuantityInput.on("change", (event) =>
{
// TODO -- should this instead be set within saveAllToLocalStorage()? Probably not...
defaultQuantity = event.target.value;
saveAllToLocalStorage();
});
defaultPriceOrMultiplierInput.on("change", (event) =>
{
// TODO -- should this instead be set within saveAllToLocalStorage()? Probably not...
defaultPriceOrMultiplier = event.target.value;
saveAllToLocalStorage();
});
refocusNameOnSubmitCheckBox.on("click", () =>
{
shouldRefocusNameOnSubmit = !shouldRefocusNameOnSubmit;
saveAllToLocalStorage();
});
focusQuantityOnAutocompleteCheckBox.on("click", () =>
{
shouldFocusQuantityOnAutocomplete = !shouldFocusQuantityOnAutocomplete;
saveAllToLocalStorage();
});
ignoreLocaleCheckBox.on("click", () =>
{
shouldIgnoreLocale = !shouldIgnoreLocale;
updateTotalPrice();
saveAllToLocalStorage();
});
// reduceAnimationsCheckBox.on("click", () =>
// {
// // TODO -- figure out how to disable animations and transitions via js; I don't see a good way currently
// });
$("#copyAsTextListButton").on("click", copyAsTextListToClipboard);
$("#clearAllButton").on("click", () =>
{
if(confirm("Are you sure? This will clear the items currently added and can't be undone."))
{
items.clear();
updateItemLayout();
saveAllToLocalStorage();
}
});
disableOutsidePriceCalculationModeElems.prop("disabled", true);
$("#priceCalculationToggleButton").on("click", () =>
{
// MUST use currentTarget (or just reference priceCalculationToggleButton); event.target gets set to the span if it is the one actually clicked ( https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget )
// TODO -- maybe change all even.target's to even.currentTarget in my code?
const toggleButton = event.currentTarget;
const wasEnabled = getIsInPriceCalculationMode();
// make relevant buttons enabled/disabled
disableInPriceCalculationModeElems.prop("disabled", !wasEnabled);
disableOutsidePriceCalculationModeElems.prop("disabled", wasEnabled);
// make relevant elements hidden/visible
// TODO - maybe make this a class/two classes like how I did enabled/disabled buttons? However, there aren't really enough elements to warrant that at the moment (though it could help express intent).
totalSelectedPriceArea.prop("hidden", wasEnabled);
priceCalculationModeSelectionInfo.prop("hidden", wasEnabled);
if(wasEnabled)
{
// disable it
priceCalculationModeStateSpan.text("Enable"); // says the "opposite," since that's what it will change the state to on click
toggleButton.classList.remove("selected");
}
else
{
// enable it
priceCalculationModeStateSpan.text("Disable"); // says the "opposite," since that's what it will change the state to on click
toggleButton.classList.add("selected");
}
// restore previous/remove all selections/custom adornments (done by refreshing the layout)
updateItemLayout();
});
$("#selectAllButton").on("click", () =>
{
const cells = $("#itemTable td");
setSelectedStateAll(items.values(), cells, true);
updateTotalPrice();
// need to update what items are and aren't visible now that all items have been selected (even previously hidden ones)
if(shouldHideUnselectedItems)
updateItemLayout();
});
$("#clearSelectionButton").on("click", () =>
{
const cells = $("#itemTable td");
setSelectedStateAll(items.values(), cells, false);
updateTotalPrice();
// need to update what items are and aren't visible now that all items have been deselected (even previously visible ones)
if(shouldHideUnselectedItems)
updateItemLayout();
});
$("#subtractSelectedQuantitiesButton").on("click", () =>
{
for(let item of items.values())
{
if(!item.isSelected)
continue;
item.quantity -= item.customQuantity ?? item.quantity;
item.customQuantity = undefined;
// it should be fine to remove elements from a map while iterating over it according to https://stackoverflow.com/questions/35940216/es6-is-it-dangerous-to-delete-elements-from-set-map-during-set-map-iteration
if(item.quantity <= 0)
items.delete(item.name);
// TODO - Should items that have a >0 quantity left stay selected? On the one hand, one might consider custom quantities to be all you selected; on the other hand, one might consider custom quantities to be just part of the whole currently being worked on in this moment (which means that after subtracting said amount, they still want to work with the rest of said item's quantity and/or keep it selected).
// If I decide to deselect all, I should put an else to the if above which does item.isSelected = false;
}
updateItemLayout();
saveAllToLocalStorage();
});
$("#deleteSelectedButton").on("click", () =>
{
for(let item of items.values())
{
if(item.isSelected)
items.delete(item.name);
}
updateItemLayout();
saveAllToLocalStorage();
});
$("#resetCustomValuesButton").on("click", () =>
{
for(let item of items.values())
{
item.customQuantity = undefined;
item.customPriceOrMultiplier = undefined;
}
updateItemLayout();
});
$("#equationVisibilityToggleButton").on("click", () =>
{
// TODO - might want to use something like this for the price calculation toggle, since it can be tied to the total price div area
const wasHidden = totalSelectedPriceEquationHolder.is("[hidden]");
equationVisibilityStateSpan.text(wasHidden ? "Hide" : "Show");
totalSelectedPriceEquationHolder.prop("hidden", !wasHidden);
const toggleButton = event.currentTarget;
if(wasHidden)
toggleButton.classList.add("selected");
else
toggleButton.classList.remove("selected");
});
$("#unselectedItemsVisibilityToggleButton").on("click", () =>
{
const wasHidden = shouldHideUnselectedItems;
unselectedItemsVisibilityStateSpan.text(wasHidden ? "Hide" : "Show");
const toggleButton = event.currentTarget;
if(wasHidden)
toggleButton.classList.remove("selected");
else
toggleButton.classList.add("selected");
shouldHideUnselectedItems = !shouldHideUnselectedItems;
updateItemLayout();
});
setUpChangelog();
changelogOverlay.showButton.on("click", () =>
{
changelogOverlay.overlay.prop("hidden", false);
// disables scrolling the main page and removes the scrollbar from the side while the settings button is focused ( https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling )
$("html, body").css("overflow-y", "hidden");
// prevents the screenshot region from shifting over to the right due to the scrollbar now missing ( https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page and https://css-tricks.com/elegant-fix-jumping-scrollbar-issue/ and https://aykevl.nl/2014/09/fix-jumping-scrollbar )
screenshotRegion.css("margin-right", "calc(100vw - 100%)");
});
changelogOverlay.hideButton.on("click", () =>
{
changelogOverlay.overlay.prop("hidden", true);
$("html, body").css("overflow-y", "visible");
screenshotRegion.css("margin-right", "unset");
});
changelogOverlay.background.on("click", () =>
{
changelogOverlay.hideButton.trigger("click");
});
handleVersionChange();
failedCopyOverlay.hideButton.on("click", () =>
{
failedCopyOverlay.overlay.prop("hidden", true);
$("html, body").css("overflow-y", "visible");
screenshotRegion.css("margin-right", "unset");
});
failedCopyOverlay.background.on("click", () =>
{
failedCopyOverlay.hideButton.trigger("click");
});
contactOverlay.showButton.on("click", () =>
{
contactOverlay.overlay.prop("hidden", false);
// disables scrolling the main page and removes the scrollbar from the side while the settings button is focused ( https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling )
$("html, body").css("overflow-y", "hidden");
// prevents the screenshot region from shifting over to the right due to the scrollbar now missing ( https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page and https://css-tricks.com/elegant-fix-jumping-scrollbar-issue/ and https://aykevl.nl/2014/09/fix-jumping-scrollbar )
screenshotRegion.css("margin-right", "calc(100vw - 100%)");
});
contactOverlay.hideButton.on("click", () =>
{
contactOverlay.overlay.prop("hidden", true);
$("html, body").css("overflow-y", "visible");
screenshotRegion.css("margin-right", "unset");
});
contactOverlay.background.on("click", () =>
{
contactOverlay.hideButton.trigger("click");
});
$("#tryNewSiteButton").on("click", () =>
{
window.open("https://hd.jjtechdev.com/", "_blank");
});
prepareAllItemNames();
// prevents zooming in on input/textarea focus in iOS
// TODO -- maybe make this some class and/or css media query-related thing?
if(isRunningIOS())
$("input, textarea").css("font-size", "16px");
// rescale screenshot region whenever window/page is resized (also invokes it for the first time immediately to ensure it starts scaled properly)
$(window).on("resize", rescaleScreenshotRegion);
rescaleScreenshotRegion();
});
/* -------- scripts/Overlay.js -------- */
// TODO -- maybe make show and hide functions?
class Overlay
{
// TODO -- extraIds is a bad name; it should be something pertaining to extra overlay elements (showButton, imageHolder, etc.)
// TODO - I might want to make a list of dictionary mappings from extra overlay element name to function for settings up (since I have repeated code pertaining to showButtons)
constructor(overlayId, ...extraIds)
{
this.overlay = $(`#${overlayId}`);
this.background = this.overlay.find(".overlayBackground");
this.box = this.overlay.find(".overlayBox");
this.hideButton = this.overlay.find(".overlayHideButton");
this.inner = this.overlay.find(".overlayInner");
// add the extra ids as valid this. entries
for(let extraId of extraIds)
{
if(!extraId.length)
continue;
const extraIdFirstUpper = extraId[0].toUpperCase() + extraId.slice(1);
this[extraId] = $(`#${overlayId}${extraIdFirstUpper}`);
}
}
}
/* -------- scripts/Item.js -------- */
// There are more operators than the ones here technically supported by math.js, but I feel like these are all the "reasonable" ones to support for the automatic prepending of the old quantity/custom quantity ( https://mathjs.org/docs/expressions/syntax.html )
// TODO -- I could theoretically make this a set, but that's probably not a good idea since the "keys" have differing lengths and I'm just looking for whether a given equation string starts with one of these keys
const operators = ['+', '-', '*', '/', '^', '%', "mod", '&', '|', "<<", ">>>", ">>"]; // >>> should be before >> to ensure the full operator gets removed then readded later (if >> was first, ">>> 5" would only remove the first 2 '>' leaving "> 5")
function handleAddingItem(e, usedSubmitButton = false)
{
// only want the name box to have the invalid red border until the user starts typing again (tabbing into this textbox also cancels it; unfortunately, this gets removed almost immediately if the user starts typing right after pressing enter, since it takes a bit of time for the fetch to occur and for the invalid class to be added, if needed)
if(itemNameInput.hasClass("invalid"))
itemNameInput.removeClass("invalid");
// Don't want to accept changes while trying to copy the image
// TODO -- I don't handle actively copying image yet for anything related to price calculation mode; maybe I should do that?
if(isActivelyCopyingImage)
return;
// TODO -- might want to be using e.key instead
if(!usedSubmitButton && e.code !== "Enter")
return;
// at this point, the user has attempted to submit (or delete), so the input should get reselected (if the setting is enabled; this mostly just matters for people who click the submit button instead of enter)
// note that this also occurs when Delete button gets clicked
if(shouldRefocusNameOnSubmit)
itemNameInput.trigger("select");
const itemNameFormatted = formatItemName(itemNameInput.val());
if(!itemNameFormatted.length)
return;
let itemQuantity, prependedQuantityOperator = "";
let itemQuantityEquation = itemQuantityInput.val().trim();
// only want to separate starting operator if the item already exists (if the item doesn't exist, the whole quantity should be evaluated as one equation)
if(items.has(itemNameFormatted))
{
for(let operator of operators)
{
if(!itemQuantityEquation.startsWith(operator))
continue;
prependedQuantityOperator = operator;
itemQuantityEquation = itemQuantityEquation.substr(prependedQuantityOperator.length);
break;
}
}
try
{
// rest of equation is calculated beforehand so that addItem() gets an actual value
itemQuantity = itemQuantityEquation.length ? math.evaluate(itemQuantityEquation) : 0;
}
catch(e)
{
console.log("Unable to evaluate quantity --", e);
return;
}
addItem(itemNameFormatted, itemQuantity, itemPriceOrMultiplierInput.val(), prependedQuantityOperator)
.then(() => updateItemLayout())
.catch(e =>
{
console.log("Failed to add item and update layout --", e);
itemNameInput.addClass("invalid");
});
itemNameInput.val("");
itemQuantityInput.val(defaultQuantity);
itemPriceOrMultiplierInput.val(defaultPriceOrMultiplier);
}
class Item
{
static fieldsToOmitFromLocalStorage = new Set(["customQuantity", "customPriceOrMultiplier", "isSelected"]);
constructor(name, quantity, url, priceOrMultiplier, maxPrice)
{
this.name = name;
this.quantity = quantity;
this.url = url;
this.priceOrMultiplier = priceOrMultiplier;
this.maxPrice = maxPrice;
// these should not persist across sessions (I also omit them from the JSON.stringify)
this.customQuantity = undefined;
this.customPriceOrMultiplier = undefined;
this.isSelected = false;
}
getHumanReadableName()
{
return this.name.replaceAll("_", " ");
}
// returns [totalPrice, equation, error, warning]
calculateTotalPrice(shouldIgnoreCustomValues = false)
{
let quantity = this.customQuantity ?? this.quantity,
priceOrMultiplier = this.customPriceOrMultiplier ?? this.priceOrMultiplier,
maxPrice = this.maxPrice;
if(shouldIgnoreCustomValues)
{
quantity = this.quantity;
priceOrMultiplier = this.priceOrMultiplier;
}
if(!maxPrice && !customItemNames.has(this.name))
return [NaN, "NaN", `${this.getHumanReadableName()} doesn't have a valid maximum price (${maxPrice}).`];
priceOrMultiplier = priceOrMultiplier.trim();
let price, mult;
let warning;
if(!priceOrMultiplier.length)
{
mult = "1";
warning = `The price/multiplier for ${this.getHumanReadableName()} was empty, so it was defaulted to 1x.` ;
}
else if(priceOrMultiplier.endsWith('x'))
{
// this is to handle when a custom item name without a maximum price reaches here
if(!maxPrice)
return [NaN, "NaN", `${this.getHumanReadableName()} is a custom item without a valid maximum price (${maxPrice}).`];
mult = priceOrMultiplier.slice(0, -1);
}
else if(priceOrMultiplier.endsWith('k'))
price = `(${priceOrMultiplier.slice(0, -1)})*10^3`;
else if(priceOrMultiplier.endsWith('m'))
price = `(${priceOrMultiplier.slice(0, -1)})*10^6`;
else
price = priceOrMultiplier;
if(mult)
price = `${maxPrice}*(${mult})`;
// I'm doing this so that it can be shown to the user in full
price = `${quantity}*(${price})`;
try
{
return [math.evaluate(price), price, undefined, warning];
}
catch(e)
{
console.log(e);
// I believe that it would only ever be an issue with the price/mult?
// return [NaN, price, `${this.getHumanReadableName()} has some invalid value (quantity: ${quantity}, price/multiplier: ${priceOrMultiplier}, max price: ${maxPrice} -- equation: ${price}).`, warning];
return [NaN, price, `${this.getHumanReadableName()} has an invalid price/multiplier (price/multiplier: ${priceOrMultiplier} -- equation: ${price}).`, warning];
}
}
}
function addItem(itemNameFormatted, itemQuantity, itemPriceOrMultiplier, prependedQuantityOperator = "")
{
const isInPriceCalculationMode = getIsInPriceCalculationMode();
// the itemQuantity is already completely calculated, but we need to ensure that it isn't floating-point
if(!prependedQuantityOperator)
itemQuantity = Math.floor(itemQuantity);
if(items.has(itemNameFormatted))
{
const currItem = items.get(itemNameFormatted);
// modifies the custom fields instead when in price calculation mode
if(isInPriceCalculationMode)
{
if(prependedQuantityOperator.length)
itemQuantity = Math.floor(math.evaluate(`${currItem.customQuantity ?? currItem.quantity} ${prependedQuantityOperator} ${itemQuantity}`));
// only stores custom if it differs; custom quantity set to <=0 defaults back to normal quantity, and custom price/mult gets wiped if its field becomes empty (otherwise the user might try to wipe it out, only to find out that it makes the mult default to 1x)
currItem.customQuantity = (itemQuantity > 0 && itemQuantity !== currItem.quantity) ? itemQuantity : undefined;
currItem.customPriceOrMultiplier = (itemPriceOrMultiplier.trim().length && itemPriceOrMultiplier !== currItem.priceOrMultiplier) ? itemPriceOrMultiplier : undefined;
// makes sure that the item just modified is selected so that the custom value is visible to the user (if the user modified the value, they likely wanted it to be selected); this is to help with the fact that clicking on a selected item's quantity/price will deselect it
currItem.isSelected = true;
return Promise.resolve();
}
if(prependedQuantityOperator.length)
itemQuantity = Math.floor(math.evaluate(`${currItem.quantity} ${prependedQuantityOperator} ${itemQuantity}`));
if(itemQuantity > 0)
{
const prevQuantity = currItem.quantity;
currItem.quantity = itemQuantity;
currItem.priceOrMultiplier = itemPriceOrMultiplier;
// need to wipe out custom values if they now match the new quantity/prices
if(currItem.customQuantity === currItem.quantity || (currItem.customQuantity > currItem.quantity && currItem.customQuantity < prevQuantity)) // after updating an item's actual quantity, custom quantities above it should reset/"snap" back to the new quantity (unless it was already above it; custom quantity won't ever equal previous quantity, since it would have just gotten reset to undefined)
currItem.customQuantity = undefined;
if(currItem.customPriceOrMultiplier === currItem.priceOrMultiplier)