vendor/assets/javascripts/unstable/angular-animate.js in angularjs-rails-1.2.22 vs vendor/assets/javascripts/unstable/angular-animate.js in angularjs-rails-1.2.25

- old
+ new

@@ -1,7 +1,7 @@ /** - * @license AngularJS v1.3.0-beta.18 + * @license AngularJS v1.3.0-rc.3 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; @@ -77,10 +77,20 @@ * ``` * * When the `on` expression value changes and an animation is triggered then each of the elements within * will all animate without the block being applied to child elements. * + * ## Are animations run when the application starts? + * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid + * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work, + * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering + * layout changes in the application will trigger animations as normal. + * + * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular + * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests + * are complete. + * * <h2>CSS-defined Animations</h2> * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported * and can be used to play along with this naming structure. * @@ -268,11 +278,11 @@ * }, 100, false); * ``` * * Stagger animations are currently only supported within CSS-defined animations. * - * <h2>JavaScript-defined Animations</h2> + * ## JavaScript-defined Animations * 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 * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. * * ```js * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. @@ -336,11 +346,11 @@ */ .directive('ngAnimateChildren', function() { var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; return function(scope, element, attrs) { var val = attrs.ngAnimateChildren; - if(angular.isString(val) && val.length === 0) { //empty attribute + if (angular.isString(val) && val.length === 0) { //empty attribute element.data(NG_ANIMATE_CHILDREN, true); } else { scope.$watch(val, function(value) { element.data(NG_ANIMATE_CHILDREN, !!value); }); @@ -370,21 +380,22 @@ .config(['$provide', '$animateProvider', function($provide, $animateProvider) { var noop = angular.noop; var forEach = angular.forEach; var selectors = $animateProvider.$$selectors; + var isArray = angular.isArray; var ELEMENT_NODE = 1; var NG_ANIMATE_STATE = '$$ngAnimateState'; var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; var NG_ANIMATE_CLASS_NAME = 'ng-animate'; var rootAnimateState = {running: true}; function extractElementNode(element) { for(var i = 0; i < element.length; i++) { var elm = element[i]; - if(elm.nodeType == ELEMENT_NODE) { + if (elm.nodeType == ELEMENT_NODE) { return elm; } } } @@ -398,51 +409,126 @@ function isMatchingElement(elm1, elm2) { return extractElementNode(elm1) == extractElementNode(elm2); } - $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', - function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) { + $provide.decorator('$animate', + ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', + function($delegate, $$q, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document, $templateRequest) { - var globalAnimationCounter = 0; $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); - // disable animations during bootstrap, but once we bootstrapped, wait again - // for another digest until enabling animations. The reason why we digest twice - // is because all structural animations (enter, leave and move) all perform a - // post digest operation before animating. If we only wait for a single digest - // to pass then the structural animation would render its animation on page load. - // (which is what we're trying to avoid when the application first boots up.) - $rootScope.$$postDigest(function() { - $rootScope.$$postDigest(function() { - rootAnimateState.running = false; - }); - }); + // Wait until all directive and route-related templates are downloaded and + // compiled. The $templateRequest.totalPendingRequests variable keeps track of + // all of the remote templates being currently downloaded. If there are no + // templates currently downloading then the watcher will still fire anyway. + var deregisterWatch = $rootScope.$watch( + function() { return $templateRequest.totalPendingRequests; }, + function(val, oldVal) { + if (val !== 0) return; + deregisterWatch(); + // Now that all templates have been downloaded, $animate will wait until + // the post digest queue is empty before enabling animations. By having two + // calls to $postDigest calls we can ensure that the flag is enabled at the + // very end of the post digest queue. Since all of the animations in $animate + // use $postDigest, it's important that the code below executes at the end. + // This basically means that the page is fully downloaded and compiled before + // any animations are triggered. + $rootScope.$$postDigest(function() { + $rootScope.$$postDigest(function() { + rootAnimateState.running = false; + }); + }); + } + ); + + var globalAnimationCounter = 0; var classNameFilter = $animateProvider.classNameFilter(); var isAnimatableClassName = !classNameFilter ? function() { return true; } : function(className) { return classNameFilter.test(className); }; - function blockElementAnimations(element) { + function classBasedAnimationsBlocked(element, setter) { var data = element.data(NG_ANIMATE_STATE) || {}; - data.running = true; - element.data(NG_ANIMATE_STATE, data); + if (setter) { + data.running = true; + data.structural = true; + element.data(NG_ANIMATE_STATE, data); + } + return data.disabled || (data.running && data.structural); } function runAnimationPostDigest(fn) { - var cancelFn; - $rootScope.$$postDigest(function() { - cancelFn = fn(); - }); - return function() { + var cancelFn, defer = $$q.defer(); + defer.promise.$$cancelFn = function() { cancelFn && cancelFn(); }; + $rootScope.$$postDigest(function() { + cancelFn = fn(function() { + defer.resolve(); + }); + }); + return defer.promise; } + function resolveElementClasses(element, cache, runningAnimations) { + runningAnimations = runningAnimations || {}; + var map = {}; + + forEach(cache.add, function(className) { + if (className && className.length) { + map[className] = map[className] || 0; + map[className]++; + } + }); + + forEach(cache.remove, function(className) { + if (className && className.length) { + map[className] = map[className] || 0; + map[className]--; + } + }); + + var lookup = []; + forEach(runningAnimations, function(data, selector) { + forEach(selector.split(' '), function(s) { + lookup[s]=data; + }); + }); + + var toAdd = [], toRemove = []; + forEach(map, function(status, className) { + var hasClass = angular.$$hasClass(element[0], className); + var matchingAnimation = lookup[className] || {}; + + // When addClass and removeClass is called then $animate will check to + // see if addClass and removeClass cancel each other out. When there are + // more calls to removeClass than addClass then the count falls below 0 + // and then the removeClass animation will be allowed. Otherwise if the + // count is above 0 then that means an addClass animation will commence. + // Once an animation is allowed then the code will also check to see if + // there exists any on-going animation that is already adding or remvoing + // the matching CSS class. + if (status < 0) { + //does it have the class or will it have the class + if (hasClass || matchingAnimation.event == 'addClass') { + toRemove.push(className); + } + } else if (status > 0) { + //is the class missing or will it be removed? + if (!hasClass || matchingAnimation.event == 'removeClass') { + toAdd.push(className); + } + } + }); + + return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')]; + } + function lookup(name) { if (name) { var matches = [], flagMap = {}, classes = name.substr(1).split('.'); @@ -460,11 +546,11 @@ } for(var i=0; i < classes.length; i++) { var klass = classes[i], selectorFactoryName = selectors[klass]; - if(selectorFactoryName && !flagMap[klass]) { + if (selectorFactoryName && !flagMap[klass]) { matches.push($injector.get(selectorFactoryName)); flagMap[klass] = true; } } return matches; @@ -473,29 +559,38 @@ function animationRunner(element, animationEvent, className) { //transcluded directives may sometimes fire an animation using only comment nodes //best to catch this early on to prevent any animation operations from occurring var node = element[0]; - if(!node) { + if (!node) { return; } + var classNameAdd; + var classNameRemove; + if (isArray(className)) { + classNameAdd = className[0]; + classNameRemove = className[1]; + if (!classNameAdd) { + className = classNameRemove; + animationEvent = 'removeClass'; + } else if (!classNameRemove) { + className = classNameAdd; + animationEvent = 'addClass'; + } else { + className = classNameAdd + ' ' + classNameRemove; + } + } + var isSetClassOperation = animationEvent == 'setClass'; var isClassBased = isSetClassOperation || animationEvent == 'addClass' || animationEvent == 'removeClass'; - var classNameAdd, classNameRemove; - if(angular.isArray(className)) { - classNameAdd = className[0]; - classNameRemove = className[1]; - className = classNameAdd + ' ' + classNameRemove; - } - var currentClassName = element.attr('class'); var classes = currentClassName + ' ' + className; - if(!isAnimatableClassName(classes)) { + if (!isAnimatableClassName(classes)) { return; } var beforeComplete = noop, beforeCancel = [], @@ -505,21 +600,21 @@ after = []; var animationLookup = (' ' + classes).replace(/\s+/g,'.'); forEach(lookup(animationLookup), function(animationFactory) { var created = registerAnimation(animationFactory, animationEvent); - if(!created && isSetClassOperation) { + if (!created && isSetClassOperation) { registerAnimation(animationFactory, 'addClass'); registerAnimation(animationFactory, 'removeClass'); } }); function registerAnimation(animationFactory, event) { var afterFn = animationFactory[event]; var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; - if(afterFn || beforeFn) { - if(event == 'leave') { + if (afterFn || beforeFn) { + if (event == 'leave') { beforeFn = afterFn; //when set as null then animation knows to skip this phase afterFn = null; } after.push({ @@ -538,13 +633,13 @@ animation.fn && animations.push(animation); }); var count = 0; function afterAnimationComplete(index) { - if(cancellations) { + if (cancellations) { (cancellations[index] || noop)(); - if(++count < animations.length) return; + if (++count < animations.length) return; cancellations = null; } allCompleteFn(); } @@ -569,11 +664,11 @@ cancellations.push(animation.fn(element, progress)); break; } }); - if(cancellations && cancellations.length === 0) { + if (cancellations && cancellations.length === 0) { allCompleteFn(); } } return { @@ -595,17 +690,17 @@ afterComplete = noop; allCompleteFn(); }); }, cancel : function() { - if(beforeCancel) { + if (beforeCancel) { forEach(beforeCancel, function(cancelFn) { (cancelFn || noop)(true); }); beforeComplete(true); } - if(afterCancel) { + if (afterCancel) { forEach(afterCancel, function(cancelFn) { (cancelFn || noop)(true); }); afterComplete(true); } @@ -614,11 +709,11 @@ } /** * @ngdoc service * @name $animate - * @kind function + * @kind object * * @description * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. * When any of these operations are run, the $animate service * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) @@ -628,11 +723,51 @@ * will work out of the box without any extra configuration. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * ## Callback Promises + * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The + * promise itself is then resolved once the animation has completed itself, has been cancelled or has been + * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still + * call the resolve function of the animation.) * + * ```js + * $animate.enter(element, container).then(function() { + * //...this is called once the animation is complete... + * }); + * ``` + * + * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope, + * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using + * `$scope.$apply(...)`; + * + * ```js + * $animate.leave(element).then(function() { + * $scope.$apply(function() { + * $location.path('/new-page'); + * }); + * }); + * ``` + * + * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided + * promise that was returned when the animation was started. + * + * ```js + * var promise = $animate.addClass(element, 'super-long-animation').then(function() { + * //this will still be called even if cancelled + * }); + * + * element.on('click', function() { + * //tooo lazy to wait for the animation to end + * $animate.cancel(promise); + * }); + * ``` + * + * (Keep in mind that the promise cancellation is unique to `$animate` since promises in + * general cannot be cancelled.) + * */ return { /** * @ngdoc method * @name $animate#enter @@ -656,27 +791,26 @@ * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter" | * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter" | * | 10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active" | * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active" | * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 13. The doneCallback() callback is fired (if provided) | class="my-animation" | + * | 13. The returned promise is resolved. | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the enter animation * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation - * @param {function()=} doneCallback the callback function that will be called once the animation is complete - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - enter : function(element, parentElement, afterElement, doneCallback) { + enter : function(element, parentElement, afterElement) { element = angular.element(element); parentElement = prepareElement(parentElement); afterElement = prepareElement(afterElement); - blockElementAnimations(element); + classBasedAnimationsBlocked(element, true); $delegate.enter(element, parentElement, afterElement); - return runAnimationPostDigest(function() { - return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, doneCallback); + return runAnimationPostDigest(function(done) { + return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, done); }); }, /** * @ngdoc method @@ -701,26 +835,25 @@ * | 8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave” | * | 9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active" | * | 10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active" | * | 11. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 12. The element is removed from the DOM | ... | - * | 13. The doneCallback() callback is fired (if provided) | ... | + * | 13. The returned promise is resolved. | ... | * * @param {DOMElement} element the element that will be the focus of the leave animation - * @param {function()=} doneCallback the callback function that will be called once the animation is complete - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - leave : function(element, doneCallback) { + leave : function(element) { element = angular.element(element); cancelChildAnimations(element); - blockElementAnimations(element); + classBasedAnimationsBlocked(element, true); this.enabled(false, element); - return runAnimationPostDigest(function() { + return runAnimationPostDigest(function(done) { return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() { $delegate.leave(element); - }, doneCallback); + }, done); }); }, /** * @ngdoc method @@ -746,28 +879,27 @@ * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move" | * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move” | * | 10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active" | * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active" | * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 13. The doneCallback() callback is fired (if provided) | class="my-animation" | + * | 13. The returned promise is resolved. | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the move animation * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation - * @param {function()=} doneCallback the callback function that will be called once the animation is complete - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - move : function(element, parentElement, afterElement, doneCallback) { + move : function(element, parentElement, afterElement) { element = angular.element(element); parentElement = prepareElement(parentElement); afterElement = prepareElement(afterElement); cancelChildAnimations(element); - blockElementAnimations(element); + classBasedAnimationsBlocked(element, true); $delegate.move(element, parentElement, afterElement); - return runAnimationPostDigest(function() { - return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, doneCallback); + return runAnimationPostDigest(function(done) { + return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, done); }); }, /** * @ngdoc method @@ -790,23 +922,18 @@ * | 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" | * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation super super-add super-add-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | * | 9. The super class is kept on the element | class="my-animation super" | - * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | + * | 10. The returned promise is resolved. | class="my-animation super" | * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be added to the element and then animated - * @param {function()=} doneCallback the callback function that will be called once the animation is complete - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - addClass : function(element, className, doneCallback) { - element = angular.element(element); - element = stripCommentsFromElement(element); - return performAnimation('addClass', className, element, null, null, function() { - $delegate.addClass(element, className); - }, doneCallback); + addClass : function(element, className) { + return this.setClass(element, className, []); }, /** * @ngdoc method * @name $animate#removeClass @@ -827,24 +954,19 @@ * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove" | * | 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" | * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | + * | 9. The returned promise is resolved. | class="my-animation" | * * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be animated and then removed from the element - * @param {function()=} doneCallback the callback function that will be called once the animation is complete - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - removeClass : function(element, className, doneCallback) { - element = angular.element(element); - element = stripCommentsFromElement(element); - return performAnimation('removeClass', className, element, null, null, function() { - $delegate.removeClass(element, className); - }, doneCallback); + removeClass : function(element, className) { + return this.setClass(element, [], className); }, /** * * @ngdoc method @@ -860,31 +982,76 @@ * | 3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off” | * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off” | * | 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” | * | 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" | * | 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" | - * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation on" | + * | 9. The returned promise is resolved. | class="my-animation on" | * * @param {DOMElement} element the element which will have its CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element - * @param {function=} done the callback function (if provided) that will be fired after the * CSS classes have been set on the element - * @return {function} the animation cancellation function + * @return {Promise} the animation callback promise */ - setClass : function(element, add, remove, doneCallback) { + setClass : function(element, add, remove) { + var STORAGE_KEY = '$$animateClasses'; element = angular.element(element); element = stripCommentsFromElement(element); - return performAnimation('setClass', [add, remove], element, null, null, function() { - $delegate.setClass(element, add, remove); - }, doneCallback); + + if (classBasedAnimationsBlocked(element)) { + return $delegate.setClass(element, add, remove); + } + + add = isArray(add) ? add : add.split(' '); + remove = isArray(remove) ? remove : remove.split(' '); + + var cache = element.data(STORAGE_KEY); + if (cache) { + cache.add = cache.add.concat(add); + cache.remove = cache.remove.concat(remove); + + //the digest cycle will combine all the animations into one function + return cache.promise; + } else { + element.data(STORAGE_KEY, cache = { + add : add, + remove : remove + }); + } + + return cache.promise = runAnimationPostDigest(function(done) { + var cache = element.data(STORAGE_KEY); + element.removeData(STORAGE_KEY); + + var state = element.data(NG_ANIMATE_STATE) || {}; + var classes = resolveElementClasses(element, cache, state.active); + return !classes + ? done() + : performAnimation('setClass', classes, element, null, null, function() { + $delegate.setClass(element, classes[0], classes[1]); + }, done); + }); }, /** * @ngdoc method + * @name $animate#cancel + * @kind function + * + * @param {Promise} animationPromise The animation promise that is returned when an animation is started. + * + * @description + * Cancels the provided animation. + */ + cancel : function(promise) { + promise.$$cancelFn(); + }, + + /** + * @ngdoc method * @name $animate#enabled * @kind function * * @param {boolean=} value If provided then set the animation on or off. * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation @@ -895,11 +1062,11 @@ * */ enabled : function(value, element) { switch(arguments.length) { case 2: - if(value) { + if (value) { cleanup(element); } else { var data = element.data(NG_ANIMATE_STATE) || {}; data.disabled = true; element.data(NG_ANIMATE_STATE, data); @@ -927,112 +1094,104 @@ */ function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { var noopCancel = noop; var runner = animationRunner(element, animationEvent, className); - if(!runner) { + if (!runner) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return noopCancel; } + animationEvent = runner.event; className = runner.className; var elementEvents = angular.element._data(runner.node); elementEvents = elementEvents && elementEvents.events; if (!parentElement) { parentElement = afterElement ? afterElement.parent() : element.parent(); } - var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; - var runningAnimations = ngAnimateState.active || {}; - var totalActiveAnimations = ngAnimateState.totalActive || 0; - var lastAnimation = ngAnimateState.last; - - //only allow animations if the currently running animation is not structural - //or if there is no animation running at all - var skipAnimations; - if (runner.isClassBased) { - skipAnimations = ngAnimateState.running || - ngAnimateState.disabled || - (lastAnimation && !lastAnimation.isClassBased); - } - //skip the animation if animations are disabled, a parent is already being animated, //the element is not currently attached to the document body or then completely close //the animation if any matching animations are not found at all. //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. - if (skipAnimations || animationsDisabled(element, parentElement)) { + if (animationsDisabled(element, parentElement)) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return noopCancel; } + var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; + var runningAnimations = ngAnimateState.active || {}; + var totalActiveAnimations = ngAnimateState.totalActive || 0; + var lastAnimation = ngAnimateState.last; var skipAnimation = false; - if(totalActiveAnimations > 0) { + + if (totalActiveAnimations > 0) { var animationsToCancel = []; - if(!runner.isClassBased) { - if(animationEvent == 'leave' && runningAnimations['ng-leave']) { + if (!runner.isClassBased) { + if (animationEvent == 'leave' && runningAnimations['ng-leave']) { skipAnimation = true; } else { //cancel all animations when a structural animation takes place for(var klass in runningAnimations) { animationsToCancel.push(runningAnimations[klass]); } ngAnimateState = {}; cleanup(element, true); } - } else if(lastAnimation.event == 'setClass') { + } else if (lastAnimation.event == 'setClass') { animationsToCancel.push(lastAnimation); cleanup(element, className); } - else if(runningAnimations[className]) { + else if (runningAnimations[className]) { var current = runningAnimations[className]; - if(current.event == animationEvent) { + if (current.event == animationEvent) { skipAnimation = true; } else { animationsToCancel.push(current); cleanup(element, className); } } - if(animationsToCancel.length > 0) { + if (animationsToCancel.length > 0) { forEach(animationsToCancel, function(operation) { operation.cancel(); }); } } - runningAnimations = ngAnimateState.active || {}; - totalActiveAnimations = ngAnimateState.totalActive || 0; - - if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) { + if (runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) { skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR } - if(skipAnimation) { + if (skipAnimation) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); fireDoneCallbackAsync(); return noopCancel; } - if(animationEvent == 'leave') { + runningAnimations = ngAnimateState.active || {}; + totalActiveAnimations = ngAnimateState.totalActive || 0; + + if (animationEvent == 'leave') { //there's no need to ever remove the listener since the element //will be removed (destroyed) after the leave animation ends or //is cancelled midway element.one('$destroy', function(e) { var element = angular.element(this); var state = element.data(NG_ANIMATE_STATE); - if(state) { + if (state) { var activeLeaveAnimation = state.active['ng-leave']; - if(activeLeaveAnimation) { + if (activeLeaveAnimation) { activeLeaveAnimation.cancel(); cleanup(element, 'ng-leave'); } } }); @@ -1061,11 +1220,11 @@ cancelled = cancelled || !data || !data.active[className] || (runner.isClassBased && data.active[className].event != animationEvent); fireDOMOperation(); - if(cancelled === true) { + if (cancelled === true) { closeAnimation(); } else { fireAfterCallbackAsync(); runner.after(closeAnimation); } @@ -1073,11 +1232,11 @@ return runner.cancel; function fireDOMCallback(animationPhase) { var eventName = '$animate:' + animationPhase; - if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { + if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { $$asyncCallback(function() { element.triggerHandler(eventName, { event : animationEvent, className : className }); @@ -1093,41 +1252,37 @@ fireDOMCallback('after'); } function fireDoneCallbackAsync() { fireDOMCallback('close'); - if(doneCallback) { - $$asyncCallback(function() { - doneCallback(); - }); - } + doneCallback(); } //it is less complicated to use a flag than managing and canceling //timeouts containing multiple callbacks. function fireDOMOperation() { - if(!fireDOMOperation.hasBeenRun) { + if (!fireDOMOperation.hasBeenRun) { fireDOMOperation.hasBeenRun = true; domOperation(); } } function closeAnimation() { - if(!closeAnimation.hasBeenRun) { + if (!closeAnimation.hasBeenRun) { closeAnimation.hasBeenRun = true; var data = element.data(NG_ANIMATE_STATE); - if(data) { + if (data) { /* only structural animations wait for reflow before removing an animation, but class-based animations don't. An example of this failing would be when a parent HTML tag has a ng-class attribute causing ALL directives below to skip animations during the digest */ - if(runner && runner.isClassBased) { + if (runner && runner.isClassBased) { cleanup(element, className); } else { $$asyncCallback(function() { var data = element.data(NG_ANIMATE_STATE) || {}; - if(localAnimationCount == data.index) { + if (localAnimationCount == data.index) { cleanup(element, className, animationEvent); } }); element.data(NG_ANIMATE_STATE, data); } @@ -1144,35 +1299,35 @@ node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); forEach(nodes, function(element) { element = angular.element(element); var data = element.data(NG_ANIMATE_STATE); - if(data && data.active) { + if (data && data.active) { forEach(data.active, function(runner) { runner.cancel(); }); } }); } } function cleanup(element, className) { - if(isMatchingElement(element, $rootElement)) { - if(!rootAnimateState.disabled) { + if (isMatchingElement(element, $rootElement)) { + if (!rootAnimateState.disabled) { rootAnimateState.running = false; rootAnimateState.structural = false; } - } else if(className) { + } else if (className) { var data = element.data(NG_ANIMATE_STATE) || {}; var removeAnimations = className === true; - if(!removeAnimations && data.active && data.active[className]) { + if (!removeAnimations && data.active && data.active[className]) { data.totalActive--; delete data.active[className]; } - if(removeAnimations || !data.totalActive) { + if (removeAnimations || !data.totalActive) { element.removeClass(NG_ANIMATE_CLASS_NAME); element.removeData(NG_ANIMATE_STATE); } } } @@ -1207,11 +1362,11 @@ //once a flag is found that is strictly false then everything before //it will be discarded and all child animations will be restricted if (allowChildAnimations !== false) { var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN); - if(angular.isDefined(animateChildrenFlag)) { + if (angular.isDefined(animateChildrenFlag)) { allowChildAnimations = animateChildrenFlag; } } parentRunningAnimation = parentRunningAnimation || @@ -1257,10 +1412,11 @@ var DURATION_KEY = 'Duration'; var PROPERTY_KEY = 'Property'; var DELAY_KEY = 'Delay'; var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; + var ANIMATION_PLAYSTATE_KEY = 'PlayState'; var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; var CLOSING_TIME_BUFFER = 1.5; var ONE_SECOND = 1000; @@ -1268,11 +1424,11 @@ var lookupCache = {}; var parentCounter = 0; var animationReflowQueue = []; var cancelAnimationReflow; function afterReflow(element, callback) { - if(cancelAnimationReflow) { + if (cancelAnimationReflow) { cancelAnimationReflow(); } animationReflowQueue.push(callback); cancelAnimationReflow = $$animateReflow(function() { forEach(animationReflowQueue, function(fn) { @@ -1297,11 +1453,11 @@ animationElementQueue.push(element); //but it may not need to cancel out the existing timeout //if the timestamp is less than the previous one var futureTimestamp = Date.now() + totalTime; - if(futureTimestamp <= closingTimestamp) { + if (futureTimestamp <= closingTimestamp) { return; } $timeout.cancel(closingTimer); @@ -1313,70 +1469,56 @@ } function closeAllAnimations(elements) { forEach(elements, function(element) { var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); - if(elementData) { + if (elementData) { forEach(elementData.closeAnimationFns, function(fn) { fn(); }); } }); } function getElementAnimationDetails(element, cacheKey) { var data = cacheKey ? lookupCache[cacheKey] : null; - if(!data) { + if (!data) { var transitionDuration = 0; var transitionDelay = 0; var animationDuration = 0; var animationDelay = 0; - var transitionDelayStyle; - var animationDelayStyle; - var transitionDurationStyle; - var transitionPropertyStyle; //we want all the styles defined before and after forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var elementStyles = $window.getComputedStyle(element) || {}; - transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; - + var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); - transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; - - transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; - + var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); - animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; + var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; + animationDelay = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay); - animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); - var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); - if(aDuration > 0) { + if (aDuration > 0) { aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; } - animationDuration = Math.max(aDuration, animationDuration); } }); data = { total : 0, - transitionPropertyStyle: transitionPropertyStyle, - transitionDurationStyle: transitionDurationStyle, - transitionDelayStyle: transitionDelayStyle, transitionDelay: transitionDelay, transitionDuration: transitionDuration, - animationDelayStyle: animationDelayStyle, animationDelay: animationDelay, animationDuration: animationDuration }; - if(cacheKey) { + if (cacheKey) { lookupCache[cacheKey] = data; } } return data; } @@ -1393,11 +1535,11 @@ } function getCacheKey(element) { var parentElement = element.parent(); var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); - if(!parentID) { + if (!parentID) { parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); parentID = parentCounter; } return parentID + '-' + extractElementNode(element).getAttribute('class'); } @@ -1408,11 +1550,11 @@ var cacheKey = getCacheKey(element); var eventCacheKey = cacheKey + ' ' + className; var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; var stagger = {}; - if(itemIndex > 0) { + if (itemIndex > 0) { var staggerClassName = className + '-stagger'; var staggerCacheKey = cacheKey + ' ' + staggerClassName; var applyClasses = !lookupCache[staggerCacheKey]; applyClasses && element.addClass(staggerClassName); @@ -1427,11 +1569,11 @@ var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; var timings = getElementAnimationDetails(element, eventCacheKey); var transitionDuration = timings.transitionDuration; var animationDuration = timings.animationDuration; - if(structural && transitionDuration === 0 && animationDuration === 0) { + if (structural && transitionDuration === 0 && animationDuration === 0) { element.removeClass(className); return false; } var blockTransition = structural && transitionDuration > 0; @@ -1444,122 +1586,132 @@ stagger : stagger, cacheKey : eventCacheKey, running : formerData.running || 0, itemIndex : itemIndex, blockTransition : blockTransition, - blockAnimation : blockAnimation, closeAnimationFns : closeAnimationFns }); var node = extractElementNode(element); - if(blockTransition) { - node.style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; + if (blockTransition) { + blockTransitions(node, true); } - if(blockAnimation) { - node.style[ANIMATION_PROP] = 'none 0s'; + if (blockAnimation) { + blockAnimations(node, true); } return true; } function animateRun(animationEvent, element, className, activeAnimationComplete) { var node = extractElementNode(element); var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); - if(node.getAttribute('class').indexOf(className) == -1 || !elementData) { + if (node.getAttribute('class').indexOf(className) == -1 || !elementData) { activeAnimationComplete(); return; } - if(elementData.blockTransition) { - node.style[TRANSITION_PROP + PROPERTY_KEY] = ''; + if (elementData.blockTransition) { + blockTransitions(node, false); } - if(elementData.blockAnimation) { - node.style[ANIMATION_PROP] = ''; - } - var activeClassName = ''; + var pendingClassName = ''; forEach(className.split(' '), function(klass, i) { - activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; + var prefix = (i > 0 ? ' ' : '') + klass; + activeClassName += prefix + '-active'; + pendingClassName += prefix + '-pending'; }); - element.addClass(activeClassName); + var style = ''; + var appliedStyles = []; + var itemIndex = elementData.itemIndex; + var stagger = elementData.stagger; + var staggerTime = 0; + if (itemIndex > 0) { + var transitionStaggerDelay = 0; + if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { + transitionStaggerDelay = stagger.transitionDelay * itemIndex; + } + + var animationStaggerDelay = 0; + if (stagger.animationDelay > 0 && stagger.animationDuration === 0) { + animationStaggerDelay = stagger.animationDelay * itemIndex; + appliedStyles.push(CSS_PREFIX + 'animation-play-state'); + } + + staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100; + } + + if (!staggerTime) { + element.addClass(activeClassName); + } + var eventCacheKey = elementData.cacheKey + ' ' + activeClassName; var timings = getElementAnimationDetails(element, eventCacheKey); - var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); - if(maxDuration === 0) { + if (maxDuration === 0) { element.removeClass(activeClassName); animateClose(element, className); activeAnimationComplete(); return; } var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); - var stagger = elementData.stagger; - var itemIndex = elementData.itemIndex; var maxDelayTime = maxDelay * ONE_SECOND; - var style = '', appliedStyles = []; - if(timings.transitionDuration > 0) { - var propertyStyle = timings.transitionPropertyStyle; - if(propertyStyle.indexOf('all') == -1) { - style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';'; - style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';'; - appliedStyles.push(CSS_PREFIX + 'transition-property'); - appliedStyles.push(CSS_PREFIX + 'transition-duration'); - } - } - - if(itemIndex > 0) { - if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { - var delayStyle = timings.transitionDelayStyle; - style += CSS_PREFIX + 'transition-delay: ' + - prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; '; - appliedStyles.push(CSS_PREFIX + 'transition-delay'); - } - - if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { - style += CSS_PREFIX + 'animation-delay: ' + - prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; '; - appliedStyles.push(CSS_PREFIX + 'animation-delay'); - } - } - - if(appliedStyles.length > 0) { + if (appliedStyles.length > 0) { //the element being animated may sometimes contain comment nodes in //the jqLite object, so we're safe to use a single variable to house //the styles since there is always only one element being animated var oldStyle = node.getAttribute('style') || ''; - node.setAttribute('style', oldStyle + '; ' + style); + if (oldStyle.charAt(oldStyle.length-1) !== ';') { + oldStyle += ';'; + } + node.setAttribute('style', oldStyle + ' ' + style); } var startTime = Date.now(); var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; + var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; + var totalTime = (staggerTime + animationTime) * ONE_SECOND; + var staggerTimeout; + if (staggerTime > 0) { + element.addClass(pendingClassName); + staggerTimeout = $timeout(function() { + staggerTimeout = null; + element.addClass(activeClassName); + element.removeClass(pendingClassName); + if (timings.animationDuration > 0) { + blockAnimations(node, false); + } + }, staggerTime * ONE_SECOND, false); + } + element.on(css3AnimationEvents, onAnimationProgress); elementData.closeAnimationFns.push(function() { onEnd(); activeAnimationComplete(); }); - var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0); - var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; - var totalTime = (staggerTime + animationTime) * ONE_SECOND; - elementData.running++; animationCloseHandler(element, totalTime); return onEnd; // This will automatically be called by $animate so // there is no need to attach this internally to the // timeout done method. function onEnd(cancelled) { element.off(css3AnimationEvents, onAnimationProgress); element.removeClass(activeClassName); + element.removeClass(pendingClassName); + if (staggerTimeout) { + $timeout.cancel(staggerTimeout); + } animateClose(element, className); var node = extractElementNode(element); for (var i in appliedStyles) { node.style.removeProperty(appliedStyles[i]); } @@ -1579,35 +1731,34 @@ * mock animations properly. Real events fallback to event.timeStamp, * or, if they don't, then a timeStamp is automatically created for them. * We're checking to see if the timeStamp surpasses the expected delay, * but we're using elapsedTime instead of the timeStamp on the 2nd * pre-condition since animations sometimes close off early */ - if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { activeAnimationComplete(); } } } - function prepareStaggerDelay(delayStyle, staggerDelay, index) { - var style = ''; - forEach(delayStyle.split(','), function(val, i) { - style += (i > 0 ? ',' : '') + - (index * staggerDelay + parseInt(val, 10)) + 's'; - }); - return style; + function blockTransitions(node, bool) { + node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : ''; } + function blockAnimations(node, bool) { + node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : ''; + } + function animateBefore(animationEvent, element, className, calculationDecorator) { - if(animateSetup(animationEvent, element, className, calculationDecorator)) { + if (animateSetup(animationEvent, element, className, calculationDecorator)) { return function(cancelled) { cancelled && animateClose(element, className); }; } } function animateAfter(animationEvent, element, className, afterAnimationComplete) { - if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { + if (element.data(NG_ANIMATE_CSS_DATA_KEY)) { return animateRun(animationEvent, element, className, afterAnimationComplete); } else { animateClose(element, className); afterAnimationComplete(); } @@ -1616,11 +1767,11 @@ function animate(animationEvent, element, className, animationComplete) { //If the animateSetup function doesn't bother returning a //cancellation function then it means that there is no animation //to perform at all var preReflowCancellation = animateBefore(animationEvent, element, className); - if(!preReflowCancellation) { + if (!preReflowCancellation) { animationComplete(); return; } //There are two cancellation functions: one is before the first @@ -1642,15 +1793,15 @@ } function animateClose(element, className) { element.removeClass(className); var data = element.data(NG_ANIMATE_CSS_DATA_KEY); - if(data) { - if(data.running) { + if (data) { + if (data.running) { data.running--; } - if(!data.running || data.running === 0) { + if (!data.running || data.running === 0) { element.removeData(NG_ANIMATE_CSS_DATA_KEY); } } } @@ -1669,29 +1820,29 @@ beforeSetClass : function(element, add, remove, animationCompleted) { var className = suffixClasses(remove, '-remove') + ' ' + suffixClasses(add, '-add'); var cancellationMethod = animateBefore('setClass', element, className); - if(cancellationMethod) { + if (cancellationMethod) { afterReflow(element, animationCompleted); return cancellationMethod; } animationCompleted(); }, beforeAddClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add')); - if(cancellationMethod) { + if (cancellationMethod) { afterReflow(element, animationCompleted); return cancellationMethod; } animationCompleted(); }, beforeRemoveClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove')); - if(cancellationMethod) { + if (cancellationMethod) { afterReflow(element, animationCompleted); return cancellationMethod; } animationCompleted(); }, @@ -1712,12 +1863,12 @@ } }; function suffixClasses(classes, suffix) { var className = ''; - classes = angular.isArray(classes) ? classes : classes.split(/\s+/); + classes = isArray(classes) ? classes : classes.split(/\s+/); forEach(classes, function(klass, i) { - if(klass && klass.length > 0) { + if (klass && klass.length > 0) { className += (i > 0 ? ' ' : '') + klass + suffix; } }); return className; }