blob: 761d622ea0994a445abb5a86379bc47d47566b94 [file] [log] [blame]
Bri Prebilic Cole8db16402015-05-18 13:50:31 -07001/**
2 * @license AngularJS v1.3.5
3 * (c) 2010-2014 Google, Inc. http://angularjs.org
4 * License: MIT
5 */
6(function(window, angular, undefined) {'use strict';
7
8/* jshint maxlen: false */
9
10/**
11 * @ngdoc module
12 * @name ngAnimate
13 * @description
14 *
15 * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.
16 *
17 * <div doc-module-components="ngAnimate"></div>
18 *
19 * # Usage
20 *
21 * To see animations in action, all that is required is to define the appropriate CSS classes
22 * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are:
23 * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation
24 * by using the `$animate` service.
25 *
26 * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:
27 *
28 * | Directive | Supported Animations |
29 * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
30 * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
31 * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
32 * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
33 * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
34 * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
35 * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
36 * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
37 * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
38 * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
39 * | {@link module:ngMessages#animations ngMessage} | enter and leave |
40 *
41 * You can find out more information about animations upon visiting each directive page.
42 *
43 * Below is an example of how to apply animations to a directive that supports animation hooks:
44 *
45 * ```html
46 * <style type="text/css">
47 * .slide.ng-enter, .slide.ng-leave {
48 * -webkit-transition:0.5s linear all;
49 * transition:0.5s linear all;
50 * }
51 *
52 * .slide.ng-enter { } /&#42; starting animations for enter &#42;/
53 * .slide.ng-enter.ng-enter-active { } /&#42; terminal animations for enter &#42;/
54 * .slide.ng-leave { } /&#42; starting animations for leave &#42;/
55 * .slide.ng-leave.ng-leave-active { } /&#42; terminal animations for leave &#42;/
56 * </style>
57 *
58 * <!--
59 * the animate service will automatically add .ng-enter and .ng-leave to the element
60 * to trigger the CSS transition/animations
61 * -->
62 * <ANY class="slide" ng-include="..."></ANY>
63 * ```
64 *
65 * Keep in mind that, by default, if an animation is running, any child elements cannot be animated
66 * until the parent element's animation has completed. This blocking feature can be overridden by
67 * placing the `ng-animate-children` attribute on a parent container tag.
68 *
69 * ```html
70 * <div class="slide-animation" ng-if="on" ng-animate-children>
71 * <div class="fade-animation" ng-if="on">
72 * <div class="explode-animation" ng-if="on">
73 * ...
74 * </div>
75 * </div>
76 * </div>
77 * ```
78 *
79 * When the `on` expression value changes and an animation is triggered then each of the elements within
80 * will all animate without the block being applied to child elements.
81 *
82 * ## Are animations run when the application starts?
83 * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid
84 * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work,
85 * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering
86 * layout changes in the application will trigger animations as normal.
87 *
88 * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular
89 * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests
90 * are complete.
91 *
92 * ## CSS-defined Animations
93 * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes
94 * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported
95 * and can be used to play along with this naming structure.
96 *
97 * The following code below demonstrates how to perform animations using **CSS transitions** with Angular:
98 *
99 * ```html
100 * <style type="text/css">
101 * /&#42;
102 * The animate class is apart of the element and the ng-enter class
103 * is attached to the element once the enter animation event is triggered
104 * &#42;/
105 * .reveal-animation.ng-enter {
106 * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/
107 * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/
108 *
109 * /&#42; The animation preparation code &#42;/
110 * opacity: 0;
111 * }
112 *
113 * /&#42;
114 * Keep in mind that you want to combine both CSS
115 * classes together to avoid any CSS-specificity
116 * conflicts
117 * &#42;/
118 * .reveal-animation.ng-enter.ng-enter-active {
119 * /&#42; The animation code itself &#42;/
120 * opacity: 1;
121 * }
122 * </style>
123 *
124 * <div class="view-container">
125 * <div ng-view class="reveal-animation"></div>
126 * </div>
127 * ```
128 *
129 * The following code below demonstrates how to perform animations using **CSS animations** with Angular:
130 *
131 * ```html
132 * <style type="text/css">
133 * .reveal-animation.ng-enter {
134 * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/
135 * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/
136 * }
137 * @-webkit-keyframes enter_sequence {
138 * from { opacity:0; }
139 * to { opacity:1; }
140 * }
141 * @keyframes enter_sequence {
142 * from { opacity:0; }
143 * to { opacity:1; }
144 * }
145 * </style>
146 *
147 * <div class="view-container">
148 * <div ng-view class="reveal-animation"></div>
149 * </div>
150 * ```
151 *
152 * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.
153 *
154 * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add
155 * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically
156 * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be
157 * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end
158 * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element
159 * has no CSS transition/animation classes applied to it.
160 *
161 * ### Structural transition animations
162 *
163 * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition
164 * value to force the browser into rendering the styles defined in the setup (.ng-enter, .ng-leave
165 * or .ng-move) class. This means that any active transition animations operating on the element
166 * will be cut off to make way for the enter, leave or move animation.
167 *
168 * ### Class-based transition animations
169 *
170 * Class-based transitions refer to transition animations that are triggered when a CSS class is
171 * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`,
172 * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`).
173 * They are different when compared to structural animations since they **do not cancel existing
174 * animations** nor do they **block successive transitions** from rendering on the same element.
175 * This distinction allows for **multiple class-based transitions** to be performed on the same element.
176 *
177 * In addition to ngAnimate supporting the default (natural) functionality of class-based transition
178 * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the
179 * developer in further styling the element throughout the transition animation. Earlier versions
180 * of ngAnimate may have caused natural CSS transitions to break and not render properly due to
181 * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class
182 * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of
183 * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS
184 * class transitions are compatible with ngAnimate.
185 *
186 * There is, however, one special case when dealing with class-based transitions in ngAnimate.
187 * When rendering class-based transitions that make use of the setup and active CSS classes
188 * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define
189 * the transition value **on the active CSS class** and not the setup class.
190 *
191 * ```css
192 * .fade-add {
193 * /&#42; remember to place a 0s transition here
194 * to ensure that the styles are applied instantly
195 * even if the element already has a transition style &#42;/
196 * transition:0s linear all;
197 *
198 * /&#42; starting CSS styles &#42;/
199 * opacity:1;
200 * }
201 * .fade-add.fade-add-active {
202 * /&#42; this will be the length of the animation &#42;/
203 * transition:1s linear all;
204 * opacity:0;
205 * }
206 * ```
207 *
208 * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it
209 * has a duration of zero. This may not be required, however, incase the browser is unable to render
210 * the styling present in this CSS class instantly then it could be that the browser is attempting
211 * to perform an unnecessary transition.
212 *
213 * This workaround, however, does not apply to standard class-based transitions that are rendered
214 * when a CSS class containing a transition is applied to an element:
215 *
216 * ```css
217 * /&#42; this works as expected &#42;/
218 * .fade {
219 * transition:1s linear all;
220 * opacity:0;
221 * }
222 * ```
223 *
224 * Please keep this in mind when coding the CSS markup that will be used within class-based transitions.
225 * Also, try not to mix the two class-based animation flavors together since the CSS code may become
226 * overly complex.
227 *
228 *
229 * ### Preventing Collisions With Third Party Libraries
230 *
231 * Some third-party frameworks place animation duration defaults across many element or className
232 * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
233 * is expecting actual animations on these elements and has to wait for their completion.
234 *
235 * You can prevent this unwanted behavior by using a prefix on all your animation classes:
236 *
237 * ```css
238 * /&#42; prefixed with animate- &#42;/
239 * .animate-fade-add.animate-fade-add-active {
240 * transition:1s linear all;
241 * opacity:0;
242 * }
243 * ```
244 *
245 * You then configure `$animate` to enforce this prefix:
246 *
247 * ```js
248 * $animateProvider.classNameFilter(/animate-/);
249 * ```
250 * </div>
251 *
252 * ### CSS Staggering Animations
253 * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
254 * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
255 * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
256 * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
257 * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
258 *
259 * ```css
260 * .my-animation.ng-enter {
261 * /&#42; standard transition code &#42;/
262 * -webkit-transition: 1s linear all;
263 * transition: 1s linear all;
264 * opacity:0;
265 * }
266 * .my-animation.ng-enter-stagger {
267 * /&#42; this will have a 100ms delay between each successive leave animation &#42;/
268 * -webkit-transition-delay: 0.1s;
269 * transition-delay: 0.1s;
270 *
271 * /&#42; in case the stagger doesn't work then these two values
272 * must be set to 0 to avoid an accidental CSS inheritance &#42;/
273 * -webkit-transition-duration: 0s;
274 * transition-duration: 0s;
275 * }
276 * .my-animation.ng-enter.ng-enter-active {
277 * /&#42; standard transition styles &#42;/
278 * opacity:1;
279 * }
280 * ```
281 *
282 * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
283 * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
284 * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
285 * will also be reset if more than 10ms has passed after the last animation has been fired.
286 *
287 * The following code will issue the **ng-leave-stagger** event on the element provided:
288 *
289 * ```js
290 * var kids = parent.children();
291 *
292 * $animate.leave(kids[0]); //stagger index=0
293 * $animate.leave(kids[1]); //stagger index=1
294 * $animate.leave(kids[2]); //stagger index=2
295 * $animate.leave(kids[3]); //stagger index=3
296 * $animate.leave(kids[4]); //stagger index=4
297 *
298 * $timeout(function() {
299 * //stagger has reset itself
300 * $animate.leave(kids[5]); //stagger index=0
301 * $animate.leave(kids[6]); //stagger index=1
302 * }, 100, false);
303 * ```
304 *
305 * Stagger animations are currently only supported within CSS-defined animations.
306 *
307 * ## JavaScript-defined Animations
308 * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not
309 * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.
310 *
311 * ```js
312 * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.
313 * var ngModule = angular.module('YourApp', ['ngAnimate']);
314 * ngModule.animation('.my-crazy-animation', function() {
315 * return {
316 * enter: function(element, done) {
317 * //run the animation here and call done when the animation is complete
318 * return function(cancelled) {
319 * //this (optional) function will be called when the animation
320 * //completes or when the animation is cancelled (the cancelled
321 * //flag will be set to true if cancelled).
322 * };
323 * },
324 * leave: function(element, done) { },
325 * move: function(element, done) { },
326 *
327 * //animation that can be triggered before the class is added
328 * beforeAddClass: function(element, className, done) { },
329 *
330 * //animation that can be triggered after the class is added
331 * addClass: function(element, className, done) { },
332 *
333 * //animation that can be triggered before the class is removed
334 * beforeRemoveClass: function(element, className, done) { },
335 *
336 * //animation that can be triggered after the class is removed
337 * removeClass: function(element, className, done) { }
338 * };
339 * });
340 * ```
341 *
342 * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run
343 * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits
344 * the element's CSS class attribute value and then run the matching animation event function (if found).
345 * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will
346 * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).
347 *
348 * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.
349 * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,
350 * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation
351 * or transition code that is defined via a stylesheet).
352 *
353 *
354 * ### Applying Directive-specific Styles to an Animation
355 * In some cases a directive or service may want to provide `$animate` with extra details that the animation will
356 * include into its animation. Let's say for example we wanted to render an animation that animates an element
357 * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click
358 * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function
359 * call to `$animate.addClass`.
360 *
361 * ```js
362 * canvas.on('click', function(e) {
363 * $animate.addClass(element, 'on', {
364 * to: {
365 * left : e.client.x + 'px',
366 * top : e.client.y + 'px'
367 * }
368 * }):
369 * });
370 * ```
371 *
372 * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will
373 * also include and transition the styling of the `left` and `top` properties into its running animation. If we want
374 * to provide some starting animation values then we can do so by placing the starting animations styles into an object
375 * called `from` in the same object as the `to` animations.
376 *
377 * ```js
378 * canvas.on('click', function(e) {
379 * $animate.addClass(element, 'on', {
380 * from: {
381 * position: 'absolute',
382 * left: '0px',
383 * top: '0px'
384 * },
385 * to: {
386 * left : e.client.x + 'px',
387 * top : e.client.y + 'px'
388 * }
389 * }):
390 * });
391 * ```
392 *
393 * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the
394 * element. If `ngAnimate` is not present then the styles will be applied immediately.
395 *
396 */
397
398angular.module('ngAnimate', ['ng'])
399
400 /**
401 * @ngdoc provider
402 * @name $animateProvider
403 * @description
404 *
405 * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.
406 * When an animation is triggered, the $animate service will query the $animate service to find any animations that match
407 * the provided name value.
408 *
409 * Requires the {@link ngAnimate `ngAnimate`} module to be installed.
410 *
411 * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
412 *
413 */
414 .directive('ngAnimateChildren', function() {
415 var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';
416 return function(scope, element, attrs) {
417 var val = attrs.ngAnimateChildren;
418 if (angular.isString(val) && val.length === 0) { //empty attribute
419 element.data(NG_ANIMATE_CHILDREN, true);
420 } else {
421 scope.$watch(val, function(value) {
422 element.data(NG_ANIMATE_CHILDREN, !!value);
423 });
424 }
425 };
426 })
427
428 //this private service is only used within CSS-enabled animations
429 //IE8 + IE9 do not support rAF natively, but that is fine since they
430 //also don't support transitions and keyframes which means that the code
431 //below will never be used by the two browsers.
432 .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {
433 var bod = $document[0].body;
434 return function(fn) {
435 //the returned function acts as the cancellation function
436 return $$rAF(function() {
437 //the line below will force the browser to perform a repaint
438 //so that all the animated elements within the animation frame
439 //will be properly updated and drawn on screen. This is
440 //required to perform multi-class CSS based animations with
441 //Firefox. DO NOT REMOVE THIS LINE.
442 var a = bod.offsetWidth + 1;
443 fn();
444 });
445 };
446 }])
447
448 .config(['$provide', '$animateProvider', function($provide, $animateProvider) {
449 var noop = angular.noop;
450 var forEach = angular.forEach;
451 var selectors = $animateProvider.$$selectors;
452 var isArray = angular.isArray;
453 var isString = angular.isString;
454 var isObject = angular.isObject;
455
456 var ELEMENT_NODE = 1;
457 var NG_ANIMATE_STATE = '$$ngAnimateState';
458 var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';
459 var NG_ANIMATE_CLASS_NAME = 'ng-animate';
460 var rootAnimateState = {running: true};
461
462 function extractElementNode(element) {
463 for (var i = 0; i < element.length; i++) {
464 var elm = element[i];
465 if (elm.nodeType == ELEMENT_NODE) {
466 return elm;
467 }
468 }
469 }
470
471 function prepareElement(element) {
472 return element && angular.element(element);
473 }
474
475 function stripCommentsFromElement(element) {
476 return angular.element(extractElementNode(element));
477 }
478
479 function isMatchingElement(elm1, elm2) {
480 return extractElementNode(elm1) == extractElementNode(elm2);
481 }
482
483 $provide.decorator('$animate',
484 ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest',
485 function($delegate, $$q, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document, $templateRequest) {
486
487 $rootElement.data(NG_ANIMATE_STATE, rootAnimateState);
488
489 // Wait until all directive and route-related templates are downloaded and
490 // compiled. The $templateRequest.totalPendingRequests variable keeps track of
491 // all of the remote templates being currently downloaded. If there are no
492 // templates currently downloading then the watcher will still fire anyway.
493 var deregisterWatch = $rootScope.$watch(
494 function() { return $templateRequest.totalPendingRequests; },
495 function(val, oldVal) {
496 if (val !== 0) return;
497 deregisterWatch();
498
499 // Now that all templates have been downloaded, $animate will wait until
500 // the post digest queue is empty before enabling animations. By having two
501 // calls to $postDigest calls we can ensure that the flag is enabled at the
502 // very end of the post digest queue. Since all of the animations in $animate
503 // use $postDigest, it's important that the code below executes at the end.
504 // This basically means that the page is fully downloaded and compiled before
505 // any animations are triggered.
506 $rootScope.$$postDigest(function() {
507 $rootScope.$$postDigest(function() {
508 rootAnimateState.running = false;
509 });
510 });
511 }
512 );
513
514 var globalAnimationCounter = 0;
515 var classNameFilter = $animateProvider.classNameFilter();
516 var isAnimatableClassName = !classNameFilter
517 ? function() { return true; }
518 : function(className) {
519 return classNameFilter.test(className);
520 };
521
522 function classBasedAnimationsBlocked(element, setter) {
523 var data = element.data(NG_ANIMATE_STATE) || {};
524 if (setter) {
525 data.running = true;
526 data.structural = true;
527 element.data(NG_ANIMATE_STATE, data);
528 }
529 return data.disabled || (data.running && data.structural);
530 }
531
532 function runAnimationPostDigest(fn) {
533 var cancelFn, defer = $$q.defer();
534 defer.promise.$$cancelFn = function() {
535 cancelFn && cancelFn();
536 };
537 $rootScope.$$postDigest(function() {
538 cancelFn = fn(function() {
539 defer.resolve();
540 });
541 });
542 return defer.promise;
543 }
544
545 function parseAnimateOptions(options) {
546 // some plugin code may still be passing in the callback
547 // function as the last param for the $animate methods so
548 // it's best to only allow string or array values for now
549 if (isObject(options)) {
550 if (options.tempClasses && isString(options.tempClasses)) {
551 options.tempClasses = options.tempClasses.split(/\s+/);
552 }
553 return options;
554 }
555 }
556
557 function resolveElementClasses(element, cache, runningAnimations) {
558 runningAnimations = runningAnimations || {};
559
560 var lookup = {};
561 forEach(runningAnimations, function(data, selector) {
562 forEach(selector.split(' '), function(s) {
563 lookup[s]=data;
564 });
565 });
566
567 var hasClasses = Object.create(null);
568 forEach((element.attr('class') || '').split(/\s+/), function(className) {
569 hasClasses[className] = true;
570 });
571
572 var toAdd = [], toRemove = [];
573 forEach((cache && cache.classes) || [], function(status, className) {
574 var hasClass = hasClasses[className];
575 var matchingAnimation = lookup[className] || {};
576
577 // When addClass and removeClass is called then $animate will check to
578 // see if addClass and removeClass cancel each other out. When there are
579 // more calls to removeClass than addClass then the count falls below 0
580 // and then the removeClass animation will be allowed. Otherwise if the
581 // count is above 0 then that means an addClass animation will commence.
582 // Once an animation is allowed then the code will also check to see if
583 // there exists any on-going animation that is already adding or remvoing
584 // the matching CSS class.
585 if (status === false) {
586 //does it have the class or will it have the class
587 if (hasClass || matchingAnimation.event == 'addClass') {
588 toRemove.push(className);
589 }
590 } else if (status === true) {
591 //is the class missing or will it be removed?
592 if (!hasClass || matchingAnimation.event == 'removeClass') {
593 toAdd.push(className);
594 }
595 }
596 });
597
598 return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')];
599 }
600
601 function lookup(name) {
602 if (name) {
603 var matches = [],
604 flagMap = {},
605 classes = name.substr(1).split('.');
606
607 //the empty string value is the default animation
608 //operation which performs CSS transition and keyframe
609 //animations sniffing. This is always included for each
610 //element animation procedure if the browser supports
611 //transitions and/or keyframe animations. The default
612 //animation is added to the top of the list to prevent
613 //any previous animations from affecting the element styling
614 //prior to the element being animated.
615 if ($sniffer.transitions || $sniffer.animations) {
616 matches.push($injector.get(selectors['']));
617 }
618
619 for (var i=0; i < classes.length; i++) {
620 var klass = classes[i],
621 selectorFactoryName = selectors[klass];
622 if (selectorFactoryName && !flagMap[klass]) {
623 matches.push($injector.get(selectorFactoryName));
624 flagMap[klass] = true;
625 }
626 }
627 return matches;
628 }
629 }
630
631 function animationRunner(element, animationEvent, className, options) {
632 //transcluded directives may sometimes fire an animation using only comment nodes
633 //best to catch this early on to prevent any animation operations from occurring
634 var node = element[0];
635 if (!node) {
636 return;
637 }
638
639 if (options) {
640 options.to = options.to || {};
641 options.from = options.from || {};
642 }
643
644 var classNameAdd;
645 var classNameRemove;
646 if (isArray(className)) {
647 classNameAdd = className[0];
648 classNameRemove = className[1];
649 if (!classNameAdd) {
650 className = classNameRemove;
651 animationEvent = 'removeClass';
652 } else if (!classNameRemove) {
653 className = classNameAdd;
654 animationEvent = 'addClass';
655 } else {
656 className = classNameAdd + ' ' + classNameRemove;
657 }
658 }
659
660 var isSetClassOperation = animationEvent == 'setClass';
661 var isClassBased = isSetClassOperation
662 || animationEvent == 'addClass'
663 || animationEvent == 'removeClass'
664 || animationEvent == 'animate';
665
666 var currentClassName = element.attr('class');
667 var classes = currentClassName + ' ' + className;
668 if (!isAnimatableClassName(classes)) {
669 return;
670 }
671
672 var beforeComplete = noop,
673 beforeCancel = [],
674 before = [],
675 afterComplete = noop,
676 afterCancel = [],
677 after = [];
678
679 var animationLookup = (' ' + classes).replace(/\s+/g,'.');
680 forEach(lookup(animationLookup), function(animationFactory) {
681 var created = registerAnimation(animationFactory, animationEvent);
682 if (!created && isSetClassOperation) {
683 registerAnimation(animationFactory, 'addClass');
684 registerAnimation(animationFactory, 'removeClass');
685 }
686 });
687
688 function registerAnimation(animationFactory, event) {
689 var afterFn = animationFactory[event];
690 var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];
691 if (afterFn || beforeFn) {
692 if (event == 'leave') {
693 beforeFn = afterFn;
694 //when set as null then animation knows to skip this phase
695 afterFn = null;
696 }
697 after.push({
698 event: event, fn: afterFn
699 });
700 before.push({
701 event: event, fn: beforeFn
702 });
703 return true;
704 }
705 }
706
707 function run(fns, cancellations, allCompleteFn) {
708 var animations = [];
709 forEach(fns, function(animation) {
710 animation.fn && animations.push(animation);
711 });
712
713 var count = 0;
714 function afterAnimationComplete(index) {
715 if (cancellations) {
716 (cancellations[index] || noop)();
717 if (++count < animations.length) return;
718 cancellations = null;
719 }
720 allCompleteFn();
721 }
722
723 //The code below adds directly to the array in order to work with
724 //both sync and async animations. Sync animations are when the done()
725 //operation is called right away. DO NOT REFACTOR!
726 forEach(animations, function(animation, index) {
727 var progress = function() {
728 afterAnimationComplete(index);
729 };
730 switch (animation.event) {
731 case 'setClass':
732 cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options));
733 break;
734 case 'animate':
735 cancellations.push(animation.fn(element, className, options.from, options.to, progress));
736 break;
737 case 'addClass':
738 cancellations.push(animation.fn(element, classNameAdd || className, progress, options));
739 break;
740 case 'removeClass':
741 cancellations.push(animation.fn(element, classNameRemove || className, progress, options));
742 break;
743 default:
744 cancellations.push(animation.fn(element, progress, options));
745 break;
746 }
747 });
748
749 if (cancellations && cancellations.length === 0) {
750 allCompleteFn();
751 }
752 }
753
754 return {
755 node: node,
756 event: animationEvent,
757 className: className,
758 isClassBased: isClassBased,
759 isSetClassOperation: isSetClassOperation,
760 applyStyles: function() {
761 if (options) {
762 element.css(angular.extend(options.from || {}, options.to || {}));
763 }
764 },
765 before: function(allCompleteFn) {
766 beforeComplete = allCompleteFn;
767 run(before, beforeCancel, function() {
768 beforeComplete = noop;
769 allCompleteFn();
770 });
771 },
772 after: function(allCompleteFn) {
773 afterComplete = allCompleteFn;
774 run(after, afterCancel, function() {
775 afterComplete = noop;
776 allCompleteFn();
777 });
778 },
779 cancel: function() {
780 if (beforeCancel) {
781 forEach(beforeCancel, function(cancelFn) {
782 (cancelFn || noop)(true);
783 });
784 beforeComplete(true);
785 }
786 if (afterCancel) {
787 forEach(afterCancel, function(cancelFn) {
788 (cancelFn || noop)(true);
789 });
790 afterComplete(true);
791 }
792 }
793 };
794 }
795
796 /**
797 * @ngdoc service
798 * @name $animate
799 * @kind object
800 *
801 * @description
802 * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.
803 * When any of these operations are run, the $animate service
804 * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)
805 * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.
806 *
807 * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives
808 * will work out of the box without any extra configuration.
809 *
810 * Requires the {@link ngAnimate `ngAnimate`} module to be installed.
811 *
812 * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
813 * ## Callback Promises
814 * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The
815 * promise itself is then resolved once the animation has completed itself, has been cancelled or has been
816 * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still
817 * call the resolve function of the animation.)
818 *
819 * ```js
820 * $animate.enter(element, container).then(function() {
821 * //...this is called once the animation is complete...
822 * });
823 * ```
824 *
825 * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope,
826 * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using
827 * `$scope.$apply(...)`;
828 *
829 * ```js
830 * $animate.leave(element).then(function() {
831 * $scope.$apply(function() {
832 * $location.path('/new-page');
833 * });
834 * });
835 * ```
836 *
837 * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided
838 * promise that was returned when the animation was started.
839 *
840 * ```js
841 * var promise = $animate.addClass(element, 'super-long-animation').then(function() {
842 * //this will still be called even if cancelled
843 * });
844 *
845 * element.on('click', function() {
846 * //tooo lazy to wait for the animation to end
847 * $animate.cancel(promise);
848 * });
849 * ```
850 *
851 * (Keep in mind that the promise cancellation is unique to `$animate` since promises in
852 * general cannot be cancelled.)
853 *
854 */
855 return {
856 /**
857 * @ngdoc method
858 * @name $animate#animate
859 * @kind function
860 *
861 * @description
862 * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element.
863 * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation
864 * will take on the provided styles. For example, if a transition animation is set for the given className then the
865 * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is
866 * detected then the provided styles will be given in as function paramters.
867 *
868 * ```js
869 * ngModule.animation('.my-inline-animation', function() {
870 * return {
871 * animate : function(element, className, from, to, done) {
872 * //styles
873 * }
874 * }
875 * });
876 * ```
877 *
878 * Below is a breakdown of each step that occurs during the `animate` animation:
879 *
880 * | Animation Step | What the element class attribute looks like |
881 * |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|
882 * | 1. $animate.animate(...) is called | class="my-animation" |
883 * | 2. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
884 * | 3. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
885 * | 4. the className class value is added to the element | class="my-animation ng-animate className" |
886 * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate className" |
887 * | 6. $animate blocks all CSS transitions on the element to ensure the .className class styling is applied right away| class="my-animation ng-animate className" |
888 * | 7. $animate applies the provided collection of `from` CSS styles to the element | class="my-animation ng-animate className" |
889 * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate className" |
890 * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate className" |
891 * | 10. the className-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate className className-active" |
892 * | 11. $animate applies the collection of `to` CSS styles to the element which are then handled by the transition | class="my-animation ng-animate className className-active" |
893 * | 12. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate className className-active" |
894 * | 13. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
895 * | 14. The returned promise is resolved. | class="my-animation" |
896 *
897 * @param {DOMElement} element the element that will be the focus of the enter animation
898 * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation
899 * @param {object} to a collection of CSS styles that the element will animate towards
900 * @param {string=} className an optional CSS class that will be added to the element for the duration of the animation (the default class is `ng-inline-animate`)
901 * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation
902 * @return {Promise} the animation callback promise
903 */
904 animate: function(element, from, to, className, options) {
905 className = className || 'ng-inline-animate';
906 options = parseAnimateOptions(options) || {};
907 options.from = to ? from : null;
908 options.to = to ? to : from;
909
910 return runAnimationPostDigest(function(done) {
911 return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done);
912 });
913 },
914
915 /**
916 * @ngdoc method
917 * @name $animate#enter
918 * @kind function
919 *
920 * @description
921 * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once
922 * the animation is started, the following CSS classes will be present on the element for the duration of the animation:
923 *
924 * Below is a breakdown of each step that occurs during enter animation:
925 *
926 * | Animation Step | What the element class attribute looks like |
927 * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
928 * | 1. $animate.enter(...) is called | class="my-animation" |
929 * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" |
930 * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
931 * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
932 * | 5. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" |
933 * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" |
934 * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-enter class styling is applied right away | class="my-animation ng-animate ng-enter" |
935 * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter" |
936 * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter" |
937 * | 10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active" |
938 * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active" |
939 * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
940 * | 13. The returned promise is resolved. | class="my-animation" |
941 *
942 * @param {DOMElement} element the element that will be the focus of the enter animation
943 * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation
944 * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation
945 * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation
946 * @return {Promise} the animation callback promise
947 */
948 enter: function(element, parentElement, afterElement, options) {
949 options = parseAnimateOptions(options);
950 element = angular.element(element);
951 parentElement = prepareElement(parentElement);
952 afterElement = prepareElement(afterElement);
953
954 classBasedAnimationsBlocked(element, true);
955 $delegate.enter(element, parentElement, afterElement);
956 return runAnimationPostDigest(function(done) {
957 return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);
958 });
959 },
960
961 /**
962 * @ngdoc method
963 * @name $animate#leave
964 * @kind function
965 *
966 * @description
967 * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once
968 * the animation is started, the following CSS classes will be added for the duration of the animation:
969 *
970 * Below is a breakdown of each step that occurs during leave animation:
971 *
972 * | Animation Step | What the element class attribute looks like |
973 * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
974 * | 1. $animate.leave(...) is called | class="my-animation" |
975 * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
976 * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
977 * | 4. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" |
978 * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" |
979 * | 6. $animate blocks all CSS transitions on the element to ensure the .ng-leave class styling is applied right away | class="my-animation ng-animate ng-leave" |
980 * | 7. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-leave" |
981 * | 8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave" |
982 * | 9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active" |
983 * | 10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active" |
984 * | 11. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
985 * | 12. The element is removed from the DOM | ... |
986 * | 13. The returned promise is resolved. | ... |
987 *
988 * @param {DOMElement} element the element that will be the focus of the leave animation
989 * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
990 * @return {Promise} the animation callback promise
991 */
992 leave: function(element, options) {
993 options = parseAnimateOptions(options);
994 element = angular.element(element);
995
996 cancelChildAnimations(element);
997 classBasedAnimationsBlocked(element, true);
998 return runAnimationPostDigest(function(done) {
999 return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {
1000 $delegate.leave(element);
1001 }, options, done);
1002 });
1003 },
1004
1005 /**
1006 * @ngdoc method
1007 * @name $animate#move
1008 * @kind function
1009 *
1010 * @description
1011 * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or
1012 * add the element directly after the afterElement element if present. Then the move animation will be run. Once
1013 * the animation is started, the following CSS classes will be added for the duration of the animation:
1014 *
1015 * Below is a breakdown of each step that occurs during move animation:
1016 *
1017 * | Animation Step | What the element class attribute looks like |
1018 * |------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------|
1019 * | 1. $animate.move(...) is called | class="my-animation" |
1020 * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" |
1021 * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
1022 * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
1023 * | 5. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" |
1024 * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" |
1025 * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-move class styling is applied right away | class="my-animation ng-animate ng-move" |
1026 * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move" |
1027 * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move" |
1028 * | 10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active" |
1029 * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active" |
1030 * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
1031 * | 13. The returned promise is resolved. | class="my-animation" |
1032 *
1033 * @param {DOMElement} element the element that will be the focus of the move animation
1034 * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation
1035 * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation
1036 * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
1037 * @return {Promise} the animation callback promise
1038 */
1039 move: function(element, parentElement, afterElement, options) {
1040 options = parseAnimateOptions(options);
1041 element = angular.element(element);
1042 parentElement = prepareElement(parentElement);
1043 afterElement = prepareElement(afterElement);
1044
1045 cancelChildAnimations(element);
1046 classBasedAnimationsBlocked(element, true);
1047 $delegate.move(element, parentElement, afterElement);
1048 return runAnimationPostDigest(function(done) {
1049 return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);
1050 });
1051 },
1052
1053 /**
1054 * @ngdoc method
1055 * @name $animate#addClass
1056 *
1057 * @description
1058 * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.
1059 * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide
1060 * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions
1061 * or keyframes are defined on the -add-active or base CSS class).
1062 *
1063 * Below is a breakdown of each step that occurs during addClass animation:
1064 *
1065 * | Animation Step | What the element class attribute looks like |
1066 * |----------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
1067 * | 1. $animate.addClass(element, 'super') is called | class="my-animation" |
1068 * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
1069 * | 3. the .super-add class is added to the element | class="my-animation ng-animate super-add" |
1070 * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate super-add" |
1071 * | 5. the .super and .super-add-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate super super-add super-add-active" |
1072 * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super super-add super-add-active" |
1073 * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super super-add super-add-active" |
1074 * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" |
1075 * | 9. The super class is kept on the element | class="my-animation super" |
1076 * | 10. The returned promise is resolved. | class="my-animation super" |
1077 *
1078 * @param {DOMElement} element the element that will be animated
1079 * @param {string} className the CSS class that will be added to the element and then animated
1080 * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
1081 * @return {Promise} the animation callback promise
1082 */
1083 addClass: function(element, className, options) {
1084 return this.setClass(element, className, [], options);
1085 },
1086
1087 /**
1088 * @ngdoc method
1089 * @name $animate#removeClass
1090 *
1091 * @description
1092 * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value
1093 * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in
1094 * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if
1095 * no CSS transitions or keyframes are defined on the -remove or base CSS classes).
1096 *
1097 * Below is a breakdown of each step that occurs during removeClass animation:
1098 *
1099 * | Animation Step | What the element class attribute looks like |
1100 * |------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
1101 * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" |
1102 * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate" |
1103 * | 3. the .super-remove class is added to the element | class="my-animation super ng-animate super-remove" |
1104 * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove" |
1105 * | 5. the .super-remove-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate super-remove super-remove-active" |
1106 * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-remove super-remove-active" |
1107 * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active" |
1108 * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
1109 * | 9. The returned promise is resolved. | class="my-animation" |
1110 *
1111 *
1112 * @param {DOMElement} element the element that will be animated
1113 * @param {string} className the CSS class that will be animated and then removed from the element
1114 * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
1115 * @return {Promise} the animation callback promise
1116 */
1117 removeClass: function(element, className, options) {
1118 return this.setClass(element, [], className, options);
1119 },
1120
1121 /**
1122 *
1123 * @ngdoc method
1124 * @name $animate#setClass
1125 *
1126 * @description Adds and/or removes the given CSS classes to and from the element.
1127 * Once complete, the done() callback will be fired (if provided).
1128 *
1129 * | Animation Step | What the element class attribute looks like |
1130 * |--------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
1131 * | 1. $animate.setClass(element, 'on', 'off') is called | class="my-animation off" |
1132 * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate off" |
1133 * | 3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off" |
1134 * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off" |
1135 * | 5. the .on, .on-add-active and .off-remove-active classes are added and .off is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
1136 * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
1137 * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
1138 * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation on" |
1139 * | 9. The returned promise is resolved. | class="my-animation on" |
1140 *
1141 * @param {DOMElement} element the element which will have its CSS classes changed
1142 * removed from it
1143 * @param {string} add the CSS classes which will be added to the element
1144 * @param {string} remove the CSS class which will be removed from the element
1145 * CSS classes have been set on the element
1146 * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
1147 * @return {Promise} the animation callback promise
1148 */
1149 setClass: function(element, add, remove, options) {
1150 options = parseAnimateOptions(options);
1151
1152 var STORAGE_KEY = '$$animateClasses';
1153 element = angular.element(element);
1154 element = stripCommentsFromElement(element);
1155
1156 if (classBasedAnimationsBlocked(element)) {
1157 return $delegate.$$setClassImmediately(element, add, remove, options);
1158 }
1159
1160 // we're using a combined array for both the add and remove
1161 // operations since the ORDER OF addClass and removeClass matters
1162 var classes, cache = element.data(STORAGE_KEY);
1163 var hasCache = !!cache;
1164 if (!cache) {
1165 cache = {};
1166 cache.classes = {};
1167 }
1168 classes = cache.classes;
1169
1170 add = isArray(add) ? add : add.split(' ');
1171 forEach(add, function(c) {
1172 if (c && c.length) {
1173 classes[c] = true;
1174 }
1175 });
1176
1177 remove = isArray(remove) ? remove : remove.split(' ');
1178 forEach(remove, function(c) {
1179 if (c && c.length) {
1180 classes[c] = false;
1181 }
1182 });
1183
1184 if (hasCache) {
1185 if (options && cache.options) {
1186 cache.options = angular.extend(cache.options || {}, options);
1187 }
1188
1189 //the digest cycle will combine all the animations into one function
1190 return cache.promise;
1191 } else {
1192 element.data(STORAGE_KEY, cache = {
1193 classes: classes,
1194 options: options
1195 });
1196 }
1197
1198 return cache.promise = runAnimationPostDigest(function(done) {
1199 var parentElement = element.parent();
1200 var elementNode = extractElementNode(element);
1201 var parentNode = elementNode.parentNode;
1202 // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed
1203 if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) {
1204 done();
1205 return;
1206 }
1207
1208 var cache = element.data(STORAGE_KEY);
1209 element.removeData(STORAGE_KEY);
1210
1211 var state = element.data(NG_ANIMATE_STATE) || {};
1212 var classes = resolveElementClasses(element, cache, state.active);
1213 return !classes
1214 ? done()
1215 : performAnimation('setClass', classes, element, parentElement, null, function() {
1216 if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]);
1217 if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]);
1218 }, cache.options, done);
1219 });
1220 },
1221
1222 /**
1223 * @ngdoc method
1224 * @name $animate#cancel
1225 * @kind function
1226 *
1227 * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
1228 *
1229 * @description
1230 * Cancels the provided animation.
1231 */
1232 cancel: function(promise) {
1233 promise.$$cancelFn();
1234 },
1235
1236 /**
1237 * @ngdoc method
1238 * @name $animate#enabled
1239 * @kind function
1240 *
1241 * @param {boolean=} value If provided then set the animation on or off.
1242 * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation
1243 * @return {boolean} Current animation state.
1244 *
1245 * @description
1246 * Globally enables/disables animations.
1247 *
1248 */
1249 enabled: function(value, element) {
1250 switch (arguments.length) {
1251 case 2:
1252 if (value) {
1253 cleanup(element);
1254 } else {
1255 var data = element.data(NG_ANIMATE_STATE) || {};
1256 data.disabled = true;
1257 element.data(NG_ANIMATE_STATE, data);
1258 }
1259 break;
1260
1261 case 1:
1262 rootAnimateState.disabled = !value;
1263 break;
1264
1265 default:
1266 value = !rootAnimateState.disabled;
1267 break;
1268 }
1269 return !!value;
1270 }
1271 };
1272
1273 /*
1274 all animations call this shared animation triggering function internally.
1275 The animationEvent variable refers to the JavaScript animation event that will be triggered
1276 and the className value is the name of the animation that will be applied within the
1277 CSS code. Element, parentElement and afterElement are provided DOM elements for the animation
1278 and the onComplete callback will be fired once the animation is fully complete.
1279 */
1280 function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) {
1281 var noopCancel = noop;
1282 var runner = animationRunner(element, animationEvent, className, options);
1283 if (!runner) {
1284 fireDOMOperation();
1285 fireBeforeCallbackAsync();
1286 fireAfterCallbackAsync();
1287 closeAnimation();
1288 return noopCancel;
1289 }
1290
1291 animationEvent = runner.event;
1292 className = runner.className;
1293 var elementEvents = angular.element._data(runner.node);
1294 elementEvents = elementEvents && elementEvents.events;
1295
1296 if (!parentElement) {
1297 parentElement = afterElement ? afterElement.parent() : element.parent();
1298 }
1299
1300 //skip the animation if animations are disabled, a parent is already being animated,
1301 //the element is not currently attached to the document body or then completely close
1302 //the animation if any matching animations are not found at all.
1303 //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.
1304 if (animationsDisabled(element, parentElement)) {
1305 fireDOMOperation();
1306 fireBeforeCallbackAsync();
1307 fireAfterCallbackAsync();
1308 closeAnimation();
1309 return noopCancel;
1310 }
1311
1312 var ngAnimateState = element.data(NG_ANIMATE_STATE) || {};
1313 var runningAnimations = ngAnimateState.active || {};
1314 var totalActiveAnimations = ngAnimateState.totalActive || 0;
1315 var lastAnimation = ngAnimateState.last;
1316 var skipAnimation = false;
1317
1318 if (totalActiveAnimations > 0) {
1319 var animationsToCancel = [];
1320 if (!runner.isClassBased) {
1321 if (animationEvent == 'leave' && runningAnimations['ng-leave']) {
1322 skipAnimation = true;
1323 } else {
1324 //cancel all animations when a structural animation takes place
1325 for (var klass in runningAnimations) {
1326 animationsToCancel.push(runningAnimations[klass]);
1327 }
1328 ngAnimateState = {};
1329 cleanup(element, true);
1330 }
1331 } else if (lastAnimation.event == 'setClass') {
1332 animationsToCancel.push(lastAnimation);
1333 cleanup(element, className);
1334 }
1335 else if (runningAnimations[className]) {
1336 var current = runningAnimations[className];
1337 if (current.event == animationEvent) {
1338 skipAnimation = true;
1339 } else {
1340 animationsToCancel.push(current);
1341 cleanup(element, className);
1342 }
1343 }
1344
1345 if (animationsToCancel.length > 0) {
1346 forEach(animationsToCancel, function(operation) {
1347 operation.cancel();
1348 });
1349 }
1350 }
1351
1352 if (runner.isClassBased
1353 && !runner.isSetClassOperation
1354 && animationEvent != 'animate'
1355 && !skipAnimation) {
1356 skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR
1357 }
1358
1359 if (skipAnimation) {
1360 fireDOMOperation();
1361 fireBeforeCallbackAsync();
1362 fireAfterCallbackAsync();
1363 fireDoneCallbackAsync();
1364 return noopCancel;
1365 }
1366
1367 runningAnimations = ngAnimateState.active || {};
1368 totalActiveAnimations = ngAnimateState.totalActive || 0;
1369
1370 if (animationEvent == 'leave') {
1371 //there's no need to ever remove the listener since the element
1372 //will be removed (destroyed) after the leave animation ends or
1373 //is cancelled midway
1374 element.one('$destroy', function(e) {
1375 var element = angular.element(this);
1376 var state = element.data(NG_ANIMATE_STATE);
1377 if (state) {
1378 var activeLeaveAnimation = state.active['ng-leave'];
1379 if (activeLeaveAnimation) {
1380 activeLeaveAnimation.cancel();
1381 cleanup(element, 'ng-leave');
1382 }
1383 }
1384 });
1385 }
1386
1387 //the ng-animate class does nothing, but it's here to allow for
1388 //parent animations to find and cancel child animations when needed
1389 element.addClass(NG_ANIMATE_CLASS_NAME);
1390 if (options && options.tempClasses) {
1391 forEach(options.tempClasses, function(className) {
1392 element.addClass(className);
1393 });
1394 }
1395
1396 var localAnimationCount = globalAnimationCounter++;
1397 totalActiveAnimations++;
1398 runningAnimations[className] = runner;
1399
1400 element.data(NG_ANIMATE_STATE, {
1401 last: runner,
1402 active: runningAnimations,
1403 index: localAnimationCount,
1404 totalActive: totalActiveAnimations
1405 });
1406
1407 //first we run the before animations and when all of those are complete
1408 //then we perform the DOM operation and run the next set of animations
1409 fireBeforeCallbackAsync();
1410 runner.before(function(cancelled) {
1411 var data = element.data(NG_ANIMATE_STATE);
1412 cancelled = cancelled ||
1413 !data || !data.active[className] ||
1414 (runner.isClassBased && data.active[className].event != animationEvent);
1415
1416 fireDOMOperation();
1417 if (cancelled === true) {
1418 closeAnimation();
1419 } else {
1420 fireAfterCallbackAsync();
1421 runner.after(closeAnimation);
1422 }
1423 });
1424
1425 return runner.cancel;
1426
1427 function fireDOMCallback(animationPhase) {
1428 var eventName = '$animate:' + animationPhase;
1429 if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {
1430 $$asyncCallback(function() {
1431 element.triggerHandler(eventName, {
1432 event: animationEvent,
1433 className: className
1434 });
1435 });
1436 }
1437 }
1438
1439 function fireBeforeCallbackAsync() {
1440 fireDOMCallback('before');
1441 }
1442
1443 function fireAfterCallbackAsync() {
1444 fireDOMCallback('after');
1445 }
1446
1447 function fireDoneCallbackAsync() {
1448 fireDOMCallback('close');
1449 doneCallback();
1450 }
1451
1452 //it is less complicated to use a flag than managing and canceling
1453 //timeouts containing multiple callbacks.
1454 function fireDOMOperation() {
1455 if (!fireDOMOperation.hasBeenRun) {
1456 fireDOMOperation.hasBeenRun = true;
1457 domOperation();
1458 }
1459 }
1460
1461 function closeAnimation() {
1462 if (!closeAnimation.hasBeenRun) {
1463 if (runner) { //the runner doesn't exist if it fails to instantiate
1464 runner.applyStyles();
1465 }
1466
1467 closeAnimation.hasBeenRun = true;
1468 if (options && options.tempClasses) {
1469 forEach(options.tempClasses, function(className) {
1470 element.removeClass(className);
1471 });
1472 }
1473
1474 var data = element.data(NG_ANIMATE_STATE);
1475 if (data) {
1476
1477 /* only structural animations wait for reflow before removing an
1478 animation, but class-based animations don't. An example of this
1479 failing would be when a parent HTML tag has a ng-class attribute
1480 causing ALL directives below to skip animations during the digest */
1481 if (runner && runner.isClassBased) {
1482 cleanup(element, className);
1483 } else {
1484 $$asyncCallback(function() {
1485 var data = element.data(NG_ANIMATE_STATE) || {};
1486 if (localAnimationCount == data.index) {
1487 cleanup(element, className, animationEvent);
1488 }
1489 });
1490 element.data(NG_ANIMATE_STATE, data);
1491 }
1492 }
1493 fireDoneCallbackAsync();
1494 }
1495 }
1496 }
1497
1498 function cancelChildAnimations(element) {
1499 var node = extractElementNode(element);
1500 if (node) {
1501 var nodes = angular.isFunction(node.getElementsByClassName) ?
1502 node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :
1503 node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);
1504 forEach(nodes, function(element) {
1505 element = angular.element(element);
1506 var data = element.data(NG_ANIMATE_STATE);
1507 if (data && data.active) {
1508 forEach(data.active, function(runner) {
1509 runner.cancel();
1510 });
1511 }
1512 });
1513 }
1514 }
1515
1516 function cleanup(element, className) {
1517 if (isMatchingElement(element, $rootElement)) {
1518 if (!rootAnimateState.disabled) {
1519 rootAnimateState.running = false;
1520 rootAnimateState.structural = false;
1521 }
1522 } else if (className) {
1523 var data = element.data(NG_ANIMATE_STATE) || {};
1524
1525 var removeAnimations = className === true;
1526 if (!removeAnimations && data.active && data.active[className]) {
1527 data.totalActive--;
1528 delete data.active[className];
1529 }
1530
1531 if (removeAnimations || !data.totalActive) {
1532 element.removeClass(NG_ANIMATE_CLASS_NAME);
1533 element.removeData(NG_ANIMATE_STATE);
1534 }
1535 }
1536 }
1537
1538 function animationsDisabled(element, parentElement) {
1539 if (rootAnimateState.disabled) {
1540 return true;
1541 }
1542
1543 if (isMatchingElement(element, $rootElement)) {
1544 return rootAnimateState.running;
1545 }
1546
1547 var allowChildAnimations, parentRunningAnimation, hasParent;
1548 do {
1549 //the element did not reach the root element which means that it
1550 //is not apart of the DOM. Therefore there is no reason to do
1551 //any animations on it
1552 if (parentElement.length === 0) break;
1553
1554 var isRoot = isMatchingElement(parentElement, $rootElement);
1555 var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {});
1556 if (state.disabled) {
1557 return true;
1558 }
1559
1560 //no matter what, for an animation to work it must reach the root element
1561 //this implies that the element is attached to the DOM when the animation is run
1562 if (isRoot) {
1563 hasParent = true;
1564 }
1565
1566 //once a flag is found that is strictly false then everything before
1567 //it will be discarded and all child animations will be restricted
1568 if (allowChildAnimations !== false) {
1569 var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN);
1570 if (angular.isDefined(animateChildrenFlag)) {
1571 allowChildAnimations = animateChildrenFlag;
1572 }
1573 }
1574
1575 parentRunningAnimation = parentRunningAnimation ||
1576 state.running ||
1577 (state.last && !state.last.isClassBased);
1578 }
1579 while (parentElement = parentElement.parent());
1580
1581 return !hasParent || (!allowChildAnimations && parentRunningAnimation);
1582 }
1583 }]);
1584
1585 $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',
1586 function($window, $sniffer, $timeout, $$animateReflow) {
1587 // Detect proper transitionend/animationend event names.
1588 var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
1589
1590 // If unprefixed events are not supported but webkit-prefixed are, use the latter.
1591 // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
1592 // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
1593 // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
1594 // Register both events in case `window.onanimationend` is not supported because of that,
1595 // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
1596 // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
1597 // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition
1598 if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
1599 CSS_PREFIX = '-webkit-';
1600 TRANSITION_PROP = 'WebkitTransition';
1601 TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
1602 } else {
1603 TRANSITION_PROP = 'transition';
1604 TRANSITIONEND_EVENT = 'transitionend';
1605 }
1606
1607 if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
1608 CSS_PREFIX = '-webkit-';
1609 ANIMATION_PROP = 'WebkitAnimation';
1610 ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
1611 } else {
1612 ANIMATION_PROP = 'animation';
1613 ANIMATIONEND_EVENT = 'animationend';
1614 }
1615
1616 var DURATION_KEY = 'Duration';
1617 var PROPERTY_KEY = 'Property';
1618 var DELAY_KEY = 'Delay';
1619 var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
1620 var ANIMATION_PLAYSTATE_KEY = 'PlayState';
1621 var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';
1622 var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';
1623 var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
1624 var CLOSING_TIME_BUFFER = 1.5;
1625 var ONE_SECOND = 1000;
1626
1627 var lookupCache = {};
1628 var parentCounter = 0;
1629 var animationReflowQueue = [];
1630 var cancelAnimationReflow;
1631 function clearCacheAfterReflow() {
1632 if (!cancelAnimationReflow) {
1633 cancelAnimationReflow = $$animateReflow(function() {
1634 animationReflowQueue = [];
1635 cancelAnimationReflow = null;
1636 lookupCache = {};
1637 });
1638 }
1639 }
1640
1641 function afterReflow(element, callback) {
1642 if (cancelAnimationReflow) {
1643 cancelAnimationReflow();
1644 }
1645 animationReflowQueue.push(callback);
1646 cancelAnimationReflow = $$animateReflow(function() {
1647 forEach(animationReflowQueue, function(fn) {
1648 fn();
1649 });
1650
1651 animationReflowQueue = [];
1652 cancelAnimationReflow = null;
1653 lookupCache = {};
1654 });
1655 }
1656
1657 var closingTimer = null;
1658 var closingTimestamp = 0;
1659 var animationElementQueue = [];
1660 function animationCloseHandler(element, totalTime) {
1661 var node = extractElementNode(element);
1662 element = angular.element(node);
1663
1664 //this item will be garbage collected by the closing
1665 //animation timeout
1666 animationElementQueue.push(element);
1667
1668 //but it may not need to cancel out the existing timeout
1669 //if the timestamp is less than the previous one
1670 var futureTimestamp = Date.now() + totalTime;
1671 if (futureTimestamp <= closingTimestamp) {
1672 return;
1673 }
1674
1675 $timeout.cancel(closingTimer);
1676
1677 closingTimestamp = futureTimestamp;
1678 closingTimer = $timeout(function() {
1679 closeAllAnimations(animationElementQueue);
1680 animationElementQueue = [];
1681 }, totalTime, false);
1682 }
1683
1684 function closeAllAnimations(elements) {
1685 forEach(elements, function(element) {
1686 var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
1687 if (elementData) {
1688 forEach(elementData.closeAnimationFns, function(fn) {
1689 fn();
1690 });
1691 }
1692 });
1693 }
1694
1695 function getElementAnimationDetails(element, cacheKey) {
1696 var data = cacheKey ? lookupCache[cacheKey] : null;
1697 if (!data) {
1698 var transitionDuration = 0;
1699 var transitionDelay = 0;
1700 var animationDuration = 0;
1701 var animationDelay = 0;
1702
1703 //we want all the styles defined before and after
1704 forEach(element, function(element) {
1705 if (element.nodeType == ELEMENT_NODE) {
1706 var elementStyles = $window.getComputedStyle(element) || {};
1707
1708 var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];
1709 transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);
1710
1711 var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];
1712 transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);
1713
1714 var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];
1715 animationDelay = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay);
1716
1717 var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);
1718
1719 if (aDuration > 0) {
1720 aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;
1721 }
1722 animationDuration = Math.max(aDuration, animationDuration);
1723 }
1724 });
1725 data = {
1726 total: 0,
1727 transitionDelay: transitionDelay,
1728 transitionDuration: transitionDuration,
1729 animationDelay: animationDelay,
1730 animationDuration: animationDuration
1731 };
1732 if (cacheKey) {
1733 lookupCache[cacheKey] = data;
1734 }
1735 }
1736 return data;
1737 }
1738
1739 function parseMaxTime(str) {
1740 var maxValue = 0;
1741 var values = isString(str) ?
1742 str.split(/\s*,\s*/) :
1743 [];
1744 forEach(values, function(value) {
1745 maxValue = Math.max(parseFloat(value) || 0, maxValue);
1746 });
1747 return maxValue;
1748 }
1749
1750 function getCacheKey(element) {
1751 var parentElement = element.parent();
1752 var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);
1753 if (!parentID) {
1754 parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);
1755 parentID = parentCounter;
1756 }
1757 return parentID + '-' + extractElementNode(element).getAttribute('class');
1758 }
1759
1760 function animateSetup(animationEvent, element, className, styles) {
1761 var structural = ['ng-enter','ng-leave','ng-move'].indexOf(className) >= 0;
1762
1763 var cacheKey = getCacheKey(element);
1764 var eventCacheKey = cacheKey + ' ' + className;
1765 var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;
1766
1767 var stagger = {};
1768 if (itemIndex > 0) {
1769 var staggerClassName = className + '-stagger';
1770 var staggerCacheKey = cacheKey + ' ' + staggerClassName;
1771 var applyClasses = !lookupCache[staggerCacheKey];
1772
1773 applyClasses && element.addClass(staggerClassName);
1774
1775 stagger = getElementAnimationDetails(element, staggerCacheKey);
1776
1777 applyClasses && element.removeClass(staggerClassName);
1778 }
1779
1780 element.addClass(className);
1781
1782 var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};
1783 var timings = getElementAnimationDetails(element, eventCacheKey);
1784 var transitionDuration = timings.transitionDuration;
1785 var animationDuration = timings.animationDuration;
1786
1787 if (structural && transitionDuration === 0 && animationDuration === 0) {
1788 element.removeClass(className);
1789 return false;
1790 }
1791
1792 var blockTransition = styles || (structural && transitionDuration > 0);
1793 var blockAnimation = animationDuration > 0 &&
1794 stagger.animationDelay > 0 &&
1795 stagger.animationDuration === 0;
1796
1797 var closeAnimationFns = formerData.closeAnimationFns || [];
1798 element.data(NG_ANIMATE_CSS_DATA_KEY, {
1799 stagger: stagger,
1800 cacheKey: eventCacheKey,
1801 running: formerData.running || 0,
1802 itemIndex: itemIndex,
1803 blockTransition: blockTransition,
1804 closeAnimationFns: closeAnimationFns
1805 });
1806
1807 var node = extractElementNode(element);
1808
1809 if (blockTransition) {
1810 blockTransitions(node, true);
1811 if (styles) {
1812 element.css(styles);
1813 }
1814 }
1815
1816 if (blockAnimation) {
1817 blockAnimations(node, true);
1818 }
1819
1820 return true;
1821 }
1822
1823 function animateRun(animationEvent, element, className, activeAnimationComplete, styles) {
1824 var node = extractElementNode(element);
1825 var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
1826 if (node.getAttribute('class').indexOf(className) == -1 || !elementData) {
1827 activeAnimationComplete();
1828 return;
1829 }
1830
1831 var activeClassName = '';
1832 var pendingClassName = '';
1833 forEach(className.split(' '), function(klass, i) {
1834 var prefix = (i > 0 ? ' ' : '') + klass;
1835 activeClassName += prefix + '-active';
1836 pendingClassName += prefix + '-pending';
1837 });
1838
1839 var style = '';
1840 var appliedStyles = [];
1841 var itemIndex = elementData.itemIndex;
1842 var stagger = elementData.stagger;
1843 var staggerTime = 0;
1844 if (itemIndex > 0) {
1845 var transitionStaggerDelay = 0;
1846 if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {
1847 transitionStaggerDelay = stagger.transitionDelay * itemIndex;
1848 }
1849
1850 var animationStaggerDelay = 0;
1851 if (stagger.animationDelay > 0 && stagger.animationDuration === 0) {
1852 animationStaggerDelay = stagger.animationDelay * itemIndex;
1853 appliedStyles.push(CSS_PREFIX + 'animation-play-state');
1854 }
1855
1856 staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100;
1857 }
1858
1859 if (!staggerTime) {
1860 element.addClass(activeClassName);
1861 if (elementData.blockTransition) {
1862 blockTransitions(node, false);
1863 }
1864 }
1865
1866 var eventCacheKey = elementData.cacheKey + ' ' + activeClassName;
1867 var timings = getElementAnimationDetails(element, eventCacheKey);
1868 var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);
1869 if (maxDuration === 0) {
1870 element.removeClass(activeClassName);
1871 animateClose(element, className);
1872 activeAnimationComplete();
1873 return;
1874 }
1875
1876 if (!staggerTime && styles) {
1877 if (!timings.transitionDuration) {
1878 element.css('transition', timings.animationDuration + 's linear all');
1879 appliedStyles.push('transition');
1880 }
1881 element.css(styles);
1882 }
1883
1884 var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);
1885 var maxDelayTime = maxDelay * ONE_SECOND;
1886
1887 if (appliedStyles.length > 0) {
1888 //the element being animated may sometimes contain comment nodes in
1889 //the jqLite object, so we're safe to use a single variable to house
1890 //the styles since there is always only one element being animated
1891 var oldStyle = node.getAttribute('style') || '';
1892 if (oldStyle.charAt(oldStyle.length - 1) !== ';') {
1893 oldStyle += ';';
1894 }
1895 node.setAttribute('style', oldStyle + ' ' + style);
1896 }
1897
1898 var startTime = Date.now();
1899 var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;
1900 var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;
1901 var totalTime = (staggerTime + animationTime) * ONE_SECOND;
1902
1903 var staggerTimeout;
1904 if (staggerTime > 0) {
1905 element.addClass(pendingClassName);
1906 staggerTimeout = $timeout(function() {
1907 staggerTimeout = null;
1908
1909 if (timings.transitionDuration > 0) {
1910 blockTransitions(node, false);
1911 }
1912 if (timings.animationDuration > 0) {
1913 blockAnimations(node, false);
1914 }
1915
1916 element.addClass(activeClassName);
1917 element.removeClass(pendingClassName);
1918
1919 if (styles) {
1920 if (timings.transitionDuration === 0) {
1921 element.css('transition', timings.animationDuration + 's linear all');
1922 }
1923 element.css(styles);
1924 appliedStyles.push('transition');
1925 }
1926 }, staggerTime * ONE_SECOND, false);
1927 }
1928
1929 element.on(css3AnimationEvents, onAnimationProgress);
1930 elementData.closeAnimationFns.push(function() {
1931 onEnd();
1932 activeAnimationComplete();
1933 });
1934
1935 elementData.running++;
1936 animationCloseHandler(element, totalTime);
1937 return onEnd;
1938
1939 // This will automatically be called by $animate so
1940 // there is no need to attach this internally to the
1941 // timeout done method.
1942 function onEnd() {
1943 element.off(css3AnimationEvents, onAnimationProgress);
1944 element.removeClass(activeClassName);
1945 element.removeClass(pendingClassName);
1946 if (staggerTimeout) {
1947 $timeout.cancel(staggerTimeout);
1948 }
1949 animateClose(element, className);
1950 var node = extractElementNode(element);
1951 for (var i in appliedStyles) {
1952 node.style.removeProperty(appliedStyles[i]);
1953 }
1954 }
1955
1956 function onAnimationProgress(event) {
1957 event.stopPropagation();
1958 var ev = event.originalEvent || event;
1959 var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
1960
1961 /* Firefox (or possibly just Gecko) likes to not round values up
1962 * when a ms measurement is used for the animation */
1963 var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
1964
1965 /* $manualTimeStamp is a mocked timeStamp value which is set
1966 * within browserTrigger(). This is only here so that tests can
1967 * mock animations properly. Real events fallback to event.timeStamp,
1968 * or, if they don't, then a timeStamp is automatically created for them.
1969 * We're checking to see if the timeStamp surpasses the expected delay,
1970 * but we're using elapsedTime instead of the timeStamp on the 2nd
1971 * pre-condition since animations sometimes close off early */
1972 if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
1973 activeAnimationComplete();
1974 }
1975 }
1976 }
1977
1978 function blockTransitions(node, bool) {
1979 node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : '';
1980 }
1981
1982 function blockAnimations(node, bool) {
1983 node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : '';
1984 }
1985
1986 function animateBefore(animationEvent, element, className, styles) {
1987 if (animateSetup(animationEvent, element, className, styles)) {
1988 return function(cancelled) {
1989 cancelled && animateClose(element, className);
1990 };
1991 }
1992 }
1993
1994 function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) {
1995 if (element.data(NG_ANIMATE_CSS_DATA_KEY)) {
1996 return animateRun(animationEvent, element, className, afterAnimationComplete, styles);
1997 } else {
1998 animateClose(element, className);
1999 afterAnimationComplete();
2000 }
2001 }
2002
2003 function animate(animationEvent, element, className, animationComplete, options) {
2004 //If the animateSetup function doesn't bother returning a
2005 //cancellation function then it means that there is no animation
2006 //to perform at all
2007 var preReflowCancellation = animateBefore(animationEvent, element, className, options.from);
2008 if (!preReflowCancellation) {
2009 clearCacheAfterReflow();
2010 animationComplete();
2011 return;
2012 }
2013
2014 //There are two cancellation functions: one is before the first
2015 //reflow animation and the second is during the active state
2016 //animation. The first function will take care of removing the
2017 //data from the element which will not make the 2nd animation
2018 //happen in the first place
2019 var cancel = preReflowCancellation;
2020 afterReflow(element, function() {
2021 //once the reflow is complete then we point cancel to
2022 //the new cancellation function which will remove all of the
2023 //animation properties from the active animation
2024 cancel = animateAfter(animationEvent, element, className, animationComplete, options.to);
2025 });
2026
2027 return function(cancelled) {
2028 (cancel || noop)(cancelled);
2029 };
2030 }
2031
2032 function animateClose(element, className) {
2033 element.removeClass(className);
2034 var data = element.data(NG_ANIMATE_CSS_DATA_KEY);
2035 if (data) {
2036 if (data.running) {
2037 data.running--;
2038 }
2039 if (!data.running || data.running === 0) {
2040 element.removeData(NG_ANIMATE_CSS_DATA_KEY);
2041 }
2042 }
2043 }
2044
2045 return {
2046 animate: function(element, className, from, to, animationCompleted, options) {
2047 options = options || {};
2048 options.from = from;
2049 options.to = to;
2050 return animate('animate', element, className, animationCompleted, options);
2051 },
2052
2053 enter: function(element, animationCompleted, options) {
2054 options = options || {};
2055 return animate('enter', element, 'ng-enter', animationCompleted, options);
2056 },
2057
2058 leave: function(element, animationCompleted, options) {
2059 options = options || {};
2060 return animate('leave', element, 'ng-leave', animationCompleted, options);
2061 },
2062
2063 move: function(element, animationCompleted, options) {
2064 options = options || {};
2065 return animate('move', element, 'ng-move', animationCompleted, options);
2066 },
2067
2068 beforeSetClass: function(element, add, remove, animationCompleted, options) {
2069 options = options || {};
2070 var className = suffixClasses(remove, '-remove') + ' ' +
2071 suffixClasses(add, '-add');
2072 var cancellationMethod = animateBefore('setClass', element, className, options.from);
2073 if (cancellationMethod) {
2074 afterReflow(element, animationCompleted);
2075 return cancellationMethod;
2076 }
2077 clearCacheAfterReflow();
2078 animationCompleted();
2079 },
2080
2081 beforeAddClass: function(element, className, animationCompleted, options) {
2082 options = options || {};
2083 var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from);
2084 if (cancellationMethod) {
2085 afterReflow(element, animationCompleted);
2086 return cancellationMethod;
2087 }
2088 clearCacheAfterReflow();
2089 animationCompleted();
2090 },
2091
2092 beforeRemoveClass: function(element, className, animationCompleted, options) {
2093 options = options || {};
2094 var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from);
2095 if (cancellationMethod) {
2096 afterReflow(element, animationCompleted);
2097 return cancellationMethod;
2098 }
2099 clearCacheAfterReflow();
2100 animationCompleted();
2101 },
2102
2103 setClass: function(element, add, remove, animationCompleted, options) {
2104 options = options || {};
2105 remove = suffixClasses(remove, '-remove');
2106 add = suffixClasses(add, '-add');
2107 var className = remove + ' ' + add;
2108 return animateAfter('setClass', element, className, animationCompleted, options.to);
2109 },
2110
2111 addClass: function(element, className, animationCompleted, options) {
2112 options = options || {};
2113 return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to);
2114 },
2115
2116 removeClass: function(element, className, animationCompleted, options) {
2117 options = options || {};
2118 return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to);
2119 }
2120 };
2121
2122 function suffixClasses(classes, suffix) {
2123 var className = '';
2124 classes = isArray(classes) ? classes : classes.split(/\s+/);
2125 forEach(classes, function(klass, i) {
2126 if (klass && klass.length > 0) {
2127 className += (i > 0 ? ' ' : '') + klass + suffix;
2128 }
2129 });
2130 return className;
2131 }
2132 }]);
2133 }]);
2134
2135
2136})(window, window.angular);