-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathq.js
More file actions
2678 lines (2550 loc) · 78.2 KB
/
q.js
File metadata and controls
2678 lines (2550 loc) · 78.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Javascript Q
* GitHub: https://github.com/AugmentLogic/Javascript-Q
* CDN: https://cdn.jsdelivr.net/gh/AugmentLogic/Javascript-Q@latest/q.js
*/
(function(JavascriptQ) {
var
// Initialize Q
q = window[JavascriptQ] = function (mixedQuery) {
var that = copy(fun);
return that.put(mixedQuery);
},
version = q.version = '3.0.2',
BYPASS_QUEUE = q.BYPASS_QUEUE = 'BYPASS_QUEUE_CONSTANT',
// Duplicates an object
copy = q.copy = function (obj) {
return extend({}, obj);
},
// Find out if an object is a DOM node
isNode = q.isNode = function (o){
return (
typeof Node === "object"
? o instanceof Node
: o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
},
// Extends the properties of an object
extend = q.extend = function (obj1, obj2) {
var keys = Object.keys(obj2);
for (var i = 0; i < keys.length; i += 1) {
var val = obj2[keys[i]];
obj1[keys[i]] = ['object', 'array'].indexOf(typeof val) != -1 && !isNode(val) ? extend(obj1[keys[i]] || {}, val || {}) : val;
}
return obj1;
},
// callback(key, value, posFlag)
// posFlag 0=start; 2=end; 1=other
iterate = q.iterate = function (that, fnCallback, boolBackwords) {
var
l=that.length,
i=boolBackwords?l-1:0;
if (isNode(that)) {
fnCallback.call(that, 0, that, 2);
} else {
if (boolBackwords) {
while (i>=0) {
if (fnCallback.call(that[i], i, that[i], i==l-1 ? 2 : (!i ? 0 : 1)) === false)
break;
i--;
}
} else {
while (i<l) {
if (fnCallback.call(that[i], i, that[i], i==l-1 ? 2 : (!i ? 0 : 1)) === false)
break;
i++;
}
}
}
return !!l;
},
riterate = q.riterate = function (that, fnCallback) {
return iterate(that,fnCallback,1);
},
preload = q.preload = function (url, fnSuccess, fnError) {
var img = new Image();
img.src=url;
if (img.complete) {
if (fnSuccess)
fnSuccess(url);
} else {
if (fnSuccess)
img.addEventListener('load', fnSuccess);
if (fnError)
img.addEventListener('error', fnError);
}
},
uriEncode = q.uriEncode = function (val) {
return encodeURIComponent(val).replace(/\+/, '%2B').replace(/ /, '+');
},
queryString = q.queryString = function (arrItem) {
var strResult = "";
for (var k in arrItem) {
var v = q.uriEncode(arrItem[k]);
strResult += k + '=' + v + '&';
}
strResult = strResult.slice(0, -1);
return strResult;
},
// change camel case for dashes
camelToDash = q.camelToDash = function (strInput) {
return strInput
.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase();
},
// Handle DOM ready
boolReadyEventsOn = false,
arrReadyPromises = [],
// check if there's a queue open and if there is add the call the sequence,
// if not just call it. used for handling animations, delays, ifs, etc...
prospectQueue = function (arrArgs,strParentName) {
var
that = this,
intTotal = that.length,
intBlocked = 0,
arrNewQueue = [],
boolLoopAdded=!that.loopOn;
arrArgs = Array.prototype.slice.call(arrArgs);
var arrArgsSequence = arrArgs.slice(0);
arrArgsSequence.unshift(strParentName);
if (
arrArgs.includes(BYPASS_QUEUE)
|| that.loopOn === 0
|| that.withoutQueueOn
)
return true;
// all elements must be queued to disable the entire process
// add elements to the sequence that are queued
// then remove those elements from the selection
// so that none queued items can continue with their normal process
iterate(that,function (intItem, el) {
if (!el) return;
var intElUid = q(el).uniqueId();
if (objQueueChain[intElUid]) {
var objLink = objQueueChain[intElUid];
if (objLink.skip_queue) {
intBlocked++;
return;
}
if (!boolLoopAdded) {
addLoopParam.call(that,arrArgsSequence);
boolLoopAdded = true;
}
if (objLink.active) {
intBlocked++;
objLink.sequence.push(arrArgsSequence);
return;
}
objLink.skip_queue = true;
objLink.active = true;
q(el)[strParentName].apply(that, arrArgs);
objLink.active = false;
objLink.skip_queue = false;
if (!that.loopOn)
q.queueNext.call(that, el, true);
}
arrNewQueue.push(el);
});
var boolContinue = intBlocked != intTotal;
if (boolContinue && intBlocked != 0) {
that.put(arrNewQueue);
}
if (intBlocked+intTotal==0) {
boolContinue = true;
}
return boolContinue;// parent proceeds
},
addLoopParam = function (arrArgsSequence) {
var that = this;
that.loopBuffer[Object.keys(that.loopBuffer).length] = Object.values(copy(arrArgsSequence));
},
// For adding new functions to the q
fnResolve = function (mixedValue) {
if (typeof mixedValue == "function")
mixedValue = mixedValue.call(this);
return mixedValue;
},
// Free up memory by removing the selections that are not part of the selection anymore
fnTrimQueue = function (intStart) {
var that = this;
that.length = intStart;
while (that[intStart]) {
delete that[intStart++];
}
},
animations = 0, // the current amount of animations that have been started
objAnimationInstances = {},
objTransformHistory = {}, // css transforms are lost in the matrix so we gotta keep track of them
// default transform scales
objTransformDefaults = {
scale : "1,1",
scaleX : 1,
scaleY : 1,
scaleZ : 1,
scale3d : "1,1,1",
},
objQueueChain = {}, // holds information for queuing animations for synchronous playback
// Don't add px postfix to these values
arrExcludePx = {'transform-scaleX':1,'transform-scaleY':1,'transform-scale':1,'column-count': 1,'fill-opacity': 1,'font-weight': 1,opacity: 1,orphans: 1,widows: 1,'z-index': 1,zoom: 1,'background-color': 1},
// create new methods in the q variable that call bind ex: q(mixed).click(function);
arrAutoBind = ["submit","click","mousedown","mouseup","mouseover","mousemove","mouseleave","mouseenter","change","load","dblclick","focus","focusin","focusout","blur","input","keydown","keypress","keyup","resize","reset","scroll","select","touchcancel","touchend","touchmove","touchstart","transitionend","unload","wheel","contextmenu"],
// Support for .data
arrDataMemory = {},
// Support for: .bind .unbind .trigger
objEventMomory = {},
// the start of the fun return variable
fun = {
length : 0,
is_q : 1,
is_qchain : 1,
version : version,
layers : 0, // how many times has the find function ran
loopOn : false,
loopCount : 0,
loopBuffer : [],
// ifs
condition_count : 0, // ifs count
conditions : [1],
orFired : false
},
hexToRgb = q.hexToRgb = function (hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
},
// a better typeof
type = q.type = function (mixedVar) {
var type = typeof(mixedVar);
if(type != "object") {
return type;
}
switch(mixedVar) {
case null:
return 'null';
case window:
return 'window';
case document:
return 'document';
case window.event:
return 'event';
default:
break;
}
switch(mixedVar.constructor) {
case Array:
return 'array';
case Boolean:
return 'boolean';
case Date:
return 'date';
case Object:
return 'object';
case RegExp:
return 'regexp';
case ReferenceError:
case Error:
return 'error';
case null:
default:
break;
}
switch(mixedVar.nodeType) {
case 1:
return 'domelement';
case 3:
return 'string';
case null:
default:
break;
}
return 'Unknown';
},
// Report an error
error = q.error = function (objError) {
console.log(objError);
return this;
},
// source: https://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript/4819886#4819886
is_touch_device = q.is_touch_device = function () {
var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
var mq = function(query) {
return window.matchMedia(query).matches;
}
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
return true;
}
var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
return mq(query);
},
// Added functions to the q lib
fn = q.plugin = function (mixedName, fnCallback) {
iterate(typeof mixedName == "string" ? [mixedName] : mixedName, function (k,strName) {
fun[strName] = function () {
var that = this;
if (that.orFired)
return that;
that.caller = strName;
if (strName == 'if' || strName == 'else') {
if (!prospectQueue.call(that,arguments,strName))
return that;
}
// pre dispatch
if (strName != 'else' && !that.conditions[that.condition_count]){ // if this level condition wasnt matched
return that; // pass the query on without doing anything
}
var mixedResult = fnCallback.apply(that,arguments);
return mixedResult;
};
});
},
// Animation easings still used for scrolling
easings = q.easings = {};
easings.linear = function(t, b, c, d) {return c * t / d + b;};
easings.easeInQuad = function(t, b, c, d) {return c * (t /= d) * t + b;};
easings.easeOutQuad = function(t, b, c, d) {return -c * (t /= d) * (t - 2) + b;};
easings.easeInOutQuad = function(t, b, c, d) {if ((t /= d / 2) < 1) return c / 2 * t * t + b;return -c / 2 * ((--t) * (t - 2) - 1) + b;};
easings.easeInCubic = function(t, b, c, d) {return c * (t /= d) * t * t + b;};
easings.easeOutCubic = function(t, b, c, d) {return c * ((t = t / d - 1) * t * t + 1) + b;};
easings.easeInOutCubic = function(t, b, c, d) {if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;return c / 2 * ((t -= 2) * t * t + 2) + b;};
easings.easeInQuart = function(t, b, c, d) {return c * (t /= d) * t * t * t + b;};
easings.easeOutQuart = function(t, b, c, d) {return -c * ((t = t / d - 1) * t * t * t - 1) + b;};
easings.easeInOutQuart = function(t, b, c, d) {if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;return -c / 2 * ((t -= 2) * t * t * t - 2) + b;};
easings.easeInQuint = function(t, b, c, d) {return c * (t /= d) * t * t * t * t + b;};
easings.easeOutQuint = function(t, b, c, d) {return c * ((t = t / d - 1) * t * t * t * t + 1) + b;};
easings.easeInOutQuint = function(t, b, c, d) {if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;};
easings.easeInSine = function(t, b, c, d) {return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;};
easings.easeOutSine = function(t, b, c, d) {return c * Math.sin(t / d * (Math.PI / 2)) + b;};
easings.easeInOutSine = function(t, b, c, d) {return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;};
easings.easeInExpo = function(t, b, c, d) {return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;};
easings.easeOutExpo = function(t, b, c, d) {return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;};
easings.easeInOutExpo = function(t, b, c, d) {if (t == 0) return b;if (t == d) return b + c;if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;};
easings.easeInCirc = function(t, b, c, d) {return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;};
easings.easeOutCirc = function(t, b, c, d) {return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;};
easings.easeInOutCirc = function(t, b, c, d) {if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;};
easings.easeInElastic = function(t, b, c, d) {var p = 0;var a = c;if (t == 0) return b;if ((t /= d) == 1) return b + c;if (!p) p = d * .3;if (a < Math.abs(c)) {a = c;var s = p / 4;}else var s = p / (2 * Math.PI) * Math.asin(c / a);return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;};
easings.easeOutElastic = function(t, b, c, d) {var p = 0;var a = c;if (t == 0) return b;if ((t /= d) == 1) return b + c;if (!p) p = d * .3;if (a < Math.abs(c)) {a = c;var s = p / 4;}else var s = p / (2 * Math.PI) * Math.asin(c / a);return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;};
easings.easeInOutElastic = function(t, b, c, d) {var p = 0;var a = c;if (t == 0) return b;if ((t /= d / 2) == 2) return b + c;if (!p) p = d * (.3 * 1.5);if (a < Math.abs(c)) {a = c;var s = p / 4;}else var s = p / (2 * Math.PI) * Math.asin(c / a);if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;};
easings.easeInBack = function(t, b, c, d, s) {if (s == undefined) s = 1.70158;return c * (t /= d) * t * ((s + 1) * t - s) + b;};
easings.easeOutBack = function(t, b, c, d, s) {if (s == undefined) s = 1.70158;return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;};
easings.easeInOutBack = function(t, b, c, d, s) {if (s == undefined) s = 1.70158;if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;};
easings.easeInBounce = function(t, b, c, d) {return c - easings.easeOutBounce(d - t, 0, c, d) + b;};
easings.easeOutBounce = function(t, b, c, d) {if ((t /= d) < (1 / 2.75)) {return c * (7.5625 * t * t) + b;} else if (t < (2 / 2.75)) {return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;} else if (t < (2.5 / 2.75)) {return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;} else {return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;}};
easings.easeInOutBounce = function(t, b, c, d) {if (t < d / 2) return easings.easeInBounce(t * 2, 0, c, d) * .5 + b;return easings.easeOutBounce(t * 2 - d, 0, c, d) * .5 + c * .5 + b;};
// define prototype object
q.prototype = fun;
q.is_q = 1;
q.first = function (objItem) {
for (var intItem in objItem) {
return objItem[intItem];
}
};
q.last = function (objItem) {
if (typeof objItem === 'object')
objItem = Object.values(objItem);
return objItem[objItem.length-1];
};
q.zIndex = {
increment: 100,
current: 1000,
add: function () {
q.zIndex.current += q.zIndex.increment;
return q.zIndex.current;
},
remove: function () {
q.zIndex.current -= q.zIndex.increment;
return q.zIndex.current;
}
};
// stores callbacks, to be recalled at a later time
// optionally watches for uniqueness to prevent duplicate calls
// params.unique for unique key value hook
q.hook = function (params) {
if (!params)
params = {};
var bank = [];
var watching = {};
return function (fnRegister) {
var arrResult = [];
var arrParams = Object.values(arguments);
arrParams.shift();
if (fnRegister !== undefined) {
bank.push(fnRegister);
} else {
for (var intItr in bank) {
if (!params.unique || watching[arrParams[0]] !== arrParams[1]) {
if (params.unique)
watching[arrParams[0]] = arrParams[1];
arrResult.push(bank[intItr].apply(this, arrParams));
}
}
}
return arrResult;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered unless the last trigger has hasnt been for longer than <wait> seconds
q.debounce = function (wait, func, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
q.clear(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Returns a function, that, as long as it continues to be invoked, will only
// trigger every N milliseconds
q.throttle = function (func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
if ( !timeout ) timeout = q.delay( wait, later );
if (callNow) func.apply(context, args);
};
};
q.escapeRegex = function (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var intHashOffset = 0;
q.hash_offset = function (offset) {
$(function () {
if ( "onhashchange" in window ) {
if (offset != undefined) {
intHashOffset = offset
$(window).unbind("hashchange.hash_offset load.hash_offset");
}
var hashHandler = function(e) {
var hash = window.location.hash.substring( 1 );
if ( !hash )
return;
var sel = 'a[name="' + hash + '"]';
var $sel = $( sel );
var $a = $('a[href="#' + hash + '"]:not(.prevented)');
if ($a.length) {
$a.bind('click.hash_offset', function (e) {
var hash = window.location.hash.substring( 1 );
if ($(this).attr('href') == '#'+hash)
e.preventDefault();
}).addClass('prevented');
}
if ($sel.length) {
var currentOffset = $sel.offset().top;
var intNewTop = currentOffset - intHashOffset;
$('body').scrollTop( intNewTop );
$.delay(10, function () {
$('body').scrollTop( intNewTop );
});
}
};
if (offset != undefined) {
$(window).bind("hashchange.hash_offset", hashHandler);
$(window).bind("load.hash_offset", hashHandler);
}
hashHandler();
}
});
};
var componentsTemplates = {};
var componentsLoadedCallbacks = {};
var components = {};
var routes = {};
var routesOpen = [];
q.component = {};
var fnComponentRoot = function (objComponent) {
return {
mount: function (mixedLocation) {
$(mixedLocation).append(objComponent.template);
if (objComponent.mounted)
objComponent.mounted();
q.component.mount.call(objComponent);
},
unmount: function (mixedLocation) {
objComponent.template.remove();
if (objComponent.unmounted)
objComponent.unmounted();
}
};
};
function checkRoutePath() {
var strLocation = window.location.hash;
var strLocationWithHash = strLocation === '' ? '#' : strLocation;
var $a = $("a[href='" + strLocationWithHash + "']");
$(".q-link-active").removeClass('q-link-active');
$a.addClass('q-link-active');
}
function checkRoute() {
var strLocation = window.location.hash;
checkRoutePath();
var route;
var strPath;
for (strPath in routes) {
if (strLocation.match(new RegExp("^" + strPath + "$"))) {
route = routes[strPath];
break;
}
}
if (route) {
// close routes
for (var intRouteOpen in routesOpen) {
var strOpenRoute = routesOpen[intRouteOpen];
var objOpenRoute = routes[strOpenRoute];
//for (var intPath in objOpenRoute.paths) {
// var strOpenPath = objOpenRoute.paths[intPath];
for (var intPath in route.paths) {
if (route.paths[intPath].match(new RegExp("^" + strOpenRoute + "$"))) {
return; // route already open
}
}
// unmount route
for (var strName in routes[strOpenRoute].components) {
var objRouteComponent = routes[strOpenRoute].components[strName];
var $placeholder = $(document.createComment(''));
objRouteComponent.tag = $placeholder;
$placeholder.appendAfter(objRouteComponent.component.template);
objRouteComponent.component.template.remove();
if (objRouteComponent.component.unmounted)
objRouteComponent.component.unmounted();
}
routesOpen.shift();
}
// open route
for (var strName in route.components) {
var objRouteComponent = route.components[strName];
routesOpen.push(strPath)
var strId = objRouteComponent.id;
function setComponent () {
var $placeholder = $(document.createComment(''));
$placeholder.appendAfter(objRouteComponent.tag);
$placeholder.replace(objComponent.template);
objRouteComponent.tag.remove();
if (objComponent.mounted)
objComponent.mounted();
q.component.mount.call(objComponent);
$.delay(10, function () {
checkRoutePath();
$.hash_offset();
});
}
var objComponent = q.component.load(strName, setComponent);
objRouteComponent.component = objComponent;
if (!objComponent.loading) {
setComponent();
}
}
}
}
window.addEventListener("popstate", checkRoute);
var intRouteCounter = 0;
q.component.route = function (mixedPath, strName) {
var arrPath = mixedPath;
if (!Array.isArray(mixedPath)) {
arrPath = [mixedPath];
}
// intialize a route for each path provided
for (var intPath in arrPath) {
// set placeholder
var strId = "q__component__router__" + intRouteCounter++;
document.write("<q__component__router id='" + strId + "' style='display:none'></q__component__router>");
var $placeholder = $("#" + strId);
$placeholder.replace(document.createComment(''));
var strPath = arrPath[intPath];
if (!routes[strPath]) {
routes[strPath] = {
name: strName,
components: {},
paths: arrPath
};
}
if (routes[strPath].components[strName])
throw "Error component " + strName + " was route injected twice";
routes[strPath].components[strName] = {
id: strId,
name: strName,
tag: $placeholder
};
}
};
q.component.set = function (strName, fnCallback) {
// generate root component
var objComponent = new fnCallback();
for (var strMethod in objComponent) {
if (typeof objComponent[strMethod] == "function") {
var objMethod = objComponent[strMethod];
objComponent[strMethod] = (function (strMethod, objMethod) {
return function () {
return objMethod.apply(components[strName], arguments);
};
})(strMethod, objMethod);
}
};
Object.assign(objComponent, fnComponentRoot(components[strName]));
// add template to new component
var $template = componentsTemplates[strName].find("template");
objComponent.template = $($template.html());
$template.remove();
$('body').append(componentsTemplates[strName].children());
checkRoutePath();
componentsTemplates[strName].remove();
delete componentsTemplates[strName];
objComponent.name = strName;
// assign new component to root
Object.assign(components[strName], objComponent);
objComponent = components[strName];
delete objComponent.loading;
objComponent.loaded = true;
objComponent.finsihed_loading();
delete objComponent.finsihed_loading;
if (objComponent.created)
objComponent.created();
if (componentsLoadedCallbacks[strName]) {
componentsLoadedCallbacks[strName].call(objComponent);
delete componentsLoadedCallbacks[strName];
}
};
q.component.get = function (strName, fnDone) {
if (components[strName]) {
fnDone.call(components[strName]);
return components[strName];
} else {
return q.component.load(strName, fnDone);
}
};
q.component.insert = function (strName) {
var strId = "q__component__inject__" + strName;
document.write("<q__component__inject id='" + strId + "'></q__component__inject>");
var objComponent = q.component.load(strName, function () {
$("#" + strId).replace(objComponent.template);
if (objComponent.mounted)
objComponent.mounted();
q.component.mount.call(objComponent);
});
};
q.component.root = "";
q.component.mount = q.hook();
q.component.load = function (strName, strUrl, fnLoaded) {
if (typeof strUrl === 'function') {
fnLoaded = strUrl;
strUrl = undefined;
}
var objComponent = components[strName];
if (!objComponent || !objComponent.loading && !objComponent.loaded) {
componentsLoadedCallbacks[strName] = fnLoaded;
// auto loader
if (!strUrl) {
q.component.root = q.component.root.replace(/\/$/, '');
var arrPath = strName.split('_');
strFileName = arrPath.pop()+".htm";
strUrl = q.component.root + '/' + arrPath.join('/') + '/' + strFileName;
}
// create root component
objComponent = {
loading: true,
finsihed_loading: q.hook()
};
components[strName] = objComponent;
$.request({
url : strUrl,
success : function (strResponse) {
componentsTemplates[strName] = $("<div style='display:none'>").appendTo('body');
$(componentsTemplates[strName]).append(strResponse);
}
});
}
return objComponent;
};
fn('rtrim', function (intFromRight) {
var that = this;
if (!prospectQueue.call(that,arguments,'rtrim'))
return that;
fnTrimQueue.call(that);
return that;
});
// add in-framework logic
fn('if', function (mixedValue) {
var that = this;
mixedValue = fnResolve.call(this,mixedValue);
that.conditions[that.condition_count+1] = !!mixedValue;
that.condition_count++;
return that;
});
// else logic
fn('else', function (mixedValue) {
var that = this,
v;
if (typeof mixedValue == "undefined") {
v = !that.conditions[that.condition_count];
} else {
mixedValue = fnResolve.call(that,mixedValue);
v = !!mixedValue;
}
that.conditions[that.condition_count] = v;
return that;
});
fn('or', function (mixedAction) {
var that = this;
if (!prospectQueue.call(that,arguments,'or') || that.length)
return that;
that.orFired = true;
if (typeof mixedAction == "function")
mixedAction.call(that);
return this;
});
fn('index', function (strMatch) {
var that = this;
if (!that.length)
return that;
return [].slice.call(that.parent().children(strMatch)).indexOf(that[0]);
});
// DOM Ready
fn('ready', function (fnCallback) {
if (document.readyState === "complete") {
if (fnCallback)
fnCallback();
return true;
} else {
if (!fnCallback)
return false;
// Create the promise
arrReadyPromises.push(fnCallback);
// Set the even listeners
if (!boolReadyEventsOn) {
boolReadyEventsOn = true;
var
// call all the promised functions
ready = function () {
for (var intItr in arrReadyPromises) {
arrReadyPromises[intItr]();
}
},
// attach event for dom ready
completed = function( event ) {
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
ready();
}
},
// detatch completed function
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
}
}
}
});
// gives a q something to do. used when q is called as a function
fn('put', function (mixedQuery,strType) {
var
that = this,
queryType = strType || typeof mixedQuery;
//if (queryType === 'string')
//mixedQuery = mixedQuery.replace(/^[\r\n]+/g, '').trim();
if (queryType == 'undefined') {
return that;
} else if (queryType == 'function') {
return that.ready(mixedQuery); // DOM ready
} else if (queryType == 'object') {
var i=0;
if (isNode(mixedQuery)) {
that[i++] = mixedQuery;
} else if (mixedQuery.is_qchain) {
return mixedQuery;
} else if (Array.isArray(mixedQuery)) {
iterate(mixedQuery,function () {
that[i++] = this;
});
} else {
that[i++] = mixedQuery;
}
fnTrimQueue.call(that,i);
} else if (queryType == 'string' && mixedQuery.match(/</) && mixedQuery.match(/>/) && mixedQuery.length >= 3) {
return that.make(mixedQuery,BYPASS_QUEUE);
} else
return fun.find(mixedQuery);
return that;
});
// Create HTML within the selection
fn('make', function (strHTML) {
var
that = this;
if (!prospectQueue.call(that,arguments,'make'))
return that;
var wrapper = document.createElement('div');
wrapper.innerHTML = strHTML;
var
children = wrapper.children,
len = Math.max(children.length, that.length),
i=0;
while (i<len)
that[i] = children[i++];
that.length = i;
fnTrimQueue.call(that,i);
var script = $(wrapper).find("script").each(function() {
var that = this;
var strJS = that.innerHTML.replace(/\t/g, "\n");
q.delay(1, function () { Function(strJS)() });
});
return that;
});
// Find elements in dom that matches a CSS selection
// Adds them as a list to a copy of the q object
fn('find', function (strQuery) {
var that = this,
l=that.length;
if (that.layers!=0 && !l)
return that;
var qcopy = copy(fun), // start with a fresh q handle
arrResult = [],
i=0;
qcopy.layers=that.layers+1;
var arrMatched = strQuery.match(/^ *> *(.+)/);
if (arrMatched) {
iterate(that.children(), function (k,el) {
if (arrMatched[1] == "*" || q(el).is(arrMatched[1]))
qcopy[i++] = el;
});
} else {
if (!l)
arrResult = [].slice.call(document.querySelectorAll(strQuery));
else while (i<l) {
var arrSubResult = [].slice.call(that[i++].querySelectorAll(strQuery));
arrResult = arrResult.concat(arrSubResult);
}
l = arrResult.length;
i=0;
while (i<l)
qcopy[i] = arrResult[i++];
}
qcopy.length = i;
return qcopy;
});
// Check if matches a selection
fn('is', function (strQuery) {
var boolIs = true;
iterate(this,function (k,el) {
if (!(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, strQuery)) {
boolIs = false;
return false;
}
});
return boolIs;
});
// Clone a dom node
fn('clone', function (boolDeep) {
var that = this;
if (!prospectQueue.call(that,arguments,'clone'))
return that;
var qcopy = copy(that),
len = 0;
boolDeep = boolDeep !== false;
iterate(that,function (k,v) {
qcopy[k] = v.cloneNode(boolDeep);
len++;
});
fnTrimQueue.call(qcopy,len);
return qcopy;
});
// Store data on a DOM node
fn('data', function (strKey, strVal) {
var
boolGet = typeof strVal == "undefined",
arrDataResult = [];
iterate(this,function (j,el) {
if (!el) return;
var intUId = q(el).uniqueId();
if (boolGet)
arrDataResult.push(arrDataMemory[intUId] && typeof arrDataMemory[intUId][strKey] != 'undefined' ? arrDataMemory[intUId][strKey] : null);
else {
if (!arrDataMemory[intUId])
arrDataMemory[intUId] = {};
arrDataMemory[intUId][strKey] = strVal;
}
});
if (boolGet)
return arrDataResult.length == 1 ? arrDataResult[0] : arrDataResult;
else
return this;
});
fn('checked', function (boolValue) {
var that = this;
if (typeof boolValue == "undefined") {
if (!that.length)
return null;
var boolResult = true;
iterate(that,function (j,el) {
if (!el.checked)
boolResult = false;
});
return boolResult;
} else {
iterate(that,function (j,el) {
el.checked = boolValue;
});
}
});
// Get all the HTML currently held as nodes in the current query
fn('html', function (strHTML, strAttrKey) {
var that = this;
var htmlAttr = strAttrKey || "innerHTML";
if (strHTML == undefined) {
strHTML = "";
iterate(that,function (k,el) {
strHTML += el[htmlAttr];
});
return strHTML;
}
if (!prospectQueue.call(that,arguments,'html'))
return that;
strHTML = fnResolve.call(that,strHTML);
iterate(that,function (k,el) {
el[htmlAttr] = strHTML;
});
return that;
});
// Get or alter the elements tag name
fn('tagName', function (strAlter) {
var that = this;
if (typeof strAlter == 'undefined') {
return that[0].tagName;
} else {
var item = q(
that[0]
.outerHTML
.replace(new RegExp('^<' + that.tagName() + ' ','i'), "<" + strAlter + ' ')
.replace(new RegExp(that.tagName() + '>','i'), strAlter + '>')
);
that.replace(item);
that[0] = item[0]; // recreate the ref
}