UNPKG

214 kBJavaScriptView Raw
1/*! VelocityJS.org (1.2.2). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
2
3/*************************
4 Velocity jQuery Shim
5*************************/
6
7/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
8
9/* This file contains the jQuery functions that Velocity relies on, thereby removing Velocity's dependency on a full copy of jQuery, and allowing it to work in any environment. */
10/* These shimmed functions are only used if jQuery isn't present. If both this shim and jQuery are loaded, Velocity defaults to jQuery proper. */
11/* Browser support: Using this shim instead of jQuery proper removes support for IE8. */
12
13;(function (window) {
14 /***************
15 Setup
16 ***************/
17
18 /* If jQuery is already loaded, there's no point in loading this shim. */
19 if (window.jQuery) {
20 return;
21 }
22
23 /* jQuery base. */
24 var $ = function (selector, context) {
25 return new $.fn.init(selector, context);
26 };
27
28 /********************
29 Private Methods
30 ********************/
31
32 /* jQuery */
33 $.isWindow = function (obj) {
34 /* jshint eqeqeq: false */
35 return obj != null && obj == obj.window;
36 };
37
38 /* jQuery */
39 $.type = function (obj) {
40 if (obj == null) {
41 return obj + "";
42 }
43
44 return typeof obj === "object" || typeof obj === "function" ?
45 class2type[toString.call(obj)] || "object" :
46 typeof obj;
47 };
48
49 /* jQuery */
50 $.isArray = Array.isArray || function (obj) {
51 return $.type(obj) === "array";
52 };
53
54 /* jQuery */
55 function isArraylike (obj) {
56 var length = obj.length,
57 type = $.type(obj);
58
59 if (type === "function" || $.isWindow(obj)) {
60 return false;
61 }
62
63 if (obj.nodeType === 1 && length) {
64 return true;
65 }
66
67 return type === "array" || length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj;
68 }
69
70 /***************
71 $ Methods
72 ***************/
73
74 /* jQuery: Support removed for IE<9. */
75 $.isPlainObject = function (obj) {
76 var key;
77
78 if (!obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow(obj)) {
79 return false;
80 }
81
82 try {
83 if (obj.constructor &&
84 !hasOwn.call(obj, "constructor") &&
85 !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
86 return false;
87 }
88 } catch (e) {
89 return false;
90 }
91
92 for (key in obj) {}
93
94 return key === undefined || hasOwn.call(obj, key);
95 };
96
97 /* jQuery */
98 $.each = function(obj, callback, args) {
99 var value,
100 i = 0,
101 length = obj.length,
102 isArray = isArraylike(obj);
103
104 if (args) {
105 if (isArray) {
106 for (; i < length; i++) {
107 value = callback.apply(obj[i], args);
108
109 if (value === false) {
110 break;
111 }
112 }
113 } else {
114 for (i in obj) {
115 value = callback.apply(obj[i], args);
116
117 if (value === false) {
118 break;
119 }
120 }
121 }
122
123 } else {
124 if (isArray) {
125 for (; i < length; i++) {
126 value = callback.call(obj[i], i, obj[i]);
127
128 if (value === false) {
129 break;
130 }
131 }
132 } else {
133 for (i in obj) {
134 value = callback.call(obj[i], i, obj[i]);
135
136 if (value === false) {
137 break;
138 }
139 }
140 }
141 }
142
143 return obj;
144 };
145
146 /* Custom */
147 $.data = function (node, key, value) {
148 /* $.getData() */
149 if (value === undefined) {
150 var id = node[$.expando],
151 store = id && cache[id];
152
153 if (key === undefined) {
154 return store;
155 } else if (store) {
156 if (key in store) {
157 return store[key];
158 }
159 }
160 /* $.setData() */
161 } else if (key !== undefined) {
162 var id = node[$.expando] || (node[$.expando] = ++$.uuid);
163
164 cache[id] = cache[id] || {};
165 cache[id][key] = value;
166
167 return value;
168 }
169 };
170
171 /* Custom */
172 $.removeData = function (node, keys) {
173 var id = node[$.expando],
174 store = id && cache[id];
175
176 if (store) {
177 $.each(keys, function(_, key) {
178 delete store[key];
179 });
180 }
181 };
182
183 /* jQuery */
184 $.extend = function () {
185 var src, copyIsArray, copy, name, options, clone,
186 target = arguments[0] || {},
187 i = 1,
188 length = arguments.length,
189 deep = false;
190
191 if (typeof target === "boolean") {
192 deep = target;
193
194 target = arguments[i] || {};
195 i++;
196 }
197
198 if (typeof target !== "object" && $.type(target) !== "function") {
199 target = {};
200 }
201
202 if (i === length) {
203 target = this;
204 i--;
205 }
206
207 for (; i < length; i++) {
208 if ((options = arguments[i]) != null) {
209 for (name in options) {
210 src = target[name];
211 copy = options[name];
212
213 if (target === copy) {
214 continue;
215 }
216
217 if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {
218 if (copyIsArray) {
219 copyIsArray = false;
220 clone = src && $.isArray(src) ? src : [];
221
222 } else {
223 clone = src && $.isPlainObject(src) ? src : {};
224 }
225
226 target[name] = $.extend(deep, clone, copy);
227
228 } else if (copy !== undefined) {
229 target[name] = copy;
230 }
231 }
232 }
233 }
234
235 return target;
236 };
237
238 /* jQuery 1.4.3 */
239 $.queue = function (elem, type, data) {
240 function $makeArray (arr, results) {
241 var ret = results || [];
242
243 if (arr != null) {
244 if (isArraylike(Object(arr))) {
245 /* $.merge */
246 (function(first, second) {
247 var len = +second.length,
248 j = 0,
249 i = first.length;
250
251 while (j < len) {
252 first[i++] = second[j++];
253 }
254
255 if (len !== len) {
256 while (second[j] !== undefined) {
257 first[i++] = second[j++];
258 }
259 }
260
261 first.length = i;
262
263 return first;
264 })(ret, typeof arr === "string" ? [arr] : arr);
265 } else {
266 [].push.call(ret, arr);
267 }
268 }
269
270 return ret;
271 }
272
273 if (!elem) {
274 return;
275 }
276
277 type = (type || "fx") + "queue";
278
279 var q = $.data(elem, type);
280
281 if (!data) {
282 return q || [];
283 }
284
285 if (!q || $.isArray(data)) {
286 q = $.data(elem, type, $makeArray(data));
287 } else {
288 q.push(data);
289 }
290
291 return q;
292 };
293
294 /* jQuery 1.4.3 */
295 $.dequeue = function (elems, type) {
296 /* Custom: Embed element iteration. */
297 $.each(elems.nodeType ? [ elems ] : elems, function(i, elem) {
298 type = type || "fx";
299
300 var queue = $.queue(elem, type),
301 fn = queue.shift();
302
303 if (fn === "inprogress") {
304 fn = queue.shift();
305 }
306
307 if (fn) {
308 if (type === "fx") {
309 queue.unshift("inprogress");
310 }
311
312 fn.call(elem, function() {
313 $.dequeue(elem, type);
314 });
315 }
316 });
317 };
318
319 /******************
320 $.fn Methods
321 ******************/
322
323 /* jQuery */
324 $.fn = $.prototype = {
325 init: function (selector) {
326 /* Just return the element wrapped inside an array; don't proceed with the actual jQuery node wrapping process. */
327 if (selector.nodeType) {
328 this[0] = selector;
329
330 return this;
331 } else {
332 throw new Error("Not a DOM node.");
333 }
334 },
335
336 offset: function () {
337 /* jQuery altered code: Dropped disconnected DOM node checking. */
338 var box = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : { top: 0, left: 0 };
339
340 return {
341 top: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),
342 left: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)
343 };
344 },
345
346 position: function () {
347 /* jQuery */
348 function offsetParent() {
349 var offsetParent = this.offsetParent || document;
350
351 while (offsetParent && (!offsetParent.nodeType.toLowerCase === "html" && offsetParent.style.position === "static")) {
352 offsetParent = offsetParent.offsetParent;
353 }
354
355 return offsetParent || document;
356 }
357
358 /* Zepto */
359 var elem = this[0],
360 offsetParent = offsetParent.apply(elem),
361 offset = this.offset(),
362 parentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? { top: 0, left: 0 } : $(offsetParent).offset()
363
364 offset.top -= parseFloat(elem.style.marginTop) || 0;
365 offset.left -= parseFloat(elem.style.marginLeft) || 0;
366
367 if (offsetParent.style) {
368 parentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0
369 parentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0
370 }
371
372 return {
373 top: offset.top - parentOffset.top,
374 left: offset.left - parentOffset.left
375 };
376 }
377 };
378
379 /**********************
380 Private Variables
381 **********************/
382
383 /* For $.data() */
384 var cache = {};
385 $.expando = "velocity" + (new Date().getTime());
386 $.uuid = 0;
387
388 /* For $.queue() */
389 var class2type = {},
390 hasOwn = class2type.hasOwnProperty,
391 toString = class2type.toString;
392
393 var types = "Boolean Number String Function Array Date RegExp Object Error".split(" ");
394 for (var i = 0; i < types.length; i++) {
395 class2type["[object " + types[i] + "]"] = types[i].toLowerCase();
396 }
397
398 /* Makes $(node) possible, without having to call init. */
399 $.fn.init.prototype = $.fn;
400
401 /* Globalize Velocity onto the window, and assign its Utilities property. */
402 window.Velocity = { Utilities: $ };
403})(window);
404
405/******************
406 Velocity.js
407******************/
408
409;(function (factory) {
410 /* CommonJS module. */
411 if (typeof module === "object" && typeof module.exports === "object") {
412 module.exports = factory();
413 /* AMD module. */
414 } else if (typeof define === "function" && define.amd) {
415 define(factory);
416 /* Browser globals. */
417 } else {
418 factory();
419 }
420}(function() {
421return function (global, window, document, undefined) {
422
423 /***************
424 Summary
425 ***************/
426
427 /*
428 - CSS: CSS stack that works independently from the rest of Velocity.
429 - animate(): Core animation method that iterates over the targeted elements and queues the incoming call onto each element individually.
430 - Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options.
431 - Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack.
432 Most logic is placed here to avoid risking it becoming stale (if the element's properties have changed).
433 - Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
434 - tick(): The single requestAnimationFrame loop responsible for tweening all in-progress calls.
435 - completeCall(): Handles the cleanup process for each Velocity call.
436 */
437
438 /*********************
439 Helper Functions
440 *********************/
441
442 /* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */
443 var IE = (function() {
444 if (document.documentMode) {
445 return document.documentMode;
446 } else {
447 for (var i = 7; i > 4; i--) {
448 var div = document.createElement("div");
449
450 div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
451
452 if (div.getElementsByTagName("span").length) {
453 div = null;
454
455 return i;
456 }
457 }
458 }
459
460 return undefined;
461 })();
462
463 /* rAF shim. Gist: https://gist.github.com/julianshapiro/9497513 */
464 var rAFShim = (function() {
465 var timeLast = 0;
466
467 return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
468 var timeCurrent = (new Date()).getTime(),
469 timeDelta;
470
471 /* Dynamically set delay on a per-tick basis to match 60fps. */
472 /* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */
473 timeDelta = Math.max(0, 16 - (timeCurrent - timeLast));
474 timeLast = timeCurrent + timeDelta;
475
476 return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta);
477 };
478 })();
479
480 /* Array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */
481 function compactSparseArray (array) {
482 var index = -1,
483 length = array ? array.length : 0,
484 result = [];
485
486 while (++index < length) {
487 var value = array[index];
488
489 if (value) {
490 result.push(value);
491 }
492 }
493
494 return result;
495 }
496
497 function sanitizeElements (elements) {
498 /* Unwrap jQuery/Zepto objects. */
499 if (Type.isWrapped(elements)) {
500 elements = [].slice.call(elements);
501 /* Wrap a single element in an array so that $.each() can iterate with the element instead of its node's children. */
502 } else if (Type.isNode(elements)) {
503 elements = [ elements ];
504 }
505
506 return elements;
507 }
508
509 var Type = {
510 isString: function (variable) {
511 return (typeof variable === "string");
512 },
513 isArray: Array.isArray || function (variable) {
514 return Object.prototype.toString.call(variable) === "[object Array]";
515 },
516 isFunction: function (variable) {
517 return Object.prototype.toString.call(variable) === "[object Function]";
518 },
519 isNode: function (variable) {
520 return variable && variable.nodeType;
521 },
522 /* Copyright Martin Bohm. MIT License: https://gist.github.com/Tomalak/818a78a226a0738eaade */
523 isNodeList: function (variable) {
524 return typeof variable === "object" &&
525 /^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(variable)) &&
526 variable.length !== undefined &&
527 (variable.length === 0 || (typeof variable[0] === "object" && variable[0].nodeType > 0));
528 },
529 /* Determine if variable is a wrapped jQuery or Zepto element. */
530 isWrapped: function (variable) {
531 return variable && (variable.jquery || (window.Zepto && window.Zepto.zepto.isZ(variable)));
532 },
533 isSVG: function (variable) {
534 return window.SVGElement && (variable instanceof window.SVGElement);
535 },
536 isEmptyObject: function (variable) {
537 for (var name in variable) {
538 return false;
539 }
540
541 return true;
542 }
543 };
544
545 /*****************
546 Dependencies
547 *****************/
548
549 var $,
550 isJQuery = false;
551
552 if (global.fn && global.fn.jquery) {
553 $ = global;
554 isJQuery = true;
555 } else {
556 $ = window.Velocity.Utilities;
557 }
558
559 if (IE <= 8 && !isJQuery) {
560 throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");
561 } else if (IE <= 7) {
562 /* Revert to jQuery's $.animate(), and lose Velocity's extra features. */
563 jQuery.fn.velocity = jQuery.fn.animate;
564
565 /* Now that $.fn.velocity is aliased, abort this Velocity declaration. */
566 return;
567 }
568
569 /*****************
570 Constants
571 *****************/
572
573 var DURATION_DEFAULT = 400,
574 EASING_DEFAULT = "swing";
575
576 /*************
577 State
578 *************/
579
580 var Velocity = {
581 /* Container for page-wide Velocity state data. */
582 State: {
583 /* Detect mobile devices to determine if mobileHA should be turned on. */
584 isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
585 /* The mobileHA option's behavior changes on older Android devices (Gingerbread, versions 2.3.3-2.3.7). */
586 isAndroid: /Android/i.test(navigator.userAgent),
587 isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent),
588 isChrome: window.chrome,
589 isFirefox: /Firefox/i.test(navigator.userAgent),
590 /* Create a cached element for re-use when checking for CSS property prefixes. */
591 prefixElement: document.createElement("div"),
592 /* Cache every prefix match to avoid repeating lookups. */
593 prefixMatches: {},
594 /* Cache the anchor used for animating window scrolling. */
595 scrollAnchor: null,
596 /* Cache the browser-specific property names associated with the scroll anchor. */
597 scrollPropertyLeft: null,
598 scrollPropertyTop: null,
599 /* Keep track of whether our RAF tick is running. */
600 isTicking: false,
601 /* Container for every in-progress call to Velocity. */
602 calls: []
603 },
604 /* Velocity's custom CSS stack. Made global for unit testing. */
605 CSS: { /* Defined below. */ },
606 /* A shim of the jQuery utility functions used by Velocity -- provided by Velocity's optional jQuery shim. */
607 Utilities: $,
608 /* Container for the user's custom animation redirects that are referenced by name in place of the properties map argument. */
609 Redirects: { /* Manually registered by the user. */ },
610 Easings: { /* Defined below. */ },
611 /* Attempt to use ES6 Promises by default. Users can override this with a third-party promises library. */
612 Promise: window.Promise,
613 /* Velocity option defaults, which can be overriden by the user. */
614 defaults: {
615 queue: "",
616 duration: DURATION_DEFAULT,
617 easing: EASING_DEFAULT,
618 begin: undefined,
619 complete: undefined,
620 progress: undefined,
621 display: undefined,
622 visibility: undefined,
623 loop: false,
624 delay: false,
625 mobileHA: true,
626 /* Advanced: Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */
627 _cacheValues: true
628 },
629 /* A design goal of Velocity is to cache data wherever possible in order to avoid DOM requerying. Accordingly, each element has a data cache. */
630 init: function (element) {
631 $.data(element, "velocity", {
632 /* Store whether this is an SVG element, since its properties are retrieved and updated differently than standard HTML elements. */
633 isSVG: Type.isSVG(element),
634 /* Keep track of whether the element is currently being animated by Velocity.
635 This is used to ensure that property values are not transferred between non-consecutive (stale) calls. */
636 isAnimating: false,
637 /* A reference to the element's live computedStyle object. Learn more here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */
638 computedStyle: null,
639 /* Tween data is cached for each animation on the element so that data can be passed across calls --
640 in particular, end values are used as subsequent start values in consecutive Velocity calls. */
641 tweensContainer: null,
642 /* The full root property values of each CSS hook being animated on this element are cached so that:
643 1) Concurrently-animating hooks sharing the same root can have their root values' merged into one while tweening.
644 2) Post-hook-injection root values can be transferred over to consecutively chained Velocity calls as starting root values. */
645 rootPropertyValueCache: {},
646 /* A cache for transform updates, which must be manually flushed via CSS.flushTransformCache(). */
647 transformCache: {}
648 });
649 },
650 /* A parallel to jQuery's $.css(), used for getting/setting Velocity's hooked CSS properties. */
651 hook: null, /* Defined below. */
652 /* Velocity-wide animation time remapping for testing purposes. */
653 mock: false,
654 version: { major: 1, minor: 2, patch: 2 },
655 /* Set to 1 or 2 (most verbose) to output debug info to console. */
656 debug: false
657 };
658
659 /* Retrieve the appropriate scroll anchor and property name for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */
660 if (window.pageYOffset !== undefined) {
661 Velocity.State.scrollAnchor = window;
662 Velocity.State.scrollPropertyLeft = "pageXOffset";
663 Velocity.State.scrollPropertyTop = "pageYOffset";
664 } else {
665 Velocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body;
666 Velocity.State.scrollPropertyLeft = "scrollLeft";
667 Velocity.State.scrollPropertyTop = "scrollTop";
668 }
669
670 /* Shorthand alias for jQuery's $.data() utility. */
671 function Data (element) {
672 /* Hardcode a reference to the plugin name. */
673 var response = $.data(element, "velocity");
674
675 /* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */
676 return response === null ? undefined : response;
677 };
678
679 /**************
680 Easing
681 **************/
682
683 /* Step easing generator. */
684 function generateStep (steps) {
685 return function (p) {
686 return Math.round(p * steps) * (1 / steps);
687 };
688 }
689
690 /* Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
691 function generateBezier (mX1, mY1, mX2, mY2) {
692 var NEWTON_ITERATIONS = 4,
693 NEWTON_MIN_SLOPE = 0.001,
694 SUBDIVISION_PRECISION = 0.0000001,
695 SUBDIVISION_MAX_ITERATIONS = 10,
696 kSplineTableSize = 11,
697 kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
698 float32ArraySupported = "Float32Array" in window;
699
700 /* Must contain four arguments. */
701 if (arguments.length !== 4) {
702 return false;
703 }
704
705 /* Arguments must be numbers. */
706 for (var i = 0; i < 4; ++i) {
707 if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
708 return false;
709 }
710 }
711
712 /* X values must be in the [0, 1] range. */
713 mX1 = Math.min(mX1, 1);
714 mX2 = Math.min(mX2, 1);
715 mX1 = Math.max(mX1, 0);
716 mX2 = Math.max(mX2, 0);
717
718 var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
719
720 function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
721 function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
722 function C (aA1) { return 3.0 * aA1; }
723
724 function calcBezier (aT, aA1, aA2) {
725 return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT;
726 }
727
728 function getSlope (aT, aA1, aA2) {
729 return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
730 }
731
732 function newtonRaphsonIterate (aX, aGuessT) {
733 for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
734 var currentSlope = getSlope(aGuessT, mX1, mX2);
735
736 if (currentSlope === 0.0) return aGuessT;
737
738 var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
739 aGuessT -= currentX / currentSlope;
740 }
741
742 return aGuessT;
743 }
744
745 function calcSampleValues () {
746 for (var i = 0; i < kSplineTableSize; ++i) {
747 mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
748 }
749 }
750
751 function binarySubdivide (aX, aA, aB) {
752 var currentX, currentT, i = 0;
753
754 do {
755 currentT = aA + (aB - aA) / 2.0;
756 currentX = calcBezier(currentT, mX1, mX2) - aX;
757 if (currentX > 0.0) {
758 aB = currentT;
759 } else {
760 aA = currentT;
761 }
762 } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
763
764 return currentT;
765 }
766
767 function getTForX (aX) {
768 var intervalStart = 0.0,
769 currentSample = 1,
770 lastSample = kSplineTableSize - 1;
771
772 for (; currentSample != lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
773 intervalStart += kSampleStepSize;
774 }
775
776 --currentSample;
777
778 var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample+1] - mSampleValues[currentSample]),
779 guessForT = intervalStart + dist * kSampleStepSize,
780 initialSlope = getSlope(guessForT, mX1, mX2);
781
782 if (initialSlope >= NEWTON_MIN_SLOPE) {
783 return newtonRaphsonIterate(aX, guessForT);
784 } else if (initialSlope == 0.0) {
785 return guessForT;
786 } else {
787 return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
788 }
789 }
790
791 var _precomputed = false;
792
793 function precompute() {
794 _precomputed = true;
795 if (mX1 != mY1 || mX2 != mY2) calcSampleValues();
796 }
797
798 var f = function (aX) {
799 if (!_precomputed) precompute();
800 if (mX1 === mY1 && mX2 === mY2) return aX;
801 if (aX === 0) return 0;
802 if (aX === 1) return 1;
803
804 return calcBezier(getTForX(aX), mY1, mY2);
805 };
806
807 f.getControlPoints = function() { return [{ x: mX1, y: mY1 }, { x: mX2, y: mY2 }]; };
808
809 var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
810 f.toString = function () { return str; };
811
812 return f;
813 }
814
815 /* Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
816 /* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass
817 then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
818 var generateSpringRK4 = (function () {
819 function springAccelerationForState (state) {
820 return (-state.tension * state.x) - (state.friction * state.v);
821 }
822
823 function springEvaluateStateWithDerivative (initialState, dt, derivative) {
824 var state = {
825 x: initialState.x + derivative.dx * dt,
826 v: initialState.v + derivative.dv * dt,
827 tension: initialState.tension,
828 friction: initialState.friction
829 };
830
831 return { dx: state.v, dv: springAccelerationForState(state) };
832 }
833
834 function springIntegrateState (state, dt) {
835 var a = {
836 dx: state.v,
837 dv: springAccelerationForState(state)
838 },
839 b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
840 c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
841 d = springEvaluateStateWithDerivative(state, dt, c),
842 dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
843 dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
844
845 state.x = state.x + dxdt * dt;
846 state.v = state.v + dvdt * dt;
847
848 return state;
849 }
850
851 return function springRK4Factory (tension, friction, duration) {
852
853 var initState = {
854 x: -1,
855 v: 0,
856 tension: null,
857 friction: null
858 },
859 path = [0],
860 time_lapsed = 0,
861 tolerance = 1 / 10000,
862 DT = 16 / 1000,
863 have_duration, dt, last_state;
864
865 tension = parseFloat(tension) || 500;
866 friction = parseFloat(friction) || 20;
867 duration = duration || null;
868
869 initState.tension = tension;
870 initState.friction = friction;
871
872 have_duration = duration !== null;
873
874 /* Calculate the actual time it takes for this animation to complete with the provided conditions. */
875 if (have_duration) {
876 /* Run the simulation without a duration. */
877 time_lapsed = springRK4Factory(tension, friction);
878 /* Compute the adjusted time delta. */
879 dt = time_lapsed / duration * DT;
880 } else {
881 dt = DT;
882 }
883
884 while (true) {
885 /* Next/step function .*/
886 last_state = springIntegrateState(last_state || initState, dt);
887 /* Store the position. */
888 path.push(1 + last_state.x);
889 time_lapsed += 16;
890 /* If the change threshold is reached, break. */
891 if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
892 break;
893 }
894 }
895
896 /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
897 computed path and returns a snapshot of the position according to a given percentComplete. */
898 return !have_duration ? time_lapsed : function(percentComplete) { return path[ (percentComplete * (path.length - 1)) | 0 ]; };
899 };
900 }());
901
902 /* jQuery easings. */
903 Velocity.Easings = {
904 linear: function(p) { return p; },
905 swing: function(p) { return 0.5 - Math.cos( p * Math.PI ) / 2 },
906 /* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */
907 spring: function(p) { return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6)); }
908 };
909
910 /* CSS3 and Robert Penner easings. */
911 $.each(
912 [
913 [ "ease", [ 0.25, 0.1, 0.25, 1.0 ] ],
914 [ "ease-in", [ 0.42, 0.0, 1.00, 1.0 ] ],
915 [ "ease-out", [ 0.00, 0.0, 0.58, 1.0 ] ],
916 [ "ease-in-out", [ 0.42, 0.0, 0.58, 1.0 ] ],
917 [ "easeInSine", [ 0.47, 0, 0.745, 0.715 ] ],
918 [ "easeOutSine", [ 0.39, 0.575, 0.565, 1 ] ],
919 [ "easeInOutSine", [ 0.445, 0.05, 0.55, 0.95 ] ],
920 [ "easeInQuad", [ 0.55, 0.085, 0.68, 0.53 ] ],
921 [ "easeOutQuad", [ 0.25, 0.46, 0.45, 0.94 ] ],
922 [ "easeInOutQuad", [ 0.455, 0.03, 0.515, 0.955 ] ],
923 [ "easeInCubic", [ 0.55, 0.055, 0.675, 0.19 ] ],
924 [ "easeOutCubic", [ 0.215, 0.61, 0.355, 1 ] ],
925 [ "easeInOutCubic", [ 0.645, 0.045, 0.355, 1 ] ],
926 [ "easeInQuart", [ 0.895, 0.03, 0.685, 0.22 ] ],
927 [ "easeOutQuart", [ 0.165, 0.84, 0.44, 1 ] ],
928 [ "easeInOutQuart", [ 0.77, 0, 0.175, 1 ] ],
929 [ "easeInQuint", [ 0.755, 0.05, 0.855, 0.06 ] ],
930 [ "easeOutQuint", [ 0.23, 1, 0.32, 1 ] ],
931 [ "easeInOutQuint", [ 0.86, 0, 0.07, 1 ] ],
932 [ "easeInExpo", [ 0.95, 0.05, 0.795, 0.035 ] ],
933 [ "easeOutExpo", [ 0.19, 1, 0.22, 1 ] ],
934 [ "easeInOutExpo", [ 1, 0, 0, 1 ] ],
935 [ "easeInCirc", [ 0.6, 0.04, 0.98, 0.335 ] ],
936 [ "easeOutCirc", [ 0.075, 0.82, 0.165, 1 ] ],
937 [ "easeInOutCirc", [ 0.785, 0.135, 0.15, 0.86 ] ]
938 ], function(i, easingArray) {
939 Velocity.Easings[easingArray[0]] = generateBezier.apply(null, easingArray[1]);
940 });
941
942 /* Determine the appropriate easing type given an easing input. */
943 function getEasing(value, duration) {
944 var easing = value;
945
946 /* The easing option can either be a string that references a pre-registered easing,
947 or it can be a two-/four-item array of integers to be converted into a bezier/spring function. */
948 if (Type.isString(value)) {
949 /* Ensure that the easing has been assigned to jQuery's Velocity.Easings object. */
950 if (!Velocity.Easings[value]) {
951 easing = false;
952 }
953 } else if (Type.isArray(value) && value.length === 1) {
954 easing = generateStep.apply(null, value);
955 } else if (Type.isArray(value) && value.length === 2) {
956 /* springRK4 must be passed the animation's duration. */
957 /* Note: If the springRK4 array contains non-numbers, generateSpringRK4() returns an easing
958 function generated with default tension and friction values. */
959 easing = generateSpringRK4.apply(null, value.concat([ duration ]));
960 } else if (Type.isArray(value) && value.length === 4) {
961 /* Note: If the bezier array contains non-numbers, generateBezier() returns false. */
962 easing = generateBezier.apply(null, value);
963 } else {
964 easing = false;
965 }
966
967 /* Revert to the Velocity-wide default easing type, or fall back to "swing" (which is also jQuery's default)
968 if the Velocity-wide default has been incorrectly modified. */
969 if (easing === false) {
970 if (Velocity.Easings[Velocity.defaults.easing]) {
971 easing = Velocity.defaults.easing;
972 } else {
973 easing = EASING_DEFAULT;
974 }
975 }
976
977 return easing;
978 }
979
980 /*****************
981 CSS Stack
982 *****************/
983
984 /* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's.
985 It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */
986 /* Note: A "CSS" shorthand is aliased so that our code is easier to read. */
987 var CSS = Velocity.CSS = {
988
989 /*************
990 RegEx
991 *************/
992
993 RegEx: {
994 isHex: /^#([A-f\d]{3}){1,2}$/i,
995 /* 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". */
996 valueUnwrap: /^[A-z]+\((.*)\)$/i,
997 wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
998 /* 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" ]. */
999 valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig
1000 },
1001
1002 /************
1003 Lists
1004 ************/
1005
1006 Lists: {
1007 colors: [ "fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor" ],
1008 transformsBase: [ "translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ" ],
1009 transforms3D: [ "transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY" ]
1010 },
1011
1012 /************
1013 Hooks
1014 ************/
1015
1016 /* Hooks allow a subproperty (e.g. "boxShadowBlur") of a compound-value CSS property
1017 (e.g. "boxShadow: X Y Blur Spread Color") to be animated as if it were a discrete property. */
1018 /* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only
1019 tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */
1020 Hooks: {
1021 /********************
1022 Registration
1023 ********************/
1024
1025 /* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */
1026 /* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */
1027 templates: {
1028 "textShadow": [ "Color X Y Blur", "black 0px 0px 0px" ],
1029 "boxShadow": [ "Color X Y Blur Spread", "black 0px 0px 0px 0px" ],
1030 "clip": [ "Top Right Bottom Left", "0px 0px 0px 0px" ],
1031 "backgroundPosition": [ "X Y", "0% 0%" ],
1032 "transformOrigin": [ "X Y Z", "50% 50% 0px" ],
1033 "perspectiveOrigin": [ "X Y", "50% 50%" ]
1034 },
1035
1036 /* A "registered" hook is one that has been converted from its template form into a live,
1037 tweenable property. It contains data to associate it with its root property. */
1038 registered: {
1039 /* Note: A registered hook looks like this ==> textShadowBlur: [ "textShadow", 3 ],
1040 which consists of the subproperty's name, the associated root property's name,
1041 and the subproperty's position in the root's value. */
1042 },
1043 /* Convert the templates into individual hooks then append them to the registered object above. */
1044 register: function () {
1045 /* Color hooks registration: Colors are defaulted to white -- as opposed to black -- since colors that are
1046 currently set to "transparent" default to their respective template below when color-animated,
1047 and white is typically a closer match to transparent than black is. An exception is made for text ("color"),
1048 which is almost always set closer to black than white. */
1049 for (var i = 0; i < CSS.Lists.colors.length; i++) {
1050 var rgbComponents = (CSS.Lists.colors[i] === "color") ? "0 0 0 1" : "255 255 255 1";
1051 CSS.Hooks.templates[CSS.Lists.colors[i]] = [ "Red Green Blue Alpha", rgbComponents ];
1052 }
1053
1054 var rootProperty,
1055 hookTemplate,
1056 hookNames;
1057
1058 /* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning.
1059 Thus, we re-arrange the templates accordingly. */
1060 if (IE) {
1061 for (rootProperty in CSS.Hooks.templates) {
1062 hookTemplate = CSS.Hooks.templates[rootProperty];
1063 hookNames = hookTemplate[0].split(" ");
1064
1065 var defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit);
1066
1067 if (hookNames[0] === "Color") {
1068 /* Reposition both the hook's name and its default value to the end of their respective strings. */
1069 hookNames.push(hookNames.shift());
1070 defaultValues.push(defaultValues.shift());
1071
1072 /* Replace the existing template for the hook's root property. */
1073 CSS.Hooks.templates[rootProperty] = [ hookNames.join(" "), defaultValues.join(" ") ];
1074 }
1075 }
1076 }
1077
1078 /* Hook registration. */
1079 for (rootProperty in CSS.Hooks.templates) {
1080 hookTemplate = CSS.Hooks.templates[rootProperty];
1081 hookNames = hookTemplate[0].split(" ");
1082
1083 for (var i in hookNames) {
1084 var fullHookName = rootProperty + hookNames[i],
1085 hookPosition = i;
1086
1087 /* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow)
1088 and the hook's position in its template's default value string. */
1089 CSS.Hooks.registered[fullHookName] = [ rootProperty, hookPosition ];
1090 }
1091 }
1092 },
1093
1094 /*****************************
1095 Injection and Extraction
1096 *****************************/
1097
1098 /* Look up the root property associated with the hook (e.g. return "textShadow" for "textShadowBlur"). */
1099 /* 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. */
1100 getRoot: function (property) {
1101 var hookData = CSS.Hooks.registered[property];
1102
1103 if (hookData) {
1104 return hookData[0];
1105 } else {
1106 /* If there was no hook match, return the property name untouched. */
1107 return property;
1108 }
1109 },
1110 /* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that
1111 the targeted hook can be injected or extracted at its standard position. */
1112 cleanRootPropertyValue: function(rootProperty, rootPropertyValue) {
1113 /* If the rootPropertyValue is wrapped with "rgb()", "clip()", etc., remove the wrapping to normalize the value before manipulation. */
1114 if (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) {
1115 rootPropertyValue = rootPropertyValue.match(CSS.RegEx.valueUnwrap)[1];
1116 }
1117
1118 /* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract),
1119 default to the root's default value as defined in CSS.Hooks.templates. */
1120 /* Note: CSS null-values include "none", "auto", and "transparent". They must be converted into their
1121 zero-values (e.g. textShadow: "none" ==> textShadow: "0px 0px 0px black") for hook manipulation to proceed. */
1122 if (CSS.Values.isCSSNullValue(rootPropertyValue)) {
1123 rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
1124 }
1125
1126 return rootPropertyValue;
1127 },
1128 /* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */
1129 extractValue: function (fullHookName, rootPropertyValue) {
1130 var hookData = CSS.Hooks.registered[fullHookName];
1131
1132 if (hookData) {
1133 var hookRoot = hookData[0],
1134 hookPosition = hookData[1];
1135
1136 rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
1137
1138 /* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */
1139 return rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition];
1140 } else {
1141 /* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
1142 return rootPropertyValue;
1143 }
1144 },
1145 /* Inject the hook's value into its root property's value. This is used to piece back together the root property
1146 once Velocity has updated one of its individually hooked values through tweening. */
1147 injectValue: function (fullHookName, hookValue, rootPropertyValue) {
1148 var hookData = CSS.Hooks.registered[fullHookName];
1149
1150 if (hookData) {
1151 var hookRoot = hookData[0],
1152 hookPosition = hookData[1],
1153 rootPropertyValueParts,
1154 rootPropertyValueUpdated;
1155
1156 rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
1157
1158 /* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue,
1159 then reconstruct the rootPropertyValue string. */
1160 rootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit);
1161 rootPropertyValueParts[hookPosition] = hookValue;
1162 rootPropertyValueUpdated = rootPropertyValueParts.join(" ");
1163
1164 return rootPropertyValueUpdated;
1165 } else {
1166 /* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
1167 return rootPropertyValue;
1168 }
1169 }
1170 },
1171
1172 /*******************
1173 Normalizations
1174 *******************/
1175
1176 /* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity)
1177 and reformatting special properties (e.g. clip, rgba) to look like standard ones. */
1178 Normalizations: {
1179 /* Normalizations are passed a normalization target (either the property's name, its extracted value, or its injected value),
1180 the targeted element (which may need to be queried), and the targeted property value. */
1181 registered: {
1182 clip: function (type, element, propertyValue) {
1183 switch (type) {
1184 case "name":
1185 return "clip";
1186 /* Clip needs to be unwrapped and stripped of its commas during extraction. */
1187 case "extract":
1188 var extracted;
1189
1190 /* If Velocity also extracted this value, skip extraction. */
1191 if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
1192 extracted = propertyValue;
1193 } else {
1194 /* Remove the "rect()" wrapper. */
1195 extracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap);
1196
1197 /* Strip off commas. */
1198 extracted = extracted ? extracted[1].replace(/,(\s+)?/g, " ") : propertyValue;
1199 }
1200
1201 return extracted;
1202 /* Clip needs to be re-wrapped during injection. */
1203 case "inject":
1204 return "rect(" + propertyValue + ")";
1205 }
1206 },
1207
1208 blur: function(type, element, propertyValue) {
1209 switch (type) {
1210 case "name":
1211 return Velocity.State.isFirefox ? "filter" : "-webkit-filter";
1212 case "extract":
1213 var extracted = parseFloat(propertyValue);
1214
1215 /* If extracted is NaN, meaning the value isn't already extracted. */
1216 if (!(extracted || extracted === 0)) {
1217 var blurComponent = propertyValue.toString().match(/blur\(([0-9]+[A-z]+)\)/i);
1218
1219 /* If the filter string had a blur component, return just the blur value and unit type. */
1220 if (blurComponent) {
1221 extracted = blurComponent[1];
1222 /* If the component doesn't exist, default blur to 0. */
1223 } else {
1224 extracted = 0;
1225 }
1226 }
1227
1228 return extracted;
1229 /* Blur needs to be re-wrapped during injection. */
1230 case "inject":
1231 /* For the blur effect to be fully de-applied, it needs to be set to "none" instead of 0. */
1232 if (!parseFloat(propertyValue)) {
1233 return "none";
1234 } else {
1235 return "blur(" + propertyValue + ")";
1236 }
1237 }
1238 },
1239
1240 /* <=IE8 do not support the standard opacity property. They use filter:alpha(opacity=INT) instead. */
1241 opacity: function (type, element, propertyValue) {
1242 if (IE <= 8) {
1243 switch (type) {
1244 case "name":
1245 return "filter";
1246 case "extract":
1247 /* <=IE8 return a "filter" value of "alpha(opacity=\d{1,3})".
1248 Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */
1249 var extracted = propertyValue.toString().match(/alpha\(opacity=(.*)\)/i);
1250
1251 if (extracted) {
1252 /* Convert to decimal value. */
1253 propertyValue = extracted[1] / 100;
1254 } else {
1255 /* When extracting opacity, default to 1 since a null value means opacity hasn't been set. */
1256 propertyValue = 1;
1257 }
1258
1259 return propertyValue;
1260 case "inject":
1261 /* Opacified elements are required to have their zoom property set to a non-zero value. */
1262 element.style.zoom = 1;
1263
1264 /* Setting the filter property on elements with certain font property combinations can result in a
1265 highly unappealing ultra-bolding effect. There's no way to remedy this throughout a tween, but dropping the
1266 value altogether (when opacity hits 1) at leasts ensures that the glitch is gone post-tweening. */
1267 if (parseFloat(propertyValue) >= 1) {
1268 return "";
1269 } else {
1270 /* As per the filter property's spec, convert the decimal value to a whole number and wrap the value. */
1271 return "alpha(opacity=" + parseInt(parseFloat(propertyValue) * 100, 10) + ")";
1272 }
1273 }
1274 /* With all other browsers, normalization is not required; return the same values that were passed in. */
1275 } else {
1276 switch (type) {
1277 case "name":
1278 return "opacity";
1279 case "extract":
1280 return propertyValue;
1281 case "inject":
1282 return propertyValue;
1283 }
1284 }
1285 }
1286 },
1287
1288 /*****************************
1289 Batched Registrations
1290 *****************************/
1291
1292 /* Note: Batched normalizations extend the CSS.Normalizations.registered object. */
1293 register: function () {
1294
1295 /*****************
1296 Transforms
1297 *****************/
1298
1299 /* Transforms are the subproperties contained by the CSS "transform" property. Transforms must undergo normalization
1300 so that they can be referenced in a properties map by their individual names. */
1301 /* Note: When transforms are "set", they are actually assigned to a per-element transformCache. When all transform
1302 setting is complete complete, CSS.flushTransformCache() must be manually called to flush the values to the DOM.
1303 Transform setting is batched in this way to improve performance: the transform style only needs to be updated
1304 once when multiple transform subproperties are being animated simultaneously. */
1305 /* Note: IE9 and Android Gingerbread have support for 2D -- but not 3D -- transforms. Since animating unsupported
1306 transform properties results in the browser ignoring the *entire* transform string, we prevent these 3D values
1307 from being normalized for these browsers so that tweening skips these properties altogether
1308 (since it will ignore them as being unsupported by the browser.) */
1309 if (!(IE <= 9) && !Velocity.State.isGingerbread) {
1310 /* Note: Since the standalone CSS "perspective" property and the CSS transform "perspective" subproperty
1311 share the same name, the latter is given a unique token within Velocity: "transformPerspective". */
1312 CSS.Lists.transformsBase = CSS.Lists.transformsBase.concat(CSS.Lists.transforms3D);
1313 }
1314
1315 for (var i = 0; i < CSS.Lists.transformsBase.length; i++) {
1316 /* Wrap the dynamically generated normalization function in a new scope so that transformName's value is
1317 paired with its respective function. (Otherwise, all functions would take the final for loop's transformName.) */
1318 (function() {
1319 var transformName = CSS.Lists.transformsBase[i];
1320
1321 CSS.Normalizations.registered[transformName] = function (type, element, propertyValue) {
1322 switch (type) {
1323 /* The normalized property name is the parent "transform" property -- the property that is actually set in CSS. */
1324 case "name":
1325 return "transform";
1326 /* Transform values are cached onto a per-element transformCache object. */
1327 case "extract":
1328 /* If this transform has yet to be assigned a value, return its null value. */
1329 if (Data(element) === undefined || Data(element).transformCache[transformName] === undefined) {
1330 /* Scale CSS.Lists.transformsBase default to 1 whereas all other transform properties default to 0. */
1331 return /^scale/i.test(transformName) ? 1 : 0;
1332 /* When transform values are set, they are wrapped in parentheses as per the CSS spec.
1333 Thus, when extracting their values (for tween calculations), we strip off the parentheses. */
1334 } else {
1335 return Data(element).transformCache[transformName].replace(/[()]/g, "");
1336 }
1337 case "inject":
1338 var invalid = false;
1339
1340 /* If an individual transform property contains an unsupported unit type, the browser ignores the *entire* transform property.
1341 Thus, protect users from themselves by skipping setting for transform values supplied with invalid unit types. */
1342 /* Switch on the base transform type; ignore the axis by removing the last letter from the transform's name. */
1343 switch (transformName.substr(0, transformName.length - 1)) {
1344 /* Whitelist unit types for each transform. */
1345 case "translate":
1346 invalid = !/(%|px|em|rem|vw|vh|\d)$/i.test(propertyValue);
1347 break;
1348 /* Since an axis-free "scale" property is supported as well, a little hack is used here to detect it by chopping off its last letter. */
1349 case "scal":
1350 case "scale":
1351 /* Chrome on Android has a bug in which scaled elements blur if their initial scale
1352 value is below 1 (which can happen with forcefeeding). Thus, we detect a yet-unset scale property
1353 and ensure that its first value is always 1. More info: http://stackoverflow.com/questions/10417890/css3-animations-with-transform-causes-blurred-elements-on-webkit/10417962#10417962 */
1354 if (Velocity.State.isAndroid && Data(element).transformCache[transformName] === undefined && propertyValue < 1) {
1355 propertyValue = 1;
1356 }
1357
1358 invalid = !/(\d)$/i.test(propertyValue);
1359 break;
1360 case "skew":
1361 invalid = !/(deg|\d)$/i.test(propertyValue);
1362 break;
1363 case "rotate":
1364 invalid = !/(deg|\d)$/i.test(propertyValue);
1365 break;
1366 }
1367
1368 if (!invalid) {
1369 /* As per the CSS spec, wrap the value in parentheses. */
1370 Data(element).transformCache[transformName] = "(" + propertyValue + ")";
1371 }
1372
1373 /* Although the value is set on the transformCache object, return the newly-updated value for the calling code to process as normal. */
1374 return Data(element).transformCache[transformName];
1375 }
1376 };
1377 })();
1378 }
1379
1380 /*************
1381 Colors
1382 *************/
1383
1384 /* Since Velocity only animates a single numeric value per property, color animation is achieved by hooking the individual RGBA components of CSS color properties.
1385 Accordingly, color values must be normalized (e.g. "#ff0000", "red", and "rgb(255, 0, 0)" ==> "255 0 0 1") so that their components can be injected/extracted by CSS.Hooks logic. */
1386 for (var i = 0; i < CSS.Lists.colors.length; i++) {
1387 /* Wrap the dynamically generated normalization function in a new scope so that colorName's value is paired with its respective function.
1388 (Otherwise, all functions would take the final for loop's colorName.) */
1389 (function () {
1390 var colorName = CSS.Lists.colors[i];
1391
1392 /* Note: In IE<=8, which support rgb but not rgba, color properties are reverted to rgb by stripping off the alpha component. */
1393 CSS.Normalizations.registered[colorName] = function(type, element, propertyValue) {
1394 switch (type) {
1395 case "name":
1396 return colorName;
1397 /* Convert all color values into the rgb format. (Old IE can return hex values and color names instead of rgb/rgba.) */
1398 case "extract":
1399 var extracted;
1400
1401 /* If the color is already in its hookable form (e.g. "255 255 255 1") due to having been previously extracted, skip extraction. */
1402 if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
1403 extracted = propertyValue;
1404 } else {
1405 var converted,
1406 colorNames = {
1407 black: "rgb(0, 0, 0)",
1408 blue: "rgb(0, 0, 255)",
1409 gray: "rgb(128, 128, 128)",
1410 green: "rgb(0, 128, 0)",
1411 red: "rgb(255, 0, 0)",
1412 white: "rgb(255, 255, 255)"
1413 };
1414
1415 /* Convert color names to rgb. */
1416 if (/^[A-z]+$/i.test(propertyValue)) {
1417 if (colorNames[propertyValue] !== undefined) {
1418 converted = colorNames[propertyValue]
1419 } else {
1420 /* If an unmatched color name is provided, default to black. */
1421 converted = colorNames.black;
1422 }
1423 /* Convert hex values to rgb. */
1424 } else if (CSS.RegEx.isHex.test(propertyValue)) {
1425 converted = "rgb(" + CSS.Values.hexToRgb(propertyValue).join(" ") + ")";
1426 /* If the provided color doesn't match any of the accepted color formats, default to black. */
1427 } else if (!(/^rgba?\(/i.test(propertyValue))) {
1428 converted = colorNames.black;
1429 }
1430
1431 /* Remove the surrounding "rgb/rgba()" string then replace commas with spaces and strip
1432 repeated spaces (in case the value included spaces to begin with). */
1433 extracted = (converted || propertyValue).toString().match(CSS.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ");
1434 }
1435
1436 /* So long as this isn't <=IE8, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
1437 if (!(IE <= 8) && extracted.split(" ").length === 3) {
1438 extracted += " 1";
1439 }
1440
1441 return extracted;
1442 case "inject":
1443 /* If this is IE<=8 and an alpha component exists, strip it off. */
1444 if (IE <= 8) {
1445 if (propertyValue.split(" ").length === 4) {
1446 propertyValue = propertyValue.split(/\s+/).slice(0, 3).join(" ");
1447 }
1448 /* Otherwise, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
1449 } else if (propertyValue.split(" ").length === 3) {
1450 propertyValue += " 1";
1451 }
1452
1453 /* Re-insert the browser-appropriate wrapper("rgb/rgba()"), insert commas, and strip off decimal units
1454 on all values but the fourth (R, G, and B only accept whole numbers). */
1455 return (IE <= 8 ? "rgb" : "rgba") + "(" + propertyValue.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")";
1456 }
1457 };
1458 })();
1459 }
1460 }
1461 },
1462
1463 /************************
1464 CSS Property Names
1465 ************************/
1466
1467 Names: {
1468 /* Camelcase a property name into its JavaScript notation (e.g. "background-color" ==> "backgroundColor").
1469 Camelcasing is used to normalize property names between and across calls. */
1470 camelCase: function (property) {
1471 return property.replace(/-(\w)/g, function (match, subMatch) {
1472 return subMatch.toUpperCase();
1473 });
1474 },
1475
1476 /* For SVG elements, some properties (namely, dimensional ones) are GET/SET via the element's HTML attributes (instead of via CSS styles). */
1477 SVGAttribute: function (property) {
1478 var SVGAttributes = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";
1479
1480 /* Certain browsers require an SVG transform to be applied as an attribute. (Otherwise, application via CSS is preferable due to 3D support.) */
1481 if (IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) {
1482 SVGAttributes += "|transform";
1483 }
1484
1485 return new RegExp("^(" + SVGAttributes + ")$", "i").test(property);
1486 },
1487
1488 /* Determine whether a property should be set with a vendor prefix. */
1489 /* If a prefixed version of the property exists, return it. Otherwise, return the original property name.
1490 If the property is not at all supported by the browser, return a false flag. */
1491 prefixCheck: function (property) {
1492 /* If this property has already been checked, return the cached value. */
1493 if (Velocity.State.prefixMatches[property]) {
1494 return [ Velocity.State.prefixMatches[property], true ];
1495 } else {
1496 var vendors = [ "", "Webkit", "Moz", "ms", "O" ];
1497
1498 for (var i = 0, vendorsLength = vendors.length; i < vendorsLength; i++) {
1499 var propertyPrefixed;
1500
1501 if (i === 0) {
1502 propertyPrefixed = property;
1503 } else {
1504 /* Capitalize the first letter of the property to conform to JavaScript vendor prefix notation (e.g. webkitFilter). */
1505 propertyPrefixed = vendors[i] + property.replace(/^\w/, function(match) { return match.toUpperCase(); });
1506 }
1507
1508 /* Check if the browser supports this property as prefixed. */
1509 if (Type.isString(Velocity.State.prefixElement.style[propertyPrefixed])) {
1510 /* Cache the match. */
1511 Velocity.State.prefixMatches[property] = propertyPrefixed;
1512
1513 return [ propertyPrefixed, true ];
1514 }
1515 }
1516
1517 /* If the browser doesn't support this property in any form, include a false flag so that the caller can decide how to proceed. */
1518 return [ property, false ];
1519 }
1520 }
1521 },
1522
1523 /************************
1524 CSS Property Values
1525 ************************/
1526
1527 Values: {
1528 /* Hex to RGB conversion. Copyright Tim Down: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */
1529 hexToRgb: function (hex) {
1530 var shortformRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
1531 longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,
1532 rgbParts;
1533
1534 hex = hex.replace(shortformRegex, function (m, r, g, b) {
1535 return r + r + g + g + b + b;
1536 });
1537
1538 rgbParts = longformRegex.exec(hex);
1539
1540 return rgbParts ? [ parseInt(rgbParts[1], 16), parseInt(rgbParts[2], 16), parseInt(rgbParts[3], 16) ] : [ 0, 0, 0 ];
1541 },
1542
1543 isCSSNullValue: function (value) {
1544 /* The browser defaults CSS values that have not been set to either 0 or one of several possible null-value strings.
1545 Thus, we check for both falsiness and these special strings. */
1546 /* Null-value checking is performed to default the special strings to 0 (for the sake of tweening) or their hook
1547 templates as defined as CSS.Hooks (for the sake of hook injection/extraction). */
1548 /* Note: Chrome returns "rgba(0, 0, 0, 0)" for an undefined color whereas IE returns "transparent". */
1549 return (value == 0 || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(value));
1550 },
1551
1552 /* Retrieve a property's default unit type. Used for assigning a unit type when one is not supplied by the user. */
1553 getUnitType: function (property) {
1554 if (/^(rotate|skew)/i.test(property)) {
1555 return "deg";
1556 } else if (/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(property)) {
1557 /* The above properties are unitless. */
1558 return "";
1559 } else {
1560 /* Default to px for all other properties. */
1561 return "px";
1562 }
1563 },
1564
1565 /* HTML elements default to an associated display type when they're not set to display:none. */
1566 /* Note: This function is used for correctly setting the non-"none" display value in certain Velocity redirects, such as fadeIn/Out. */
1567 getDisplayType: function (element) {
1568 var tagName = element && element.tagName.toString().toLowerCase();
1569
1570 if (/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(tagName)) {
1571 return "inline";
1572 } else if (/^(li)$/i.test(tagName)) {
1573 return "list-item";
1574 } else if (/^(tr)$/i.test(tagName)) {
1575 return "table-row";
1576 } else if (/^(table)$/i.test(tagName)) {
1577 return "table";
1578 } else if (/^(tbody)$/i.test(tagName)) {
1579 return "table-row-group";
1580 /* Default to "block" when no match is found. */
1581 } else {
1582 return "block";
1583 }
1584 },
1585
1586 /* The class add/remove functions are used to temporarily apply a "velocity-animating" class to elements while they're animating. */
1587 addClass: function (element, className) {
1588 if (element.classList) {
1589 element.classList.add(className);
1590 } else {
1591 element.className += (element.className.length ? " " : "") + className;
1592 }
1593 },
1594
1595 removeClass: function (element, className) {
1596 if (element.classList) {
1597 element.classList.remove(className);
1598 } else {
1599 element.className = element.className.toString().replace(new RegExp("(^|\\s)" + className.split(" ").join("|") + "(\\s|$)", "gi"), " ");
1600 }
1601 }
1602 },
1603
1604 /****************************
1605 Style Getting & Setting
1606 ****************************/
1607
1608 /* The singular getPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */
1609 getPropertyValue: function (element, property, rootPropertyValue, forceStyleLookup) {
1610 /* Get an element's computed property value. */
1611 /* Note: Retrieving the value of a CSS property cannot simply be performed by checking an element's
1612 style attribute (which only reflects user-defined values). Instead, the browser must be queried for a property's
1613 *computed* value. You can read more about getComputedStyle here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */
1614 function computePropertyValue (element, property) {
1615 /* When box-sizing isn't set to border-box, height and width style values are incorrectly computed when an
1616 element's scrollbars are visible (which expands the element's dimensions). Thus, we defer to the more accurate
1617 offsetHeight/Width property, which includes the total dimensions for interior, border, padding, and scrollbar.
1618 We subtract border and padding to get the sum of interior + scrollbar. */
1619 var computedValue = 0;
1620
1621 /* IE<=8 doesn't support window.getComputedStyle, thus we defer to jQuery, which has an extensive array
1622 of hacks to accurately retrieve IE8 property values. Re-implementing that logic here is not worth bloating the
1623 codebase for a dying browser. The performance repercussions of using jQuery here are minimal since
1624 Velocity is optimized to rarely (and sometimes never) query the DOM. Further, the $.css() codepath isn't that slow. */
1625 if (IE <= 8) {
1626 computedValue = $.css(element, property); /* GET */
1627 /* All other browsers support getComputedStyle. The returned live object reference is cached onto its
1628 associated element so that it does not need to be refetched upon every GET. */
1629 } else {
1630 /* Browsers do not return height and width values for elements that are set to display:"none". Thus, we temporarily
1631 toggle display to the element type's default value. */
1632 var toggleDisplay = false;
1633
1634 if (/^(width|height)$/.test(property) && CSS.getPropertyValue(element, "display") === 0) {
1635 toggleDisplay = true;
1636 CSS.setPropertyValue(element, "display", CSS.Values.getDisplayType(element));
1637 }
1638
1639 function revertDisplay () {
1640 if (toggleDisplay) {
1641 CSS.setPropertyValue(element, "display", "none");
1642 }
1643 }
1644
1645 if (!forceStyleLookup) {
1646 if (property === "height" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") {
1647 var contentBoxHeight = element.offsetHeight - (parseFloat(CSS.getPropertyValue(element, "borderTopWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderBottomWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingTop")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingBottom")) || 0);
1648 revertDisplay();
1649
1650 return contentBoxHeight;
1651 } else if (property === "width" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") {
1652 var contentBoxWidth = element.offsetWidth - (parseFloat(CSS.getPropertyValue(element, "borderLeftWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderRightWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingLeft")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingRight")) || 0);
1653 revertDisplay();
1654
1655 return contentBoxWidth;
1656 }
1657 }
1658
1659 var computedStyle;
1660
1661 /* For elements that Velocity hasn't been called on directly (e.g. when Velocity queries the DOM on behalf
1662 of a parent of an element its animating), perform a direct getComputedStyle lookup since the object isn't cached. */
1663 if (Data(element) === undefined) {
1664 computedStyle = window.getComputedStyle(element, null); /* GET */
1665 /* If the computedStyle object has yet to be cached, do so now. */
1666 } else if (!Data(element).computedStyle) {
1667 computedStyle = Data(element).computedStyle = window.getComputedStyle(element, null); /* GET */
1668 /* If computedStyle is cached, use it. */
1669 } else {
1670 computedStyle = Data(element).computedStyle;
1671 }
1672
1673 /* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color.
1674 Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse.
1675 So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */
1676 if (property === "borderColor") {
1677 property = "borderTopColor";
1678 }
1679
1680 /* IE9 has a bug in which the "filter" property must be accessed from computedStyle using the getPropertyValue method
1681 instead of a direct property lookup. The getPropertyValue method is slower than a direct lookup, which is why we avoid it by default. */
1682 if (IE === 9 && property === "filter") {
1683 computedValue = computedStyle.getPropertyValue(property); /* GET */
1684 } else {
1685 computedValue = computedStyle[property];
1686 }
1687
1688 /* Fall back to the property's style value (if defined) when computedValue returns nothing,
1689 which can happen when the element hasn't been painted. */
1690 if (computedValue === "" || computedValue === null) {
1691 computedValue = element.style[property];
1692 }
1693
1694 revertDisplay();
1695 }
1696
1697 /* For top, right, bottom, and left (TRBL) values that are set to "auto" on elements of "fixed" or "absolute" position,
1698 defer to jQuery for converting "auto" to a numeric value. (For elements with a "static" or "relative" position, "auto" has the same
1699 effect as being set to 0, so no conversion is necessary.) */
1700 /* An example of why numeric conversion is necessary: When an element with "position:absolute" has an untouched "left"
1701 property, which reverts to "auto", left's value is 0 relative to its parent element, but is often non-zero relative
1702 to its *containing* (not parent) element, which is the nearest "position:relative" ancestor or the viewport (and always the viewport in the case of "position:fixed"). */
1703 if (computedValue === "auto" && /^(top|right|bottom|left)$/i.test(property)) {
1704 var position = computePropertyValue(element, "position"); /* GET */
1705
1706 /* For absolute positioning, jQuery's $.position() only returns values for top and left;
1707 right and bottom will have their "auto" value reverted to 0. */
1708 /* Note: A jQuery object must be created here since jQuery doesn't have a low-level alias for $.position().
1709 Not a big deal since we're currently in a GET batch anyway. */
1710 if (position === "fixed" || (position === "absolute" && /top|left/i.test(property))) {
1711 /* Note: jQuery strips the pixel unit from its returned values; we re-add it here to conform with computePropertyValue's behavior. */
1712 computedValue = $(element).position()[property] + "px"; /* GET */
1713 }
1714 }
1715
1716 return computedValue;
1717 }
1718
1719 var propertyValue;
1720
1721 /* If this is a hooked property (e.g. "clipLeft" instead of the root property of "clip"),
1722 extract the hook's value from a normalized rootPropertyValue using CSS.Hooks.extractValue(). */
1723 if (CSS.Hooks.registered[property]) {
1724 var hook = property,
1725 hookRoot = CSS.Hooks.getRoot(hook);
1726
1727 /* If a cached rootPropertyValue wasn't passed in (which Velocity always attempts to do in order to avoid requerying the DOM),
1728 query the DOM for the root property's value. */
1729 if (rootPropertyValue === undefined) {
1730 /* Since the browser is now being directly queried, use the official post-prefixing property name for this lookup. */
1731 rootPropertyValue = CSS.getPropertyValue(element, CSS.Names.prefixCheck(hookRoot)[0]); /* GET */
1732 }
1733
1734 /* If this root has a normalization registered, peform the associated normalization extraction. */
1735 if (CSS.Normalizations.registered[hookRoot]) {
1736 rootPropertyValue = CSS.Normalizations.registered[hookRoot]("extract", element, rootPropertyValue);
1737 }
1738
1739 /* Extract the hook's value. */
1740 propertyValue = CSS.Hooks.extractValue(hook, rootPropertyValue);
1741
1742 /* If this is a normalized property (e.g. "opacity" becomes "filter" in <=IE8) or "translateX" becomes "transform"),
1743 normalize the property's name and value, and handle the special case of transforms. */
1744 /* Note: Normalizing a property is mutually exclusive from hooking a property since hook-extracted values are strictly
1745 numerical and therefore do not require normalization extraction. */
1746 } else if (CSS.Normalizations.registered[property]) {
1747 var normalizedPropertyName,
1748 normalizedPropertyValue;
1749
1750 normalizedPropertyName = CSS.Normalizations.registered[property]("name", element);
1751
1752 /* Transform values are calculated via normalization extraction (see below), which checks against the element's transformCache.
1753 At no point do transform GETs ever actually query the DOM; initial stylesheet values are never processed.
1754 This is because parsing 3D transform matrices is not always accurate and would bloat our codebase;
1755 thus, normalization extraction defaults initial transform values to their zero-values (e.g. 1 for scaleX and 0 for translateX). */
1756 if (normalizedPropertyName !== "transform") {
1757 normalizedPropertyValue = computePropertyValue(element, CSS.Names.prefixCheck(normalizedPropertyName)[0]); /* GET */
1758
1759 /* If the value is a CSS null-value and this property has a hook template, use that zero-value template so that hooks can be extracted from it. */
1760 if (CSS.Values.isCSSNullValue(normalizedPropertyValue) && CSS.Hooks.templates[property]) {
1761 normalizedPropertyValue = CSS.Hooks.templates[property][1];
1762 }
1763 }
1764
1765 propertyValue = CSS.Normalizations.registered[property]("extract", element, normalizedPropertyValue);
1766 }
1767
1768 /* If a (numeric) value wasn't produced via hook extraction or normalization, query the DOM. */
1769 if (!/^[\d-]/.test(propertyValue)) {
1770 /* For SVG elements, dimensional properties (which SVGAttribute() detects) are tweened via
1771 their HTML attribute values instead of their CSS style values. */
1772 if (Data(element) && Data(element).isSVG && CSS.Names.SVGAttribute(property)) {
1773 /* Since the height/width attribute values must be set manually, they don't reflect computed values.
1774 Thus, we use use getBBox() to ensure we always get values for elements with undefined height/width attributes. */
1775 if (/^(height|width)$/i.test(property)) {
1776 /* Firefox throws an error if .getBBox() is called on an SVG that isn't attached to the DOM. */
1777 try {
1778 propertyValue = element.getBBox()[property];
1779 } catch (error) {
1780 propertyValue = 0;
1781 }
1782 /* Otherwise, access the attribute value directly. */
1783 } else {
1784 propertyValue = element.getAttribute(property);
1785 }
1786 } else {
1787 propertyValue = computePropertyValue(element, CSS.Names.prefixCheck(property)[0]); /* GET */
1788 }
1789 }
1790
1791 /* Since property lookups are for animation purposes (which entails computing the numeric delta between start and end values),
1792 convert CSS null-values to an integer of value 0. */
1793 if (CSS.Values.isCSSNullValue(propertyValue)) {
1794 propertyValue = 0;
1795 }
1796
1797 if (Velocity.debug >= 2) console.log("Get " + property + ": " + propertyValue);
1798
1799 return propertyValue;
1800 },
1801
1802 /* The singular setPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */
1803 setPropertyValue: function(element, property, propertyValue, rootPropertyValue, scrollData) {
1804 var propertyName = property;
1805
1806 /* In order to be subjected to call options and element queueing, scroll animation is routed through Velocity as if it were a standard CSS property. */
1807 if (property === "scroll") {
1808 /* If a container option is present, scroll the container instead of the browser window. */
1809 if (scrollData.container) {
1810 scrollData.container["scroll" + scrollData.direction] = propertyValue;
1811 /* Otherwise, Velocity defaults to scrolling the browser window. */
1812 } else {
1813 if (scrollData.direction === "Left") {
1814 window.scrollTo(propertyValue, scrollData.alternateValue);
1815 } else {
1816 window.scrollTo(scrollData.alternateValue, propertyValue);
1817 }
1818 }
1819 } else {
1820 /* Transforms (translateX, rotateZ, etc.) are applied to a per-element transformCache object, which is manually flushed via flushTransformCache().
1821 Thus, for now, we merely cache transforms being SET. */
1822 if (CSS.Normalizations.registered[property] && CSS.Normalizations.registered[property]("name", element) === "transform") {
1823 /* Perform a normalization injection. */
1824 /* Note: The normalization logic handles the transformCache updating. */
1825 CSS.Normalizations.registered[property]("inject", element, propertyValue);
1826
1827 propertyName = "transform";
1828 propertyValue = Data(element).transformCache[property];
1829 } else {
1830 /* Inject hooks. */
1831 if (CSS.Hooks.registered[property]) {
1832 var hookName = property,
1833 hookRoot = CSS.Hooks.getRoot(property);
1834
1835 /* If a cached rootPropertyValue was not provided, query the DOM for the hookRoot's current value. */
1836 rootPropertyValue = rootPropertyValue || CSS.getPropertyValue(element, hookRoot); /* GET */
1837
1838 propertyValue = CSS.Hooks.injectValue(hookName, propertyValue, rootPropertyValue);
1839 property = hookRoot;
1840 }
1841
1842 /* Normalize names and values. */
1843 if (CSS.Normalizations.registered[property]) {
1844 propertyValue = CSS.Normalizations.registered[property]("inject", element, propertyValue);
1845 property = CSS.Normalizations.registered[property]("name", element);
1846 }
1847
1848 /* Assign the appropriate vendor prefix before performing an official style update. */
1849 propertyName = CSS.Names.prefixCheck(property)[0];
1850
1851 /* A try/catch is used for IE<=8, which throws an error when "invalid" CSS values are set, e.g. a negative width.
1852 Try/catch is avoided for other browsers since it incurs a performance overhead. */
1853 if (IE <= 8) {
1854 try {
1855 element.style[propertyName] = propertyValue;
1856 } catch (error) { if (Velocity.debug) console.log("Browser does not support [" + propertyValue + "] for [" + propertyName + "]"); }
1857 /* SVG elements have their dimensional properties (width, height, x, y, cx, etc.) applied directly as attributes instead of as styles. */
1858 /* Note: IE8 does not support SVG elements, so it's okay that we skip it for SVG animation. */
1859 } else if (Data(element) && Data(element).isSVG && CSS.Names.SVGAttribute(property)) {
1860 /* Note: For SVG attributes, vendor-prefixed property names are never used. */
1861 /* Note: Not all CSS properties can be animated via attributes, but the browser won't throw an error for unsupported properties. */
1862 element.setAttribute(property, propertyValue);
1863 } else {
1864 element.style[propertyName] = propertyValue;
1865 }
1866
1867 if (Velocity.debug >= 2) console.log("Set " + property + " (" + propertyName + "): " + propertyValue);
1868 }
1869 }
1870
1871 /* Return the normalized property name and value in case the caller wants to know how these values were modified before being applied to the DOM. */
1872 return [ propertyName, propertyValue ];
1873 },
1874
1875 /* To increase performance by batching transform updates into a single SET, transforms are not directly applied to an element until flushTransformCache() is called. */
1876 /* Note: Velocity applies transform properties in the same order that they are chronogically introduced to the element's CSS styles. */
1877 flushTransformCache: function(element) {
1878 var transformString = "";
1879
1880 /* Certain browsers require that SVG transforms be applied as an attribute. However, the SVG transform attribute takes a modified version of CSS's transform string
1881 (units are dropped and, except for skewX/Y, subproperties are merged into their master property -- e.g. scaleX and scaleY are merged into scale(X Y). */
1882 if ((IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) && Data(element).isSVG) {
1883 /* Since transform values are stored in their parentheses-wrapped form, we use a helper function to strip out their numeric values.
1884 Further, SVG transform properties only take unitless (representing pixels) values, so it's okay that parseFloat() strips the unit suffixed to the float value. */
1885 function getTransformFloat (transformProperty) {
1886 return parseFloat(CSS.getPropertyValue(element, transformProperty));
1887 }
1888
1889 /* Create an object to organize all the transforms that we'll apply to the SVG element. To keep the logic simple,
1890 we process *all* transform properties -- even those that may not be explicitly applied (since they default to their zero-values anyway). */
1891 var SVGTransforms = {
1892 translate: [ getTransformFloat("translateX"), getTransformFloat("translateY") ],
1893 skewX: [ getTransformFloat("skewX") ], skewY: [ getTransformFloat("skewY") ],
1894 /* If the scale property is set (non-1), use that value for the scaleX and scaleY values
1895 (this behavior mimics the result of animating all these properties at once on HTML elements). */
1896 scale: getTransformFloat("scale") !== 1 ? [ getTransformFloat("scale"), getTransformFloat("scale") ] : [ getTransformFloat("scaleX"), getTransformFloat("scaleY") ],
1897 /* Note: SVG's rotate transform takes three values: rotation degrees followed by the X and Y values
1898 defining the rotation's origin point. We ignore the origin values (default them to 0). */
1899 rotate: [ getTransformFloat("rotateZ"), 0, 0 ]
1900 };
1901
1902 /* Iterate through the transform properties in the user-defined property map order.
1903 (This mimics the behavior of non-SVG transform animation.) */
1904 $.each(Data(element).transformCache, function(transformName) {
1905 /* Except for with skewX/Y, revert the axis-specific transform subproperties to their axis-free master
1906 properties so that they match up with SVG's accepted transform properties. */
1907 if (/^translate/i.test(transformName)) {
1908 transformName = "translate";
1909 } else if (/^scale/i.test(transformName)) {
1910 transformName = "scale";
1911 } else if (/^rotate/i.test(transformName)) {
1912 transformName = "rotate";
1913 }
1914
1915 /* Check that we haven't yet deleted the property from the SVGTransforms container. */
1916 if (SVGTransforms[transformName]) {
1917 /* Append the transform property in the SVG-supported transform format. As per the spec, surround the space-delimited values in parentheses. */
1918 transformString += transformName + "(" + SVGTransforms[transformName].join(" ") + ")" + " ";
1919
1920 /* After processing an SVG transform property, delete it from the SVGTransforms container so we don't
1921 re-insert the same master property if we encounter another one of its axis-specific properties. */
1922 delete SVGTransforms[transformName];
1923 }
1924 });
1925 } else {
1926 var transformValue,
1927 perspective;
1928
1929 /* Transform properties are stored as members of the transformCache object. Concatenate all the members into a string. */
1930 $.each(Data(element).transformCache, function(transformName) {
1931 transformValue = Data(element).transformCache[transformName];
1932
1933 /* Transform's perspective subproperty must be set first in order to take effect. Store it temporarily. */
1934 if (transformName === "transformPerspective") {
1935 perspective = transformValue;
1936 return true;
1937 }
1938
1939 /* IE9 only supports one rotation type, rotateZ, which it refers to as "rotate". */
1940 if (IE === 9 && transformName === "rotateZ") {
1941 transformName = "rotate";
1942 }
1943
1944 transformString += transformName + transformValue + " ";
1945 });
1946
1947 /* If present, set the perspective subproperty first. */
1948 if (perspective) {
1949 transformString = "perspective" + perspective + " " + transformString;
1950 }
1951 }
1952
1953 CSS.setPropertyValue(element, "transform", transformString);
1954 }
1955 };
1956
1957 /* Register hooks and normalizations. */
1958 CSS.Hooks.register();
1959 CSS.Normalizations.register();
1960
1961 /* Allow hook setting in the same fashion as jQuery's $.css(). */
1962 Velocity.hook = function (elements, arg2, arg3) {
1963 var value = undefined;
1964
1965 elements = sanitizeElements(elements);
1966
1967 $.each(elements, function(i, element) {
1968 /* Initialize Velocity's per-element data cache if this element hasn't previously been animated. */
1969 if (Data(element) === undefined) {
1970 Velocity.init(element);
1971 }
1972
1973 /* Get property value. If an element set was passed in, only return the value for the first element. */
1974 if (arg3 === undefined) {
1975 if (value === undefined) {
1976 value = Velocity.CSS.getPropertyValue(element, arg2);
1977 }
1978 /* Set property value. */
1979 } else {
1980 /* sPV returns an array of the normalized propertyName/propertyValue pair used to update the DOM. */
1981 var adjustedSet = Velocity.CSS.setPropertyValue(element, arg2, arg3);
1982
1983 /* Transform properties don't automatically set. They have to be flushed to the DOM. */
1984 if (adjustedSet[0] === "transform") {
1985 Velocity.CSS.flushTransformCache(element);
1986 }
1987
1988 value = adjustedSet;
1989 }
1990 });
1991
1992 return value;
1993 };
1994
1995 /*****************
1996 Animation
1997 *****************/
1998
1999 var animate = function() {
2000
2001 /******************
2002 Call Chain
2003 ******************/
2004
2005 /* Logic for determining what to return to the call stack when exiting out of Velocity. */
2006 function getChain () {
2007 /* If we are using the utility function, attempt to return this call's promise. If no promise library was detected,
2008 default to null instead of returning the targeted elements so that utility function's return value is standardized. */
2009 if (isUtility) {
2010 return promiseData.promise || null;
2011 /* Otherwise, if we're using $.fn, return the jQuery-/Zepto-wrapped element set. */
2012 } else {
2013 return elementsWrapped;
2014 }
2015 }
2016
2017 /*************************
2018 Arguments Assignment
2019 *************************/
2020
2021 /* To allow for expressive CoffeeScript code, Velocity supports an alternative syntax in which "elements" (or "e"), "properties" (or "p"), and "options" (or "o")
2022 objects are defined on a container object that's passed in as Velocity's sole argument. */
2023 /* Note: Some browsers automatically populate arguments with a "properties" object. We detect it by checking for its default "names" property. */
2024 var syntacticSugar = (arguments[0] && (arguments[0].p || (($.isPlainObject(arguments[0].properties) && !arguments[0].properties.names) || Type.isString(arguments[0].properties)))),
2025 /* Whether Velocity was called via the utility function (as opposed to on a jQuery/Zepto object). */
2026 isUtility,
2027 /* When Velocity is called via the utility function ($.Velocity()/Velocity()), elements are explicitly
2028 passed in as the first parameter. Thus, argument positioning varies. We normalize them here. */
2029 elementsWrapped,
2030 argumentIndex;
2031
2032 var elements,
2033 propertiesMap,
2034 options;
2035
2036 /* Detect jQuery/Zepto elements being animated via the $.fn method. */
2037 if (Type.isWrapped(this)) {
2038 isUtility = false;
2039
2040 argumentIndex = 0;
2041 elements = this;
2042 elementsWrapped = this;
2043 /* Otherwise, raw elements are being animated via the utility function. */
2044 } else {
2045 isUtility = true;
2046
2047 argumentIndex = 1;
2048 elements = syntacticSugar ? (arguments[0].elements || arguments[0].e) : arguments[0];
2049 }
2050
2051 elements = sanitizeElements(elements);
2052
2053 if (!elements) {
2054 return;
2055 }
2056
2057 if (syntacticSugar) {
2058 propertiesMap = arguments[0].properties || arguments[0].p;
2059 options = arguments[0].options || arguments[0].o;
2060 } else {
2061 propertiesMap = arguments[argumentIndex];
2062 options = arguments[argumentIndex + 1];
2063 }
2064
2065 /* The length of the element set (in the form of a nodeList or an array of elements) is defaulted to 1 in case a
2066 single raw DOM element is passed in (which doesn't contain a length property). */
2067 var elementsLength = elements.length,
2068 elementsIndex = 0;
2069
2070 /***************************
2071 Argument Overloading
2072 ***************************/
2073
2074 /* Support is included for jQuery's argument overloading: $.animate(propertyMap [, duration] [, easing] [, complete]).
2075 Overloading is detected by checking for the absence of an object being passed into options. */
2076 /* Note: The stop and finish actions do not accept animation options, and are therefore excluded from this check. */
2077 if (!/^(stop|finish)$/i.test(propertiesMap) && !$.isPlainObject(options)) {
2078 /* The utility function shifts all arguments one position to the right, so we adjust for that offset. */
2079 var startingArgumentPosition = argumentIndex + 1;
2080
2081 options = {};
2082
2083 /* Iterate through all options arguments */
2084 for (var i = startingArgumentPosition; i < arguments.length; i++) {
2085 /* Treat a number as a duration. Parse it out. */
2086 /* Note: The following RegEx will return true if passed an array with a number as its first item.
2087 Thus, arrays are skipped from this check. */
2088 if (!Type.isArray(arguments[i]) && (/^(fast|normal|slow)$/i.test(arguments[i]) || /^\d/.test(arguments[i]))) {
2089 options.duration = arguments[i];
2090 /* Treat strings and arrays as easings. */
2091 } else if (Type.isString(arguments[i]) || Type.isArray(arguments[i])) {
2092 options.easing = arguments[i];
2093 /* Treat a function as a complete callback. */
2094 } else if (Type.isFunction(arguments[i])) {
2095 options.complete = arguments[i];
2096 }
2097 }
2098 }
2099
2100 /***************
2101 Promises
2102 ***************/
2103
2104 var promiseData = {
2105 promise: null,
2106 resolver: null,
2107 rejecter: null
2108 };
2109
2110 /* If this call was made via the utility function (which is the default method of invocation when jQuery/Zepto are not being used), and if
2111 promise support was detected, create a promise object for this call and store references to its resolver and rejecter methods. The resolve
2112 method is used when a call completes naturally or is prematurely stopped by the user. In both cases, completeCall() handles the associated
2113 call cleanup and promise resolving logic. The reject method is used when an invalid set of arguments is passed into a Velocity call. */
2114 /* Note: Velocity employs a call-based queueing architecture, which means that stopping an animating element actually stops the full call that
2115 triggered it -- not that one element exclusively. Similarly, there is one promise per call, and all elements targeted by a Velocity call are
2116 grouped together for the purposes of resolving and rejecting a promise. */
2117 if (isUtility && Velocity.Promise) {
2118 promiseData.promise = new Velocity.Promise(function (resolve, reject) {
2119 promiseData.resolver = resolve;
2120 promiseData.rejecter = reject;
2121 });
2122 }
2123
2124 /*********************
2125 Action Detection
2126 *********************/
2127
2128 /* Velocity's behavior is categorized into "actions": Elements can either be specially scrolled into view,
2129 or they can be started, stopped, or reversed. If a literal or referenced properties map is passed in as Velocity's
2130 first argument, the associated action is "start". Alternatively, "scroll", "reverse", or "stop" can be passed in instead of a properties map. */
2131 var action;
2132
2133 switch (propertiesMap) {
2134 case "scroll":
2135 action = "scroll";
2136 break;
2137
2138 case "reverse":
2139 action = "reverse";
2140 break;
2141
2142 case "finish":
2143 case "stop":
2144 /*******************
2145 Action: Stop
2146 *******************/
2147
2148 /* Clear the currently-active delay on each targeted element. */
2149 $.each(elements, function(i, element) {
2150 if (Data(element) && Data(element).delayTimer) {
2151 /* Stop the timer from triggering its cached next() function. */
2152 clearTimeout(Data(element).delayTimer.setTimeout);
2153
2154 /* Manually call the next() function so that the subsequent queue items can progress. */
2155 if (Data(element).delayTimer.next) {
2156 Data(element).delayTimer.next();
2157 }
2158
2159 delete Data(element).delayTimer;
2160 }
2161 });
2162
2163 var callsToStop = [];
2164
2165 /* When the stop action is triggered, the elements' currently active call is immediately stopped. The active call might have
2166 been applied to multiple elements, in which case all of the call's elements will be stopped. When an element
2167 is stopped, the next item in its animation queue is immediately triggered. */
2168 /* An additional argument may be passed in to clear an element's remaining queued calls. Either true (which defaults to the "fx" queue)
2169 or a custom queue string can be passed in. */
2170 /* Note: The stop command runs prior to Velocity's Queueing phase since its behavior is intended to take effect *immediately*,
2171 regardless of the element's current queue state. */
2172
2173 /* Iterate through every active call. */
2174 $.each(Velocity.State.calls, function(i, activeCall) {
2175 /* Inactive calls are set to false by the logic inside completeCall(). Skip them. */
2176 if (activeCall) {
2177 /* Iterate through the active call's targeted elements. */
2178 $.each(activeCall[1], function(k, activeElement) {
2179 /* If true was passed in as a secondary argument, clear absolutely all calls on this element. Otherwise, only
2180 clear calls associated with the relevant queue. */
2181 /* Call stopping logic works as follows:
2182 - options === true --> stop current default queue calls (and queue:false calls), including remaining queued ones.
2183 - options === undefined --> stop current queue:"" call and all queue:false calls.
2184 - options === false --> stop only queue:false calls.
2185 - options === "custom" --> stop current queue:"custom" call, including remaining queued ones (there is no functionality to only clear the currently-running queue:"custom" call). */
2186 var queueName = (options === undefined) ? "" : options;
2187
2188 if (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) {
2189 return true;
2190 }
2191
2192 /* Iterate through the calls targeted by the stop command. */
2193 $.each(elements, function(l, element) {
2194 /* Check that this call was applied to the target element. */
2195 if (element === activeElement) {
2196 /* Optionally clear the remaining queued calls. */
2197 if (options === true || Type.isString(options)) {
2198 /* Iterate through the items in the element's queue. */
2199 $.each($.queue(element, Type.isString(options) ? options : ""), function(_, item) {
2200 /* The queue array can contain an "inprogress" string, which we skip. */
2201 if (Type.isFunction(item)) {
2202 /* Pass the item's callback a flag indicating that we want to abort from the queue call.
2203 (Specifically, the queue will resolve the call's associated promise then abort.) */
2204 item(null, true);
2205 }
2206 });
2207
2208 /* Clearing the $.queue() array is achieved by resetting it to []. */
2209 $.queue(element, Type.isString(options) ? options : "", []);
2210 }
2211
2212 if (propertiesMap === "stop") {
2213 /* Since "reverse" uses cached start values (the previous call's endValues), these values must be
2214 changed to reflect the final value that the elements were actually tweened to. */
2215 /* Note: If only queue:false animations are currently running on an element, it won't have a tweensContainer
2216 object. Also, queue:false animations can't be reversed. */
2217 if (Data(element) && Data(element).tweensContainer && queueName !== false) {
2218 $.each(Data(element).tweensContainer, function(m, activeTween) {
2219 activeTween.endValue = activeTween.currentValue;
2220 });
2221 }
2222
2223 callsToStop.push(i);
2224 } else if (propertiesMap === "finish") {
2225 /* To get active tweens to finish immediately, we forcefully shorten their durations to 1ms so that
2226 they finish upon the next rAf tick then proceed with normal call completion logic. */
2227 activeCall[2].duration = 1;
2228 }
2229 }
2230 });
2231 });
2232 }
2233 });
2234
2235 /* Prematurely call completeCall() on each matched active call. Pass an additional flag for "stop" to indicate
2236 that the complete callback and display:none setting should be skipped since we're completing prematurely. */
2237 if (propertiesMap === "stop") {
2238 $.each(callsToStop, function(i, j) {
2239 completeCall(j, true);
2240 });
2241
2242 if (promiseData.promise) {
2243 /* Immediately resolve the promise associated with this stop call since stop runs synchronously. */
2244 promiseData.resolver(elements);
2245 }
2246 }
2247
2248 /* Since we're stopping, and not proceeding with queueing, exit out of Velocity. */
2249 return getChain();
2250
2251 default:
2252 /* Treat a non-empty plain object as a literal properties map. */
2253 if ($.isPlainObject(propertiesMap) && !Type.isEmptyObject(propertiesMap)) {
2254 action = "start";
2255
2256 /****************
2257 Redirects
2258 ****************/
2259
2260 /* Check if a string matches a registered redirect (see Redirects above). */
2261 } else if (Type.isString(propertiesMap) && Velocity.Redirects[propertiesMap]) {
2262 var opts = $.extend({}, options),
2263 durationOriginal = opts.duration,
2264 delayOriginal = opts.delay || 0;
2265
2266 /* If the backwards option was passed in, reverse the element set so that elements animate from the last to the first. */
2267 if (opts.backwards === true) {
2268 elements = $.extend(true, [], elements).reverse();
2269 }
2270
2271 /* Individually trigger the redirect for each element in the set to prevent users from having to handle iteration logic in their redirect. */
2272 $.each(elements, function(elementIndex, element) {
2273 /* If the stagger option was passed in, successively delay each element by the stagger value (in ms). Retain the original delay value. */
2274 if (parseFloat(opts.stagger)) {
2275 opts.delay = delayOriginal + (parseFloat(opts.stagger) * elementIndex);
2276 } else if (Type.isFunction(opts.stagger)) {
2277 opts.delay = delayOriginal + opts.stagger.call(element, elementIndex, elementsLength);
2278 }
2279
2280 /* If the drag option was passed in, successively increase/decrease (depending on the presense of opts.backwards)
2281 the duration of each element's animation, using floors to prevent producing very short durations. */
2282 if (opts.drag) {
2283 /* Default the duration of UI pack effects (callouts and transitions) to 1000ms instead of the usual default duration of 400ms. */
2284 opts.duration = parseFloat(durationOriginal) || (/^(callout|transition)/.test(propertiesMap) ? 1000 : DURATION_DEFAULT);
2285
2286 /* For each element, take the greater duration of: A) animation completion percentage relative to the original duration,
2287 B) 75% of the original duration, or C) a 200ms fallback (in case duration is already set to a low value).
2288 The end result is a baseline of 75% of the redirect's duration that increases/decreases as the end of the element set is approached. */
2289 opts.duration = Math.max(opts.duration * (opts.backwards ? 1 - elementIndex/elementsLength : (elementIndex + 1) / elementsLength), opts.duration * 0.75, 200);
2290 }
2291
2292 /* Pass in the call's opts object so that the redirect can optionally extend it. It defaults to an empty object instead of null to
2293 reduce the opts checking logic required inside the redirect. */
2294 Velocity.Redirects[propertiesMap].call(element, element, opts || {}, elementIndex, elementsLength, elements, promiseData.promise ? promiseData : undefined);
2295 });
2296
2297 /* Since the animation logic resides within the redirect's own code, abort the remainder of this call.
2298 (The performance overhead up to this point is virtually non-existant.) */
2299 /* Note: The jQuery call chain is kept intact by returning the complete element set. */
2300 return getChain();
2301 } else {
2302 var abortError = "Velocity: First argument (" + propertiesMap + ") was not a property map, a known action, or a registered redirect. Aborting.";
2303
2304 if (promiseData.promise) {
2305 promiseData.rejecter(new Error(abortError));
2306 } else {
2307 console.log(abortError);
2308 }
2309
2310 return getChain();
2311 }
2312 }
2313
2314 /**************************
2315 Call-Wide Variables
2316 **************************/
2317
2318 /* A container for CSS unit conversion ratios (e.g. %, rem, and em ==> px) that is used to cache ratios across all elements
2319 being animated in a single Velocity call. Calculating unit ratios necessitates DOM querying and updating, and is therefore
2320 avoided (via caching) wherever possible. This container is call-wide instead of page-wide to avoid the risk of using stale
2321 conversion metrics across Velocity animations that are not immediately consecutively chained. */
2322 var callUnitConversionData = {
2323 lastParent: null,
2324 lastPosition: null,
2325 lastFontSize: null,
2326 lastPercentToPxWidth: null,
2327 lastPercentToPxHeight: null,
2328 lastEmToPx: null,
2329 remToPx: null,
2330 vwToPx: null,
2331 vhToPx: null
2332 };
2333
2334 /* A container for all the ensuing tween data and metadata associated with this call. This container gets pushed to the page-wide
2335 Velocity.State.calls array that is processed during animation ticking. */
2336 var call = [];
2337
2338 /************************
2339 Element Processing
2340 ************************/
2341
2342 /* Element processing consists of three parts -- data processing that cannot go stale and data processing that *can* go stale (i.e. third-party style modifications):
2343 1) Pre-Queueing: Element-wide variables, including the element's data storage, are instantiated. Call options are prepared. If triggered, the Stop action is executed.
2344 2) Queueing: The logic that runs once this call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale.
2345 3) Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
2346 */
2347
2348 function processElement () {
2349
2350 /*************************
2351 Part I: Pre-Queueing
2352 *************************/
2353
2354 /***************************
2355 Element-Wide Variables
2356 ***************************/
2357
2358 var element = this,
2359 /* The runtime opts object is the extension of the current call's options and Velocity's page-wide option defaults. */
2360 opts = $.extend({}, Velocity.defaults, options),
2361 /* A container for the processed data associated with each property in the propertyMap.
2362 (Each property in the map produces its own "tween".) */
2363 tweensContainer = {},
2364 elementUnitConversionData;
2365
2366 /******************
2367 Element Init
2368 ******************/
2369
2370 if (Data(element) === undefined) {
2371 Velocity.init(element);
2372 }
2373
2374 /******************
2375 Option: Delay
2376 ******************/
2377
2378 /* Since queue:false doesn't respect the item's existing queue, we avoid injecting its delay here (it's set later on). */
2379 /* Note: Velocity rolls its own delay function since jQuery doesn't have a utility alias for $.fn.delay()
2380 (and thus requires jQuery element creation, which we avoid since its overhead includes DOM querying). */
2381 if (parseFloat(opts.delay) && opts.queue !== false) {
2382 $.queue(element, opts.queue, function(next) {
2383 /* This is a flag used to indicate to the upcoming completeCall() function that this queue entry was initiated by Velocity. See completeCall() for further details. */
2384 Velocity.velocityQueueEntryFlag = true;
2385
2386 /* The ensuing queue item (which is assigned to the "next" argument that $.queue() automatically passes in) will be triggered after a setTimeout delay.
2387 The setTimeout is stored so that it can be subjected to clearTimeout() if this animation is prematurely stopped via Velocity's "stop" command. */
2388 Data(element).delayTimer = {
2389 setTimeout: setTimeout(next, parseFloat(opts.delay)),
2390 next: next
2391 };
2392 });
2393 }
2394
2395 /*********************
2396 Option: Duration
2397 *********************/
2398
2399 /* Support for jQuery's named durations. */
2400 switch (opts.duration.toString().toLowerCase()) {
2401 case "fast":
2402 opts.duration = 200;
2403 break;
2404
2405 case "normal":
2406 opts.duration = DURATION_DEFAULT;
2407 break;
2408
2409 case "slow":
2410 opts.duration = 600;
2411 break;
2412
2413 default:
2414 /* Remove the potential "ms" suffix and default to 1 if the user is attempting to set a duration of 0 (in order to produce an immediate style change). */
2415 opts.duration = parseFloat(opts.duration) || 1;
2416 }
2417
2418 /************************
2419 Global Option: Mock
2420 ************************/
2421
2422 if (Velocity.mock !== false) {
2423 /* In mock mode, all animations are forced to 1ms so that they occur immediately upon the next rAF tick.
2424 Alternatively, a multiplier can be passed in to time remap all delays and durations. */
2425 if (Velocity.mock === true) {
2426 opts.duration = opts.delay = 1;
2427 } else {
2428 opts.duration *= parseFloat(Velocity.mock) || 1;
2429 opts.delay *= parseFloat(Velocity.mock) || 1;
2430 }
2431 }
2432
2433 /*******************
2434 Option: Easing
2435 *******************/
2436
2437 opts.easing = getEasing(opts.easing, opts.duration);
2438
2439 /**********************
2440 Option: Callbacks
2441 **********************/
2442
2443 /* Callbacks must functions. Otherwise, default to null. */
2444 if (opts.begin && !Type.isFunction(opts.begin)) {
2445 opts.begin = null;
2446 }
2447
2448 if (opts.progress && !Type.isFunction(opts.progress)) {
2449 opts.progress = null;
2450 }
2451
2452 if (opts.complete && !Type.isFunction(opts.complete)) {
2453 opts.complete = null;
2454 }
2455
2456 /*********************************
2457 Option: Display & Visibility
2458 *********************************/
2459
2460 /* Refer to Velocity's documentation (VelocityJS.org/#displayAndVisibility) for a description of the display and visibility options' behavior. */
2461 /* Note: We strictly check for undefined instead of falsiness because display accepts an empty string value. */
2462 if (opts.display !== undefined && opts.display !== null) {
2463 opts.display = opts.display.toString().toLowerCase();
2464
2465 /* Users can pass in a special "auto" value to instruct Velocity to set the element to its default display value. */
2466 if (opts.display === "auto") {
2467 opts.display = Velocity.CSS.Values.getDisplayType(element);
2468 }
2469 }
2470
2471 if (opts.visibility !== undefined && opts.visibility !== null) {
2472 opts.visibility = opts.visibility.toString().toLowerCase();
2473 }
2474
2475 /**********************
2476 Option: mobileHA
2477 **********************/
2478
2479 /* When set to true, and if this is a mobile device, mobileHA automatically enables hardware acceleration (via a null transform hack)
2480 on animating elements. HA is removed from the element at the completion of its animation. */
2481 /* Note: Android Gingerbread doesn't support HA. If a null transform hack (mobileHA) is in fact set, it will prevent other tranform subproperties from taking effect. */
2482 /* Note: You can read more about the use of mobileHA in Velocity's documentation: VelocityJS.org/#mobileHA. */
2483 opts.mobileHA = (opts.mobileHA && Velocity.State.isMobile && !Velocity.State.isGingerbread);
2484
2485 /***********************
2486 Part II: Queueing
2487 ***********************/
2488
2489 /* When a set of elements is targeted by a Velocity call, the set is broken up and each element has the current Velocity call individually queued onto it.
2490 In this way, each element's existing queue is respected; some elements may already be animating and accordingly should not have this current Velocity call triggered immediately. */
2491 /* In each queue, tween data is processed for each animating property then pushed onto the call-wide calls array. When the last element in the set has had its tweens processed,
2492 the call array is pushed to Velocity.State.calls for live processing by the requestAnimationFrame tick. */
2493 function buildQueue (next) {
2494
2495 /*******************
2496 Option: Begin
2497 *******************/
2498
2499 /* The begin callback is fired once per call -- not once per elemenet -- and is passed the full raw DOM element set as both its context and its first argument. */
2500 if (opts.begin && elementsIndex === 0) {
2501 /* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */
2502 try {
2503 opts.begin.call(elements, elements);
2504 } catch (error) {
2505 setTimeout(function() { throw error; }, 1);
2506 }
2507 }
2508
2509 /*****************************************
2510 Tween Data Construction (for Scroll)
2511 *****************************************/
2512
2513 /* Note: In order to be subjected to chaining and animation options, scroll's tweening is routed through Velocity as if it were a standard CSS property animation. */
2514 if (action === "scroll") {
2515 /* The scroll action uniquely takes an optional "offset" option -- specified in pixels -- that offsets the targeted scroll position. */
2516 var scrollDirection = (/^x$/i.test(opts.axis) ? "Left" : "Top"),
2517 scrollOffset = parseFloat(opts.offset) || 0,
2518 scrollPositionCurrent,
2519 scrollPositionCurrentAlternate,
2520 scrollPositionEnd;
2521
2522 /* Scroll also uniquely takes an optional "container" option, which indicates the parent element that should be scrolled --
2523 as opposed to the browser window itself. This is useful for scrolling toward an element that's inside an overflowing parent element. */
2524 if (opts.container) {
2525 /* Ensure that either a jQuery object or a raw DOM element was passed in. */
2526 if (Type.isWrapped(opts.container) || Type.isNode(opts.container)) {
2527 /* Extract the raw DOM element from the jQuery wrapper. */
2528 opts.container = opts.container[0] || opts.container;
2529 /* Note: Unlike other properties in Velocity, the browser's scroll position is never cached since it so frequently changes
2530 (due to the user's natural interaction with the page). */
2531 scrollPositionCurrent = opts.container["scroll" + scrollDirection]; /* GET */
2532
2533 /* $.position() values are relative to the container's currently viewable area (without taking into account the container's true dimensions
2534 -- say, for example, if the container was not overflowing). Thus, the scroll end value is the sum of the child element's position *and*
2535 the scroll container's current scroll position. */
2536 scrollPositionEnd = (scrollPositionCurrent + $(element).position()[scrollDirection.toLowerCase()]) + scrollOffset; /* GET */
2537 /* If a value other than a jQuery object or a raw DOM element was passed in, default to null so that this option is ignored. */
2538 } else {
2539 opts.container = null;
2540 }
2541 } else {
2542 /* If the window itself is being scrolled -- not a containing element -- perform a live scroll position lookup using
2543 the appropriate cached property names (which differ based on browser type). */
2544 scrollPositionCurrent = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + scrollDirection]]; /* GET */
2545 /* When scrolling the browser window, cache the alternate axis's current value since window.scrollTo() doesn't let us change only one value at a time. */
2546 scrollPositionCurrentAlternate = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + (scrollDirection === "Left" ? "Top" : "Left")]]; /* GET */
2547
2548 /* Unlike $.position(), $.offset() values are relative to the browser window's true dimensions -- not merely its currently viewable area --
2549 and therefore end values do not need to be compounded onto current values. */
2550 scrollPositionEnd = $(element).offset()[scrollDirection.toLowerCase()] + scrollOffset; /* GET */
2551 }
2552
2553 /* Since there's only one format that scroll's associated tweensContainer can take, we create it manually. */
2554 tweensContainer = {
2555 scroll: {
2556 rootPropertyValue: false,
2557 startValue: scrollPositionCurrent,
2558 currentValue: scrollPositionCurrent,
2559 endValue: scrollPositionEnd,
2560 unitType: "",
2561 easing: opts.easing,
2562 scrollData: {
2563 container: opts.container,
2564 direction: scrollDirection,
2565 alternateValue: scrollPositionCurrentAlternate
2566 }
2567 },
2568 element: element
2569 };
2570
2571 if (Velocity.debug) console.log("tweensContainer (scroll): ", tweensContainer.scroll, element);
2572
2573 /******************************************
2574 Tween Data Construction (for Reverse)
2575 ******************************************/
2576
2577 /* Reverse acts like a "start" action in that a property map is animated toward. The only difference is
2578 that the property map used for reverse is the inverse of the map used in the previous call. Thus, we manipulate
2579 the previous call to construct our new map: use the previous map's end values as our new map's start values. Copy over all other data. */
2580 /* Note: Reverse can be directly called via the "reverse" parameter, or it can be indirectly triggered via the loop option. (Loops are composed of multiple reverses.) */
2581 /* Note: Reverse calls do not need to be consecutively chained onto a currently-animating element in order to operate on cached values;
2582 there is no harm to reverse being called on a potentially stale data cache since reverse's behavior is simply defined
2583 as reverting to the element's values as they were prior to the previous *Velocity* call. */
2584 } else if (action === "reverse") {
2585 /* Abort if there is no prior animation data to reverse to. */
2586 if (!Data(element).tweensContainer) {
2587 /* Dequeue the element so that this queue entry releases itself immediately, allowing subsequent queue entries to run. */
2588 $.dequeue(element, opts.queue);
2589
2590 return;
2591 } else {
2592 /*********************
2593 Options Parsing
2594 *********************/
2595
2596 /* If the element was hidden via the display option in the previous call,
2597 revert display to "auto" prior to reversal so that the element is visible again. */
2598 if (Data(element).opts.display === "none") {
2599 Data(element).opts.display = "auto";
2600 }
2601
2602 if (Data(element).opts.visibility === "hidden") {
2603 Data(element).opts.visibility = "visible";
2604 }
2605
2606 /* If the loop option was set in the previous call, disable it so that "reverse" calls aren't recursively generated.
2607 Further, remove the previous call's callback options; typically, users do not want these to be refired. */
2608 Data(element).opts.loop = false;
2609 Data(element).opts.begin = null;
2610 Data(element).opts.complete = null;
2611
2612 /* Since we're extending an opts object that has already been extended with the defaults options object,
2613 we remove non-explicitly-defined properties that are auto-assigned values. */
2614 if (!options.easing) {
2615 delete opts.easing;
2616 }
2617
2618 if (!options.duration) {
2619 delete opts.duration;
2620 }
2621
2622 /* The opts object used for reversal is an extension of the options object optionally passed into this
2623 reverse call plus the options used in the previous Velocity call. */
2624 opts = $.extend({}, Data(element).opts, opts);
2625
2626 /*************************************
2627 Tweens Container Reconstruction
2628 *************************************/
2629
2630 /* Create a deepy copy (indicated via the true flag) of the previous call's tweensContainer. */
2631 var lastTweensContainer = $.extend(true, {}, Data(element).tweensContainer);
2632
2633 /* Manipulate the previous tweensContainer by replacing its end values and currentValues with its start values. */
2634 for (var lastTween in lastTweensContainer) {
2635 /* In addition to tween data, tweensContainers contain an element property that we ignore here. */
2636 if (lastTween !== "element") {
2637 var lastStartValue = lastTweensContainer[lastTween].startValue;
2638
2639 lastTweensContainer[lastTween].startValue = lastTweensContainer[lastTween].currentValue = lastTweensContainer[lastTween].endValue;
2640 lastTweensContainer[lastTween].endValue = lastStartValue;
2641
2642 /* Easing is the only option that embeds into the individual tween data (since it can be defined on a per-property basis).
2643 Accordingly, every property's easing value must be updated when an options object is passed in with a reverse call.
2644 The side effect of this extensibility is that all per-property easing values are forcefully reset to the new value. */
2645 if (!Type.isEmptyObject(options)) {
2646 lastTweensContainer[lastTween].easing = opts.easing;
2647 }
2648
2649 if (Velocity.debug) console.log("reverse tweensContainer (" + lastTween + "): " + JSON.stringify(lastTweensContainer[lastTween]), element);
2650 }
2651 }
2652
2653 tweensContainer = lastTweensContainer;
2654 }
2655
2656 /*****************************************
2657 Tween Data Construction (for Start)
2658 *****************************************/
2659
2660 } else if (action === "start") {
2661
2662 /*************************
2663 Value Transferring
2664 *************************/
2665
2666 /* If this queue entry follows a previous Velocity-initiated queue entry *and* if this entry was created
2667 while the element was in the process of being animated by Velocity, then this current call is safe to use
2668 the end values from the prior call as its start values. Velocity attempts to perform this value transfer
2669 process whenever possible in order to avoid requerying the DOM. */
2670 /* If values aren't transferred from a prior call and start values were not forcefed by the user (more on this below),
2671 then the DOM is queried for the element's current values as a last resort. */
2672 /* Note: Conversely, animation reversal (and looping) *always* perform inter-call value transfers; they never requery the DOM. */
2673 var lastTweensContainer;
2674
2675 /* The per-element isAnimating flag is used to indicate whether it's safe (i.e. the data isn't stale)
2676 to transfer over end values to use as start values. If it's set to true and there is a previous
2677 Velocity call to pull values from, do so. */
2678 if (Data(element).tweensContainer && Data(element).isAnimating === true) {
2679 lastTweensContainer = Data(element).tweensContainer;
2680 }
2681
2682 /***************************
2683 Tween Data Calculation
2684 ***************************/
2685
2686 /* This function parses property data and defaults endValue, easing, and startValue as appropriate. */
2687 /* Property map values can either take the form of 1) a single value representing the end value,
2688 or 2) an array in the form of [ endValue, [, easing] [, startValue] ].
2689 The optional third parameter is a forcefed startValue to be used instead of querying the DOM for
2690 the element's current value. Read Velocity's docmentation to learn more about forcefeeding: VelocityJS.org/#forcefeeding */
2691 function parsePropertyValue (valueData, skipResolvingEasing) {
2692 var endValue = undefined,
2693 easing = undefined,
2694 startValue = undefined;
2695
2696 /* Handle the array format, which can be structured as one of three potential overloads:
2697 A) [ endValue, easing, startValue ], B) [ endValue, easing ], or C) [ endValue, startValue ] */
2698 if (Type.isArray(valueData)) {
2699 /* endValue is always the first item in the array. Don't bother validating endValue's value now
2700 since the ensuing property cycling logic does that. */
2701 endValue = valueData[0];
2702
2703 /* Two-item array format: If the second item is a number, function, or hex string, treat it as a
2704 start value since easings can only be non-hex strings or arrays. */
2705 if ((!Type.isArray(valueData[1]) && /^[\d-]/.test(valueData[1])) || Type.isFunction(valueData[1]) || CSS.RegEx.isHex.test(valueData[1])) {
2706 startValue = valueData[1];
2707 /* Two or three-item array: If the second item is a non-hex string or an array, treat it as an easing. */
2708 } else if ((Type.isString(valueData[1]) && !CSS.RegEx.isHex.test(valueData[1])) || Type.isArray(valueData[1])) {
2709 easing = skipResolvingEasing ? valueData[1] : getEasing(valueData[1], opts.duration);
2710
2711 /* Don't bother validating startValue's value now since the ensuing property cycling logic inherently does that. */
2712 if (valueData[2] !== undefined) {
2713 startValue = valueData[2];
2714 }
2715 }
2716 /* Handle the single-value format. */
2717 } else {
2718 endValue = valueData;
2719 }
2720
2721 /* Default to the call's easing if a per-property easing type was not defined. */
2722 if (!skipResolvingEasing) {
2723 easing = easing || opts.easing;
2724 }
2725
2726 /* If functions were passed in as values, pass the function the current element as its context,
2727 plus the element's index and the element set's size as arguments. Then, assign the returned value. */
2728 if (Type.isFunction(endValue)) {
2729 endValue = endValue.call(element, elementsIndex, elementsLength);
2730 }
2731
2732 if (Type.isFunction(startValue)) {
2733 startValue = startValue.call(element, elementsIndex, elementsLength);
2734 }
2735
2736 /* Allow startValue to be left as undefined to indicate to the ensuing code that its value was not forcefed. */
2737 return [ endValue || 0, easing, startValue ];
2738 }
2739
2740 /* Cycle through each property in the map, looking for shorthand color properties (e.g. "color" as opposed to "colorRed"). Inject the corresponding
2741 colorRed, colorGreen, and colorBlue RGB component tweens into the propertiesMap (which Velocity understands) and remove the shorthand property. */
2742 $.each(propertiesMap, function(property, value) {
2743 /* Find shorthand color properties that have been passed a hex string. */
2744 if (RegExp("^" + CSS.Lists.colors.join("$|^") + "$").test(property)) {
2745 /* Parse the value data for each shorthand. */
2746 var valueData = parsePropertyValue(value, true),
2747 endValue = valueData[0],
2748 easing = valueData[1],
2749 startValue = valueData[2];
2750
2751 if (CSS.RegEx.isHex.test(endValue)) {
2752 /* Convert the hex strings into their RGB component arrays. */
2753 var colorComponents = [ "Red", "Green", "Blue" ],
2754 endValueRGB = CSS.Values.hexToRgb(endValue),
2755 startValueRGB = startValue ? CSS.Values.hexToRgb(startValue) : undefined;
2756
2757 /* Inject the RGB component tweens into propertiesMap. */
2758 for (var i = 0; i < colorComponents.length; i++) {
2759 var dataArray = [ endValueRGB[i] ];
2760
2761 if (easing) {
2762 dataArray.push(easing);
2763 }
2764
2765 if (startValueRGB !== undefined) {
2766 dataArray.push(startValueRGB[i]);
2767 }
2768
2769 propertiesMap[property + colorComponents[i]] = dataArray;
2770 }
2771
2772 /* Remove the intermediary shorthand property entry now that we've processed it. */
2773 delete propertiesMap[property];
2774 }
2775 }
2776 });
2777
2778 /* Create a tween out of each property, and append its associated data to tweensContainer. */
2779 for (var property in propertiesMap) {
2780
2781 /**************************
2782 Start Value Sourcing
2783 **************************/
2784
2785 /* Parse out endValue, easing, and startValue from the property's data. */
2786 var valueData = parsePropertyValue(propertiesMap[property]),
2787 endValue = valueData[0],
2788 easing = valueData[1],
2789 startValue = valueData[2];
2790
2791 /* Now that the original property name's format has been used for the parsePropertyValue() lookup above,
2792 we force the property to its camelCase styling to normalize it for manipulation. */
2793 property = CSS.Names.camelCase(property);
2794
2795 /* In case this property is a hook, there are circumstances where we will intend to work on the hook's root property and not the hooked subproperty. */
2796 var rootProperty = CSS.Hooks.getRoot(property),
2797 rootPropertyValue = false;
2798
2799 /* Other than for the dummy tween property, properties that are not supported by the browser (and do not have an associated normalization) will
2800 inherently produce no style changes when set, so they are skipped in order to decrease animation tick overhead.
2801 Property support is determined via prefixCheck(), which returns a false flag when no supported is detected. */
2802 /* Note: Since SVG elements have some of their properties directly applied as HTML attributes,
2803 there is no way to check for their explicit browser support, and so we skip skip this check for them. */
2804 if (!Data(element).isSVG && rootProperty !== "tween" && CSS.Names.prefixCheck(rootProperty)[1] === false && CSS.Normalizations.registered[rootProperty] === undefined) {
2805 if (Velocity.debug) console.log("Skipping [" + rootProperty + "] due to a lack of browser support.");
2806
2807 continue;
2808 }
2809
2810 /* If the display option is being set to a non-"none" (e.g. "block") and opacity (filter on IE<=8) is being
2811 animated to an endValue of non-zero, the user's intention is to fade in from invisible, thus we forcefeed opacity
2812 a startValue of 0 if its startValue hasn't already been sourced by value transferring or prior forcefeeding. */
2813 if (((opts.display !== undefined && opts.display !== null && opts.display !== "none") || (opts.visibility !== undefined && opts.visibility !== "hidden")) && /opacity|filter/.test(property) && !startValue && endValue !== 0) {
2814 startValue = 0;
2815 }
2816
2817 /* If values have been transferred from the previous Velocity call, extract the endValue and rootPropertyValue
2818 for all of the current call's properties that were *also* animated in the previous call. */
2819 /* Note: Value transferring can optionally be disabled by the user via the _cacheValues option. */
2820 if (opts._cacheValues && lastTweensContainer && lastTweensContainer[property]) {
2821 if (startValue === undefined) {
2822 startValue = lastTweensContainer[property].endValue + lastTweensContainer[property].unitType;
2823 }
2824
2825 /* The previous call's rootPropertyValue is extracted from the element's data cache since that's the
2826 instance of rootPropertyValue that gets freshly updated by the tweening process, whereas the rootPropertyValue
2827 attached to the incoming lastTweensContainer is equal to the root property's value prior to any tweening. */
2828 rootPropertyValue = Data(element).rootPropertyValueCache[rootProperty];
2829 /* If values were not transferred from a previous Velocity call, query the DOM as needed. */
2830 } else {
2831 /* Handle hooked properties. */
2832 if (CSS.Hooks.registered[property]) {
2833 if (startValue === undefined) {
2834 rootPropertyValue = CSS.getPropertyValue(element, rootProperty); /* GET */
2835 /* Note: The following getPropertyValue() call does not actually trigger a DOM query;
2836 getPropertyValue() will extract the hook from rootPropertyValue. */
2837 startValue = CSS.getPropertyValue(element, property, rootPropertyValue);
2838 /* If startValue is already defined via forcefeeding, do not query the DOM for the root property's value;
2839 just grab rootProperty's zero-value template from CSS.Hooks. This overwrites the element's actual
2840 root property value (if one is set), but this is acceptable since the primary reason users forcefeed is
2841 to avoid DOM queries, and thus we likewise avoid querying the DOM for the root property's value. */
2842 } else {
2843 /* Grab this hook's zero-value template, e.g. "0px 0px 0px black". */
2844 rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
2845 }
2846 /* Handle non-hooked properties that haven't already been defined via forcefeeding. */
2847 } else if (startValue === undefined) {
2848 startValue = CSS.getPropertyValue(element, property); /* GET */
2849 }
2850 }
2851
2852 /**************************
2853 Value Data Extraction
2854 **************************/
2855
2856 var separatedValue,
2857 endValueUnitType,
2858 startValueUnitType,
2859 operator = false;
2860
2861 /* Separates a property value into its numeric value and its unit type. */
2862 function separateValue (property, value) {
2863 var unitType,
2864 numericValue;
2865
2866 numericValue = (value || "0")
2867 .toString()
2868 .toLowerCase()
2869 /* Match the unit type at the end of the value. */
2870 .replace(/[%A-z]+$/, function(match) {
2871 /* Grab the unit type. */
2872 unitType = match;
2873
2874 /* Strip the unit type off of value. */
2875 return "";
2876 });
2877
2878 /* If no unit type was supplied, assign one that is appropriate for this property (e.g. "deg" for rotateZ or "px" for width). */
2879 if (!unitType) {
2880 unitType = CSS.Values.getUnitType(property);
2881 }
2882
2883 return [ numericValue, unitType ];
2884 }
2885
2886 /* Separate startValue. */
2887 separatedValue = separateValue(property, startValue);
2888 startValue = separatedValue[0];
2889 startValueUnitType = separatedValue[1];
2890
2891 /* Separate endValue, and extract a value operator (e.g. "+=", "-=") if one exists. */
2892 separatedValue = separateValue(property, endValue);
2893 endValue = separatedValue[0].replace(/^([+-\/*])=/, function(match, subMatch) {
2894 operator = subMatch;
2895
2896 /* Strip the operator off of the value. */
2897 return "";
2898 });
2899 endValueUnitType = separatedValue[1];
2900
2901 /* Parse float values from endValue and startValue. Default to 0 if NaN is returned. */
2902 startValue = parseFloat(startValue) || 0;
2903 endValue = parseFloat(endValue) || 0;
2904
2905 /***************************************
2906 Property-Specific Value Conversion
2907 ***************************************/
2908
2909 /* Custom support for properties that don't actually accept the % unit type, but where pollyfilling is trivial and relatively foolproof. */
2910 if (endValueUnitType === "%") {
2911 /* A %-value fontSize/lineHeight is relative to the parent's fontSize (as opposed to the parent's dimensions),
2912 which is identical to the em unit's behavior, so we piggyback off of that. */
2913 if (/^(fontSize|lineHeight)$/.test(property)) {
2914 /* Convert % into an em decimal value. */
2915 endValue = endValue / 100;
2916 endValueUnitType = "em";
2917 /* For scaleX and scaleY, convert the value into its decimal format and strip off the unit type. */
2918 } else if (/^scale/.test(property)) {
2919 endValue = endValue / 100;
2920 endValueUnitType = "";
2921 /* For RGB components, take the defined percentage of 255 and strip off the unit type. */
2922 } else if (/(Red|Green|Blue)$/i.test(property)) {
2923 endValue = (endValue / 100) * 255;
2924 endValueUnitType = "";
2925 }
2926 }
2927
2928 /***************************
2929 Unit Ratio Calculation
2930 ***************************/
2931
2932 /* When queried, the browser returns (most) CSS property values in pixels. Therefore, if an endValue with a unit type of
2933 %, em, or rem is animated toward, startValue must be converted from pixels into the same unit type as endValue in order
2934 for value manipulation logic (increment/decrement) to proceed. Further, if the startValue was forcefed or transferred
2935 from a previous call, startValue may also not be in pixels. Unit conversion logic therefore consists of two steps:
2936 1) Calculating the ratio of %/em/rem/vh/vw relative to pixels
2937 2) Converting startValue into the same unit of measurement as endValue based on these ratios. */
2938 /* Unit conversion ratios are calculated by inserting a sibling node next to the target node, copying over its position property,
2939 setting values with the target unit type then comparing the returned pixel value. */
2940 /* Note: Even if only one of these unit types is being animated, all unit ratios are calculated at once since the overhead
2941 of batching the SETs and GETs together upfront outweights the potential overhead
2942 of layout thrashing caused by re-querying for uncalculated ratios for subsequently-processed properties. */
2943 /* Todo: Shift this logic into the calls' first tick instance so that it's synced with RAF. */
2944 function calculateUnitRatios () {
2945
2946 /************************
2947 Same Ratio Checks
2948 ************************/
2949
2950 /* The properties below are used to determine whether the element differs sufficiently from this call's
2951 previously iterated element to also differ in its unit conversion ratios. If the properties match up with those
2952 of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,
2953 this is done to minimize DOM querying. */
2954 var sameRatioIndicators = {
2955 myParent: element.parentNode || document.body, /* GET */
2956 position: CSS.getPropertyValue(element, "position"), /* GET */
2957 fontSize: CSS.getPropertyValue(element, "fontSize") /* GET */
2958 },
2959 /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */
2960 samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),
2961 /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */
2962 sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);
2963
2964 /* Store these ratio indicators call-wide for the next element to compare against. */
2965 callUnitConversionData.lastParent = sameRatioIndicators.myParent;
2966 callUnitConversionData.lastPosition = sameRatioIndicators.position;
2967 callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;
2968
2969 /***************************
2970 Element-Specific Units
2971 ***************************/
2972
2973 /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement
2974 of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */
2975 var measurement = 100,
2976 unitRatios = {};
2977
2978 if (!sameEmRatio || !samePercentRatio) {
2979 var dummy = Data(element).isSVG ? document.createElementNS("http://www.w3.org/2000/svg", "rect") : document.createElement("div");
2980
2981 Velocity.init(dummy);
2982 sameRatioIndicators.myParent.appendChild(dummy);
2983
2984 /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.
2985 Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */
2986 /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */
2987 $.each([ "overflow", "overflowX", "overflowY" ], function(i, property) {
2988 Velocity.CSS.setPropertyValue(dummy, property, "hidden");
2989 });
2990 Velocity.CSS.setPropertyValue(dummy, "position", sameRatioIndicators.position);
2991 Velocity.CSS.setPropertyValue(dummy, "fontSize", sameRatioIndicators.fontSize);
2992 Velocity.CSS.setPropertyValue(dummy, "boxSizing", "content-box");
2993
2994 /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */
2995 $.each([ "minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height" ], function(i, property) {
2996 Velocity.CSS.setPropertyValue(dummy, property, measurement + "%");
2997 });
2998 /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */
2999 Velocity.CSS.setPropertyValue(dummy, "paddingLeft", measurement + "em");
3000
3001 /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */
3002 unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, "width", null, true)) || 1) / measurement; /* GET */
3003 unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, "height", null, true)) || 1) / measurement; /* GET */
3004 unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, "paddingLeft")) || 1) / measurement; /* GET */
3005
3006 sameRatioIndicators.myParent.removeChild(dummy);
3007 } else {
3008 unitRatios.emToPx = callUnitConversionData.lastEmToPx;
3009 unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;
3010 unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;
3011 }
3012
3013 /***************************
3014 Element-Agnostic Units
3015 ***************************/
3016
3017 /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked
3018 once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time
3019 that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,
3020 so we calculate it now. */
3021 if (callUnitConversionData.remToPx === null) {
3022 /* Default to browsers' default fontSize of 16px in the case of 0. */
3023 callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, "fontSize")) || 16; /* GET */
3024 }
3025
3026 /* Similarly, viewport units are %-relative to the window's inner dimensions. */
3027 if (callUnitConversionData.vwToPx === null) {
3028 callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */
3029 callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */
3030 }
3031
3032 unitRatios.remToPx = callUnitConversionData.remToPx;
3033 unitRatios.vwToPx = callUnitConversionData.vwToPx;
3034 unitRatios.vhToPx = callUnitConversionData.vhToPx;
3035
3036 if (Velocity.debug >= 1) console.log("Unit ratios: " + JSON.stringify(unitRatios), element);
3037
3038 return unitRatios;
3039 }
3040
3041 /********************
3042 Unit Conversion
3043 ********************/
3044
3045 /* The * and / operators, which are not passed in with an associated unit, inherently use startValue's unit. Skip value and unit conversion. */
3046 if (/[\/*]/.test(operator)) {
3047 endValueUnitType = startValueUnitType;
3048 /* If startValue and endValue differ in unit type, convert startValue into the same unit type as endValue so that if endValueUnitType
3049 is a relative unit (%, em, rem), the values set during tweening will continue to be accurately relative even if the metrics they depend
3050 on are dynamically changing during the course of the animation. Conversely, if we always normalized into px and used px for setting values, the px ratio
3051 would become stale if the original unit being animated toward was relative and the underlying metrics change during the animation. */
3052 /* Since 0 is 0 in any unit type, no conversion is necessary when startValue is 0 -- we just start at 0 with endValueUnitType. */
3053 } else if ((startValueUnitType !== endValueUnitType) && startValue !== 0) {
3054 /* Unit conversion is also skipped when endValue is 0, but *startValueUnitType* must be used for tween values to remain accurate. */
3055 /* Note: Skipping unit conversion here means that if endValueUnitType was originally a relative unit, the animation won't relatively
3056 match the underlying metrics if they change, but this is acceptable since we're animating toward invisibility instead of toward visibility,
3057 which remains past the point of the animation's completion. */
3058 if (endValue === 0) {
3059 endValueUnitType = startValueUnitType;
3060 } else {
3061 /* By this point, we cannot avoid unit conversion (it's undesirable since it causes layout thrashing).
3062 If we haven't already, we trigger calculateUnitRatios(), which runs once per element per call. */
3063 elementUnitConversionData = elementUnitConversionData || calculateUnitRatios();
3064
3065 /* The following RegEx matches CSS properties that have their % values measured relative to the x-axis. */
3066 /* Note: W3C spec mandates that all of margin and padding's properties (even top and bottom) are %-relative to the *width* of the parent element. */
3067 var axis = (/margin|padding|left|right|width|text|word|letter/i.test(property) || /X$/.test(property) || property === "x") ? "x" : "y";
3068
3069 /* In order to avoid generating n^2 bespoke conversion functions, unit conversion is a two-step process:
3070 1) Convert startValue into pixels. 2) Convert this new pixel value into endValue's unit type. */
3071 switch (startValueUnitType) {
3072 case "%":
3073 /* Note: translateX and translateY are the only properties that are %-relative to an element's own dimensions -- not its parent's dimensions.
3074 Velocity does not include a special conversion process to account for this behavior. Therefore, animating translateX/Y from a % value
3075 to a non-% value will produce an incorrect start value. Fortunately, this sort of cross-unit conversion is rarely done by users in practice. */
3076 startValue *= (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);
3077 break;
3078
3079 case "px":
3080 /* px acts as our midpoint in the unit conversion process; do nothing. */
3081 break;
3082
3083 default:
3084 startValue *= elementUnitConversionData[startValueUnitType + "ToPx"];
3085 }
3086
3087 /* Invert the px ratios to convert into to the target unit. */
3088 switch (endValueUnitType) {
3089 case "%":
3090 startValue *= 1 / (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);
3091 break;
3092
3093 case "px":
3094 /* startValue is already in px, do nothing; we're done. */
3095 break;
3096
3097 default:
3098 startValue *= 1 / elementUnitConversionData[endValueUnitType + "ToPx"];
3099 }
3100 }
3101 }
3102
3103 /*********************
3104 Relative Values
3105 *********************/
3106
3107 /* Operator logic must be performed last since it requires unit-normalized start and end values. */
3108 /* Note: Relative *percent values* do not behave how most people think; while one would expect "+=50%"
3109 to increase the property 1.5x its current value, it in fact increases the percent units in absolute terms:
3110 50 points is added on top of the current % value. */
3111 switch (operator) {
3112 case "+":
3113 endValue = startValue + endValue;
3114 break;
3115
3116 case "-":
3117 endValue = startValue - endValue;
3118 break;
3119
3120 case "*":
3121 endValue = startValue * endValue;
3122 break;
3123
3124 case "/":
3125 endValue = startValue / endValue;
3126 break;
3127 }
3128
3129 /**************************
3130 tweensContainer Push
3131 **************************/
3132
3133 /* Construct the per-property tween object, and push it to the element's tweensContainer. */
3134 tweensContainer[property] = {
3135 rootPropertyValue: rootPropertyValue,
3136 startValue: startValue,
3137 currentValue: startValue,
3138 endValue: endValue,
3139 unitType: endValueUnitType,
3140 easing: easing
3141 };
3142
3143 if (Velocity.debug) console.log("tweensContainer (" + property + "): " + JSON.stringify(tweensContainer[property]), element);
3144 }
3145
3146 /* Along with its property data, store a reference to the element itself onto tweensContainer. */
3147 tweensContainer.element = element;
3148 }
3149
3150 /*****************
3151 Call Push
3152 *****************/
3153
3154 /* Note: tweensContainer can be empty if all of the properties in this call's property map were skipped due to not
3155 being supported by the browser. The element property is used for checking that the tweensContainer has been appended to. */
3156 if (tweensContainer.element) {
3157 /* Apply the "velocity-animating" indicator class. */
3158 CSS.Values.addClass(element, "velocity-animating");
3159
3160 /* The call array houses the tweensContainers for each element being animated in the current call. */
3161 call.push(tweensContainer);
3162
3163 /* Store the tweensContainer and options if we're working on the default effects queue, so that they can be used by the reverse command. */
3164 if (opts.queue === "") {
3165 Data(element).tweensContainer = tweensContainer;
3166 Data(element).opts = opts;
3167 }
3168
3169 /* Switch on the element's animating flag. */
3170 Data(element).isAnimating = true;
3171
3172 /* Once the final element in this call's element set has been processed, push the call array onto
3173 Velocity.State.calls for the animation tick to immediately begin processing. */
3174 if (elementsIndex === elementsLength - 1) {
3175 /* Add the current call plus its associated metadata (the element set and the call's options) onto the global call container.
3176 Anything on this call container is subjected to tick() processing. */
3177 Velocity.State.calls.push([ call, elements, opts, null, promiseData.resolver ]);
3178
3179 /* If the animation tick isn't running, start it. (Velocity shuts it off when there are no active calls to process.) */
3180 if (Velocity.State.isTicking === false) {
3181 Velocity.State.isTicking = true;
3182
3183 /* Start the tick loop. */
3184 tick();
3185 }
3186 } else {
3187 elementsIndex++;
3188 }
3189 }
3190 }
3191
3192 /* When the queue option is set to false, the call skips the element's queue and fires immediately. */
3193 if (opts.queue === false) {
3194 /* Since this buildQueue call doesn't respect the element's existing queue (which is where a delay option would have been appended),
3195 we manually inject the delay property here with an explicit setTimeout. */
3196 if (opts.delay) {
3197 setTimeout(buildQueue, opts.delay);
3198 } else {
3199 buildQueue();
3200 }
3201 /* Otherwise, the call undergoes element queueing as normal. */
3202 /* Note: To interoperate with jQuery, Velocity uses jQuery's own $.queue() stack for queuing logic. */
3203 } else {
3204 $.queue(element, opts.queue, function(next, clearQueue) {
3205 /* If the clearQueue flag was passed in by the stop command, resolve this call's promise. (Promises can only be resolved once,
3206 so it's fine if this is repeatedly triggered for each element in the associated call.) */
3207 if (clearQueue === true) {
3208 if (promiseData.promise) {
3209 promiseData.resolver(elements);
3210 }
3211
3212 /* Do not continue with animation queueing. */
3213 return true;
3214 }
3215
3216 /* This flag indicates to the upcoming completeCall() function that this queue entry was initiated by Velocity.
3217 See completeCall() for further details. */
3218 Velocity.velocityQueueEntryFlag = true;
3219
3220 buildQueue(next);
3221 });
3222 }
3223
3224 /*********************
3225 Auto-Dequeuing
3226 *********************/
3227
3228 /* As per jQuery's $.queue() behavior, to fire the first non-custom-queue entry on an element, the element
3229 must be dequeued if its queue stack consists *solely* of the current call. (This can be determined by checking
3230 for the "inprogress" item that jQuery prepends to active queue stack arrays.) Regardless, whenever the element's
3231 queue is further appended with additional items -- including $.delay()'s or even $.animate() calls, the queue's
3232 first entry is automatically fired. This behavior contrasts that of custom queues, which never auto-fire. */
3233 /* Note: When an element set is being subjected to a non-parallel Velocity call, the animation will not begin until
3234 each one of the elements in the set has reached the end of its individually pre-existing queue chain. */
3235 /* Note: Unfortunately, most people don't fully grasp jQuery's powerful, yet quirky, $.queue() function.
3236 Lean more here: http://stackoverflow.com/questions/1058158/can-somebody-explain-jquery-queue-to-me */
3237 if ((opts.queue === "" || opts.queue === "fx") && $.queue(element)[0] !== "inprogress") {
3238 $.dequeue(element);
3239 }
3240 }
3241
3242 /**************************
3243 Element Set Iteration
3244 **************************/
3245
3246 /* If the "nodeType" property exists on the elements variable, we're animating a single element.
3247 Place it in an array so that $.each() can iterate over it. */
3248 $.each(elements, function(i, element) {
3249 /* Ensure each element in a set has a nodeType (is a real element) to avoid throwing errors. */
3250 if (Type.isNode(element)) {
3251 processElement.call(element);
3252 }
3253 });
3254
3255 /******************
3256 Option: Loop
3257 ******************/
3258
3259 /* The loop option accepts an integer indicating how many times the element should loop between the values in the
3260 current call's properties map and the element's property values prior to this call. */
3261 /* Note: The loop option's logic is performed here -- after element processing -- because the current call needs
3262 to undergo its queue insertion prior to the loop option generating its series of constituent "reverse" calls,
3263 which chain after the current call. Two reverse calls (two "alternations") constitute one loop. */
3264 var opts = $.extend({}, Velocity.defaults, options),
3265 reverseCallsCount;
3266
3267 opts.loop = parseInt(opts.loop);
3268 reverseCallsCount = (opts.loop * 2) - 1;
3269
3270 if (opts.loop) {
3271 /* Double the loop count to convert it into its appropriate number of "reverse" calls.
3272 Subtract 1 from the resulting value since the current call is included in the total alternation count. */
3273 for (var x = 0; x < reverseCallsCount; x++) {
3274 /* Since the logic for the reverse action occurs inside Queueing and therefore this call's options object
3275 isn't parsed until then as well, the current call's delay option must be explicitly passed into the reverse
3276 call so that the delay logic that occurs inside *Pre-Queueing* can process it. */
3277 var reverseOptions = {
3278 delay: opts.delay,
3279 progress: opts.progress
3280 };
3281
3282 /* If a complete callback was passed into this call, transfer it to the loop redirect's final "reverse" call
3283 so that it's triggered when the entire redirect is complete (and not when the very first animation is complete). */
3284 if (x === reverseCallsCount - 1) {
3285 reverseOptions.display = opts.display;
3286 reverseOptions.visibility = opts.visibility;
3287 reverseOptions.complete = opts.complete;
3288 }
3289
3290 animate(elements, "reverse", reverseOptions);
3291 }
3292 }
3293
3294 /***************
3295 Chaining
3296 ***************/
3297
3298 /* Return the elements back to the call chain, with wrapped elements taking precedence in case Velocity was called via the $.fn. extension. */
3299 return getChain();
3300 };
3301
3302 /* Turn Velocity into the animation function, extended with the pre-existing Velocity object. */
3303 Velocity = $.extend(animate, Velocity);
3304 /* For legacy support, also expose the literal animate method. */
3305 Velocity.animate = animate;
3306
3307 /**************
3308 Timing
3309 **************/
3310
3311 /* Ticker function. */
3312 var ticker = window.requestAnimationFrame || rAFShim;
3313
3314 /* Inactive browser tabs pause rAF, which results in all active animations immediately sprinting to their completion states when the tab refocuses.
3315 To get around this, we dynamically switch rAF to setTimeout (which the browser *doesn't* pause) when the tab loses focus. We skip this for mobile
3316 devices to avoid wasting battery power on inactive tabs. */
3317 /* Note: Tab focus detection doesn't work on older versions of IE, but that's okay since they don't support rAF to begin with. */
3318 if (!Velocity.State.isMobile && document.hidden !== undefined) {
3319 document.addEventListener("visibilitychange", function() {
3320 /* Reassign the rAF function (which the global tick() function uses) based on the tab's focus state. */
3321 if (document.hidden) {
3322 ticker = function(callback) {
3323 /* The tick function needs a truthy first argument in order to pass its internal timestamp check. */
3324 return setTimeout(function() { callback(true) }, 16);
3325 };
3326
3327 /* The rAF loop has been paused by the browser, so we manually restart the tick. */
3328 tick();
3329 } else {
3330 ticker = window.requestAnimationFrame || rAFShim;
3331 }
3332 });
3333 }
3334
3335 /************
3336 Tick
3337 ************/
3338
3339 /* Note: All calls to Velocity are pushed to the Velocity.State.calls array, which is fully iterated through upon each tick. */
3340 function tick (timestamp) {
3341 /* An empty timestamp argument indicates that this is the first tick occurence since ticking was turned on.
3342 We leverage this metadata to fully ignore the first tick pass since RAF's initial pass is fired whenever
3343 the browser's next tick sync time occurs, which results in the first elements subjected to Velocity
3344 calls being animated out of sync with any elements animated immediately thereafter. In short, we ignore
3345 the first RAF tick pass so that elements being immediately consecutively animated -- instead of simultaneously animated
3346 by the same Velocity call -- are properly batched into the same initial RAF tick and consequently remain in sync thereafter. */
3347 if (timestamp) {
3348 /* We ignore RAF's high resolution timestamp since it can be significantly offset when the browser is
3349 under high stress; we opt for choppiness over allowing the browser to drop huge chunks of frames. */
3350 var timeCurrent = (new Date).getTime();
3351
3352 /********************
3353 Call Iteration
3354 ********************/
3355
3356 var callsLength = Velocity.State.calls.length;
3357
3358 /* To speed up iterating over this array, it is compacted (falsey items -- calls that have completed -- are removed)
3359 when its length has ballooned to a point that can impact tick performance. This only becomes necessary when animation
3360 has been continuous with many elements over a long period of time; whenever all active calls are completed, completeCall() clears Velocity.State.calls. */
3361 if (callsLength > 10000) {
3362 Velocity.State.calls = compactSparseArray(Velocity.State.calls);
3363 }
3364
3365 /* Iterate through each active call. */
3366 for (var i = 0; i < callsLength; i++) {
3367 /* When a Velocity call is completed, its Velocity.State.calls entry is set to false. Continue on to the next call. */
3368 if (!Velocity.State.calls[i]) {
3369 continue;
3370 }
3371
3372 /************************
3373 Call-Wide Variables
3374 ************************/
3375
3376 var callContainer = Velocity.State.calls[i],
3377 call = callContainer[0],
3378 opts = callContainer[2],
3379 timeStart = callContainer[3],
3380 firstTick = !!timeStart,
3381 tweenDummyValue = null;
3382
3383 /* If timeStart is undefined, then this is the first time that this call has been processed by tick().
3384 We assign timeStart now so that its value is as close to the real animation start time as possible.
3385 (Conversely, had timeStart been defined when this call was added to Velocity.State.calls, the delay
3386 between that time and now would cause the first few frames of the tween to be skipped since
3387 percentComplete is calculated relative to timeStart.) */
3388 /* Further, subtract 16ms (the approximate resolution of RAF) from the current time value so that the
3389 first tick iteration isn't wasted by animating at 0% tween completion, which would produce the
3390 same style value as the element's current value. */
3391 if (!timeStart) {
3392 timeStart = Velocity.State.calls[i][3] = timeCurrent - 16;
3393 }
3394
3395 /* The tween's completion percentage is relative to the tween's start time, not the tween's start value
3396 (which would result in unpredictable tween durations since JavaScript's timers are not particularly accurate).
3397 Accordingly, we ensure that percentComplete does not exceed 1. */
3398 var percentComplete = Math.min((timeCurrent - timeStart) / opts.duration, 1);
3399
3400 /**********************
3401 Element Iteration
3402 **********************/
3403
3404 /* For every call, iterate through each of the elements in its set. */
3405 for (var j = 0, callLength = call.length; j < callLength; j++) {
3406 var tweensContainer = call[j],
3407 element = tweensContainer.element;
3408
3409 /* Check to see if this element has been deleted midway through the animation by checking for the
3410 continued existence of its data cache. If it's gone, skip animating this element. */
3411 if (!Data(element)) {
3412 continue;
3413 }
3414
3415 var transformPropertyExists = false;
3416
3417 /**********************************
3418 Display & Visibility Toggling
3419 **********************************/
3420
3421 /* If the display option is set to non-"none", set it upfront so that the element can become visible before tweening begins.
3422 (Otherwise, display's "none" value is set in completeCall() once the animation has completed.) */
3423 if (opts.display !== undefined && opts.display !== null && opts.display !== "none") {
3424 if (opts.display === "flex") {
3425 var flexValues = [ "-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex" ];
3426
3427 $.each(flexValues, function(i, flexValue) {
3428 CSS.setPropertyValue(element, "display", flexValue);
3429 });
3430 }
3431
3432 CSS.setPropertyValue(element, "display", opts.display);
3433 }
3434
3435 /* Same goes with the visibility option, but its "none" equivalent is "hidden". */
3436 if (opts.visibility !== undefined && opts.visibility !== "hidden") {
3437 CSS.setPropertyValue(element, "visibility", opts.visibility);
3438 }
3439
3440 /************************
3441 Property Iteration
3442 ************************/
3443
3444 /* For every element, iterate through each property. */
3445 for (var property in tweensContainer) {
3446 /* Note: In addition to property tween data, tweensContainer contains a reference to its associated element. */
3447 if (property !== "element") {
3448 var tween = tweensContainer[property],
3449 currentValue,
3450 /* Easing can either be a pre-genereated function or a string that references a pre-registered easing
3451 on the Velocity.Easings object. In either case, return the appropriate easing *function*. */
3452 easing = Type.isString(tween.easing) ? Velocity.Easings[tween.easing] : tween.easing;
3453
3454 /******************************
3455 Current Value Calculation
3456 ******************************/
3457
3458 /* If this is the last tick pass (if we've reached 100% completion for this tween),
3459 ensure that currentValue is explicitly set to its target endValue so that it's not subjected to any rounding. */
3460 if (percentComplete === 1) {
3461 currentValue = tween.endValue;
3462 /* Otherwise, calculate currentValue based on the current delta from startValue. */
3463 } else {
3464 var tweenDelta = tween.endValue - tween.startValue;
3465 currentValue = tween.startValue + (tweenDelta * easing(percentComplete, opts, tweenDelta));
3466
3467 /* If no value change is occurring, don't proceed with DOM updating. */
3468 if (!firstTick && (currentValue === tween.currentValue)) {
3469 continue;
3470 }
3471 }
3472
3473 tween.currentValue = currentValue;
3474
3475 /* If we're tweening a fake 'tween' property in order to log transition values, update the one-per-call variable so that
3476 it can be passed into the progress callback. */
3477 if (property === "tween") {
3478 tweenDummyValue = currentValue;
3479 } else {
3480 /******************
3481 Hooks: Part I
3482 ******************/
3483
3484 /* For hooked properties, the newly-updated rootPropertyValueCache is cached onto the element so that it can be used
3485 for subsequent hooks in this call that are associated with the same root property. If we didn't cache the updated
3486 rootPropertyValue, each subsequent update to the root property in this tick pass would reset the previous hook's
3487 updates to rootPropertyValue prior to injection. A nice performance byproduct of rootPropertyValue caching is that
3488 subsequently chained animations using the same hookRoot but a different hook can use this cached rootPropertyValue. */
3489 if (CSS.Hooks.registered[property]) {
3490 var hookRoot = CSS.Hooks.getRoot(property),
3491 rootPropertyValueCache = Data(element).rootPropertyValueCache[hookRoot];
3492
3493 if (rootPropertyValueCache) {
3494 tween.rootPropertyValue = rootPropertyValueCache;
3495 }
3496 }
3497
3498 /*****************
3499 DOM Update
3500 *****************/
3501
3502 /* setPropertyValue() returns an array of the property name and property value post any normalization that may have been performed. */
3503 /* Note: To solve an IE<=8 positioning bug, the unit type is dropped when setting a property value of 0. */
3504 var adjustedSetData = CSS.setPropertyValue(element, /* SET */
3505 property,
3506 tween.currentValue + (parseFloat(currentValue) === 0 ? "" : tween.unitType),
3507 tween.rootPropertyValue,
3508 tween.scrollData);
3509
3510 /*******************
3511 Hooks: Part II
3512 *******************/
3513
3514 /* Now that we have the hook's updated rootPropertyValue (the post-processed value provided by adjustedSetData), cache it onto the element. */
3515 if (CSS.Hooks.registered[property]) {
3516 /* Since adjustedSetData contains normalized data ready for DOM updating, the rootPropertyValue needs to be re-extracted from its normalized form. ?? */
3517 if (CSS.Normalizations.registered[hookRoot]) {
3518 Data(element).rootPropertyValueCache[hookRoot] = CSS.Normalizations.registered[hookRoot]("extract", null, adjustedSetData[1]);
3519 } else {
3520 Data(element).rootPropertyValueCache[hookRoot] = adjustedSetData[1];
3521 }
3522 }
3523
3524 /***************
3525 Transforms
3526 ***************/
3527
3528 /* Flag whether a transform property is being animated so that flushTransformCache() can be triggered once this tick pass is complete. */
3529 if (adjustedSetData[0] === "transform") {
3530 transformPropertyExists = true;
3531 }
3532
3533 }
3534 }
3535 }
3536
3537 /****************
3538 mobileHA
3539 ****************/
3540
3541 /* If mobileHA is enabled, set the translate3d transform to null to force hardware acceleration.
3542 It's safe to override this property since Velocity doesn't actually support its animation (hooks are used in its place). */
3543 if (opts.mobileHA) {
3544 /* Don't set the null transform hack if we've already done so. */
3545 if (Data(element).transformCache.translate3d === undefined) {
3546 /* All entries on the transformCache object are later concatenated into a single transform string via flushTransformCache(). */
3547 Data(element).transformCache.translate3d = "(0px, 0px, 0px)";
3548
3549 transformPropertyExists = true;
3550 }
3551 }
3552
3553 if (transformPropertyExists) {
3554 CSS.flushTransformCache(element);
3555 }
3556 }
3557
3558 /* The non-"none" display value is only applied to an element once -- when its associated call is first ticked through.
3559 Accordingly, it's set to false so that it isn't re-processed by this call in the next tick. */
3560 if (opts.display !== undefined && opts.display !== "none") {
3561 Velocity.State.calls[i][2].display = false;
3562 }
3563 if (opts.visibility !== undefined && opts.visibility !== "hidden") {
3564 Velocity.State.calls[i][2].visibility = false;
3565 }
3566
3567 /* Pass the elements and the timing data (percentComplete, msRemaining, timeStart, tweenDummyValue) into the progress callback. */
3568 if (opts.progress) {
3569 opts.progress.call(callContainer[1],
3570 callContainer[1],
3571 percentComplete,
3572 Math.max(0, (timeStart + opts.duration) - timeCurrent),
3573 timeStart,
3574 tweenDummyValue);
3575 }
3576
3577 /* If this call has finished tweening, pass its index to completeCall() to handle call cleanup. */
3578 if (percentComplete === 1) {
3579 completeCall(i);
3580 }
3581 }
3582 }
3583
3584 /* Note: completeCall() sets the isTicking flag to false when the last call on Velocity.State.calls has completed. */
3585 if (Velocity.State.isTicking) {
3586 ticker(tick);
3587 }
3588 }
3589
3590 /**********************
3591 Call Completion
3592 **********************/
3593
3594 /* Note: Unlike tick(), which processes all active calls at once, call completion is handled on a per-call basis. */
3595 function completeCall (callIndex, isStopped) {
3596 /* Ensure the call exists. */
3597 if (!Velocity.State.calls[callIndex]) {
3598 return false;
3599 }
3600
3601 /* Pull the metadata from the call. */
3602 var call = Velocity.State.calls[callIndex][0],
3603 elements = Velocity.State.calls[callIndex][1],
3604 opts = Velocity.State.calls[callIndex][2],
3605 resolver = Velocity.State.calls[callIndex][4];
3606
3607 var remainingCallsExist = false;
3608
3609 /*************************
3610 Element Finalization
3611 *************************/
3612
3613 for (var i = 0, callLength = call.length; i < callLength; i++) {
3614 var element = call[i].element;
3615
3616 /* If the user set display to "none" (intending to hide the element), set it now that the animation has completed. */
3617 /* Note: display:none isn't set when calls are manually stopped (via Velocity("stop"). */
3618 /* Note: Display gets ignored with "reverse" calls and infinite loops, since this behavior would be undesirable. */
3619 if (!isStopped && !opts.loop) {
3620 if (opts.display === "none") {
3621 CSS.setPropertyValue(element, "display", opts.display);
3622 }
3623
3624 if (opts.visibility === "hidden") {
3625 CSS.setPropertyValue(element, "visibility", opts.visibility);
3626 }
3627 }
3628
3629 /* If the element's queue is empty (if only the "inprogress" item is left at position 0) or if its queue is about to run
3630 a non-Velocity-initiated entry, turn off the isAnimating flag. A non-Velocity-initiatied queue entry's logic might alter
3631 an element's CSS values and thereby cause Velocity's cached value data to go stale. To detect if a queue entry was initiated by Velocity,
3632 we check for the existence of our special Velocity.queueEntryFlag declaration, which minifiers won't rename since the flag
3633 is assigned to jQuery's global $ object and thus exists out of Velocity's own scope. */
3634 if (opts.loop !== true && ($.queue(element)[1] === undefined || !/\.velocityQueueEntryFlag/i.test($.queue(element)[1]))) {
3635 /* The element may have been deleted. Ensure that its data cache still exists before acting on it. */
3636 if (Data(element)) {
3637 Data(element).isAnimating = false;
3638 /* Clear the element's rootPropertyValueCache, which will become stale. */
3639 Data(element).rootPropertyValueCache = {};
3640
3641 var transformHAPropertyExists = false;
3642 /* If any 3D transform subproperty is at its default value (regardless of unit type), remove it. */
3643 $.each(CSS.Lists.transforms3D, function(i, transformName) {
3644 var defaultValue = /^scale/.test(transformName) ? 1 : 0,
3645 currentValue = Data(element).transformCache[transformName];
3646
3647 if (Data(element).transformCache[transformName] !== undefined && new RegExp("^\\(" + defaultValue + "[^.]").test(currentValue)) {
3648 transformHAPropertyExists = true;
3649
3650 delete Data(element).transformCache[transformName];
3651 }
3652 });
3653
3654 /* Mobile devices have hardware acceleration removed at the end of the animation in order to avoid hogging the GPU's memory. */
3655 if (opts.mobileHA) {
3656 transformHAPropertyExists = true;
3657 delete Data(element).transformCache.translate3d;
3658 }
3659
3660 /* Flush the subproperty removals to the DOM. */
3661 if (transformHAPropertyExists) {
3662 CSS.flushTransformCache(element);
3663 }
3664
3665 /* Remove the "velocity-animating" indicator class. */
3666 CSS.Values.removeClass(element, "velocity-animating");
3667 }
3668 }
3669
3670 /*********************
3671 Option: Complete
3672 *********************/
3673
3674 /* Complete is fired once per call (not once per element) and is passed the full raw DOM element set as both its context and its first argument. */
3675 /* Note: Callbacks aren't fired when calls are manually stopped (via Velocity("stop"). */
3676 if (!isStopped && opts.complete && !opts.loop && (i === callLength - 1)) {
3677 /* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */
3678 try {
3679 opts.complete.call(elements, elements);
3680 } catch (error) {
3681 setTimeout(function() { throw error; }, 1);
3682 }
3683 }
3684
3685 /**********************
3686 Promise Resolving
3687 **********************/
3688
3689 /* Note: Infinite loops don't return promises. */
3690 if (resolver && opts.loop !== true) {
3691 resolver(elements);
3692 }
3693
3694 /****************************
3695 Option: Loop (Infinite)
3696 ****************************/
3697
3698 if (Data(element) && opts.loop === true && !isStopped) {
3699 /* If a rotateX/Y/Z property is being animated to 360 deg with loop:true, swap tween start/end values to enable
3700 continuous iterative rotation looping. (Otherise, the element would just rotate back and forth.) */
3701 $.each(Data(element).tweensContainer, function(propertyName, tweenContainer) {
3702 if (/^rotate/.test(propertyName) && parseFloat(tweenContainer.endValue) === 360) {
3703 tweenContainer.endValue = 0;
3704 tweenContainer.startValue = 360;
3705 }
3706
3707 if (/^backgroundPosition/.test(propertyName) && parseFloat(tweenContainer.endValue) === 100 && tweenContainer.unitType === "%") {
3708 tweenContainer.endValue = 0;
3709 tweenContainer.startValue = 100;
3710 }
3711 });
3712
3713 Velocity(element, "reverse", { loop: true, delay: opts.delay });
3714 }
3715
3716 /***************
3717 Dequeueing
3718 ***************/
3719
3720 /* Fire the next call in the queue so long as this call's queue wasn't set to false (to trigger a parallel animation),
3721 which would have already caused the next call to fire. Note: Even if the end of the animation queue has been reached,
3722 $.dequeue() must still be called in order to completely clear jQuery's animation queue. */
3723 if (opts.queue !== false) {
3724 $.dequeue(element, opts.queue);
3725 }
3726 }
3727
3728 /************************
3729 Calls Array Cleanup
3730 ************************/
3731
3732 /* Since this call is complete, set it to false so that the rAF tick skips it. This array is later compacted via compactSparseArray().
3733 (For performance reasons, the call is set to false instead of being deleted from the array: http://www.html5rocks.com/en/tutorials/speed/v8/) */
3734 Velocity.State.calls[callIndex] = false;
3735
3736 /* Iterate through the calls array to determine if this was the final in-progress animation.
3737 If so, set a flag to end ticking and clear the calls array. */
3738 for (var j = 0, callsLength = Velocity.State.calls.length; j < callsLength; j++) {
3739 if (Velocity.State.calls[j] !== false) {
3740 remainingCallsExist = true;
3741
3742 break;
3743 }
3744 }
3745
3746 if (remainingCallsExist === false) {
3747 /* tick() will detect this flag upon its next iteration and subsequently turn itself off. */
3748 Velocity.State.isTicking = false;
3749
3750 /* Clear the calls array so that its length is reset. */
3751 delete Velocity.State.calls;
3752 Velocity.State.calls = [];
3753 }
3754 }
3755
3756 /******************
3757 Frameworks
3758 ******************/
3759
3760 /* Both jQuery and Zepto allow their $.fn object to be extended to allow wrapped elements to be subjected to plugin calls.
3761 If either framework is loaded, register a "velocity" extension pointing to Velocity's core animate() method. Velocity
3762 also registers itself onto a global container (window.jQuery || window.Zepto || window) so that certain features are
3763 accessible beyond just a per-element scope. This master object contains an .animate() method, which is later assigned to $.fn
3764 (if jQuery or Zepto are present). Accordingly, Velocity can both act on wrapped DOM elements and stand alone for targeting raw DOM elements. */
3765 global.Velocity = Velocity;
3766
3767 if (global !== window) {
3768 /* Assign the element function to Velocity's core animate() method. */
3769 global.fn.velocity = animate;
3770 /* Assign the object function's defaults to Velocity's global defaults object. */
3771 global.fn.velocity.defaults = Velocity.defaults;
3772 }
3773
3774 /***********************
3775 Packaged Redirects
3776 ***********************/
3777
3778 /* slideUp, slideDown */
3779 $.each([ "Down", "Up" ], function(i, direction) {
3780 Velocity.Redirects["slide" + direction] = function (element, options, elementsIndex, elementsSize, elements, promiseData) {
3781 var opts = $.extend({}, options),
3782 begin = opts.begin,
3783 complete = opts.complete,
3784 computedValues = { height: "", marginTop: "", marginBottom: "", paddingTop: "", paddingBottom: "" },
3785 inlineValues = {};
3786
3787 if (opts.display === undefined) {
3788 /* Show the element before slideDown begins and hide the element after slideUp completes. */
3789 /* Note: Inline elements cannot have dimensions animated, so they're reverted to inline-block. */
3790 opts.display = (direction === "Down" ? (Velocity.CSS.Values.getDisplayType(element) === "inline" ? "inline-block" : "block") : "none");
3791 }
3792
3793 opts.begin = function() {
3794 /* If the user passed in a begin callback, fire it now. */
3795 begin && begin.call(elements, elements);
3796
3797 /* Cache the elements' original vertical dimensional property values so that we can animate back to them. */
3798 for (var property in computedValues) {
3799 inlineValues[property] = element.style[property];
3800
3801 /* For slideDown, use forcefeeding to animate all vertical properties from 0. For slideUp,
3802 use forcefeeding to start from computed values and animate down to 0. */
3803 var propertyValue = Velocity.CSS.getPropertyValue(element, property);
3804 computedValues[property] = (direction === "Down") ? [ propertyValue, 0 ] : [ 0, propertyValue ];
3805 }
3806
3807 /* Force vertical overflow content to clip so that sliding works as expected. */
3808 inlineValues.overflow = element.style.overflow;
3809 element.style.overflow = "hidden";
3810 }
3811
3812 opts.complete = function() {
3813 /* Reset element to its pre-slide inline values once its slide animation is complete. */
3814 for (var property in inlineValues) {
3815 element.style[property] = inlineValues[property];
3816 }
3817
3818 /* If the user passed in a complete callback, fire it now. */
3819 complete && complete.call(elements, elements);
3820 promiseData && promiseData.resolver(elements);
3821 };
3822
3823 Velocity(element, computedValues, opts);
3824 };
3825 });
3826
3827 /* fadeIn, fadeOut */
3828 $.each([ "In", "Out" ], function(i, direction) {
3829 Velocity.Redirects["fade" + direction] = function (element, options, elementsIndex, elementsSize, elements, promiseData) {
3830 var opts = $.extend({}, options),
3831 propertiesMap = { opacity: (direction === "In") ? 1 : 0 },
3832 originalComplete = opts.complete;
3833
3834 /* Since redirects are triggered individually for each element in the animated set, avoid repeatedly triggering
3835 callbacks by firing them only when the final element has been reached. */
3836 if (elementsIndex !== elementsSize - 1) {
3837 opts.complete = opts.begin = null;
3838 } else {
3839 opts.complete = function() {
3840 if (originalComplete) {
3841 originalComplete.call(elements, elements);
3842 }
3843
3844 promiseData && promiseData.resolver(elements);
3845 }
3846 }
3847
3848 /* If a display was passed in, use it. Otherwise, default to "none" for fadeOut or the element-specific default for fadeIn. */
3849 /* Note: We allow users to pass in "null" to skip display setting altogether. */
3850 if (opts.display === undefined) {
3851 opts.display = (direction === "In" ? "auto" : "none");
3852 }
3853
3854 Velocity(this, propertiesMap, opts);
3855 };
3856 });
3857
3858 return Velocity;
3859}((window.jQuery || window.Zepto || window), window, document);
3860}));
3861
3862/******************
3863 Known Issues
3864******************/
3865
3866/* The CSS spec mandates that the translateX/Y/Z transforms are %-relative to the element itself -- not its parent.
3867Velocity, however, doesn't make this distinction. Thus, converting to or from the % unit with these subproperties
3868will produce an inaccurate conversion value. The same issue exists with the cx/cy attributes of SVG circles and ellipses. */
\No newline at end of file