forked from julianshapiro/velocity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvelocity.js
2867 lines (2423 loc) · 165 KB
/
velocity.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
/***************
Details
***************/
/*!
* Velocity.js: Accelerated JavaScript animation.
* @version 0.0.0
* @docs VelocityJS.org
* @license Copyright 2014 Julian Shapiro. MIT License: http://en.wikipedia.org/wiki/MIT_License
*/
/****************
Summary
****************/
/*
Velocity recreates the entirety of jQuery's CSS stack and builds a concise animation layer on top of it. To minimize DOM interaction, Velocity reuses previous animation values and batches DOM queries.
Whenever Velocity triggers a DOM query (a GET) or a DOM update (a SET), a comment indicating as much is placed next to the offending line of code.
Watch these talks to learn about the nuances of DOM performance: https://www.youtube.com/watch?v=cmZqLzPy0XE and https://www.youtube.com/watch?v=n8ep4leoN9A
Velocity is structured into four sections:
- CSS Stack: Works independently from the rest of Velocity.
- $.fn.velocity is the jQuery object extension that, when triggered, iterates over the targeted element set and queues the incoming Velocity animation onto each element individually. This process consists of:
- Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options argument.
- Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale.
- Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
- Tick: The single requestAnimationFrame loop responsible for tweening all in-progress calls.
- completeCall: Handles the cleanup process for each Velocity call.
To interoperate with jQuery, Velocity uses jQuery's own $.queue() stack for all queuing logic. This has the byproduct of slightly bloating our codebase since $.queue()'s behavior is not straightforward.
The biggest cause of both codebase bloat and codepath obfuscation in Velocity is its support for animating compound-value CSS properties (e.g. "textShadow: 0px 0px 0px black" and "transform: skew(45) scale(1.5)").
*/
;(function (global, document, undefined) {
/*********************
Helper Functions
*********************/
/* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 4; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
div = null;
return i;
}
}
}
return undefined;
})();
/* RAF polyfill. Gist: https://gist.github.com/julianshapiro/9497513 */
var requestAnimationFrame = window.requestAnimationFrame || (function() {
var timeLast = 0;
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
var timeCurrent = (new Date()).getTime(),
timeDelta;
/* Dynamically set delay on a per-tick basis to match 60fps. */
/* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */
timeDelta = Math.max(0, 16 - (timeCurrent - timeLast));
timeLast = timeCurrent + timeDelta;
return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta);
};
})();
/* Sparse array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */
function compactSparseArray (array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
/* Determine if a variable is a function. */
function isFunction(variable) {
return Object.prototype.toString.call(variable) === "[object Function]";
}
/****************
jQuery utilities
****************/
/* Whilst requiring the whole jQuery library as a dependency causes many problems, integrating key parts of it (the parts velocity actually uses.) */
/* The following acts as a fallback in case jQuery isn't loaded, as to limit the overhead for the users using it anyway. */
/* jQuery: Copyright The jQuery Foundation. MIT License: https://jquery.org/license */
/* Zepto.js: Copyright Thomas Fuchs. MIT License: http://zeptojs.com/license/ */
var $ = window.jQuery || (function() {
/* Declaration of the actual jQuery-like object, window.jQuery */
var $ = function (selector, context) {
return new $.fn.init(selector, context);
};
/*****************
$.methods()
****************/
/* Creation of the fn prototype alias, used in the $().method calls */
$.fn = $.prototype = {
init: function(selector) {
if (selector.nodeType) {
this[0] = selector;
return this;
}
throw new Error('The parameter given was not a DOM node.');
},
offset: function () {
/* jQuery altered code */
var box = this[0].getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),
left: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)
};
},
position: function () {
/* jQuery/Zepto altered code */
function offsetParent() {
var offsetParent = this.offsetParent || document;
while (offsetParent && (!offsetParent.nodeType.toLowerCase === "html" && offsetParent.style.position === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = offsetParent.apply(elem),
// Get correct offsets
offset = this.offset(),
parentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? { top: 0, left: 0 } : $(offsetParent).offset()
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat(elem.style.marginTop) || 0;
offset.left -= parseFloat(elem.style.marginLeft) || 0;
// Add offsetParent borders
if(offsetParent.style) {
parentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0
parentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0
}
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
}
}
};
/* Makes $(nodeElement) possible, without having to call init. */
$.fn.init.prototype = $.fn;
/*****************
Private methods
****************/
var optionsCache = {},
data = {},
class2type = {}
hasOwn = class2type.hasOwnProperty,
toString = class2type.toString;
"Boolean Number String Function Array Date RegExp Object Error".split(" ").forEach(function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
});
$.expando = "velocity" + (Math.random() + '').replace(/\D/g, "");
$.cache = {};
$.uuid = 1;
function isArraylike(obj) {
/* jQuery altered code */
var length = obj.length,
type = $.type(obj);
if (type === "function" || $.isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && length) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && (length - 1) in obj;
}
function createOptions(options) {
/* jQuery original code */
var object = optionsCache[options] = {};
$.each(options.match(/\S+/g) || [], function(_, flag) {
object[flag] = true;
});
return object;
}
/* Functions used in more than just one helper, so they weren't absorbed */
$.isWindow = function (obj) {
/* jQuery original code */
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
};
$.type = function (obj) {
/* Zepto altered code */
if (obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[toString.call(obj)] || "object" :
typeof obj;
};
$.isArray = Array.isArray || function (obj) {
/* jQuery original code */
return $.type(obj) === "array";
};
$.camelCase = function (string) {
/* jQuery altered code */
return string.replace(/^-ms-/, "ms-")
.replace(/-([\da-z])/gi, function(all, letter) {
return letter.toUpperCase();
});
};
/*****************
$.methods()
****************/
/* Creation of the jQuery.methods() */
$.each = function(obj, callback, args) {
/* jQuery altered code */
var i = 0,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < obj.length; i++) {
if ((callback.apply(obj[i], args)) === false) {
break;
}
}
} else {
for (i in obj) {
if ((callback.apply(obj[i], args)) === false) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if (isArray) {
for (; i < obj.length; i++) {
if ((callback.call(obj[i], i, obj[i])) === false) {
break;
}
}
} else {
for (i in obj) {
if ((callback.call(obj[i], i, obj[i])) === false) {
break;
}
}
}
}
return obj;
};
$.data = function(node, name, value) {
/* Zepto altered code */
var id = node[$.expando] || (node[$.expando] = ++$.uuid),
camelName = $.camelCase(name),
store;
/* $.getData() */
if(value !== undefined) {
store = data[id] || (data[id] = {});
if (name !== undefined) {
store[camelName] = value;
}
return store;
}
/* $.setData() */
store = id && data[id];
if (store) {
if (name in store) {
return store[name];
}
if (camelName in store) {
return store[camelName]
}
}
};
$.extend = function (target) {
/* Zepto altered code */
function extend (target, source, deep) {
for (key in source) {
if (deep && ($.isPlainObject(source[key]) || $.isArray(source[key]))) {
if ($.isPlainObject(source[key]) && !$.isPlainObject(target[key]))
target[key] = {};
if ($.isArray(source[key]) && !$.isArray(target[key]))
target[key] = [];
extend(target[key], source[key], deep);
}
else if (source[key] !== undefined) target[key] = source[key];
}
}
var deep, args = [].slice.call(arguments, 1);
if (typeof target == 'boolean') {
deep = target;
target = args.shift();
}
$.each(args, function (_, arg) {
extend(target, arg, deep)
});
return target;
};
$.queue = function (elem, type, data) {
/* jQuery altered code */
/* Courtesy of https://gist.github.com/zohararad/6291798 */
if(elem) {
function $makeArray (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
/* $.merge */
(function(first, second) {
/* jQuery altered code */
var l = second.length,
i = first.length,
j = 0;
if (typeof l === "number") {
for (; j < l; j++) {
first[i++] = second[j];
}
} else {
while (second[j] !== undefined) {
first[i++] = second[j++];
}
}
first.length = i;
return first;
})(ret, typeof arr === "string" ? [arr] : arr);
} else {
[].push.call(ret, arr);
}
}
return ret;
}
var queue;
type = (type || "fx") + "queue";
queue = $.data(elem, type);
// Speed up dequeue by getting out quickly if this is just a lookup
if (data) {
if (!queue || $.isArray(data)) {
queue = $.data(elem, type, $makeArray(data));
} else {
queue.push(data);
}
}
return queue || [];
}
};
$.dequeue = function (elem, type) {
/* jQuery altered code */
/* Courtesy of https://gist.github.com/zohararad/6291798 */
type = type || "fx";
var queue = $.queue(elem, type),
startLength = queue.length,
fn = queue.shift(),
_queueHooks = function (elem, type) {
/* jQuery altered code */
var key = type + "queueHooks";
return $.data(elem, key) || $.data(elem, key, {
empty: $.Callbacks("once memory").add(function() {
$.removeData(elem, [type + "queue", key]);
})
});
},
hooks = _queueHooks(elem, type),
next = function () {
$.dequeue(elem, type);
};
// If the fx queue is dequeued, always remove the progress sentinel
if (fn === "inprogress") {
fn = queue.shift();
startLength--;
}
if (fn) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if (type === "fx") {
queue.unshift("inprogress");
}
// clear up the last queue stop function
delete hooks.stop;
fn.call(elem, next, hooks);
}
if (!startLength && hooks && hooks.empty) {
hooks.empty.fire();
}
};
$.isPlainObject = function (obj) {
/* jQuery altered code */
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow(obj)) {
return false;
}
try {
// Not own constructor property must be Object
if (obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
$.isEmptyObject = function (obj) {
/* jQuery original code */
var name;
for(name in obj) {
return false;
}
return true;
};
$.removeData = function (node, names) {
/* Zepto altered code */
var id = node[$.expando],
store = id && data[id];
if (store) {
$.each(names, function(_, name) {
delete store[name ? $.camelCase(this) : name];
});
}
};
$.Callbacks = function (options) {
/* jQuery altered code */
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
(optionsCache[options] || createOptions(options)) :
$.extend({}, options);
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function (data) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for (; list && firingIndex < firingLength; firingIndex++) {
if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if (list) {
if (stack) {
if (stack.length) {
fire(stack.shift());
}
} else if (memory) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function () {
if (list) {
// First, we save the current length
var start = list.length;
(function add(args) {
$.each(args, function (_, arg) {
var type = $.type(arg);
if (type === "function") {
if (!options.unique || !self.has(arg)) {
list.push(arg);
}
} else if (arg && arg.length && type !== "string") {
// Inspect recursively
add(arg);
}
});
})(arguments);
// Do we need to add the callbacks to the
// current firing batch?
if (firing) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if (memory) {
firingStart = start;
fire(memory);
}
}
return this;
},
// Remove a callback from the list
remove: function () {
if (list) {
var $inArray = function (elem, arr, i) {
var len,
indexOf = arr.indexOf || function (elem) {
var i = 0,
len = this.length;
for (; i < len; i++) {
if (this[i] === elem) {
return i;
}
}
return -1;
};
if (arr) {
if (indexOf) {
return indexOf.call(arr, elem, i);
}
len = arr.length;
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
for (; i < len; i++) {
// Skip accessing in sparse arrays
if (i in arr && arr[i] === elem) {
return i;
}
}
}
return -1;
};
$.each(arguments, function (_, arg) {
var index;
while ((index = $inArray(arg, list, index)) > -1) {
list.splice(index, 1);
// Handle firing indexes
if (firing) {
if (index <= firingLength) {
firingLength--;
}
if (index <= firingIndex) {
firingIndex--;
}
}
}
});
}
return this;
},
// Remove all callbacks from the list
empty: function () {
list = [];
firingLength = 0;
return this;
},
// Call all callbacks with the given context and arguments
fireWith: function (context, args) {
if (list && (!fired || stack)) {
args = args || [];
args = [context, args.slice ? args.slice() : args];
if (firing) {
stack.push(args);
} else {
fire(args);
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function () {
self.fireWith(this, arguments);
return this;
}
};
return self;
};
return $;
})();
/*****************
Constants
*****************/
var NAME = "velocity";
/******************************
Utility Function & State
******************************/
/* In addition to extending jQuery's $.fn object, Velocity also registers itself as a jQuery utility ($.) function so that certain features are accessible beyond just a per-element scope. */
/* Note: The utility function doubles as a publicly-accessible data store for the purposes of unit testing. */
var velocity = {
/* Container for page-wide Velocity state data. */
State: {
/* Detect mobile devices to determine if mobileHA should be turned on. */
isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
/* Create a cached element for re-use when checking for CSS property prefixes. */
prefixElement: document.createElement("div"),
/* Cache every prefix match to avoid repeating lookups. */
prefixMatches: {},
/* Cache the anchor used for animating window scrolling. */
scrollAnchor: null,
/* Cache the property name associated with the scroll anchor. */
scrollProperty: null,
/* Keep track of whether our RAF tick is running. */
isTicking: false,
/* Container for every in-progress call to Velocity. */
calls: []
},
Classes: {
/* Container for CSS classes extracted from the page's stylesheets. */
extracted: {},
/* Function to allow users to force stylesheet re-extraction. */
extract: function() { /* Defined below. */ }
},
/* Velocity's full re-implementation of jQuery's CSS stack. Made global for unit testing. */
CSS: { /* Defined below. */ },
/* Container for custom animation sequences that are referenced by name via Velocity's first argument (instead of passing in a properties map). */
Sequences: {
/* Manually extended by the user. */
},
/* Even if referred as $ internally, we export the set of utilities generated above, mostly for testing purposes, as it is the only way to access the data store. */
Utilities: $,
/* Utility function's alias of $.fn.velocity(). Used for raw DOM element animation. */
animate: function () { /* Defined below. */ },
/* Set to 1 or 2 (most verbose) to log debug info to console. */
debug: false
};
/* Retrieve the appropriate scroll anchor and property name for this browser. Learn more here: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */
if (window.pageYOffset !== undefined) {
velocity.State.scrollAnchor = window;
velocity.State.scrollProperty = "pageYOffset";
} else {
velocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body;
velocity.State.scrollProperty = "scrollTop";
}
/**************
Easings
**************/
/* Velocity embeds jQuery UI's easings to save users from having to include an additional library to their page. */
/* Copyright The jQuery Foundation. MIT License: https://jquery.org/license */
(function () {
var baseEasings = {};
velocity.Easings = {};
$.each(["Quad", "Cubic", "Quart", "Quint", "Expo"], function(i, name) {
baseEasings[name] = function(p) {
return Math.pow(p, i + 2);
};
});
$.extend(baseEasings, {
Sine: function (p) {
return 1 - Math.cos(p * Math.PI / 2);
},
Circ: function (p) {
return 1 - Math.sqrt(1 - p * p);
},
Elastic: function(p) {
return p === 0 || p === 1 ? p :
-Math.pow(2, 8 * (p - 1)) * Math.sin(((p - 1) * 80 - 7.5) * Math.PI / 15);
},
Back: function(p) {
return p * p * (3 * p - 2);
},
Bounce: function (p) {
var pow2,
bounce = 4;
while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {}
return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2);
}
});
$.each(baseEasings, function(name, easeIn) {
velocity.Easings["easeIn" + name] = easeIn;
velocity.Easings["easeOut" + name] = function(p) {
return 1 - easeIn(1 - p);
};
velocity.Easings["easeInOut" + name] = function(p) {
return p < 0.5 ?
easeIn(p * 2) / 2 :
1 - easeIn(p * -2 + 2) / 2;
};
});
/* jQuery swing's, because jQuery wasn't loaded, as it is our default easing. */
velocity.Easings["swing"] = velocity.Easings["swing"] || function(p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
};
/* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */
velocity.Easings["spring"] = function(p) {
return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6));
};
})();
/*****************
CSS Stack
*****************/
/* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's. It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */
/* Note: A "CSS" shorthand is defined so that our code is easier to read. */
var CSS = velocity.CSS = {
/*************
RegEx
*************/
RegEx: {
/* Unwrap a property value's surrounding text, e.g. "rgba(4, 3, 2, 1)" ==> "4, 3, 2, 1" and "rect(4px 3px 2px 1px)" ==> "4px 3px 2px 1px". */
valueUnwrap: /^[A-z]+\((.*)\)$/i,
wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
/* Split a multi-value property into an array of subvalues, e.g. "rgba(4, 3, 2, 1) 4px 3px 2px 1px" ==> [ "rgba(4, 3, 2, 1)", "4px", "3px", "2px", "1px" ]. */
valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig
},
/************
Hooks
************/
/* Hooks allow a subproperty (e.g. "boxShadowBlur") of a compound-value CSS property (e.g. "boxShadow: X Y Blur Spread Color") to be animated as if it were a discrete property. */
/* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */
Hooks: {
/********************
Registration
********************/
/* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */
/* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */
templates: {
/* Note: Colors are defaulted to white -- as opposed to black -- since colors that are currently set to "transparent" default to their respective template below when color-animated,
and white is typically a closer match to transparent than black is. */
"color": [ "Red Green Blue Alpha", "255 255 255 1" ],
"backgroundColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"outlineColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"textShadow": [ "Color X Y Blur", "black 0px 0px 0px" ],
/* Todo: Add support for inset boxShadows. (webkit places it last whereas IE places it first.) */
"boxShadow": [ "Color X Y Blur Spread", "black 0px 0px 0px 0px" ],
"clip": [ "Top Right Bottom Left", "0px 0px 0px 0px" ],
"backgroundPosition": [ "X Y", "0% 0%" ],
"transformOrigin": [ "X Y Z", "50% 50% 0%" ],
"perspectiveOrigin": [ "X Y", "50% 50%" ]
},
/* A "registered" hook is one that has been converted from its template form into a live, tweenable property. It contains data to associate it with its root property. */
registered: {
/* Note: A registered hook looks like this ==> textShadowBlur: [ "textShadow", 3 ], which consists of the subproperty's name, the associated root property's name,
and the subproperty's position in the root's value. */
},
/* Convert the templates into individual hooks then append them to the registered object above. */
register: function () {
var rootProperty,
hookTemplate,
hookNames;
/* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning. Thus, we re-arrange the templates accordingly. */
if (IE) {
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
var defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit);
if (hookNames[0] === "Color") {
/* Reposition both the hook's name and its default value to the end of their respective strings. */
hookNames.push(hookNames.shift());
defaultValues.push(defaultValues.shift());
/* Replace the existing template for the hook's root property. */
CSS.Hooks.templates[rootProperty] = [ hookNames.join(" "), defaultValues.join(" ") ];
}
}
}
/* Hook registration. */
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
for (var i in hookNames) {
var fullHookName = rootProperty + hookNames[i],
hookPosition = i;
/* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow) and the hook's position in its template's default value string. */
CSS.Hooks.registered[fullHookName] = [ rootProperty, hookPosition ];
}
}
},
/*****************************
Injection and Extraction
*****************************/
/* Look up the root property associated with the hook (e.g. return "textShadow" for "textShadowBlur"). */
/* Since a hook cannot be set directly (the browser won't recognize it), style updating for hooks is routed through the hook's root property. */
getRoot: function (property) {
var hookData = CSS.Hooks.registered[property];
if (hookData) {
return hookData[0];
} else {
/* If there was no hook match, return the property name untouched. */
return property;
}
},
/* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that the targeted hook can be injected or extracted at its standard position. */
cleanRootPropertyValue: function(rootProperty, rootPropertyValue) {
/* If the rootPropertyValue is wrapped with "rgb()", "clip()", etc., remove the wrapping to normalize the value before manipulation. */
if (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) {
rootPropertyValue = rootPropertyValue.match(CSS.Hooks.RegEx.valueUnwrap)[1];
}
/* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract), default to the root's default value as defined in CSS.Hooks.templates. */
/* Note: CSS null-values include "none", "auto", and "transparent". They must be converted into their zero-values (e.g. textShadow: "none" ==> textShadow: "0px 0px 0px black") for hook manipulation to proceed. */
if (CSS.Values.isCSSNullValue(rootPropertyValue)) {
rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
}
return rootPropertyValue;
},
/* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */
extractValue: function (fullHookName, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1];
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */
return rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition];
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
},
/* Inject the hook's value into its root property's value. This is used to piece back together the root property once Velocity has updated one of its individually hooked values through tweening. */
injectValue: function (fullHookName, hookValue, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1],
rootPropertyValueParts,
rootPropertyValueUpdated;
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue, then reconstruct the rootPropertyValue string. */
rootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit);
rootPropertyValueParts[hookPosition] = hookValue;
rootPropertyValueUpdated = rootPropertyValueParts.join(" ");
return rootPropertyValueUpdated;
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
}
},
/*******************
Normalizations
*******************/
/* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity) and reformatting special properties (e.g. clip, rgba) to look like standard ones. */
Normalizations: {
/* Normalizations are passed a normalization vector (either the property's name, its extracted value, or its injected value), the targeted element (which may need to be queried), and the targeted property value. */
registered: {
clip: function(type, element, propertyValue) {
switch (type) {
case "name":
return "clip";
/* Clip needs to be unwrapped and stripped of its commas during extraction. */
case "extract":
var extracted;
/* If Velocity also extracted this value, skip extraction. */
if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
extracted = propertyValue;
} else {
/* Remove the "rect()" wrapper. */
extracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap);
if (extracted) {
/* Strip off commas. */
extracted = extracted[1].replace(/,(\s+)?/g, " ");
}
}
return extracted;
/* Clip needs to be re-wrapped during injection. */
case "inject":
return "rect(" + propertyValue + ")";
}
},
/* <=IE8 do not support the opacity property. Further, they require opacified elements to have their zoom property set to a non-zero value. */
opacity: function (type, element, propertyValue) {
if (IE <= 8) {
switch (type) {
case "name":
return "filter";
case "extract":
/* <=IE8 return a "filter" value of "alpha(opacity=\d{1,3})". Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */
var extracted = propertyValue.toString().match(/alpha\(opacity=(.*)\)/i);
if (extracted) {
/* Convert to decimal value. */
propertyValue = extracted[1] / 100;
} else {
/* When extracting opacity, default to 1 (fully visible) since a null value means opacity hasn't been set and the element is therefore fully visible. */
propertyValue = 1;
}