-
Notifications
You must be signed in to change notification settings - Fork 2
/
velocity.js
executable file
·3868 lines (3240 loc) · 213 KB
/
velocity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! VelocityJS.org (1.2.2). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
/*************************
Velocity jQuery Shim
*************************/
/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
/* 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. */
/* These shimmed functions are only used if jQuery isn't present. If both this shim and jQuery are loaded, Velocity defaults to jQuery proper. */
/* Browser support: Using this shim instead of jQuery proper removes support for IE8. */
;(function (window) {
/***************
Setup
***************/
/* If jQuery is already loaded, there's no point in loading this shim. */
if (window.jQuery) {
return;
}
/* jQuery base. */
var $ = function (selector, context) {
return new $.fn.init(selector, context);
};
/********************
Private Methods
********************/
/* jQuery */
$.isWindow = function (obj) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
};
/* jQuery */
$.type = function (obj) {
if (obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[toString.call(obj)] || "object" :
typeof obj;
};
/* jQuery */
$.isArray = Array.isArray || function (obj) {
return $.type(obj) === "array";
};
/* jQuery */
function isArraylike (obj) {
var length = obj.length,
type = $.type(obj);
if (type === "function" || $.isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && length) {
return true;
}
return type === "array" || length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj;
}
/***************
$ Methods
***************/
/* jQuery: Support removed for IE<9. */
$.isPlainObject = function (obj) {
var key;
if (!obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow(obj)) {
return false;
}
try {
if (obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
return false;
}
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
/* jQuery */
$.each = function(obj, callback, args) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
}
} else {
if (isArray) {
for (; i < length; i++) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
}
}
return obj;
};
/* Custom */
$.data = function (node, key, value) {
/* $.getData() */
if (value === undefined) {
var id = node[$.expando],
store = id && cache[id];
if (key === undefined) {
return store;
} else if (store) {
if (key in store) {
return store[key];
}
}
/* $.setData() */
} else if (key !== undefined) {
var id = node[$.expando] || (node[$.expando] = ++$.uuid);
cache[id] = cache[id] || {};
cache[id][key] = value;
return value;
}
};
/* Custom */
$.removeData = function (node, keys) {
var id = node[$.expando],
store = id && cache[id];
if (store) {
$.each(keys, function(_, key) {
delete store[key];
});
}
};
/* jQuery */
$.extend = function () {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if (typeof target === "boolean") {
deep = target;
target = arguments[i] || {};
i++;
}
if (typeof target !== "object" && $.type(target) !== "function") {
target = {};
}
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue;
}
if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && $.isArray(src) ? src : [];
} else {
clone = src && $.isPlainObject(src) ? src : {};
}
target[name] = $.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
/* jQuery 1.4.3 */
$.queue = function (elem, type, data) {
function $makeArray (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
/* $.merge */
(function(first, second) {
var len = +second.length,
j = 0,
i = first.length;
while (j < len) {
first[i++] = second[j++];
}
if (len !== len) {
while (second[j] !== undefined) {
first[i++] = second[j++];
}
}
first.length = i;
return first;
})(ret, typeof arr === "string" ? [arr] : arr);
} else {
[].push.call(ret, arr);
}
}
return ret;
}
if (!elem) {
return;
}
type = (type || "fx") + "queue";
var q = $.data(elem, type);
if (!data) {
return q || [];
}
if (!q || $.isArray(data)) {
q = $.data(elem, type, $makeArray(data));
} else {
q.push(data);
}
return q;
};
/* jQuery 1.4.3 */
$.dequeue = function (elems, type) {
/* Custom: Embed element iteration. */
$.each(elems.nodeType ? [ elems ] : elems, function(i, elem) {
type = type || "fx";
var queue = $.queue(elem, type),
fn = queue.shift();
if (fn === "inprogress") {
fn = queue.shift();
}
if (fn) {
if (type === "fx") {
queue.unshift("inprogress");
}
fn.call(elem, function() {
$.dequeue(elem, type);
});
}
});
};
/******************
$.fn Methods
******************/
/* jQuery */
$.fn = $.prototype = {
init: function (selector) {
/* Just return the element wrapped inside an array; don't proceed with the actual jQuery node wrapping process. */
if (selector.nodeType) {
this[0] = selector;
return this;
} else {
throw new Error("Not a DOM node.");
}
},
offset: function () {
/* jQuery altered code: Dropped disconnected DOM node checking. */
var box = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : { top: 0, left: 0 };
return {
top: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),
left: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)
};
},
position: function () {
/* jQuery */
function offsetParent() {
var offsetParent = this.offsetParent || document;
while (offsetParent && (!offsetParent.nodeType.toLowerCase === "html" && offsetParent.style.position === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document;
}
/* Zepto */
var elem = this[0],
offsetParent = offsetParent.apply(elem),
offset = this.offset(),
parentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? { top: 0, left: 0 } : $(offsetParent).offset()
offset.top -= parseFloat(elem.style.marginTop) || 0;
offset.left -= parseFloat(elem.style.marginLeft) || 0;
if (offsetParent.style) {
parentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0
parentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0
}
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
};
/**********************
Private Variables
**********************/
/* For $.data() */
var cache = {};
$.expando = "velocity" + (new Date().getTime());
$.uuid = 0;
/* For $.queue() */
var class2type = {},
hasOwn = class2type.hasOwnProperty,
toString = class2type.toString;
var types = "Boolean Number String Function Array Date RegExp Object Error".split(" ");
for (var i = 0; i < types.length; i++) {
class2type["[object " + types[i] + "]"] = types[i].toLowerCase();
}
/* Makes $(node) possible, without having to call init. */
$.fn.init.prototype = $.fn;
/* Globalize Velocity onto the window, and assign its Utilities property. */
window.Velocity = { Utilities: $ };
})(window);
/******************
Velocity.js
******************/
;(function (factory) {
/* CommonJS module. */
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory();
/* AMD module. */
} else if (typeof define === "function" && define.amd) {
define(factory);
/* Browser globals. */
} else {
factory();
}
}(function() {
return function (global, window, document, undefined) {
/***************
Summary
***************/
/*
- CSS: CSS stack that works independently from the rest of Velocity.
- animate(): Core animation method that iterates over the targeted elements and queues the incoming call onto each element individually.
- Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options.
- Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack.
Most logic is placed here to avoid risking it becoming stale (if the element's properties have changed).
- Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
- tick(): The single requestAnimationFrame loop responsible for tweening all in-progress calls.
- completeCall(): Handles the cleanup process for each Velocity call.
*/
/*********************
Helper Functions
*********************/
/* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 4; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
div = null;
return i;
}
}
}
return undefined;
})();
/* rAF shim. Gist: https://gist.github.com/julianshapiro/9497513 */
var rAFShim = (function() {
var timeLast = 0;
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
var timeCurrent = (new Date()).getTime(),
timeDelta;
/* Dynamically set delay on a per-tick basis to match 60fps. */
/* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */
timeDelta = Math.max(0, 16 - (timeCurrent - timeLast));
timeLast = timeCurrent + timeDelta;
return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta);
};
})();
/* Array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */
function compactSparseArray (array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
function sanitizeElements (elements) {
/* Unwrap jQuery/Zepto objects. */
if (Type.isWrapped(elements)) {
elements = [].slice.call(elements);
/* Wrap a single element in an array so that $.each() can iterate with the element instead of its node's children. */
} else if (Type.isNode(elements)) {
elements = [ elements ];
}
return elements;
}
var Type = {
isString: function (variable) {
return (typeof variable === "string");
},
isArray: Array.isArray || function (variable) {
return Object.prototype.toString.call(variable) === "[object Array]";
},
isFunction: function (variable) {
return Object.prototype.toString.call(variable) === "[object Function]";
},
isNode: function (variable) {
return variable && variable.nodeType;
},
/* Copyright Martin Bohm. MIT License: https://gist.github.com/Tomalak/818a78a226a0738eaade */
isNodeList: function (variable) {
return typeof variable === "object" &&
/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(variable)) &&
variable.length !== undefined &&
(variable.length === 0 || (typeof variable[0] === "object" && variable[0].nodeType > 0));
},
/* Determine if variable is a wrapped jQuery or Zepto element. */
isWrapped: function (variable) {
return variable && (variable.jquery || (window.Zepto && window.Zepto.zepto.isZ(variable)));
},
isSVG: function (variable) {
return window.SVGElement && (variable instanceof window.SVGElement);
},
isEmptyObject: function (variable) {
for (var name in variable) {
return false;
}
return true;
}
};
/*****************
Dependencies
*****************/
var $,
isJQuery = false;
if (global.fn && global.fn.jquery) {
$ = global;
isJQuery = true;
} else {
$ = window.Velocity.Utilities;
}
if (IE <= 8 && !isJQuery) {
throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");
} else if (IE <= 7) {
/* Revert to jQuery's $.animate(), and lose Velocity's extra features. */
jQuery.fn.velocity = jQuery.fn.animate;
/* Now that $.fn.velocity is aliased, abort this Velocity declaration. */
return;
}
/*****************
Constants
*****************/
var DURATION_DEFAULT = 400,
EASING_DEFAULT = "swing";
/*************
State
*************/
var Velocity = {
/* Container for page-wide Velocity state data. */
State: {
/* Detect mobile devices to determine if mobileHA should be turned on. */
isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
/* The mobileHA option's behavior changes on older Android devices (Gingerbread, versions 2.3.3-2.3.7). */
isAndroid: /Android/i.test(navigator.userAgent),
isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent),
isChrome: window.chrome,
isFirefox: /Firefox/i.test(navigator.userAgent),
/* Create a cached element for re-use when checking for CSS property prefixes. */
prefixElement: document.createElement("div"),
/* Cache every prefix match to avoid repeating lookups. */
prefixMatches: {},
/* Cache the anchor used for animating window scrolling. */
scrollAnchor: null,
/* Cache the browser-specific property names associated with the scroll anchor. */
scrollPropertyLeft: null,
scrollPropertyTop: null,
/* Keep track of whether our RAF tick is running. */
isTicking: false,
/* Container for every in-progress call to Velocity. */
calls: []
},
/* Velocity's custom CSS stack. Made global for unit testing. */
CSS: { /* Defined below. */ },
/* A shim of the jQuery utility functions used by Velocity -- provided by Velocity's optional jQuery shim. */
Utilities: $,
/* Container for the user's custom animation redirects that are referenced by name in place of the properties map argument. */
Redirects: { /* Manually registered by the user. */ },
Easings: { /* Defined below. */ },
/* Attempt to use ES6 Promises by default. Users can override this with a third-party promises library. */
Promise: window.Promise,
/* Velocity option defaults, which can be overriden by the user. */
defaults: {
queue: "",
duration: DURATION_DEFAULT,
easing: EASING_DEFAULT,
begin: undefined,
complete: undefined,
progress: undefined,
display: undefined,
visibility: undefined,
loop: false,
delay: false,
mobileHA: true,
/* Advanced: Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */
_cacheValues: true
},
/* A design goal of Velocity is to cache data wherever possible in order to avoid DOM requerying. Accordingly, each element has a data cache. */
init: function (element) {
$.data(element, "velocity", {
/* Store whether this is an SVG element, since its properties are retrieved and updated differently than standard HTML elements. */
isSVG: Type.isSVG(element),
/* Keep track of whether the element is currently being animated by Velocity.
This is used to ensure that property values are not transferred between non-consecutive (stale) calls. */
isAnimating: false,
/* A reference to the element's live computedStyle object. Learn more here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */
computedStyle: null,
/* Tween data is cached for each animation on the element so that data can be passed across calls --
in particular, end values are used as subsequent start values in consecutive Velocity calls. */
tweensContainer: null,
/* The full root property values of each CSS hook being animated on this element are cached so that:
1) Concurrently-animating hooks sharing the same root can have their root values' merged into one while tweening.
2) Post-hook-injection root values can be transferred over to consecutively chained Velocity calls as starting root values. */
rootPropertyValueCache: {},
/* A cache for transform updates, which must be manually flushed via CSS.flushTransformCache(). */
transformCache: {}
});
},
/* A parallel to jQuery's $.css(), used for getting/setting Velocity's hooked CSS properties. */
hook: null, /* Defined below. */
/* Velocity-wide animation time remapping for testing purposes. */
mock: false,
version: { major: 1, minor: 2, patch: 2 },
/* Set to 1 or 2 (most verbose) to output debug info to console. */
debug: false
};
/* Retrieve the appropriate scroll anchor and property name for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */
if (window.pageYOffset !== undefined) {
Velocity.State.scrollAnchor = window;
Velocity.State.scrollPropertyLeft = "pageXOffset";
Velocity.State.scrollPropertyTop = "pageYOffset";
} else {
Velocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body;
Velocity.State.scrollPropertyLeft = "scrollLeft";
Velocity.State.scrollPropertyTop = "scrollTop";
}
/* Shorthand alias for jQuery's $.data() utility. */
function Data (element) {
/* Hardcode a reference to the plugin name. */
var response = $.data(element, "velocity");
/* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */
return response === null ? undefined : response;
};
/**************
Easing
**************/
/* Step easing generator. */
function generateStep (steps) {
return function (p) {
return Math.round(p * steps) * (1 / steps);
};
}
/* Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
function generateBezier (mX1, mY1, mX2, mY2) {
var NEWTON_ITERATIONS = 4,
NEWTON_MIN_SLOPE = 0.001,
SUBDIVISION_PRECISION = 0.0000001,
SUBDIVISION_MAX_ITERATIONS = 10,
kSplineTableSize = 11,
kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
float32ArraySupported = "Float32Array" in window;
/* Must contain four arguments. */
if (arguments.length !== 4) {
return false;
}
/* Arguments must be numbers. */
for (var i = 0; i < 4; ++i) {
if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
return false;
}
}
/* X values must be in the [0, 1] range. */
mX1 = Math.min(mX1, 1);
mX2 = Math.min(mX2, 1);
mX1 = Math.max(mX1, 0);
mX2 = Math.max(mX2, 0);
var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
function C (aA1) { return 3.0 * aA1; }
function calcBezier (aT, aA1, aA2) {
return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT;
}
function getSlope (aT, aA1, aA2) {
return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function newtonRaphsonIterate (aX, aGuessT) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) return aGuessT;
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function calcSampleValues () {
for (var i = 0; i < kSplineTableSize; ++i) {
mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function binarySubdivide (aX, aA, aB) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function getTForX (aX) {
var intervalStart = 0.0,
currentSample = 1,
lastSample = kSplineTableSize - 1;
for (; currentSample != lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample+1] - mSampleValues[currentSample]),
guessForT = intervalStart + dist * kSampleStepSize,
initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT);
} else if (initialSlope == 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
}
}
var _precomputed = false;
function precompute() {
_precomputed = true;
if (mX1 != mY1 || mX2 != mY2) calcSampleValues();
}
var f = function (aX) {
if (!_precomputed) precompute();
if (mX1 === mY1 && mX2 === mY2) return aX;
if (aX === 0) return 0;
if (aX === 1) return 1;
return calcBezier(getTForX(aX), mY1, mY2);
};
f.getControlPoints = function() { return [{ x: mX1, y: mY1 }, { x: mX2, y: mY2 }]; };
var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
f.toString = function () { return str; };
return f;
}
/* Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
/* 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
then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
var generateSpringRK4 = (function () {
function springAccelerationForState (state) {
return (-state.tension * state.x) - (state.friction * state.v);
}
function springEvaluateStateWithDerivative (initialState, dt, derivative) {
var state = {
x: initialState.x + derivative.dx * dt,
v: initialState.v + derivative.dv * dt,
tension: initialState.tension,
friction: initialState.friction
};
return { dx: state.v, dv: springAccelerationForState(state) };
}
function springIntegrateState (state, dt) {
var a = {
dx: state.v,
dv: springAccelerationForState(state)
},
b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
d = springEvaluateStateWithDerivative(state, dt, c),
dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
state.x = state.x + dxdt * dt;
state.v = state.v + dvdt * dt;
return state;
}
return function springRK4Factory (tension, friction, duration) {
var initState = {
x: -1,
v: 0,
tension: null,
friction: null
},
path = [0],
time_lapsed = 0,
tolerance = 1 / 10000,
DT = 16 / 1000,
have_duration, dt, last_state;
tension = parseFloat(tension) || 500;
friction = parseFloat(friction) || 20;
duration = duration || null;
initState.tension = tension;
initState.friction = friction;
have_duration = duration !== null;
/* Calculate the actual time it takes for this animation to complete with the provided conditions. */
if (have_duration) {
/* Run the simulation without a duration. */
time_lapsed = springRK4Factory(tension, friction);
/* Compute the adjusted time delta. */
dt = time_lapsed / duration * DT;
} else {
dt = DT;
}
while (true) {
/* Next/step function .*/
last_state = springIntegrateState(last_state || initState, dt);
/* Store the position. */
path.push(1 + last_state.x);
time_lapsed += 16;
/* If the change threshold is reached, break. */
if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
break;
}
}
/* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
computed path and returns a snapshot of the position according to a given percentComplete. */
return !have_duration ? time_lapsed : function(percentComplete) { return path[ (percentComplete * (path.length - 1)) | 0 ]; };
};
}());
/* jQuery easings. */
Velocity.Easings = {
linear: function(p) { return p; },
swing: function(p) { return 0.5 - Math.cos( p * Math.PI ) / 2 },
/* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */
spring: function(p) { return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6)); }
};
/* CSS3 and Robert Penner easings. */
$.each(
[
[ "ease", [ 0.25, 0.1, 0.25, 1.0 ] ],
[ "ease-in", [ 0.42, 0.0, 1.00, 1.0 ] ],
[ "ease-out", [ 0.00, 0.0, 0.58, 1.0 ] ],
[ "ease-in-out", [ 0.42, 0.0, 0.58, 1.0 ] ],
[ "easeInSine", [ 0.47, 0, 0.745, 0.715 ] ],
[ "easeOutSine", [ 0.39, 0.575, 0.565, 1 ] ],
[ "easeInOutSine", [ 0.445, 0.05, 0.55, 0.95 ] ],
[ "easeInQuad", [ 0.55, 0.085, 0.68, 0.53 ] ],
[ "easeOutQuad", [ 0.25, 0.46, 0.45, 0.94 ] ],
[ "easeInOutQuad", [ 0.455, 0.03, 0.515, 0.955 ] ],
[ "easeInCubic", [ 0.55, 0.055, 0.675, 0.19 ] ],
[ "easeOutCubic", [ 0.215, 0.61, 0.355, 1 ] ],
[ "easeInOutCubic", [ 0.645, 0.045, 0.355, 1 ] ],
[ "easeInQuart", [ 0.895, 0.03, 0.685, 0.22 ] ],
[ "easeOutQuart", [ 0.165, 0.84, 0.44, 1 ] ],
[ "easeInOutQuart", [ 0.77, 0, 0.175, 1 ] ],
[ "easeInQuint", [ 0.755, 0.05, 0.855, 0.06 ] ],
[ "easeOutQuint", [ 0.23, 1, 0.32, 1 ] ],
[ "easeInOutQuint", [ 0.86, 0, 0.07, 1 ] ],
[ "easeInExpo", [ 0.95, 0.05, 0.795, 0.035 ] ],
[ "easeOutExpo", [ 0.19, 1, 0.22, 1 ] ],
[ "easeInOutExpo", [ 1, 0, 0, 1 ] ],
[ "easeInCirc", [ 0.6, 0.04, 0.98, 0.335 ] ],
[ "easeOutCirc", [ 0.075, 0.82, 0.165, 1 ] ],
[ "easeInOutCirc", [ 0.785, 0.135, 0.15, 0.86 ] ]
], function(i, easingArray) {
Velocity.Easings[easingArray[0]] = generateBezier.apply(null, easingArray[1]);
});
/* Determine the appropriate easing type given an easing input. */
function getEasing(value, duration) {
var easing = value;
/* The easing option can either be a string that references a pre-registered easing,
or it can be a two-/four-item array of integers to be converted into a bezier/spring function. */
if (Type.isString(value)) {
/* Ensure that the easing has been assigned to jQuery's Velocity.Easings object. */
if (!Velocity.Easings[value]) {
easing = false;
}
} else if (Type.isArray(value) && value.length === 1) {
easing = generateStep.apply(null, value);
} else if (Type.isArray(value) && value.length === 2) {
/* springRK4 must be passed the animation's duration. */
/* Note: If the springRK4 array contains non-numbers, generateSpringRK4() returns an easing
function generated with default tension and friction values. */
easing = generateSpringRK4.apply(null, value.concat([ duration ]));
} else if (Type.isArray(value) && value.length === 4) {
/* Note: If the bezier array contains non-numbers, generateBezier() returns false. */
easing = generateBezier.apply(null, value);
} else {
easing = false;
}
/* Revert to the Velocity-wide default easing type, or fall back to "swing" (which is also jQuery's default)
if the Velocity-wide default has been incorrectly modified. */
if (easing === false) {
if (Velocity.Easings[Velocity.defaults.easing]) {
easing = Velocity.defaults.easing;
} else {
easing = EASING_DEFAULT;
}
}
return easing;
}
/*****************
CSS Stack
*****************/
/* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's.
It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */
/* Note: A "CSS" shorthand is aliased so that our code is easier to read. */
var CSS = Velocity.CSS = {
/*************
RegEx
*************/
RegEx: {
isHex: /^#([A-f\d]{3}){1,2}$/i,
/* Unwrap a property value's surrounding text, e.g. "rgba(4, 3, 2, 1)" ==> "4, 3, 2, 1" and "rect(4px 3px 2px 1px)" ==> "4px 3px 2px 1px". */
valueUnwrap: /^[A-z]+\((.*)\)$/i,
wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
/* Split a multi-value property into an array of subvalues, e.g. "rgba(4, 3, 2, 1) 4px 3px 2px 1px" ==> [ "rgba(4, 3, 2, 1)", "4px", "3px", "2px", "1px" ]. */
valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig
},