-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandomous.js
2244 lines (2053 loc) · 69.3 KB
/
randomous.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
// Carlos Sanchez - 2017
// An enormous library full of garbage
// ---- List of utilities ----
// * TypeUtilities
// * HTMLUtilities
// * StorageUtilities
// * URLUtilities
// * RequestUtilities
// * StyleUtilities
// * CanvasUtilities
// * EventUtilities
// * ScreenUtilities
// * MathUtilities
// * DateUtilities
// * ArrayUtilities
// --- Shims ---
// Maybe your browser sucks and we have to fill in for it. Whatever.
//At LEAST make sure console logging doesn't completely break the script.
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function() {};
if (!String.prototype.trim)
String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); };
if (!Array.prototype.indexOf)
{
//Taken directly from ECMA-262 or whatever.
Array.prototype.indexOf = function(value, fromIndex)
{
if(this === null) throw new TypeError('"this" is null or not defined');
var o = Object(this);
var len = o.length >>> 0;
if(len === 0) return -1;
var n = fromIndex | 0;
if(n >= len) return -1;
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) if (k in o && o[k] === searchElement) return k;
return -1;
};
}
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart)
{
String.prototype.padStart = function padStart(targetLength,padString)
{
targetLength = targetLength>>0; //floor if number or convert non-number to 0;
padString = String(padString || ' ');
if (this.length > targetLength)
{
return String(this);
}
else
{
targetLength = targetLength-this.length;
if (targetLength > padString.length)
{
padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0,targetLength) + String(this);
}
};
}
//This type of shim doesn't execute the selector function every time. A
//suitable function is chosen NOW, then assigned as a shim.
window.requestAnimationFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { window.setTimeout(callback, 1000 / 60); };
})();
// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md
(function (arr)
{
arr.forEach(function (item)
{
if (item.hasOwnProperty('prepend'))
{
return;
}
Object.defineProperty(item, 'prepend',
{
configurable: true,
enumerable: true,
writable: true,
value: function prepend()
{
var argArr = Array.prototype.slice.call(arguments),
docFrag = document.createDocumentFragment();
argArr.forEach(function (argItem)
{
var isNode = argItem instanceof Node;
docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
});
this.insertBefore(docFrag, this.firstChild);
}
});
});
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
// --- Library OnLoad Setup ---
// This stuff needs to be performed AFTER the document is loaded and all that.
window.addEventListener("load", function()
{
UXUtilities._Setup();
});
// --- Extensions ---
// Extensions to existing prototypes (yeah, I know you're not supposed to do this)
//Returns a function that calls the associated function with any extra
//given arguments. It fixes loop closure issues. Altered from
//www.cosmocode.de/en/blog/gohr/2009-10/15-javascript-fixing-the-closure-scope-in-loops
//Example: You want x.addEventListener("click", myfunc(i)) in a loop.
//Do this: x.addEventListener("click", myfunc.callBind(i))
Function.prototype.callBind = function()
{
var fnc = this;
var args = arguments;
return function()
{
return fnc.apply(this, args);
};
};
// --- TypeUtilities ---
// Functions for working with or detecting types.
var TypeUtilities =
{
IsFunction: function(x)
{
return x && Object.prototype.toString.call(x) == '[object Function]';
},
IsArray: function(x)
{
return x && x.constructor === Array;
},
IsString: function(x)
{
return x && x.constructor === String;
}
};
// --- HTMLUtilities ---
// Encode or decode HTML entitities / generate unique IDs for elements / etc.
var HTMLUtilities =
{
_nextID : 0,
UnescapeHTML : function(string)
{
var elem = document.createElement("textarea");
elem.innerHTML = string;
return elem.value;
},
EscapeHTML : function(html)
{
var text = document.createTextNode(html);
var div = document.createElement('div');
div.appendChild(text);
return div.innerHTML;
},
RemoveSelf : function(element)
{
element.parentNode.removeChild(element);
},
InsertBeforeSelf : function(newElement, element)
{
element.parentNode.insertBefore(newElement, element);
},
InsertAfterSelf : function(newElement, element)
{
element.parentNode.insertBefore(newElement, element.nextSibling);
},
InsertFirst : function(newElement, parent)
{
parent.insertBefore(newElement, parent.firstElementChild);
},
Replace : function(oldElement, newElement)
{
HTMLUtilities.InsertBeforeSelf(newElement, oldElement);
HTMLUtilities.RemoveSelf(oldElement);
},
MoveToEnd : function(element)
{
element.parentNode.appendChild(element);
},
GetUniqueID : function(base)
{
return "genID_" + this._nextID++ + (base ? "_" + base : "");
},
NodeListToArray : function(nodeList)
{
var tempArray = [];
for(var i = 0; i < nodeList.length; i++)
tempArray.push(nodeList[i]);
return tempArray;
},
FindParentFromAction : function(element, action)
{
var nextElement = element;
while(!action(nextElement))
{
if(nextElement.tagName.toLowerCase() === "body")
return false;
nextElement = nextElement.parentNode;
}
return nextElement;
},
FindParentWithClass : function(element, className)
{
var regex = new RegExp("\\b" + className + "\\b");
return HTMLUtilities.FindParentFromAction(element,
function(nextElement)
{
return regex.test(nextElement.className);
});
},
FindParentWithTag : function(element, tagName)
{
return HTMLUtilities.FindParentFromAction(element,
function(nextElement)
{
return nextElement.tagName.toLowerCase() === tagName.toLowerCase();
});
},
SimulateRadioSelect : function(selected, parent, selectedAttribute, selectedValue)
{
selectedAttribute = selectedAttribute || "data-selected";
selectedValue = selectedValue || "true";
var fakeRadios = parent.querySelectorAll("[" + selectedAttribute + "]");
for(var i = 0; i < fakeRadios.length; i++)
fakeRadios[i].removeAttribute(selectedAttribute);
selected.setAttribute(selectedAttribute, selectedValue);
},
//Make "scrollbar" a real scrollbar, using scrollnub as the little thing you
//drag, scrollbar as the bar itself, and scrollitem as the thing that is
//absolutely positioned within its parent
SimulateScrollbar : function(scrollbar, scrollnub, scrollitem, allowJump)
{
var target = false;
var srect = false;
var sirect = false;
var snheight = false;
var wheight = false;
var min = false;
var max = false;
var cacheValues = () =>
{
srect = scrollbar.getBoundingClientRect();
sirect = scrollitem.getBoundingClientRect();
snheight = scrollnub.clientHeight;
wheight = window.innerHeight;
min = srect.top;
max = srect.bottom - snheight;
};
var setScroll = (relpos) =>
{
scrollnub.style.top = relpos;
scrollitem.style.top = - (relpos / (max - min)) * (sirect.bottom - sirect.top - wheight);
};
var down = e =>
{
e.preventDefault();
//We ASSUME these won't change during the duration of the scroll...
target = e.target;
cacheValues();
if(allowJump)
move(e);
};
var up = e =>
{
target = false;
};
var move = e =>
{
//We need a target and either allowing jumps or the target is the nub
if(!(target && (allowJump || target.isSameNode(scrollnub))))
return;
var pos = EventUtilities.GetPosition(e);
var newpos = MathUtilities.MinMax(pos.y - snheight / 2, min, max);
setScroll(newpos - min);
};
scrollbar.addEventListener("mousedown", down);
scrollbar.addEventListener("touchstart", down);
scrollbar.refreshScroll = () =>
{
cacheValues();
setScroll(Number(scrollnub.style.top.replace("px", "")));
};
//These are permanent
document.addEventListener("mouseup", up);
document.addEventListener("touchend", up);
document.addEventListener("mousemove", move);
document.addEventListener("touchmove", move);
},
CreateUnsubmittableButton : function(text)
{
var button = document.createElement('button');
button.setAttribute("type", "button");
if(text) button.innerHTML = text;
return button;
},
CreateContainer : function(className, id)
{
var container = document.createElement("div");
container.className = className;
if(id) container.id = id;
container.dataset.createdon = new Date().getTime();
return container;
},
CreateSelect : function(options, name)
{
var select = document.createElement("select");
if(name) select.setAttribute("name", name);
for(var i = 0; i < options.length; i++)
{
var option = document.createElement("option");
if(options[i].value && options[i].text)
{
option.innerHTML = options[i].text;
option.setAttribute("value", options[i].value);
}
else
{
option.innerHTML = options[i];
}
select.appendChild(option);
}
return select;
},
CreateSvg : function(width, height)
{
var svg = HTMLUtilities.CreateSvgElement("svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
//document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute('width', width || "100%");
svg.setAttribute('height', height || "100%");
return svg;
},
CreateSvgElement : function(type)
{
return document.createElementNS("http://www.w3.org/2000/svg", type);
},
FillSvgBackground : function(svg, color)
{
var rect = HTMLUtilities.CreateSvgElement("rect");
rect.setAttribute("x", "0");
rect.setAttribute("y", "0");
rect.setAttribute("width", svg.getAttribute("width"));
rect.setAttribute("height", svg.getAttribute("height"));
rect.setAttribute("fill", color);
svg.insertBefore(rect, svg.firstChild);
},
SwapElements : function (obj1, obj2)
{
// save the location of obj2
var parent2 = obj2.parentNode;
var next2 = obj2.nextSibling;
// special case for obj1 is the next sibling of obj2
if (next2 === obj1) {
// just put obj1 before obj2
parent2.insertBefore(obj1, obj2);
} else {
// insert obj2 right before obj1
obj1.parentNode.insertBefore(obj2, obj1);
// now insert obj1 where obj2 was
if (next2) {
// if there was an element after obj2, then insert obj1 right before that
parent2.insertBefore(obj1, next2);
} else {
// otherwise, just append as last child
parent2.appendChild(obj1);
}
}
}
};
//Allows the generation of a simulated radio using any type of element. More
//robust than the HTMLUtilities function; allows selection of radios based on
//string value.
var RadioSimulator = function(container, attribute, callback, clickCycle)
{
this.container = container;
this.attribute = attribute;
this.callback = callback;
this.clickCycle = clickCycle; //Clicking repeatedly cycles (forward) through radios
this.selectedAttribute = "data-selected";
};
//Allows manual selection of radio button. Can also select by value (simply
//pass the string value of the button to select.)
RadioSimulator.prototype.SelectRadio = function(button)
{
console.debug("Selecting radio: ");
console.debug(button);
if(TypeUtilities.IsString(button))
{
button = this.container.querySelector('[' + this.attribute + '="' + button + '"]');
}
else if(this.clickCycle && button.hasAttribute(this.selectedAttribute))
{
var radios = this.container.querySelectorAll("[" + this.attribute + "]");
for(var i = 0; i < radios.length; i++)
{
if(radios[i] === button)
{
button = radios[(i + 1) % radios.length];
break;
}
}
}
var value = button.getAttribute(this.attribute);
if(!value)
{
console.log("Could not select radio using this button! There is no " + this.attribute + " attribute!");
return;
}
if(this.callback)
this.callback(value, button);
if(!this.container)
{
console.log("There is no container for this RadioSimulator!");
return;
}
HTMLUtilities.SimulateRadioSelect(button, this.container, this.selectedAttribute);
};
RadioSimulator.prototype.CreateRadioButton = function(text, value)
{
var button = HTMLUtilities.CreateUnsubmittableButton(text);
var me = this;
button.setAttribute(this.attribute, value);
button.addEventListener("click", function(e) { me.SelectRadio(button); });
return button;
};
RadioSimulator.prototype.GetSelected = function()
{
return this.container.querySelector("[" + this.selectedAttribute + "]");
};
//Provides toast messages in a container centered near the bottom of the
//screen. You can create multiple toasters, but by default they'll all overlap
//each other. If you need custom styling per toaster, style off the
//container.id
function Toaster()
{
this.minDuration = 2000;
this.maxDuration = 10000;
this.container = false;
}
Toaster.ToastClass = "randomousToast";
Toaster.ContainerClass = "randomousToastContainer";
Toaster.StyleID = HTMLUtilities.GetUniqueID("toastStyle");
Toaster.TrySetDefaultStyles = function()
{
var style = StyleUtilities.TrySingleStyle(Toaster.StyleID);
if(style)
{
console.log("Setting up Toast default styles for the first time");
style.AppendClasses(Toaster.ContainerClass,
["position:absolute","bottom:1em","left:50%","transform:translate(-50%,0)",
"z-index:2000000000","pointer-events: none"]);
style.Append("." + Toaster.ContainerClass + "[data-fullscreen]",
["position:fixed"]);
style.AppendClasses(Toaster.ToastClass,
["max-width: 70vw","font-family:monospace","font-size:0.8rem",
"padding:0.5em 0.7em","background-color:#EEE","border-radius:0.5em",
"color:#333","opacity:1.0","transition: opacity 1s", "display: block",
"margin-bottom:0.1em","box-shadow: 0 0 1em -0.3em rgba(0,0,0,0.6)",
"overflow: hidden","text-overflow: ellipsis","text-align: center"]);
style.Append("." + Toaster.ToastClass + "[data-fadingout]",
["opacity:0"]);
style.Append("." + Toaster.ToastClass + "[data-initialize]",
["opacity:0"]);
style.Append("." + Toaster.ToastClass + "[data-fadingin]",
["transition:opacity 0.2s"]);
}
};
Toaster.prototype.Attach = function(toasterParent)
{
Toaster.TrySetDefaultStyles();
if(this.container) throw "Toaster already attached: " + this.container.id;
this.container = HTMLUtilities.CreateContainer(Toaster.ContainerClass,
HTMLUtilities.GetUniqueID("toastContainer"));
toasterParent.appendChild(this.container);
};
Toaster.prototype.AttachFullscreen = function(toasterParent)
{
this.Attach(toasterParent || document.body);
this.container.dataset.fullscreen = "true";
};
Toaster.prototype.Detach = function()
{
if(!this.container) throw "Toaster not attached yet!";
HTMLUtilities.RemoveSelf(this.container);
this.container = false;
};
Toaster.prototype.Toast = function(text, duration)
{
if(!this.container) throw "Toaster not attached yet!";
duration = duration || MathUtilities.MinMax(text.length * 50, this.minDuration, this.maxDuration);
var toast = document.createElement("div");
toast.className = Toaster.ToastClass;
toast.dataset.createdon = new Date().getTime();
toast.dataset.initialize = "true";
toast.dataset.fadingin = "true";
toast.innerHTML = text;
console.debug("Popping toast: " + text);
this.container.appendChild(toast);
setTimeout(function() { toast.removeAttribute("data-initialize"); }, 10);
//Give a big buffer zone of fadingin just in case people have long effects
setTimeout(function() { toast.removeAttribute("data-fadingin"); }, 1000);
setTimeout(function() { toast.dataset.fadingout = "true"; }, duration);
//Give a big buffer zone of fadingout just in case people have long effects
setTimeout(function() { HTMLUtilities.RemoveSelf(toast); }, duration + 2000);
};
//Allows fading of any element it's attached to. Element must have position:
//relative or absolute or something.
function Fader() { }
Fader.FaderClass = "randomousFader";
Fader.StyleID = HTMLUtilities.GetUniqueID("faderStyle");
Fader.TrySetDefaultStyles = function()
{
var style = StyleUtilities.TrySingleStyle(Fader.StyleID);
if(style)
{
console.log("Setting up Fader default styles for the first time");
style.AppendClasses(Fader.FaderClass,
["position:absolute","top:0","left:0","width:100%","height:100%",
"padding:0","margin:0","pointer-events:none","display:block",
"z-index:1900000000"]);
style.Append("." + Fader.FaderClass + "[data-fullscreen]",
["width:100vw","height:100vh","position:fixed"]);
}
};
Fader.CreateFadeElement = function()
{
var element = document.createElement("div");
element.className = Fader.FaderClass;
element.id = HTMLUtilities.GetUniqueID("fader");
return element;
};
Fader.prototype.Attach = function(faderParent)
{
Fader.TrySetDefaultStyles();
if(this.element) throw "Tried to attach fader but already attached: " + this.element.id;
this.element = Fader.CreateFadeElement();
faderParent.appendChild(this.element);
};
Fader.prototype.AttachFullscreen = function(faderParent)
{
this.Attach(faderParent || document.body);
this.element.dataset.fullscreen = "true";
};
Fader.prototype.Detach = function()
{
if(!this.element) throw "Not attached yet";
HTMLUtilities.RemoveSelf(this.element);
this.element = false;
};
Fader.prototype.Fade = function(fadeDuration, color, cover)
{
if(cover)
this.element.style.pointerEvents = "auto";
else
this.element.style.pointerEvents = "none";
this.element.style.transition = "background-color " + fadeDuration + "ms";
var me = this;
setTimeout(function() { me.element.style.backgroundColor = color; }, 1);
};
//Creates a dialog-box complete with buttons. A good replacement for
//alert/confirm/etc.
function DialogBox()
{
//Since fader is "internal", parameters for fading should be too.
this.fader = new Fader();
this.fadeInTime = 100;
this.fadeOutTime = 100;
this.fadeColor = "rgba(0,0,0,0.5)";
this.container = false;
}
DialogBox.DialogClass = "randomousDialog";
DialogBox.ContainerClass = "randomousDialogContainer";
DialogBox.TextClass = "randomousDialogText";
DialogBox.ButtonContainerClass = "randomousDialogButtonContainer";
DialogBox.StyleID = HTMLUtilities.GetUniqueID("dialogStyle");
DialogBox.TrySetDefaultStyles = function()
{
var style = StyleUtilities.TrySingleStyle(DialogBox.StyleID);
if(style)
{
console.log("Setting up DialogBox default styles for the first time");
style.AppendClasses(DialogBox.ContainerClass,
["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)",
"padding:0","margin:0","z-index:2000000000"]);
style.Append("." + DialogBox.ContainerClass + "[data-fullscreen]",
["position:fixed"]);
style.AppendClasses(DialogBox.DialogClass,
["max-width: 70vw","font-family:monospace","font-size:1.0rem",
"padding:1.0em 1.2em","background-color:#EEE","border-radius:0.5em",
"color:#333","opacity:1.0","transition: opacity 0.2s",
"display: block","box-shadow: 0 0 1em -0.3em rgba(0,0,0,0.6)"]);
style.AppendClasses(DialogBox.TextClass,
["display: block","font-family: monospace", "overflow: hidden",
"text-overflow: ellipsis","margin-bottom: 0.5em","white-space:pre-wrap"]);
style.AppendClasses(DialogBox.ButtonContainerClass,
["text-align: center","display: block"]);
style.Append("." + DialogBox.ButtonContainerClass + " button",
["border: none","font-family: monospace", "overflow: hidden",
"text-overflow: ellipsis","font-size: 1.0em","font-weight:bold",
"padding: 0.3em 0.5em","margin: 0.2em 0.4em","border-radius:0.35em",
"background-color: #DDD","display: inline","cursor:pointer"]);
style.Append("." + DialogBox.ButtonContainerClass + " button:hover",
["background-color: #CCC"]);
}
};
DialogBox.prototype.Attach = function(dialogParent)
{
DialogBox.TrySetDefaultStyles();
if(this.container) throw "DialogBox already attached: " + this.container.id;
this.container = HTMLUtilities.CreateContainer(DialogBox.ContainerClass,
HTMLUtilities.GetUniqueID("dialogContainer"));
this.fader.Attach(dialogParent);
dialogParent.appendChild(this.container);
};
DialogBox.prototype.AttachFullscreen = function(dialogParent)
{
this.Attach(dialogParent || document.body);
this.fader.Detach();
this.fader.AttachFullscreen(dialogParent);
this.container.dataset.fullscreen = "true";
};
DialogBox.prototype.Detach = function()
{
if(!this.container) throw "DialogBox not attached yet!";
this.fader.Detach();
HTMLUtilities.RemoveSelf(this.container);
this.container = false;
};
DialogBox.prototype.Show = function(text, buttons)
{
var dialog = HTMLUtilities.CreateContainer(DialogBox.DialogClass);
var dialogText = document.createElement("span");
var dialogButtons = HTMLUtilities.CreateContainer(DialogBox.ButtonContainerClass);
dialogText.innerHTML = text;
dialogText.className = DialogBox.TextClass;
dialog.appendChild(dialogText);
dialog.appendChild(dialogButtons);
var i;
var me = this;
for(i = 0; i < buttons.length; i++)
{
var btext = buttons[i];
if(buttons[i].text) btext = buttons[i].text;
var callback = buttons[i].callback;
var newButton = HTMLUtilities.CreateUnsubmittableButton(btext);
/* jshint ignore: start */
newButton.addEventListener("click", function(callback)
{
HTMLUtilities.RemoveSelf(dialog);
if(me.container.childNodes.length === 0)
me.fader.Fade(me.fadeOutTime, "rgba(0,0,0,0)", false);
if(callback)
callback();
}.callBind(callback));
/* jshint ignore: end */
dialogButtons.appendChild(newButton);
}
me.fader.Fade(me.fadeInTime, me.fadeColor, true);
me.container.appendChild(dialog);
};
// --- UXUtilities ---
// Utilities specifically for User Experience. Things like custom alerts,
// custom confirms, toast, etc.
var UXUtilities =
{
UtilitiesContainer : HTMLUtilities.CreateContainer("randomousUtilitiesContainer",
HTMLUtilities.GetUniqueID("utilitiesContainer")),
_DefaultToaster : new Toaster(),
_ScreenFader : new Fader(),
_DefaultDialog : new DialogBox(),
_Setup : function()
{
document.body.appendChild(UXUtilities.UtilitiesContainer);
UXUtilities._DefaultToaster.AttachFullscreen(UXUtilities.UtilitiesContainer);
UXUtilities._ScreenFader.AttachFullscreen(UXUtilities.UtilitiesContainer);
UXUtilities._DefaultDialog.AttachFullscreen(UXUtilities.UtilitiesContainer);
},
Toast : function(message, duration)
{
UXUtilities._DefaultToaster.Toast(message,duration);
},
FadeScreen : function(duration, color)
{
UXUtilities._ScreenFader.Fade(duration, color);
},
Confirm : function(message, callback, yesMessage, noMessage)
{
UXUtilities._DefaultDialog.Show(message, [
{ text: noMessage || "No", callback: function() { callback(false); }},
{ text: yesMessage || "Yes", callback: function() { callback(true); }}
]);
},
Alert : function(message, callback, okMessage)
{
UXUtilities._DefaultDialog.Show(message, [
{ text: okMessage || "OK", callback: function() { if(callback) callback(); }}
]);
}
};
// --- StorageUtilities ---
// Retrieve and store data put into browser storage (such as cookies,
// localstorage, etc.
var StorageUtilities =
{
GetAllCookies : function()
{
var cookies = {};
var cookieStrings = document.cookie.split(";");
for(var i = 0; i < cookieStrings.length; i++)
{
var matches = /([^=]+)=(.*)/.exec(cookieStrings[i]);
if(matches && matches.length >= 3)
cookies[matches[1].trim()] = matches[2].trim();
}
return cookies;
},
GetPHPSession : function()
{
return StorageUtilities.GetAllCookies().PHPSESSID;
},
WriteSafeCookie : function(name, value, expireDays)
{
var expire = new Date();
var storeValue = Base64.encode(JSON.stringify(value));
expireDays = expireDays || 356;
expire.setTime(expire.getTime() + (expireDays * 24 * 60 * 60 * 1000));
document.cookie = name + "=" + storeValue + "; expires=" + expire.toUTCString();
},
ReadRawCookie : function(name)
{
return StorageUtilities.GetAllCookies()[name];
},
ReadSafeCookie : function(name)
{
var raw = StorageUtilities.ReadRawCookie(name);
if(raw)
return JSON.parse(Base64.decode(raw));
return null;
},
HasCookie : function(name)
{
return name in StorageUtilities.GetAllCookies();
},
WriteLocal : function(name, value)
{
localStorage.setItem(name, JSON.stringify(value));
},
ReadLocal : function (name)
{
try
{
return JSON.parse(localStorage.getItem(name));
}
catch(error)
{
//console.log("Failed to retrieve " + name + " from local storage");
return undefined;
}
}
};
// --- URLUtilities ---
// Functions for parsing/manipulating URLs and... stuff.
var URLUtilities =
{
GetQueryString : function(url)
{
var queryPart = url.match(/(\?[^#]*)/);
if(!queryPart) return "";
return queryPart[1];
},
//Taken from Tarik on StackOverflow:
//http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
GetQueryVariable : function(variable, url)
{
var query = url ? URLUtilities.GetQueryString(url) : window.location.search;
var vars = query.substring(1).split('&');
for (var i = 0; i < vars.length; i++)
{
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable)
return decodeURIComponent(pair[1]);
}
return null;
},
AddQueryVariable : function(variable, value, url)
{
if(URLUtilities.GetQueryString(url))
url += "&";
else
url += "?";
return url + variable + "=" + value;
}
};
//Special console logging
var _loglevel = 0;
console.debug = function() {};
console.trace = function() {};
if(URLUtilities.GetQueryVariable("trace"))
_loglevel = 100;
else if(URLUtilities.GetQueryVariable("debug"))
_loglevel = 50;
if(_loglevel >= 50)
{
console.log("Debug mode is activated.");
console.debug = console.log;
}
if(_loglevel >= 100)
{
console.log("Trace mode is activated.");
console.trace = console.log;
}
// --- Request ---
// Helpers for POST/GET requests
var RequestUtilities =
{
XHRSimple : function(page, callback, data, extraHeaders)
{
var xhr = new XMLHttpRequest();
if(data)
xhr.open("POST", page);
else
xhr.open("GET", page);
if(extraHeaders)
{
for(var key in extraHeaders)
{
if(extraHeaders.hasOwnProperty(key))
xhr.setRequestHeader(key, extraHeaders[key]);
}
}
//Use generic completion function with given success callback
xhr.addEventListener("load", function(event)
{
try
{
callback(event.target.response);
}
catch(e)
{
console.log("Oops, XHR callback didn't work. Dumping exception");
console.log(e);
}
});
if(data)
xhr.send(data);
else
xhr.send();
},
XHRJSON: function(page, callback, data)
{
RequestUtilities.XHRSimple(page, function(response)
{
callback(JSON.parse(response));
}, data, {"Content-type": "application/json"});
}
};
// --- Color / Color Utilities ---
// Functions objects for working with colors in a generic way. Any canvas
// functions will use this object rather than some specific format.
function Color(r,g,b,a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a; //This should be a decimal a ranging from 0 to 1
if(this.a === undefined) this.a = 1;
}
Color.prototype.ToArray = function(expandedAlpha)
{
return [this.r, this.g, this.b, this.a * (expandedAlpha ? 255 : 1)];
};
Color.prototype.ToRGBString = function()
{
var pre = "rgb";
var vars = this.r + "," + this.g + "," + this.b;
if(this.a !== 1)
{
pre += "a";
vars += "," + this.a;
}
return pre + "(" + vars + ")";
};
Color.prototype.ToHexString = function(includeAlpha)
{
var string = "#" + this.r.toString(16).padStart(2, "0") +
this.g.toString(16).padStart(2, "0") +