-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUniversalInventorySystem.js
12453 lines (11990 loc) · 536 KB
/
UniversalInventorySystem.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
/*
Universal Inventory System (UInv)
by HiEv v0.9.7.3
A JavaScript inventory "plugin" for Twine 2 / SugarCube 2.
Home Page: https://github.com/HiEv/UInv
v0.5.7 - March 29, 2018 - (preview release 1)
- 62 functions written out of 108 planned functions
v0.6.9 - April 6, 2018 - (preview release 2)
- 28 new functions written + 23 new functions planned
- some functions renamed to conform to consistent naming style
v0.7.7 - April 18, 2018 - (preview release 3)
- 32 new functions written + 27 new functions planned
- some functions renamed to conform to consistent naming style
- most previously incomplete functions are now complete
- lots of debugging and additional error checking done
v0.8.6 - April 24, 2018 - (preview release 4)
- 25 new functions written + 13 new functions planned
- some functions renamed to conform to consistent naming style
- work on help file started (very preliminary)
v0.9.1 - May 10, 2018 - (preview release 5)
- 18 new functions written + 11 new functions planned
- added default bags
- major rework of engine to allow deletion of default properties
- some bugs fixed
v0.9.2 - May 23, 2018 - (preview release 6)
- 10 new functions written + 8 new functions planned
- renamed BagCount to GetBagCount for more consistent naming style
- moved data sections to bottom to make updating UInv easier
- some bugs fixed
- Item Builder added to UInv help file
v0.9.4 - July 8, 2018 - (preview release 7)
- 22 new functions written + 19 new functions planned
- some functions renamed to conform to consistent naming style
- centralized more functions for display utilities
- saved a bit more memory/history size
- handled a potential problem with non-static default properties
- improved compatibility with other browsers
- moved utility functions inside UInv namespace
v0.9.5 - July 23, 2018 - (preview release 8)
- 12 new functions written + 12 new functions planned
- revamped error handling to add thrown errors
- added utility functions for engine detection
- saved a bit more memory/history size
- major restructuring of item data
- added handling of variable items and variable bags
v0.9.6 - September 25, 2018 - (preview release 9)
- 31 new functions written + 27 new functions planned
- major bugfix in SwapItems and many "Tag" functions
- all utility function names now start lowercase
- added the ability to cache images for online usage
- the UInv Safe Save Code has been updated (see help)
- added option for sending UInv errors to console
- typing "xyzzy" now toggles console (F12) error log
- began implementation of display elements
* table
* radialMenu
- began implementation of event handlers
"general" events:
* MouseDown
* MouseUp
"bag" events:
* Touched
"table" events:
* Accept
* DragStart
* Drop
* DragStop
"radialMenu" events:
* Open
* WedgeClick
* DisabledWedgeClick
* Cancel
"cacheImages" events:
* Loaded
* Error
- added Font Awesome support: https://fontawesome.com/free
just add the following line to your stylesheet section:
@import url('https://use.fontawesome.com/releases/v5.3.1/css/all.css');
see the "FA_Icons.html" sample for the list of icons
- jQuery UI is now required to support display elements
https://api.jqueryui.com/category/all/
just include and load the jquery-ui.css and jquery-ui.js
files, along with the "images/ui-*.png" images
v0.9.7 - December 29, 2018 - (preview release 10)
- 40 new functions written (including 2 macros) + 38 new functions planned
- added Pocket/Container functions; items can now contain other items
- updated existing functions to work with pockets properly
- updated more functions to support bag name arrays
- added a <<UInvSet>> macro to shorten calls to multiple UInv functions
- added a <<UInvTry>> macro to simplify error handling in TwineScript
- added more ways to add default items to default bags
- default return value on error was standardized to "undefined"
- enforced stricter verification of values for item names (must be lowercase, etc...)
- removed LockUpdates function; use IncrementUpdateLock and DecrementUpdateLock instead
- removed capitalizeFirstLetter function; use SugarCube's .toUpperFirst() instead
- discovered a function I wrote and apparently forgot to document anywhere (LOL)
- renamed the following functions to conform to consistent naming style (aliases added):
* ArrayHasAllBagProperties to BagHasAllProperties
* ArrayHasAllItemProperties to ItemHasAllProperties
* GetBagArrayWithAllProperties to GetBagsArrayWithAllProperties (added an "s")
* GetHighestBagPropertyValue to GetBagWithHighestPropertyValue
* GetHighestItemPropertyValue to GetItemWithHighestPropertyValue
* GetLowestBagPropertyValue to GetBagWithLowestPropertyValue
* GetLowestItemPropertyValue to GetItemWithLowestPropertyValue
* SetItemsPropertyValues to SetItemsPropertyValue (removed an "s")
* UpdateItemProperties to SetItemPropertyValues
- fixes/improvements to valuesAreEqual, arraysAreEqual, and objectsAreEqual
- corrected two minor inefficiencies in memory/history usage
- fixed a few incorrect function names in error messages
- fixed a problem with items changed to variable type still using default properties
- fixed a problem where variable type items might not merge when they should
- fixed GetBagWithHighestPropertyValue and GetBagWithLowestPropertyValue functions
- fixed a bug in BagHasAllProperties
- preliminary work on unit/regression testing tool (37 functions fully tested)
- property values may now be set to "undefined"
- new/updated general help file sections:
* Changelog
* Function Cheat Sheet
* Basic UInv Functions (incomplete)
* Error Handling (incomplete)
* Efficient UInv Coding
* Arrays vs Generic Objects (major improvements; incomplete)
* The UInv Data Structure
- worked on how help file entries should look for UInv functions (see "AddBag")
- modified UInv structure to support internal-use-only functions and variables
* this means you'll need to insert your bag, item, and alias definitions this update
- Over 10,000 non-blank lines of code and comments! Yay for arbitrary milestones!
v0.9.7.1 (bugfix) - September 7, 2019 - (preview release 11)
- 7 new functions written + 5 new functions planned
- added support for Set and Map objects; UInv now supports all of SugarCube's supported types
- added an "Idle" event to the "cacheImages" events.
- fixed a problem the image cache had with some browsers
- fixed a couple of bugs in the event handler code
* note: this required some minor changes to the CSS generated for tables
* Table Builder updated to accommodate CSS changes
- added another bit of sample code to the UInv_Sample_Code.html file
- another update to the "UInv Safe Save Code" in the UInv help file
- numerous help file updates and fixes
v0.9.7.2 (minor update) - September 9, 2019 - (preview release 12)
- 4 new functions written
- added some missing JavaScript Date, Map, and Set object support
- added missing documentation for new utility functions to help file
v0.9.7.3 (bugfix) - January 16, 2022 - (preview release 13)
- bugfix: the BagHasAllItems() and BagHasAnyItem() functions were only checking the first item in the array of items
- bugfix: fixed a problem with UInv elements in the UI bar not working properly
- bugfix: fixed GetAllBagPockets() incorrectly returning duplicate pocket names
*/
/*
The next few comment blocks are to support JavaScript validators such as:
https://eslint.org/demo/
http://JSHint.com/
https://deepscan.io/demo/
http://beautifytools.com/javascript-validator.php
*/
/* jshint -W014 */
/* eslint-disable no-unused-vars */
/*
global UInv, $, setup, clone, opr, safari, Config, Browser, State, random, passage, Macro, Scripting, version
*/
/* jshint ignore:start */ /* Disable this line to test with JSHint. It's too slow to leave enabled. */
/* Increase SugarCube maxLoopIterations if needed. */
if (Config.macros.maxLoopIterations < 2000) {
Config.macros.maxLoopIterations = 2000;
}
if (setup.ImagePath === undefined) { /* Do this better later *** */
setup.ImagePath = "";
}
/* -- Universal Inventory System (UInv) -- */
/* UInvObject: UInv constructor and initialization object. */
function UInvObject () {
if ((typeof version == "undefined") || (typeof version.title == "undefined") || (version.title != "SugarCube")
|| (typeof version.major == "undefined") || (version.major < 2)
|| (typeof version.minor == "undefined") || (version.minor < 8)) {
throw new Error("UInv requires SugarCube v2.8.0 or greater. Please upgrade to the latest version of the SugarCube v2 story format.");
}
/* deepFreeze: Freeze everything in an object's property tree. */
function deepFreeze (Obj) {
var value, name, i, propNames = Object.getOwnPropertyNames(Obj);
/* Freeze the object's child properties before freezing the object. */
for (i = 0; i < propNames.length; i++) {
name = propNames[i];
value = Obj[name];
Obj[name] = value && typeof value === "object" ? deepFreeze(value) : value; /* Recursively handle sub-properties, if any exist. */
}
return Object.freeze(Obj);
}
/* parseUInvLine: Returns a string with "UInv." added in front of any UInv function names in the Txt string, provided that:
* they're a valid UInv function name (including aliases)
* they're preceded by a " ", tab, ",", "+", "-", "/", "*", "%", "=", "<", ">", "!", "&", "|", "?", "(", "[", "{", or ":"
* they're immediately followed by a "(" (the left parenthesis)
* they're not within a string (within a pair of single or double-quotes)
*/
function parseUInvLine (TxtIn) {
var Prec = [" ", " ", ",", "+", "-", "/", "*", "%", "=", "<", ">", "!", "&", "|", "?", "(", "[", "{", ":"];
var Group = ["'", '"'];
TxtIn = TxtIn.trim();
var TxtOut = "", Word = "", Prv = "+", n = 0, g = -1;
while (n < TxtIn.length) {
if (g < 0) {
if (TxtIn[n] == "(") {
if (Prec.includes(Prv) && (UInv.isFunction(UInv[Word]) || UInv.isProperty(UInv, Word))) {
TxtOut += "UInv." + Word;
} else {
TxtOut += Word;
}
Word = "";
}
if (Prec.includes(TxtIn[n])) {
TxtOut += Word + TxtIn[n];
Prv = TxtIn[n];
Word = "";
} else if (Group.includes(TxtIn[n])) {
g = Group.indexOf(TxtIn[n]);
TxtOut += Word;
Word = TxtIn[n];
} else {
Word += TxtIn[n];
}
} else {
Word += TxtIn[n];
if (TxtIn[n] == Group[g]) {
Prv = Group[g];
g = -1;
TxtOut += Word;
Word = "";
}
}
n++;
}
TxtOut += Word;
return TxtOut;
}
/* Lock the existing property values to prevent accidental changes. */
deepFreeze(this);
/* Debugging Feature: Enables directing errors to the console by typing "xyzzy". */
var UInvDebugTrigger = "";
$(document).on("keypress", function (ev) {
UInvDebugTrigger += ev.key;
if (UInvDebugTrigger.length > 5) {
UInvDebugTrigger = UInvDebugTrigger.slice(-5);
}
if (UInvDebugTrigger === "xyzzy") {
if (UInv.isUndefined(setup.UInvUserAlertsDebug)) {
setup.UInvUserAlertsBackup = UInv.GetUserAlerts();
UInv.SetUserAlerts(UInv.ERROR_SHOW_PASSAGE_NAME + UInv.ERROR_TO_CONSOLE);
setup.UInvUserAlertsDebug = UInv.ERROR_SHOW_PASSAGE_NAME + UInv.ERROR_TO_CONSOLE;
alert("UInv: Errors will now be shown in the console window.\nHit F12 to open the console window.");
console.log("UInv: Error logging enabled.\n$UInvLastErrorMessage = " + State.variables.UInvLastErrorMessage);
} else {
UInv.SetUserAlerts(setup.UInvUserAlertsBackup);
delete setup.UInvUserAlertsBackup;
console.log("UInv: Error logging reverted to default. (" + setup.UInvUserAlertsDebug + ")");
alert("UInv: Error logging reverted to default. (" + setup.UInvUserAlertsDebug + ")");
delete setup.UInvUserAlertsDebug;
}
}
});
/* Automatically link up UInv display elements when passage is rendered. */
$(document).on(":passageend", function (ev) {
if (!UInv.UpdatesAreLocked()) {
UInv.UpdateDisplay();
}
var el = $("#uinv-radial-menu").get(0);
if (UInv.isUndefined(el)) {
UInv.InitializeRadialMenu();
} else {
if (el.dataset.status == "opened") { /* Cancel radial menu */
ev.cancelType = "NewPassage";
var Ret = UInv.CallEventHandler("radialMenu", "Cancel", ev); /* radialMenu Cancel event (New passage) */
if (Ret.keepOpen !== true) {
el.dataset.status = "closed";
el.style.transform = "scale(0, 0)";
el.style.opacity = 0;
}
UInv.UpdateDisplay();
}
}
/* Textarea cursor fix for Chrome & Firefox. */
$("textarea").mousemove(function (e) {
var myPos = $(this).offset();
myPos.bottom = $(this).offset().top + $(this).outerHeight();
myPos.right = $(this).offset().left + $(this).outerWidth();
if (myPos.right > e.pageX && e.pageX > myPos.right - 16) {
if (myPos.bottom > e.pageY && e.pageY > myPos.bottom - 16) {
if ($(this).css("cursor") != "ns-resize") {
$(this).css("cursor", "ns-resize"); /* Chrome fix */
}
} else {
if ($(this).prop("clientHeight") < $(this).prop("scrollHeight")) {
if ($(this).css("cursor") != "default") {
$(this).css("cursor", "default"); /* Firefox fix */
}
} else {
if ($(this).css("cursor") != "auto") {
$(this).css("cursor", "auto");
}
}
}
} else {
if ($(this).css("cursor") != "auto") {
$(this).css("cursor", "auto");
}
}
});
});
/* <<UInvSet>> macro: This macro wraps each line in <<set (line)>>, adds "UInv." in front of any UInv function calls (including custom aliases), and executes it. */
/* Usage:
<<UInvSet>>
AddBag("backpack")
AddItem("", "pants")
SetItemQuantity("", "", 5 + BagHasItem("", ""))
_Items = GetType(_itemType)
<</UInvSet>>
*/
Macro.add('UInvSet', {
skipArgs : true,
tags : null,
handler : function () {
var Lines = this.payload[0].contents.split("\n"), i, output = "";
for (i = 0; i < Lines.length; i++) {
Lines[i] = parseUInvLine(Lines[i]);
if (Lines[i] != "") {
output += "<<set " + Lines[i].trim() + ">>";
}
}
$(this.output).wiki(output);
}
});
/* <<UInvTry>> macro: This macro tries to execute a <<set>> macro, adding "UInv." in front of any UInv functions. Failure is determined by whether or not UInv (or any other code) throws an error. */
/* If it succeeds, the chunk of code between <<UInvTry>> and <<Failure>> will execute normally, and the code between <<Failure>> and <</UInvTry>> will *not* execute. */
/* If there is an error, the chunk of code between <<Failure>> and <</UInvTry>> will execute normally, and the code between <<UInvTry>> and <<Failure>> will *not* execute. */
/* Usage:
<<UInvTry "AddBag('backpack')">>\
Success!
<<Fail>>\
Failure: $UInvLastErrorMessage
<</UInvTry>>\
*/
Macro.add('UInvTry', {
skipArgs : false,
tags : ["Fail"],
handler : function () {
if ((this.args.length < 1) || (!UInv.isString(this.args[0]))) {
throw new Error("<<UInvTry>> macro needs a string of code as an argument to test.");
}
if (this.payload.length != 2) {
throw new Error('<<UInvTry>> macro needs to be set up using the <<UInvTry "(code to try here)">>(success code here)<<Fail>>(failure code here)<</UInvTry>> format.');
}
var Action = "_UInvResult = " + parseUInvLine(this.args[0]);
try {
var TmpErr = UInv.GetLastError(true);
Scripting.evalTwineScript(Action);
if (UInv.GetLastError() === "") {
if (TmpErr) {
State.variables.UInvLastErrorMessage = TmpErr;
}
/* Success */
$(this.output).wiki(this.payload[0].contents);
} else {
/* Failure */
$(this.output).wiki(this.payload[1].contents);
}
} catch(error) {
/* Failure */
State.variables.UInvLastErrorMessage = "SugarCube Error: " + error.message;
$(this.output).wiki(this.payload[1].contents);
}
}
});
}
UInvObject.prototype = (function () {
/* UInv Private Functions: (internal use only)
=======================
Error: Handle setting $UInvLastErrorMessage to the error string and possibly displaying UInv errors based on the value of $UInvShowAlerts.
This can be used for debugging and/or letting users know how to report this error.
*/
function UInvError (ErrStr) {
var AlertMsg = "Error: " + ErrStr, Txt, GUA = UInv.GetUserAlerts();
if (GUA) {
if (GUA & UInv.ERROR_SHOW_PASSAGE_NAME) { /* jshint ignore:line */
Txt = 'Passage = "' + passage() + '"';
AlertMsg += "\n" + Txt;
}
if (UInv.isProperty(State.variables, "UInvErrorStringAddendum")) {
Txt = State.variables.UInvErrorStringAddendum;
AlertMsg += "\n" + Txt;
}
}
State.variables.UInvLastErrorMessage = AlertMsg;
if (GUA & UInv.ERROR_SHOW_ALERT) { /* jshint ignore:line */
alert(AlertMsg);
}
if (GUA & UInv.ERROR_TO_CONSOLE) { /* jshint ignore:line */
console.log(AlertMsg);
}
if (GUA & UInv.ERROR_THROW_ERROR) { /* jshint ignore:line */
throw new Error("\nUInv " + State.variables.UInvLastErrorMessage); /* This must be last because it exits the function here. */
}
return GUA; /* Success */
}
/* FixBagName: Returns $UInvCurrentBagName if BagName === "", else returns BagName, or undefined on error. */
function FixBagName (BagName) {
if (UInv.isString(BagName)) {
if ((BagName === "") && UInv.isString(UInv.GetCurrentBagName())) {
return UInv.GetCurrentBagName();
}
return BagName; /* Success */
} else {
UInvError('BagName passed to FixBagName is not a string.'); /* Error */
return undefined;
}
}
/* ValidateItemName: Returns validated ItemName or undefined on failure. */
function ValidateItemName (ItemName) {
if (UInv.isString(ItemName)) {
var NewItemName = ItemName.toLowerCase();
if (!UInv.ReservedBagProperties_LC.includes(NewItemName)) {
return NewItemName; /* Success */
} else {
return undefined; /* Failure */
}
} else {
return undefined; /* Failure */
}
}
/* FixItemName: Returns $UInvCurrentItemName if ItemName === "", else returns ItemName, or undefined on error. */
function FixItemName (ItemName) {
if (UInv.isString(ItemName)) {
var NewItemName = ItemName.toLowerCase(); /* fix case since all item names are lowercase */
if (!UInv.ReservedBagProperties_LC.includes(NewItemName)) {
if ((NewItemName === "") && UInv.isString(UInv.GetCurrentItemName())) { /* OOO function call */
NewItemName = ValidateItemName(UInv.GetCurrentItemName()); /* OOO function call */
if (NewItemName) {
return NewItemName; /* Success */
} else {
delete State.variables.UInvCurrentItemName; /* delete invalid value */
return ""; /* Success */
}
}
return NewItemName; /* Success */
} else {
UInvError('FixItemName failed. Illegal item name "' + ItemName + '" used.'); /* Error */
return undefined;
}
} else {
UInvError('ItemName passed to FixItemName is not a string.'); /* Error */
return undefined;
}
}
function FixContainerReferences (OldBagName, OldItemName, NewBagName, NewItemName) {
var PocketNames = UInv.GetItemPocketNameArray(NewBagName, NewItemName);
if (PocketNames.length > 0) {
var PocketBag, Containers, i, j;
for (i = 0; i < PocketNames.length; i++) { /* Update pockets' references to match the container's new bag and/or item name(s) */
PocketBag = UInv.GetItemPocketBagName(NewBagName, NewItemName, PocketNames[i]);
Containers = UInv.GetPocketBagContainerArray(PocketBag);
for (j = 0; j < Containers.length; j++) {
if ((Containers[j].ContainerBagName == OldBagName) && (Containers[j].ContainerName == OldItemName) && (Containers[j].PocketName == PocketNames[i])) {
State.variables.UInvBags[PocketBag].UInvContainer[j].ContainerBagName = NewBagName;
State.variables.UInvBags[PocketBag].UInvContainer[j].ContainerName = NewItemName;
}
}
}
}
return true; /* Success */
}
/* tryIntParse: Attempts to parse strings to integers if Value is a string, returns either a number or undefined if Value isn't a number. */
/* !!NOTE!! - The return value from this function will not necessarily be an integer. Values which are already numbers will be returned as-is. */
function tryIntParse (Value) {
if (UInv.isString(Value)) {
if (UInv.isNumber(parseInt(Value, 10))) {
Value = parseInt(Value, 10);
}
}
if (UInv.isNumber(Value)) {
return Value; /* Success */
}
return undefined; /* Unable to parse */
}
/* RemoveItemObjectsDefaultProperties: Removes all default properties from Obj. Returns true on success or undefined on error. */
/* !!!IMPORTANT!!! - The object passed to this function is directly modified by this function. Do not pass objects that shouldn't be modified!!! */
function RemoveItemObjectsDefaultProperties (Obj, DefaultItemType) {
if (UInv.isGenericObject(Obj)) {
if (UInv.isString(DefaultItemType)) {
var DefItem = UInv.GetDefaultItemObject(DefaultItemType);
if (DefItem) { /* Delete all properties that are equal to GetDefaultItemObject properties of DefaultItemType. */
var DefKeys = Object.keys(DefItem), i;
if ((DefKeys.length > 0) && (!DefKeys.includes("UInvVariableType"))) {
for (i = 0; i < DefKeys.length; i++) {
if (!["UInvPocket", "UInvQuantity"].includes(DefKeys[i])) {
if (UInv.isProperty(Obj, DefKeys[i])) {
if (UInv.valuesAreEqual(Obj[DefKeys[i]], DefItem[DefKeys[i]])) { /* OOO function call. (OOO = Out Of Order, meaning that function exists in the code below, instead of above.) */
delete Obj[DefKeys[i]]; /* Matches default value of GetDefaultItemObject version. */
}
}
}
}
}
}
return true; /* Success */
} else {
UInvError('DefaultItemType passed to RemoveItemObjectsDefaultProperties is not a string.'); /* Error */
return undefined;
}
} else {
UInvError('RemoveItemObjectsDefaultProperties failed. Obj is not a generic object.'); /* Error */
return undefined;
}
}
return {
/* UInv Public Functions: */
/* ====================== */
/* UInv Constructor: */
/* ================= */
constructor : UInvObject,
/* UInv Constants: */
/* =============== */
/* Values for UInvMergeItemMethod and UInv.SetMergeItemMethod to determine how UInv handles item collision. */
MERGE_USE_ONLY_DESTINATION_PROPERTIES : 1, /* Ignore source properties, just increment destination's quantity. (default) */
MERGE_USE_ONLY_SOURCE_PROPERTIES : 2, /* Delete the destination's properties, replace with the source's properties and values, and increment the quantity. */
MERGE_PREFER_DESTINATION_PROPERTIES : 3, /* Keep the properties and values in the destination, add any properties and values the source had but the destination didn't, and increment the quantity. */
MERGE_PREFER_SOURCE_PROPERTIES : 4, /* Keep the properties and values in the source, add any properties and values the destination had but source the didn't, and increment the quantity. */
MERGE_RENAME_SOURCE_ITEMNAME : 5, /* Rename the source's unique identifier so that it's stored separately in the destination bag. */
MERGE_FAIL_WITH_ERROR : 6, /* Fail with an error. */
/* Values for $UInvShowAlerts, used with SetUserAlerts. Values can be added together except for ERROR_NONE. */
ERROR_NONE : false, /* Do not display any error messages to users. */
ERROR_SHOW_PASSAGE_NAME : 1, /* Displays the current passage name in any error messages. */
ERROR_SHOW_ALERT : 2, /* Displays a modal dialog box for each error message and pauses execution. */
ERROR_THROW_ERROR : 4, /* Throws traditional Twine/SugarCube error messages, instead of silently returning a value which indicates that a UInv error occurred. */
ERROR_TO_CONSOLE : 8, /* Outputs any error messages to the console window. */
/* AP style says that positive integers less than 10 should be written as text. This array converts values zero through nine a text. (e.g. UInv.NumText[5] === "five") */
NumText : ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"], /* Used in Display functions. */
/* AP style says that ordinals from one through nine should be written as text. This array converts values one through nine to text. (e.g. UInv.OrdinalText[5] === "fifth") */
OrdinalText : ["0th", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth"], /* do not use 0 */
OrdinalSuffix : ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"],
/* The default maximum number of images to cache. */
DefaultMaxCache : 100,
/* The default maximum number of images to download at the same time using the image cache code. */
DefaultMaxConcurrent : 5,
/* Reserved property names within bags. */
ReservedBagProperties : ["", "-", "UInvTouched", "UInvProperties", "UInvDefaultBagType", "UInvContainer"],
ReservedBagProperties_LC : ["", "-", "uinvtouched", "uinvproperties", "uinvdefaultbagtype", "uinvcontainer"], /* lowercase version */
/* Reserved property names within items. */
ReservedItemProperties : ["UInvQuantity", "UInvDefaultItemType", "UInvVariableType", "UInvPocket", "UInvCell"],
/* This is the maximum pocket depth allowed on default items or bags to prevent accidental infinite recursion or exponential explosions. */
MaximumPocketDepth : 3,
/* UInv Utility Functions: */
/* ======================= */
/* isArray: Returns if a value is an array. */
isArray : function (Value) {
return Array.isArray(Value);
},
/* isBoolean: Returns if a value is a boolean. */
isBoolean : function (Value) {
return typeof Value === "boolean";
},
/* isDate: Returns if value is a date object. */
isDate : function (Value) {
return UInv.isObject(Value) && Value instanceof Date;
},
/* isFunction: Returns if a value is a function. */
isFunction : function (Value) {
return typeof Value === "function";
},
/* isGenericObject: Returns if a value is a generic object. */
isGenericObject : function (Value) {
return UInv.isObject(Value) && Value.constructor === Object;
},
/* isInteger: Returns if a value is an integer. */
isInteger : function (Value) {
return Number.isInteger(Value);
},
/* isMap: Returns if a value is a map. */
isMap : function (Value) {
return UInv.isObject(Value) && Value instanceof Map;
},
/* isNumber: Returns if a value is a number. */
isNumber : function (Value) {
return typeof Value === "number" && Number.isFinite(Value);
},
/* isObject: Returns if a value is an object. */
isObject : function (Value) {
return !!Value && typeof Value === "object";
},
/* isProperty: Returns if Prop is a property of the object Obj. */
isProperty : function (Obj, Prop) {
if (UInv.isObject(Obj)) {
return Obj ? hasOwnProperty.call(Obj, Prop) : false;
}
return false;
},
/* Returns if a value is a regexp. */
isRegExp : function (Value) {
return UInv.isObject(Value) && Value.constructor === RegExp;
},
/* isSet: Returns if a value is a set. */
isSet : function (Value) {
return UInv.isObject(Value) && Value instanceof Set;
},
/* isString: Returns if a value is a string. */
isString : function (Value) {
return typeof Value === "string" || Value instanceof String;
},
/* isUndefined: Returns if a value is undefined. */
isUndefined : function (Value) {
return typeof Value === "undefined";
},
/* spread: Returns a Map, Set, or String converted to an array. If the second parameter is an Array, Map, Set, or String, then the two objects are spread and returned as a single array.
If a function is passed as the second parameter, this calls the function with the spread array as parameters and returns that function's value. */
spread : function (Value, Funct) {
var arr = [];
if (UInv.isArray(Value)) {
arr = clone(Value);
} else if (UInv.isMap(Value)) {
/* eslint-disable-next-line no-unused-vars */
Value.forEach(function(val, key, map) {
arr.push([key, val]);
});
} else if (UInv.isSet(Value)) {
/* eslint-disable-next-line no-unused-vars */
Value.forEach(function(val, key, set) {
arr.push(val);
});
} else if (UInv.isString(Value)) {
arr = Value.split('');
}
if (UInv.isFunction(Funct)) {
return Funct.apply(null, arr);
} else if (UInv.isObject(Funct)) {
arr = arr.concat(UInv.spread(Funct));
}
return arr;
},
/* arraysAreEqual: Check two arrays to see if they're identical. IgnoreObjectPairs is for internal use to prevent infinite loops of objects. */
arraysAreEqual : function (Array1, Array2, IgnoreObjectPairs) {
if (UInv.isArray(Array1) && UInv.isArray(Array2)) {
var i = 0;
if (UInv.isUndefined(IgnoreObjectPairs)) {
IgnoreObjectPairs = [];
}
if (IgnoreObjectPairs.length > 0) {
for (i = 0; i < IgnoreObjectPairs.length; i++) {
if (((IgnoreObjectPairs[i][0] === Array1) && (IgnoreObjectPairs[i][1] === Array2)) ||
((IgnoreObjectPairs[i][0] === Array2) && (IgnoreObjectPairs[i][1] === Array1))) {
return true; /* Ignores object pairs that have already been checked to prevent infinite loops. */
}
}
}
IgnoreObjectPairs.push([Array1, Array2]);
if (Array1.length !== Array2.length) {
return false; /* Arrays are not the same length. */
}
if (Array1.length > 0) {
for (i = 0; i < Array1.length; i++) {
if (!UInv.valuesAreEqual(Array1[i], Array2[i], IgnoreObjectPairs)) { /* OOO function call. */
return false; /* Values or types do not match. */
}
}
}
return true; /* All values match. */
}
return false; /* Both are not arrays. */
},
/* mapsAreEqual: Returns if two maps contain the same values in the same order. IgnoreObjectPairs is for internal use to prevent infinite loops of objects. */
mapsAreEqual : function (Map1, Map2, IgnoreObjectPairs) {
if (UInv.isMap(Map1) && UInv.isMap(Map2)) {
if (Map1.size === Map2.size) {
if (UInv.isUndefined(IgnoreObjectPairs)) {
IgnoreObjectPairs = [];
}
if (IgnoreObjectPairs.length > 0) {
for (var i = 0; i < IgnoreObjectPairs.length; i++) {
if (((IgnoreObjectPairs[i][0] === Map1) && (IgnoreObjectPairs[i][1] === Map2)) ||
((IgnoreObjectPairs[i][0] === Map2) && (IgnoreObjectPairs[i][1] === Map1))) {
return true; /* Ignores object pairs that have already been checked to prevent infinite loops. */
}
}
}
IgnoreObjectPairs.push([Map1, Map2]);
var a = UInv.spread(Map1), b = UInv.spread(Map2);
return UInv.arraysAreEqual(a, b, IgnoreObjectPairs); /* Compares maps. */
}
}
return false; /* Both are either not maps or are maps of different sizes. */
},
/* objectsAreEqual: Check two objects to see if they're identical. IgnoreObjectPairs is for internal use to prevent infinite loops of objects. */
objectsAreEqual : function (Obj1, Obj2, IgnoreObjectPairs) {
if (UInv.isObject(Obj1) && UInv.isObject(Obj2)) {
var i = 0;
if (UInv.isUndefined(IgnoreObjectPairs)) {
IgnoreObjectPairs = [];
}
if (IgnoreObjectPairs.length > 0) {
for (i = 0; i < IgnoreObjectPairs.length; i++) {
if (((IgnoreObjectPairs[i][0] === Obj1) && (IgnoreObjectPairs[i][1] === Obj2)) ||
((IgnoreObjectPairs[i][0] === Obj2) && (IgnoreObjectPairs[i][1] === Obj1))) {
return true; /* Ignores object pairs that have already been checked to prevent infinite loops. */
}
}
}
IgnoreObjectPairs.push([Obj1, Obj2]);
if (UInv.isGenericObject(Obj1) && UInv.isGenericObject(Obj2)) {
var Keys1 = Object.keys(Obj1).sort(), Keys2 = Object.keys(Obj2).sort();
if (!UInv.arraysAreEqual(Keys1, Keys2)) {
return false; /* Objects have a different number of keys or have different keys. */
}
if (Keys1.length > 0) {
var Key;
for (i = 0; i < Keys1.length; i++) {
Key = Keys1[i];
if (!UInv.valuesAreEqual(Obj1[Key], Obj2[Key], IgnoreObjectPairs)) { /* OOO function call. */
return false; /* Values do not match. */
}
}
}
return true; /* All values match. */
} else {
return UInv.valuesAreEqual(Obj1, Obj2, IgnoreObjectPairs); /* Return whether objects match. OOO function call. */
}
}
return false; /* Both are not objects. */
},
/* setsAreEqual: Returns if two sets contain the same values in the same order. IgnoreObjectPairs is for internal use to prevent infinite loops of objects. */
setsAreEqual : function (Set1, Set2, IgnoreObjectPairs) {
if (UInv.isSet(Set1) && UInv.isSet(Set2)) {
if (Set1.size === Set2.size) {
if (UInv.isUndefined(IgnoreObjectPairs)) {
IgnoreObjectPairs = [];
}
if (IgnoreObjectPairs.length > 0) {
for (var i = 0; i < IgnoreObjectPairs.length; i++) {
if (((IgnoreObjectPairs[i][0] === Set1) && (IgnoreObjectPairs[i][1] === Set2)) ||
((IgnoreObjectPairs[i][0] === Set2) && (IgnoreObjectPairs[i][1] === Set1))) {
return true; /* Ignores object pairs that have already been checked to prevent infinite loops. */
}
}
}
IgnoreObjectPairs.push([Set1, Set2]);
var a = UInv.spread(Set1), b = UInv.spread(Set2);
return UInv.arraysAreEqual(a, b, IgnoreObjectPairs); /* Compares sets. */
}
}
return false; /* Both are either not sets or are sets of different sizes. */
},
/* setsMatch: Returns if two sets contain matches for all values in any order. */
setsMatch : function (Set1, Set2) {
if (UInv.isSet(Set1) && UInv.isSet(Set2)) {
if (Set1.size === Set2.size) {
if (Set1.size > 0) { /* Compare sets. */
var setIterator = Set1.values();
var result = setIterator.next();
while (!result.done) {
if (!Set2.has(result.value)) return false; /* Sets do not match. */
result = setIterator.next();
}
}
return true; /* Sets match. */
}
}
},
/* valuesAreEqual: Check two variables to see if they're identical. This function does not support comparing symbols, functions, or custom types. */
/* IgnoreObjectPairs is for internal use to prevent infinite loops of objects. */
valuesAreEqual : function (Var1, Var2, IgnoreObjectPairs) {
if (typeof Var1 === typeof Var2) {
switch (typeof Var1) {
/* String */
case "string":
/* Number */
case "number":
/* Boolean */
case "boolean":
return Var1 === Var2; /* Returns whether variables are equal or not. */
/* Undefined */
case "undefined":
return true; /* Variables are both undefined. */
/* Object */
case "object":
/* Array Object */
if (UInv.isArray(Var1) && UInv.isArray(Var2)) {
return UInv.arraysAreEqual(Var1, Var2, IgnoreObjectPairs); /* Return whether arrays are equal. */
/* Generic Object */
} else if (UInv.isGenericObject(Var1) && UInv.isGenericObject(Var2)) {
return UInv.objectsAreEqual(Var1, Var2, IgnoreObjectPairs); /* Return whether generic objects are equal. */
/* Date Object */
} else if (UInv.isDate(Var1) && UInv.isDate(Var2)) {
return (Var1 - Var2) == 0; /* Returns whether dates are equal. */
/* Map Object */
} else if (UInv.isMap(Var1) && UInv.isMap(Var2)) {
return UInv.mapsAreEqual(Var1, Var2, IgnoreObjectPairs); /* Return whether maps are equal. */
/* Set Object */
} else if (UInv.isSet(Var1) && UInv.isSet(Var2)) {
return UInv.setsAreEqual(Var1, Var2, IgnoreObjectPairs); /* Return whether sets are equal. */
/* Null Object */
} else if ((Var1 === null) && (Var2 === null)) {
return true; /* Objects are both null. */
}
return false; /* Objects either don't match or are of an unsupported type. */
default:
return false; /* Unsupported type. */
}
} else {
return false; /* Variables are not of the same type. */
}
},
/* arrayHasTag: Returns the number of times Tag is found in array, or undefined if there is an error. */
arrayHasTag : function (Arr, Tag) {
if (!UInv.isUndefined(Tag) && UInv.isArray(Arr)) {
return Arr.count(Tag);
} else {
return undefined; /* Error */
}
},
/* arrayHasAllTags: Returns true if Array1 has an equal or greater number of all tags in TagArray, or undefined if there is an error. */
arrayHasAllTags : function (Arr, TagArray) {
if (UInv.isArray(Arr) && UInv.isArray(TagArray)) {
if (TagArray.length > 0) {
if (Arr.length >= TagArray.length) {
var i = 0;
for (i = 0; i < TagArray.length; i++) {
if (Arr.count(TagArray[i]) < TagArray.count(TagArray[i])) {
return false;
}
}
} else {
return false; /* Array1 can't have enough tags to satisfy test. */
}
return true;
} else {
return false; /* TagArray is empty. */
}
} else {
return undefined; /* Error */
}
},
/* arrayHasAnyTag: Returns true if Array1 has at least one of the tags in TagArray, or undefined if there is an error. */
arrayHasAnyTag : function (Arr, TagArray) {
if (UInv.isArray(Arr) && UInv.isArray(TagArray)) {
if (TagArray.length > 0) {
var i = 0;
for (i = 0; i < TagArray.length; i++) {
if (Arr.includes(TagArray[i])) {
return true;
}
}
return false;
} else {
return false; /* TagArray is empty */
}
} else {
return undefined; /* Error */
}
},
/* isArrayOfType: Test an array to see if all the values in the array are of one type. */
isArrayOfType : function (Arr, Type) {
if (UInv.isArray(Arr)) {
var i = 0;
if (Arr.length) {
var funct;
Type = Type.toLowerCase();
switch (Type) {
case "array":
funct = UInv.isArray;
break;
case "boolean":
funct = UInv.isBoolean;
break;
case "date":
funct = UInv.isBoolean;
break;
case "generic object":
funct = UInv.isGenericObject;
break;
case "integer":
funct = UInv.isInteger;
break;
case "map":
funct = UInv.isMap;
break;
case "number":
funct = UInv.isNumber;
break;
case "object":
funct = UInv.isObject;
break;
case "set":
funct = UInv.isSet;
break;
case "string":
funct = UInv.isString;
break;
default:
return undefined; /* Error: Unknown type */
}
for (i = 0; i < Arr.length; i++) {
if (!funct(Arr[i])) {
return false; /* Array is not all of that type */
}
}
return true; /* Array is all of that type */
}
return false; /* Array is empty */
} else {
return undefined; /* Error: Not an array */
}
},
/* isArrayOfArrays: Test an array to see if all the values are arrays. */
isArrayOfArrays : function (Arr) {
return UInv.isArrayOfType(Arr, "array");
},
/* isArrayOfBooleans: Test an array to see if all the values are booleans. */
isArrayOfBooleans : function (Arr) {
return UInv.isArrayOfType(Arr, "boolean");
},
/* isArrayOfDates: Test an array to see if all the values are dates. */
isArrayOfDates : function (Arr) {
return UInv.isArrayOfType(Arr, "date");
},
/* isArrayOfGenericObjects: Test an array to see if all the values are generic objects. */
isArrayOfGenericObjects : function (Arr) {
return UInv.isArrayOfType(Arr, "generic object");
},
/* isArrayOfIntegers: Test an array to see if all the values are integers. */
isArrayOfIntegers : function (Arr) {
return UInv.isArrayOfType(Arr, "integer");
},
/* isArrayOfMaps: Test an array to see if all the values are maps. */
isArrayOfMaps : function (Arr) {
return UInv.isArrayOfType(Arr, "map");