forked from julianshapiro/velocity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.velocity.js
3203 lines (2706 loc) · 188 KB
/
jquery.velocity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************
Details
***************/
/*!
* Velocity.js: Accelerated JavaScript animation.
* @version 0.4.1
* @docs http://velocityjs.org
* @license Copyright 2014 Julian Shapiro. MIT License: http://en.wikipedia.org/wiki/MIT_License
*/
/****************
Summary
****************/
/*
Velocity's structure:
- CSS Stack: Works independently from the rest of Velocity.
- Velocity.animate(): Core method that iterates over the targeted elements and queues the incoming call onto each element individually. Consists of:
- 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.
*/
/* NOTICE: Despite the ensuing code indicating that Velocity works *without* jQuery and *with* Zepto, this support has not yet landed. */
/******************
Velocity.js
******************/
;(function (global, window, document, undefined) {
/*****************
Constants
*****************/
var NAME = "velocity",
DEFAULT_DURATION = 400,
DEFAULT_EASING = "swing";
/*********************
Helper Functions
*********************/
/* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 4; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
div = null;
return i;
}
}
}
return undefined;
})();
/* RAF polyfill. Gist: https://gist.github.com/julianshapiro/9497513 */
var requestAnimationFrame = window.requestAnimationFrame || (function() {
var timeLast = 0;
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
var timeCurrent = (new Date()).getTime(),
timeDelta;
/* Dynamically set delay on a per-tick basis to match 60fps. */
/* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */
timeDelta = Math.max(0, 16 - (timeCurrent - timeLast));
timeLast = timeCurrent + timeDelta;
return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta);
};
})();
/* 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;
}
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]";
},
/* 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 SVGElement);
}
};
/*****************
Dependencies
*****************/
/* Local to our Velocity scope, assign $ to our jQuery shim if jQuery itself isn't loaded.
(The shim is a port of the jQuery utility functions that Velocity uses.) */
/* Note: We can't default to Zepto since the shimless version of Velocity does not work with Zepto,
which is missing several utility functions that Velocity requires. */
var $ = window.jQuery || (global.Velocity && global.Velocity.Utilities);
if (!$) {
throw new Error("Velocity: Either jQuery or Velocity's jQuery shim must first be loaded.")
/* We allow the global Velocity variable to pre-exist so long as we were responsible for its creation
(via the jQuery shim, which uniquely assigns a Utilities property to the Velocity object). */
} else if (global.Velocity !== undefined && !global.Velocity.Utilities) {
throw new Error("Velocity: Namespace is occupied.");
/* Nothing prevents Velocity from working on IE6+7, but it is not worth the time to test on them.
Revert to jQuery's $.animate(), and lose Velocity's extra features. */
} else if (IE <= 7) {
if (!window.jQuery) {
throw new Error("Velocity: For IE<=7, Velocity falls back to jQuery, which must first be loaded.");
} else {
window.jQuery.fn.velocity = window.jQuery.fn.animate;
/* Now that $.fn.velocity is aliased, abort this Velocity declaration. */
return;
}
/* IE8 doesn't work with the jQuery shim; it requires jQuery proper. */
} else if (IE === 8 && !window.jQuery) {
throw new Error("Velocity: For IE8, Velocity requires jQuery to be loaded. (Velocity's jQuery shim does not work with IE8.)");
}
/* Shorthand alias for jQuery's $.data() utility. */
function Data (element) {
/* Hardcode a reference to the plugin name. */
var response = $.data(element, NAME);
/* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */
return response === null ? undefined : response;
};
/*************
State
*************/
/* Velocity registers itself onto a global container (window.jQuery || window.Zepto || window) so that that
certain features are accessible beyond just a per-element scope. This master object contains an .animate() method,
which is later assigned to $.fn (if jQuery or Zepto are present). Accordingly, Velocity can both act on wrapped
DOM elements and stand alone for targeting raw DOM elements. */
/* Note: The global object also doubles as a publicly-accessible data store for the purposes of unit testing. */
/* Note: Alias the lowercase and uppercase variants of "velocity" to minimize user confusion due to the lowercase nature of the $.fn extension. */
var Velocity = global.Velocity = global.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,
/* Create a cached element for re-use when checking for CSS property prefixes. */
prefixElement: document.createElement("div"),
/* Cache every prefix match to avoid repeating lookups. */
prefixMatches: {},
/* Cache the anchor used for animating window scrolling. */
scrollAnchor: null,
/* Cache the property 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. */ },
/* Defined by Velocity's optional jQuery shim. */
Utilities: window.jQuery ? {} : $,
/* Container for the user's custom animation sequences that are referenced by name in place of a properties map object. */
Sequences: {
/* Manually registered by the user. Learn more: VelocityJS.org/#sequences */
},
Easings: {
/* Defined below. */
},
/* Page-wide option defaults, which can be overriden by the user. */
defaults: {
queue: "",
duration: DEFAULT_DURATION,
easing: DEFAULT_EASING,
begin: null,
complete: null,
progress: null,
display: null,
loop: false,
delay: false,
mobileHA: true,
/* Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */
_cacheValues: true
},
/* Velocity's core animation method, subsequently aliased to $.fn. */
animate: function () { /* Defined below. */ },
/* Set to true to force a duration of 1ms for all animations so that UI testing can be performed without waiting on animations to complete. */
mock: false,
/* 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";
}
/**************
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 */
var generateBezier = (function () {
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);
}
return function (mX1, mY1, mX2, mY2) {
/* 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);
function getTForX (aX) {
var aGuessT = aX;
for (var i = 0; i < 8; ++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;
}
return function (aX) {
if (mX1 === mY1 && mX2 === mY2) {
return aX;
} else {
return calcBezier(getTForX(aX), mY1, mY2);
}
};
};
}());
/* 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 dela -- 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 ]; };
};
}());
/* Velocity embeds the named easings from jQuery, jQuery UI, and CSS3 in order to save users from having to include additional libraries on their page. */
(function () {
/* jQuery's default named easing types. */
Velocity.Easings["linear"] = function(p) {
return p;
};
Velocity.Easings["swing"] = function(p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
};
/* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */
Velocity.Easings["spring"] = function(p) {
return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6));
};
/* CSS3's named easing types. */
Velocity.Easings["ease"] = generateBezier(0.25, 0.1, 0.25, 1.0);
Velocity.Easings["ease-in"] = generateBezier(0.42, 0.0, 1.00, 1.0);
Velocity.Easings["ease-out"] = generateBezier(0.00, 0.0, 0.58, 1.0);
Velocity.Easings["ease-in-out"] = generateBezier(0.42, 0.0, 0.58, 1.0);
/* jQuery UI's Robert Penner easing equations. Copyright The jQuery Foundation. MIT License: https://jquery.org/license */
var baseEasings = {};
$.each(["Quad", "Cubic", "Quart", "Quint", "Expo"], function(i, name) {
baseEasings[name] = function(p) {
return Math.pow(p, i + 2);
};
});
$.extend(baseEasings, {
Sine: function (p) {
return 1 - Math.cos(p * Math.PI / 2);
},
Circ: function (p) {
return 1 - Math.sqrt(1 - p * p);
},
Elastic: function(p) {
return p === 0 || p === 1 ? p :
-Math.pow(2, 8 * (p - 1)) * Math.sin(((p - 1) * 80 - 7.5) * Math.PI / 15);
},
Back: function(p) {
return p * p * (3 * p - 2);
},
Bounce: function (p) {
var pow2,
bounce = 4;
while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {}
return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2);
}
});
/* jQuery's easing generator for the object above. */
$.each(baseEasings, function(name, easeIn) {
Velocity.Easings["easeIn" + name] = easeIn;
Velocity.Easings["easeOut" + name] = function(p) {
return 1 - easeIn(1 - p);
};
Velocity.Easings["easeInOut" + name] = function(p) {
return p < 0.5 ?
easeIn(p * 2) / 2 :
1 - easeIn(p * -2 + 2) / 2;
};
});
})();
/* 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 = DEFAULT_EASING;
}
}
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: {
/* Unwrap a property value's surrounding text, e.g. "rgba(4, 3, 2, 1)" ==> "4, 3, 2, 1" and "rect(4px 3px 2px 1px)" ==> "4px 3px 2px 1px". */
valueUnwrap: /^[A-z]+\((.*)\)$/i,
wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
/* Split a multi-value property into an array of subvalues, e.g. "rgba(4, 3, 2, 1) 4px 3px 2px 1px" ==> [ "rgba(4, 3, 2, 1)", "4px", "3px", "2px", "1px" ]. */
valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig
},
/************
Hooks
************/
/* Hooks allow a subproperty (e.g. "boxShadowBlur") of a compound-value CSS property
(e.g. "boxShadow: X Y Blur Spread Color") to be animated as if it were a discrete property. */
/* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only
tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */
Hooks: {
/********************
Registration
********************/
/* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */
/* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */
templates: {
/* Note: Colors are defaulted to white -- as opposed to black -- since colors that are
currently set to "transparent" default to their respective template below when color-animated,
and white is typically a closer match to transparent than black is. */
"color": [ "Red Green Blue Alpha", "255 255 255 1" ],
"backgroundColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderTopColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderRightColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderBottomColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"borderLeftColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"outlineColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"fill": [ "Red Green Blue Alpha", "255 255 255 1" ],
"stroke": [ "Red Green Blue Alpha", "255 255 255 1" ],
"stopColor": [ "Red Green Blue Alpha", "255 255 255 1" ],
"textShadow": [ "Color X Y Blur", "black 0px 0px 0px" ],
/* Todo: Add support for inset boxShadows. (webkit places it last whereas IE places it first.) */
"boxShadow": [ "Color X Y Blur Spread", "black 0px 0px 0px 0px" ],
"clip": [ "Top Right Bottom Left", "0px 0px 0px 0px" ],
"backgroundPosition": [ "X Y", "0% 0%" ],
"transformOrigin": [ "X Y Z", "50% 50% 0px" ],
"perspectiveOrigin": [ "X Y", "50% 50%" ]
},
/* A "registered" hook is one that has been converted from its template form into a live,
tweenable property. It contains data to associate it with its root property. */
registered: {
/* Note: A registered hook looks like this ==> textShadowBlur: [ "textShadow", 3 ],
which consists of the subproperty's name, the associated root property's name,
and the subproperty's position in the root's value. */
},
/* Convert the templates into individual hooks then append them to the registered object above. */
register: function () {
var rootProperty,
hookTemplate,
hookNames;
/* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning.
Thus, we re-arrange the templates accordingly. */
if (IE) {
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
var defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit);
if (hookNames[0] === "Color") {
/* Reposition both the hook's name and its default value to the end of their respective strings. */
hookNames.push(hookNames.shift());
defaultValues.push(defaultValues.shift());
/* Replace the existing template for the hook's root property. */
CSS.Hooks.templates[rootProperty] = [ hookNames.join(" "), defaultValues.join(" ") ];
}
}
}
/* Hook registration. */
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
for (var i in hookNames) {
var fullHookName = rootProperty + hookNames[i],
hookPosition = i;
/* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow)
and the hook's position in its template's default value string. */
CSS.Hooks.registered[fullHookName] = [ rootProperty, hookPosition ];
}
}
},
/*****************************
Injection and Extraction
*****************************/
/* Look up the root property associated with the hook (e.g. return "textShadow" for "textShadowBlur"). */
/* Since a hook cannot be set directly (the browser won't recognize it), style updating for hooks is routed through the hook's root property. */
getRoot: function (property) {
var hookData = CSS.Hooks.registered[property];
if (hookData) {
return hookData[0];
} else {
/* If there was no hook match, return the property name untouched. */
return property;
}
},
/* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that
the targeted hook can be injected or extracted at its standard position. */
cleanRootPropertyValue: function(rootProperty, rootPropertyValue) {
/* If the rootPropertyValue is wrapped with "rgb()", "clip()", etc., remove the wrapping to normalize the value before manipulation. */
if (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) {
rootPropertyValue = rootPropertyValue.match(CSS.Hooks.RegEx.valueUnwrap)[1];
}
/* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract),
default to the root's default value as defined in CSS.Hooks.templates. */
/* Note: CSS null-values include "none", "auto", and "transparent". They must be converted into their
zero-values (e.g. textShadow: "none" ==> textShadow: "0px 0px 0px black") for hook manipulation to proceed. */
if (CSS.Values.isCSSNullValue(rootPropertyValue)) {
rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
}
return rootPropertyValue;
},
/* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */
extractValue: function (fullHookName, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1];
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */
return rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition];
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
},
/* Inject the hook's value into its root property's value. This is used to piece back together the root property
once Velocity has updated one of its individually hooked values through tweening. */
injectValue: function (fullHookName, hookValue, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1],
rootPropertyValueParts,
rootPropertyValueUpdated;
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue,
then reconstruct the rootPropertyValue string. */
rootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit);
rootPropertyValueParts[hookPosition] = hookValue;
rootPropertyValueUpdated = rootPropertyValueParts.join(" ");
return rootPropertyValueUpdated;
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
}
},
/*******************
Normalizations
*******************/
/* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity)
and reformatting special properties (e.g. clip, rgba) to look like standard ones. */
Normalizations: {
/* Normalizations are passed a normalization target (either the property's name, its extracted value, or its injected value),
the targeted element (which may need to be queried), and the targeted property value. */
registered: {
clip: function(type, element, propertyValue) {
switch (type) {
case "name":
return "clip";
/* Clip needs to be unwrapped and stripped of its commas during extraction. */
case "extract":
var extracted;
/* If Velocity also extracted this value, skip extraction. */
if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
extracted = propertyValue;
} else {
/* Remove the "rect()" wrapper. */
extracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap);
/* Strip off commas. */
extracted = extracted ? extracted[1].replace(/,(\s+)?/g, " ") : propertyValue;
}
return extracted;
/* Clip needs to be re-wrapped during injection. */
case "inject":
return "rect(" + propertyValue + ")";
}
},
/* <=IE8 do not support the standard opacity property. They use filter:alpha(opacity=INT) instead. */
opacity: function (type, element, propertyValue) {
if (IE <= 8) {
switch (type) {
case "name":
return "filter";
case "extract":
/* <=IE8 return a "filter" value of "alpha(opacity=\d{1,3})".
Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */
var extracted = propertyValue.toString().match(/alpha\(opacity=(.*)\)/i);
if (extracted) {
/* Convert to decimal value. */
propertyValue = extracted[1] / 100;
} else {
/* When extracting opacity, default to 1 since a null value means opacity hasn't been set. */
propertyValue = 1;
}
return propertyValue;
case "inject":
/* Opacified elements are required to have their zoom property set to a non-zero value. */
element.style.zoom = 1;
/* Setting the filter property on elements with certain font property combinations can result in a
highly unappealing ultra-bolding effect. There's no way to remedy this throughout a tween, but dropping the
value altogether (when opacity hits 1) at leasts ensures that the glitch is gone post-tweening. */
if (parseFloat(propertyValue) >= 1) {
return "";
} else {
/* As per the filter property's spec, convert the decimal value to a whole number and wrap the value. */
return "alpha(opacity=" + parseInt(parseFloat(propertyValue) * 100, 10) + ")";
}
}
/* With all other browsers, normalization is not required; return the same values that were passed in. */
} else {
switch (type) {
case "name":
return "opacity";
case "extract":
return propertyValue;
case "inject":
return propertyValue;
}
}
}
},
/*****************************
Batched Registrations
*****************************/
/* Note: Batched normalizations extend the CSS.Normalizations.registered object. */
register: function () {
/*****************
Transforms
*****************/
/* Transforms are the subproperties contained by the CSS "transform" property. Transforms must undergo normalization
so that they can be referenced in a properties map by their individual names. */
/* Note: When transforms are "set", they are actually assigned to a per-element transformCache. When all transform
setting is complete complete, CSS.flushTransformCache() must be manually called to flush the values to the DOM.
Transform setting is batched in this way to improve performance: the transform style only needs to be updated
once when multiple transform subproperties are being animated simultaneously. */
var transformProperties = [ "translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ" ];
/* IE9 and Android Gingerbread have support for 2D -- but not 3D -- transforms. Since animating unsupported
transform properties results in the browser ignoring the *entire* transform string, we prevent these 3D values
from being normalized for these browsers so that tweening skips these properties altogether
(since it will ignore them as being unsupported by the browser.) */
if (!(IE <= 9) && !Velocity.State.isGingerbread) {
/* Append 3D transform properties onto transformProperties. */
/* Note: Since the standalone CSS "perspective" property and the CSS transform "perspective" subproperty
share the same name, the latter is given a unique token within Velocity: "transformPerspective". */
transformProperties = transformProperties.concat([ "transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY" ]);
}
for (var i = 0, transformPropertiesLength = transformProperties.length; i < transformPropertiesLength; i++) {
/* Wrap the dynamically generated normalization function in a new scope so that transformName's value is
paired with its respective function. (Otherwise, all functions would take the final for loop's transformName.) */
(function() {
var transformName = transformProperties[i];
CSS.Normalizations.registered[transformName] = function (type, element, propertyValue) {
switch (type) {
/* The normalized property name is the parent "transform" property -- the property that is actually set in CSS. */
case "name":
return "transform";
/* Transform values are cached onto a per-element transformCache object. */
case "extract":
/* If this transform has yet to be assigned a value, return its null value. */
if (Data(element).transformCache[transformName] === undefined) {
/* Scale transformProperties default to 1 whereas all other transform properties default to 0. */
return /^scale/i.test(transformName) ? 1 : 0;
/* When transform values are set, they are wrapped in parentheses as per the CSS spec.
Thus, when extracting their values (for tween calculations), we strip off the parentheses. */
} else {
return Data(element).transformCache[transformName].replace(/[()]/g, "");
}
case "inject":
var invalid = false;
/* If an individual transform property contains an unsupported unit type, the browser ignores the *entire* transform property.
Thus, protect users from themselves by skipping setting for transform values supplied with invalid unit types. */
/* Switch on the base transform type; ignore the axis by removing the last letter from the transform's name. */
switch (transformName.substr(0, transformName.length - 1)) {
/* Whitelist unit types for each transform. */
case "translate":
invalid = !/(%|px|em|rem|\d)$/i.test(propertyValue);
break;
/* 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. */
case "scal":
case "scale":
/* Chrome on Android has a bug in which scaled elements blur if their initial scale
value is below 1 (which can happen with forcefeeding). Thus, we detect a yet-unset scale property
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 */
if (Velocity.State.isAndroid && Data(element).transformCache[transformName] === undefined) {
propertyValue = 1;
}
invalid = !/(\d)$/i.test(propertyValue);
break;
case "skew":
invalid = !/(deg|\d)$/i.test(propertyValue);
break;
case "rotate":
invalid = !/(deg|\d)$/i.test(propertyValue);
break;
}
if (!invalid) {
/* As per the CSS spec, wrap the value in parentheses. */
Data(element).transformCache[transformName] = "(" + propertyValue + ")";
}
/* Although the value is set on the transformCache object, return the newly-updated value for the calling code to process as normal. */
return Data(element).transformCache[transformName];
}
};
})();
}
/*************
Colors
*************/
/* Since Velocity only animates a single numeric value per property, color animation is achieved by hooking the individual RGBA components of CSS color properties.
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. */
var colorProperties = [ "fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor",
"borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor" ];
for (var i = 0, colorPropertiesLength = colorProperties.length; i < colorPropertiesLength; i++) {
/* Hex to RGB conversion. Copyright Tim Down: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */
function hexToRgb (hex) {
var shortformRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,
rgbParts;
hex = hex.replace(shortformRegex, function (m, r, g, b) {
return r + r + g + g + b + b;
});
rgbParts = longformRegex.exec(hex);
return rgbParts ? "rgb(" + (parseInt(rgbParts[1], 16) + " " + parseInt(rgbParts[2], 16) + " " + parseInt(rgbParts[3], 16)) + ")" : "rgb(0 0 0)";
}
/* Wrap the dynamically generated normalization function in a new scope so that colorName's value is paired with its respective function.
(Otherwise, all functions would take the final for loop's colorName.) */
(function () {
var colorName = colorProperties[i];
/* Note: In IE<=8, which support rgb but not rgba, colorProperties are reverted to rgb by stripping off the alpha component. */
CSS.Normalizations.registered[colorName] = function(type, element, propertyValue) {
switch (type) {
case "name":
return colorName;
/* Convert all color values into the rgb format. (Old IE can return hex values and color names instead of rgb/rgba.) */
case "extract":
var extracted;
/* If the color is already in its hookable form (e.g. "255 255 255 1") due to having been previously extracted, skip extraction. */
if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
extracted = propertyValue;
} else {
var converted,
colorNames = {
aqua: "rgb(0, 255, 255);",
black: "rgb(0, 0, 0)",
blue: "rgb(0, 0, 255)",
fuchsia: "rgb(255, 0, 255)",
gray: "rgb(128, 128, 128)",
green: "rgb(0, 128, 0)",
lime: "rgb(0, 255, 0)",
maroon: "rgb(128, 0, 0)",
navy: "rgb(0, 0, 128)",
olive: "rgb(128, 128, 0)",
purple: "rgb(128, 0, 128)",
red: "rgb(255, 0, 0)",
silver: "rgb(192, 192, 192)",
teal: "rgb(0, 128, 128)",
white: "rgb(255, 255, 255)",
yellow: "rgb(255, 255, 0)"
};
/* Convert color names to rgb. */
if (/^[A-z]+$/i.test(propertyValue)) {
if (colorNames[propertyValue] !== undefined) {
converted = colorNames[propertyValue]
} else {
/* If an unmatched color name is provided, default to black. */
converted = colorNames.black;
}
/* Convert hex values to rgb. */
} else if (/^#([A-f\d]{3}){1,2}$/i.test(propertyValue)) {
converted = hexToRgb(propertyValue);
/* If the provided color doesn't match any of the accepted color formats, default to black. */
} else if (!(/^rgba?\(/i.test(propertyValue))) {
converted = colorNames.black;
}
/* Remove the surrounding "rgb/rgba()" string then replace commas with spaces and strip
repeated spaces (in case the value included spaces to begin with). */
extracted = (converted || propertyValue).toString().match(CSS.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ");
}
/* So long as this isn't <=IE8, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
if (!(IE <= 8) && extracted.split(" ").length === 3) {
extracted += " 1";
}
return extracted;
case "inject":
/* If this is IE<=8 and an alpha component exists, strip it off. */
if (IE <= 8) {
if (propertyValue.split(" ").length === 4) {
propertyValue = propertyValue.split(/\s+/).slice(0, 3).join(" ");
}
/* Otherwise, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
} else if (propertyValue.split(" ").length === 3) {
propertyValue += " 1";
}
/* Re-insert the browser-appropriate wrapper("rgb/rgba()"), insert commas, and strip off decimal units
on all values but the fourth (R, G, and B only accept whole numbers). */
return (IE <= 8 ? "rgb" : "rgba") + "(" + propertyValue.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")";
}