-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmalibu.js
3227 lines (2647 loc) · 85.8 KB
/
malibu.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
/* --- --- [Version] --- --- */
/**
* @const Framework
* @description autogenerated with build script, holds current verison info
* @property {string} version - the version
* @property {string} build - the build number
* @property {string} date - the date of the build
*/
// DO NOT EDIT. Updated from version.json
var Framework = {"version":"4","build":224,"date":"2022-06-27T21:09:39.716Z"}
/* --- --- [Simplrz] --- --- */
/**
* @namespace Simplrz
*
* @description Feature detection utility.
*
* <p><h2>Using Simplrz</h2>
*
* <p>Simplr is initialized at startup and all test are done immediately.
* The results of the tests are stored in boolean variables listed below.
* Overtime new features are added and some old ones can be discarded,
* so be sure to check the docs from time to time.
*
* <blockquote>
* <h5>Note on detecting some CSS features</h5>
*
* <p>After reading this (https://github.com/zamiang/detect-css3-3d-transform)
* I realized detecting css3d transforms is unreliable. But also - we don't really need it
* because typically the only browser we need to support that doesn't do css 3d transforms
* is IE9 and IE8 so why not do some good old browser sniffing?
*
* <p>As a reminder: IE9 - only 2d transforms, no transitions, no animations, IE8 - not even 2d.
* </blockquote>
*
* <p>Using Simplrz is very simple in JS, please refer to the first example below.
* Simplrz also sets the names of the properties as classes to the <html> element of the document.
* Each class follows the same naming pattern:
*
* <p><code>webgl</code> - if feature is supported the class name is simply the name of the feature.
* <p><code>no-webgl</code> - if feature is not supported the class name is the name of the feature with a <code>no-</code> prefix.
*
* <p>CSS stylesheets can use those classes to use conditiojnal logic.
* Especially handy for example to define hover effects for non-touch only (see example below).
*
* <p>Example that runs the cod in your browser and prints out all the results <a href='http://work.bartekdrozdz.com/malibu/test/simplrz.html'>is here</a>.
*
* @example
if(Simplrz.touch) {
document.addEventListener('touchstart', onDown);
} else {
document.addEventListener('mousedown', onDown);
}
*
* @example
// Assuming we use LESS
// This will only work on non-touch screens
.no-touch a:hover {
text-decoration: underline;
}
#app {
.webgl-warning {
display: none;
}
// If webgl is not supported, show the warning
.no-webgl & .webgl-warning {
display: block;
}
}
*/
var Simplrz = (function() {
var s = {}, classes = ['js']; // Add 'js' class by default (bc if this code runs, JS is enabled, right?)
var isLocal = location.host.indexOf('local') > -1 || location.host.indexOf('192.168') > -1 || location.host.indexOf('10.0') > -1;
var check = function(feature, test) {
var result = test();
s[feature] = (result) ? true : false;
classes.push( (result) ? feature : "no-" + feature );
document.documentElement.setAttribute("class", classes.join(" "));
}
/**
* @member pixelRatio
* @memberof Simplrz
* @description Same vallue as <code>window.devicePixelRatio</code>
*/
s.pixelRatio = window.devicePixelRatio || 1;
var prefix = (function () {
var styles = "", pre = "", dom = "";
if(window.getComputedStyle) {
styles = window.getComputedStyle(document.documentElement, '');
if(styles) { // Bug in Firefox - this will be null if in iframe and it's set to display:none
var m = Array.prototype.slice.call(styles).join('');
if(m) {
pre = (m.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o']))[1];
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
}
}
}
return {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: (pre == "") ? "" : pre[0].toUpperCase() + pre.substr(1)
};
})();
/**
* @member prefix
* @memberof Simplrz
* @description whar is the browser vendor prefix (-ms, -webkit, -moz...)
*
* @returns {Object} contins several versions of the prefix, see example below.
*
* @example
{
dom: "Webkit",
lowercase: "webkit,
css: "-webkit-",
js: "Webkit"
}
*/
s["prefix"] = prefix;
classes.push(prefix.lowercase);
s.prefixedProp = function(prop) {
switch(prefix.lowercase) {
case "webkit": return "webkit" + prop.charAt(0).toUpperCase() + prop.slice(1);
case "ms": return "-ms-" + prop;
case "moz": return "Moz" + prop.charAt(0).toUpperCase() + prop.slice(1);
default: return prefix.css + prop;
}
}
// -- BROWSER HACKS BEGIN --
/**
* @member {Boolean} ie
* @memberof Simplrz
* @description false if browser is not IE, true it is is. No version detection.
*/
s.ie = navigator.userAgent.match(/MSIE/) || navigator.userAgent.match(/Trident/);
classes.push(s.ie ? "ie" : "no-ie");
/**
* @member {Boolean} firefox
* @memberof Simplrz
* @description True if the device is an iPad.
*/
s.firefox = navigator.userAgent.match(/Firefox/); // prefix.lowercase == "moz";
classes.push(s.firefox ? "firefox" : "no-firefox");
/**
* @member {Boolean} safariDesktop
* @memberof Simplrz
* @description True if the the browser is a Safari on desktop Mac.
*/
s.safariDesktop = navigator.userAgent.match(/Safari/) && !navigator.userAgent.match(/Chrome/) && !('ontouchstart' in document);
classes.push(s.safariDesktop ? "safari-desktop" : "no-safari-desktop");
// s.ipad7 = navigator.userAgent.match(/iPad;.*CPU.*OS 7_\d/i) || false;
// classes.push(s.ipad7 ? "ipad7" : "no-ipad7");
/**
* @member {Boolean} iOS
* @memberof Simplrz
* @description True if the device runs on iOS (as of iOS 13 we need to outsmart Apple a bit)
*/
s.iOS = /(iPad|iPhone|iPod)/g.test(navigator.platform) || (navigator.platform == "MacIntel" && 'ontouchstart' in document);
classes.push(s.iOS ? "ios" : "no-ios");
/**
* @member {Boolean} iPad
* @memberof Simplrz
* @description True if the device is an iPad (as of iOS 13 we need to outsmart Apple a bit)
*/
s.iPad = (navigator.platform == 'iPad') || (navigator.platform == "MacIntel" && 'ontouchstart' in document);
classes.push(s.iPad ? "ipad" : "no-ipad");
/**
* @member {Boolean} win
* @memberof Simplrz
* @description True if the device is running Windows.
*/
s.win = (navigator.platform == 'Win32' || navigator.platform == 'Win64');
classes.push(s.win ? "win" : "no-win");
/**
* @member {Boolean} osx
* @memberof Simplrz
* @description True if the device is a Mac running OSX.
*/
s.osx = navigator.platform.toLowerCase().indexOf('mac') >= 0;
classes.push(s.osx ? "osx" : "no-osx");
/**
* @member {Boolean} android
* @memberof Simplrz
* @description True if the device is running Windows.
*/
s.android = ( navigator.userAgent.toLowerCase().indexOf("android") > -1);
classes.push(s.android ? "android" : "no-android");
s.vrbrowser = /(OculusBrowser|Mobile\sVR)/g.test(navigator.userAgent);
classes.push(s.vrbrowser ? "vrbrowser" : "no-vrbrowser");
// -- BROWSER HACKS END --
/**
* @member {Boolean} css3d
* @memberof Simplrz
* @description True if CSS 3d transforms are supported.
*/
check("css3d", function() {
if(prefix.lowercase == 'webkit' || prefix.lowercase == 'moz') return true;
if(prefix.lowercase == 'ms') {
var div = document.createElement("div");
div.style[prefix.css + "transform"] = 'translateZ(0px)';
var cs = window.getComputedStyle(div);
if(cs) { // Bug in Firefox - this will be null if in iframe and it's set to display:none
var a = cs.getPropertyValue(prefix.css + "transform");
return a && a != '' && a != 'none';
}
}
return false;
});
/**
* @member {Boolean} csstransitions
* @memberof Simplrz
* @description True if CSS Transitions are supported - as of b197 (Jan 2019) always true.
*/
check("csstransitions", function() { return true; });
/**
* @member {Boolean} cssanimations
* @memberof Simplrz
* @description True if CSS Animations are supported - as of b197 (Jan 2019) always true.
*/
check("cssanimations", function() { return true; });
/**
* @member {Boolean} css2d
* @memberof Simplrz
* @description True if CSS 2d transforms are supported - as of b197 (Jan 2019) always true
*/
check("css2d", function() { return true; });
/**
* @member {Boolean} touch
* @memberof Simplrz
* @description True if touch events are supported.
*/
check("touch", function() {
return 'ontouchstart' in document && (navigator.platform.indexOf("Win") == -1 || isLocal);
});
/**
* @member {Boolean} pointer
* @memberof Simplrz
* @description True if pointer API (sort of like touch but different spec, used mostly by MS) is supported.
*/
check("pointer", function() {
return !!window.navigator.pointerEnabled || !!window.navigator.msPointerEnabled;
});
/**
* @member {Boolean} canvas
* @memberof Simplrz
* @description True if canvas 2d API is supported.
*/
check("canvas", function() {
try {
var canvas = document.createElement('canvas');
return canvas.getContext('2d');
} catch(e) {
return false;
}
});
/**
* @member {Boolean} history
* @memberof Simplrz
* @description True if the history API is supported.
*/
check("history", function() {
return !!(window.history && history.pushState);
});
/**
* @member {Boolean} webrtc
* @memberof Simplrz
* @description True if webrtc is supported.
*/
check("webrtc", function() {
return ('getUserMedia' in navigator || 'webkitGetUserMedia' in navigator);
});
/**
* @member {Boolean} webgl
* @memberof Simplrz
* @description True if webgl is supported.
*/
check("webgl", function() {
try {
var canvas = document.createElement('canvas');
return !!window.WebGLRenderingContext &&
(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
} catch(e) {
return false;
}
});
// Flash is dead anyway!
// check("flash", function() {
// return !!(
// navigator.mimeTypes["application/x-shockwave-flash"] ||
// window.ActiveXObject && new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
// );
// });
/**
* @member {Array} classes
* @memberof Simplrz
* @description An array containing all the classes that have been added to the <html> element.
*/
s.classes = classes;
return s;
})();
/* --- --- [Trigger] --- --- */
/**
* @class Trigger
*
* @description Trigger is a simple utility used to create events.
* <p>A Trigger can only send one type of event and it will always notify all of its listeners.
* <p>In order to build a more robust event system, use multiple
* Trigger objects as properties.
*
* @example
// Simple usage for a single type of event
var menuPress = new Trigger();
var menuPressListener = function(params) {
console.log("menuPress trigger fired");
// params = whatever was passed to the trigger method (see below)
console.log(params);
}
menuPress.on(menuPressListener);
// ... then somewhere in the code:
menuPress.trigger({ id: 5 });
// ... and eventually
menuPress.off(menuPressListener);
*
* @example
// If there are multiple events to handle,
// simply create multiple triggers
var car = {
engineStarted: new Trigger(),
brakeApplied: new Trigger(),
gearChanged: new Trigger()
}
*/
var Trigger = function() {
var t = {};
var listeners = [];
var lock = false;
var lateTriggers = [];
var lateRemovals = [];
/**
* @method on
* @memberof Trigger.prototype
* @param {Function} callback - the function used as callback for the listener
* @param {Object=} context - the context in which to invoke the function
* @description Adds a listener to this trigger
*/
t.on = function (callback, context, callOnInit) {
if(listeners.indexOf(callback) > -1) { return; }
callback.context = context;
listeners.push(callback);
if(callOnInit) callback();
};
/**
* @method off
* @memberof Trigger.prototype
* @param {Function} callback - the function used as callback for the listener.
* Needs to be the same function as passed to the <code>on()</code> when it was being registered.
* @description Removes a listener from this trigger.
* <p>If the passed callback is not a listener of this trigger,
* this function will not throw any warnings, it will just return.
* <p>If this function is called from within a function that is a listener for that trigger,
* the callback will not be removed until all other listeners are called.
*/
t.off = function (callback) {
var i = listeners.indexOf(callback);
if(i == -1) return;
if(lock) {
lateRemovals.push({ callback: callback });
return;
}
listeners.splice(i, 1);
};
/**
* @method trigger
* @memberof Trigger.prototype
* @param {Object=} data - An object specifying the events parameters. All listeners will receive this object as argument.
* @description Fires this trigger passing data as srgument to all listeners.
* <p>If this function is called from within a function that is a listener for that trigger,
* the trigger will not be fired until all other listeners
* are called for the previous one.
*/
t.trigger = function (data) {
if(lock) {
lateTriggers.push({ data: data });
return;
}
lock = true;
var i = 0, nl = listeners.length;
while(i < nl) {
var f = listeners[i];
f.call(f.context, data);
i++;
}
lock = false;
var d;
while(d = lateTriggers.shift()) t.trigger(d.data);
while(d = lateRemovals.shift()) t.off(d.callback);
};
return t;
};
/* --- --- [Timer] --- --- */
/**
* @class Timer
*
* @description A timer utility used to invoke function once or repeatedly in time.
*
* @param {Boolean} autostart - if true the Timer will start counting time immediately. Otherwise start() needs to be called manually later.
* @param {Boolean} autoupdate - if true the Timer will be updating on every frame. Otherwise, update() needs to be called on every frame.
*/
var Timer = function(autostart, autoupdate) {
var that = this;
// If frame is longer than 250ms (4 FPS) it will skip it.
// TODO: what is the logic behind this?
var MAX_FRAME_TIME = 250;
var paused = false;
this.time = 0;
this.frame = 0;
this.deltatime = 0;
var startTime, elapsedTime = 0;
var tasks = [];
var trackTask = function(e, i) {
if(e._time < that.time) {
if(e._repeat != 0) {
e.callback(e._time);
var it = e._interval;
if(it instanceof Array) e._time += it[0] + Math.random() * (it[1] - it[0]);
else e._time += it;
e._repeat--;
} else {
setTimeout(that.off, 0, e); // <- is it good enough?
}
}
};
var run = function() {
requestAnimationFrame(run);
that.update();
}
/**
* @method pause
* @memberof Timer.prototype
* @description Pauses/resumes the execution of the timer.
* @param {Boolean} p - true to pause, false to resume
* @return {Timer} self, for chaining.
*/
this.pause = function(p) {
paused = p;
return this;
}
/**
* @method paused
* @memberof Timer.prototype
* @description Returns true is timer is paused, false otherwise.
*/
this.paused = function() {
return paused;
}
/**
* @method start
* @memberof Timer.prototype
* @description Start the timer manually.
* <p>If autostart was set to false or omitted in the constructor, this function needs to be invoked.
*/
this.start = function() {
startTime = new Date().getTime(),
elapsedTime = 0,
that.frame = 0;
that.time = 0;
if(autoupdate) run();
return that;
}
/**
* @method update
* @memberof Timer.prototype
* @description Updates the timer.
*
* <p>If autoupdate was set to false or omitted in the constructor,
* this function need to be invoked in a requestAnimationFrame loop or a similar interval.
*/
this.update = function() {
var t = new Date().getTime() - startTime;
var d = t - elapsedTime;
elapsedTime = t;
if(d < MAX_FRAME_TIME && !paused) {
that.time += d;
that.frame++;
that.deltatime = d;
}
tasks.forEach(trackTask);
return that.time;
}
/**
* @method onAt
* @memberof Timer.prototype
* @description Executes callback after a delay. All time values in milliseconds.
*
* @param {Number} time - when to start (i.e. delay counted from 'now' i.e from when this method is called)
* @param {Function} callback - the callback to be invoked
*
* @returns {Object} - an special object that can be used to remove the task later.
*/
this.onAt = function(_time, callback) {
var so = {
callback: callback,
_time: that.time + _time,
_repeat: 1
};
tasks.push(so);
return so;
}
/**
* @method onEvery
* @memberof Timer.prototype
* @description Invokes the callback repeatedly overtime. All time values in ms.
*
* @param {Number} interval - how often to invoked the function. It can be an array of two elements specyfing a min/max range
* @param {Number} time - when to start (i.e. delay, counted from 'now' i.e from when this method is called)
* @param {Number} callback - the callback to be invoked
* @param {Number} repeat - how many times to repeat. If ommited or -1 will repeat infinitely
* 0 will never invoke the function (in fact it won't even be added)
*
* @returns {Object} an object that can be later used to remove the task.
*/
this.onEvery = function(_interval, _time, callback, _repeat) {
if(_repeat === 0) return;
var so = {
callback: callback,
_time: that.time + _time,
_interval: _interval,
_repeat: _repeat || -1
};
tasks.push(so);
return so;
}
/**
* @method off
* @memberof Timer.prototype
* @description Remove a scheduled task.
*
* @param {Object} so - Object referencing the callback.
* <p>DO NOT PASS the original callback to this function (you'll get a warning if you do).
* Instead you need to pass the object returned from onAt or onEvery.
*/
this.off = function(so) {
if(so instanceof Function) {
var m = 'You are probably using the callback directly to remove it.\n';
m += 'You should use the object returned from onAt or onEvery instead.';
console.warn(m);
console.warn(so);
return;
}
if(so == null) {
return;
}
var i = tasks.indexOf(so);
if(i > -1) {
tasks.splice(i, 1);
return true;
} else {
return false;
}
}
/**
* @method clearTasks
* @memberof Timer.prototype
* @description Remove all tasks scheduled using onAt or onEvery
*/
this.clearTasks = function() {
tasks.length = 0;
}
if(autostart) {
that.start();
}
}
/**
* @member global
* @memberof Timer
* @static
*
* @description A global static instance of a Timer for simple use cases.
*/
Timer.global = new Timer(true, true);
/* --- --- [Value] --- --- */
/**
* @class Value
*
* @description <p>Value is an object that hold a property.
*
* <p>Properties are great to keep track of the state of on object.
* For example "how many times the spaceship has been hit" or
* "what is the current section on a website" or a lot of other things.
*
* <p>A simple property can do the job well, example: "spaceship.numHits" is a number
* that increases each time the spacehip has been hit by enemy lasers.
*
* <p>Usually there will be several objects in each application that will need
* to do something whenever this value changes. To make this possible each of those
* objects would need to implement some sort of loop or timer and check the value of
* this property at regular intervals.
*
* <p>This is where the Value object comes in handy. It keeps the value of the property
* in it's own property (called 'value') but, using the object observer pattern,
* each time this value changes, it will send out a notification to every
* registered listener.
*
* <p>The Value object works best with primitive values, especially Numbers.
* But it can hold any object as value.
*
* @param {Object} v - the initial value to set
*
* @example
// sets the value to 1
var health = new Value(1);
health.on(function(current, last) {
console.log('The value of health is', current);
console.log('The previous value was', last);
console.log('Current value can also be accessed from', health.value);
});
// value changed, the listener will be invoked
health.value = 2;
// value stays the same, the listener won't be invoked
health.value = 2;
*/
/*
* Also read this http://www.html5rocks.com/en/tutorials/es7/observe/
*/
var Value = function(_value, noInitCallback) {
var that = this,
value = _value,
last = null;
var min = null, max = null, wrap = false;
var observers = [];
that.observers = function() {
return observers;
}
/**
* @method on
* @memberof Value.prototype
*
* @param {Function} callback - the callback to invoke whenever the value changes.
* The callback function will receive up to 3 arguments. First is the current value,
* second is the last value (if there was any, null otherwise). Third is a custom param (see below).
*
* @param {Function} test - a test function to check if value changed. If the value is a Object,
* some of it's properties might chnage and this function allows to inject the logic that will
* decide whether the entire value should be considered "chnaged" or not. See example below.
*
* @param {Object} param - a parameter to pass to the callback on each change. It will be passed as 3rd parameter.
*
* @param {Boolean=} noInitCallback - if this is set explicitely to true, the callback will not be invoked immediately
* on registration. Otherwise the callback is always called immediately, so that any state can be adjusted to the current
* value.
*
* @description sets the value property of thie Value to whatever is passed as parameter.
* Same as saying <code>someValue.value = v;</code> but this method can be useful when chaining.
*/
that.on = function(callback, test, param) {
if(observers.indexOf(callback) > -1) return;
var o = callback;
o.test = test;
o.param = param;
// Fire the callback initially so that all values/flags of the subscriber can be adjusted at startup
if(!noInitCallback && (!o.test || o.test(value, last))) o(value, last, param);
observers.push(o);
return o;
}
/**
* @method threshold
* @memberof Value.prototype
*
* @param {Number} min - the low value of the range of the threshold. It can be null, in this case there won't be a low value to the threshold.
* @param {Number} max - the high value of the range of the threshold. It can be null, in this case there won't be a high value to the threshold.
*
* @description Similar to on, but the callback will only be invoked when the value crosses a certain threshold and it's value is within a range.
*/
that.threshold = function(callback, min, max, param, noInitCallback) {
var test;
if(min != null && max != null) {
test = function(c, l) { return (c >= min && l < min) || (c < max && l >= max); }
if(_value >= min && _value < max && !noInitCallback) callback(_value);
} else if(min != null && max == null) {
test = function(c, l) { return (c >= min && l < min); }
if(_value >= min && !noInitCallback) callback(_value);
} else if(min == null && max != null) {
test = function(c, l) { return (c < max && l >= max); }
if(_value < max && !noInitCallback) callback(_value);
}
return that.on(callback, test, param, true);
}
/**
* @method off
* @memberof Value.prototype
* @param {Function} callback - the callback that was originally passed to <code>on</code>.
* @description Removes the callback from the list of listeners for this value.
*/
that.off = function(callback) {
var i = observers.indexOf(callback);
if(i > -1) observers.splice(i, 1);
}
/**
* @method range
* @memberof Value.prototype
* @param {Number} _min - minimum value (inclusive)
* @param {Number} _max - minimum value (inclusive)
* @param {Number} _wrap - if true if value goes over max or below min it will be wrapped, otherwise it will clamped to min, max.
*
* @description This method allows to add minumim and maximum allowed value to the Value object. Mostly useful for numbers, if
* we need to make sure the value will not go over a certain threshold.
*/
that.range = function(_min, _max, _wrap) {
min = _min;
max = _max;
wrap = _wrap;
return that;
}
/**
* @method set
* @memberof Value.prototype
* @param {Object} v
* @description sets the value property of thie Value to whatever is passed as parameter.
* Same as saying <code>someValue.value = v;</code> but this method can be useful when chaining.
*/
that.set = function(v) {
that.value = v;
return that;
}
var changed = function() {
var o;
for(var i = 0, n = observers.length; i < n; i++) {
o = observers[i];
if(!o.test || o.test(value, last)) {
o(value, last, o.param);
}
}
}
Object.defineProperty(this, 'value', {
get: function() {
return value;
},
set: function(n) {
if(min != null && max != null) {
if(n < min) {
wrap ? n = n % (max+1) : n = min;
if(wrap) while(n < min) n += (max+1);
}
if(n > max) {
wrap ? n = n % (max+1) : n = max;
if(wrap) while(n < min) n += (max+1);
}
}
if(n == value) return;
last = value;
value = n;
changed();
// setTimeout(changed, 0);
}
});
Object.defineProperty(this, 'last', {
get: function() {
return last;
},
});
}
/* --- --- [Application] --- --- */
/**
* @namespace Application
*/
var Application = (function() {
var app = {};
var router;
/**
* @member {Object} flags
* @memberof Application
* @static
*/
app.flags = {};
var fs = document.location.search.substring(1).split('&');
fs.forEach(function(f) {
var ff = f.split('=');
app.flags[ff[0]] = parseFloat(ff[1]);
});
/**
* @member {Trigger} start
* @memberof Application
* @static
*/
app.start = new Trigger();
/**
* @member {Trigger} resize
* @memberof Application
* @static
*/
app.resize = new Trigger();
/**
* @member {Value} route
* @memberof Application
* @static
*/
app.route = new Value({
parts: []
}, true);
/**
* @function init
* @memberof Application
* @static
*/
app.init = function(params) {
params = params || {};
if(!params.dontPrintVersion) {
console.log('%cMalibu v' +
Framework.version +
' b' + Framework.build +
' (history:' + !params.disableHistoryAPI + ')'
, 'background: #ff3600; color: #ffdede; padding: 4px 10px 4px 10px');
}
var r = {
width: 0,
height: 0,
aspect: 0,
orientation: -1,
event: null
}
var triggerResize = function(e) {
var f = function() {
r.width = window.innerWidth;
r.height = window.innerHeight;
r.aspect = r.width / r.height;
r.orientation = window.orientation;
r.event = e;
app.resize.trigger(r);
}
f();
if(Simplrz.iOS) {
// window.scroll(0, 0); // This was causing some weird behavior on iPhones, of course!
setTimeout(f, 400);
setTimeout(f, 1000);
}
}
window.addEventListener('resize', triggerResize);
router = HistoryRouter(app, params);
router.init();