You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4115 lines
146 KiB

  1. /**
  2. * @license AngularJS v1.5.3
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular, undefined) {'use strict';
  7. /* jshint ignore:start */
  8. var noop = angular.noop;
  9. var copy = angular.copy;
  10. var extend = angular.extend;
  11. var jqLite = angular.element;
  12. var forEach = angular.forEach;
  13. var isArray = angular.isArray;
  14. var isString = angular.isString;
  15. var isObject = angular.isObject;
  16. var isUndefined = angular.isUndefined;
  17. var isDefined = angular.isDefined;
  18. var isFunction = angular.isFunction;
  19. var isElement = angular.isElement;
  20. var ELEMENT_NODE = 1;
  21. var COMMENT_NODE = 8;
  22. var ADD_CLASS_SUFFIX = '-add';
  23. var REMOVE_CLASS_SUFFIX = '-remove';
  24. var EVENT_CLASS_PREFIX = 'ng-';
  25. var ACTIVE_CLASS_SUFFIX = '-active';
  26. var PREPARE_CLASS_SUFFIX = '-prepare';
  27. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  28. var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
  29. // Detect proper transitionend/animationend event names.
  30. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
  31. // If unprefixed events are not supported but webkit-prefixed are, use the latter.
  32. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
  33. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
  34. // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
  35. // Register both events in case `window.onanimationend` is not supported because of that,
  36. // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
  37. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
  38. // therefore there is no reason to test anymore for other vendor prefixes:
  39. // http://caniuse.com/#search=transition
  40. if (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {
  41. CSS_PREFIX = '-webkit-';
  42. TRANSITION_PROP = 'WebkitTransition';
  43. TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
  44. } else {
  45. TRANSITION_PROP = 'transition';
  46. TRANSITIONEND_EVENT = 'transitionend';
  47. }
  48. if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {
  49. CSS_PREFIX = '-webkit-';
  50. ANIMATION_PROP = 'WebkitAnimation';
  51. ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
  52. } else {
  53. ANIMATION_PROP = 'animation';
  54. ANIMATIONEND_EVENT = 'animationend';
  55. }
  56. var DURATION_KEY = 'Duration';
  57. var PROPERTY_KEY = 'Property';
  58. var DELAY_KEY = 'Delay';
  59. var TIMING_KEY = 'TimingFunction';
  60. var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
  61. var ANIMATION_PLAYSTATE_KEY = 'PlayState';
  62. var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
  63. var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
  64. var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
  65. var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
  66. var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
  67. var isPromiseLike = function(p) {
  68. return p && p.then ? true : false;
  69. };
  70. var ngMinErr = angular.$$minErr('ng');
  71. function assertArg(arg, name, reason) {
  72. if (!arg) {
  73. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  74. }
  75. return arg;
  76. }
  77. function mergeClasses(a,b) {
  78. if (!a && !b) return '';
  79. if (!a) return b;
  80. if (!b) return a;
  81. if (isArray(a)) a = a.join(' ');
  82. if (isArray(b)) b = b.join(' ');
  83. return a + ' ' + b;
  84. }
  85. function packageStyles(options) {
  86. var styles = {};
  87. if (options && (options.to || options.from)) {
  88. styles.to = options.to;
  89. styles.from = options.from;
  90. }
  91. return styles;
  92. }
  93. function pendClasses(classes, fix, isPrefix) {
  94. var className = '';
  95. classes = isArray(classes)
  96. ? classes
  97. : classes && isString(classes) && classes.length
  98. ? classes.split(/\s+/)
  99. : [];
  100. forEach(classes, function(klass, i) {
  101. if (klass && klass.length > 0) {
  102. className += (i > 0) ? ' ' : '';
  103. className += isPrefix ? fix + klass
  104. : klass + fix;
  105. }
  106. });
  107. return className;
  108. }
  109. function removeFromArray(arr, val) {
  110. var index = arr.indexOf(val);
  111. if (val >= 0) {
  112. arr.splice(index, 1);
  113. }
  114. }
  115. function stripCommentsFromElement(element) {
  116. if (element instanceof jqLite) {
  117. switch (element.length) {
  118. case 0:
  119. return [];
  120. break;
  121. case 1:
  122. // there is no point of stripping anything if the element
  123. // is the only element within the jqLite wrapper.
  124. // (it's important that we retain the element instance.)
  125. if (element[0].nodeType === ELEMENT_NODE) {
  126. return element;
  127. }
  128. break;
  129. default:
  130. return jqLite(extractElementNode(element));
  131. break;
  132. }
  133. }
  134. if (element.nodeType === ELEMENT_NODE) {
  135. return jqLite(element);
  136. }
  137. }
  138. function extractElementNode(element) {
  139. if (!element[0]) return element;
  140. for (var i = 0; i < element.length; i++) {
  141. var elm = element[i];
  142. if (elm.nodeType == ELEMENT_NODE) {
  143. return elm;
  144. }
  145. }
  146. }
  147. function $$addClass($$jqLite, element, className) {
  148. forEach(element, function(elm) {
  149. $$jqLite.addClass(elm, className);
  150. });
  151. }
  152. function $$removeClass($$jqLite, element, className) {
  153. forEach(element, function(elm) {
  154. $$jqLite.removeClass(elm, className);
  155. });
  156. }
  157. function applyAnimationClassesFactory($$jqLite) {
  158. return function(element, options) {
  159. if (options.addClass) {
  160. $$addClass($$jqLite, element, options.addClass);
  161. options.addClass = null;
  162. }
  163. if (options.removeClass) {
  164. $$removeClass($$jqLite, element, options.removeClass);
  165. options.removeClass = null;
  166. }
  167. }
  168. }
  169. function prepareAnimationOptions(options) {
  170. options = options || {};
  171. if (!options.$$prepared) {
  172. var domOperation = options.domOperation || noop;
  173. options.domOperation = function() {
  174. options.$$domOperationFired = true;
  175. domOperation();
  176. domOperation = noop;
  177. };
  178. options.$$prepared = true;
  179. }
  180. return options;
  181. }
  182. function applyAnimationStyles(element, options) {
  183. applyAnimationFromStyles(element, options);
  184. applyAnimationToStyles(element, options);
  185. }
  186. function applyAnimationFromStyles(element, options) {
  187. if (options.from) {
  188. element.css(options.from);
  189. options.from = null;
  190. }
  191. }
  192. function applyAnimationToStyles(element, options) {
  193. if (options.to) {
  194. element.css(options.to);
  195. options.to = null;
  196. }
  197. }
  198. function mergeAnimationDetails(element, oldAnimation, newAnimation) {
  199. var target = oldAnimation.options || {};
  200. var newOptions = newAnimation.options || {};
  201. var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
  202. var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
  203. var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
  204. if (newOptions.preparationClasses) {
  205. target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
  206. delete newOptions.preparationClasses;
  207. }
  208. // noop is basically when there is no callback; otherwise something has been set
  209. var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
  210. extend(target, newOptions);
  211. // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
  212. if (realDomOperation) {
  213. target.domOperation = realDomOperation;
  214. }
  215. if (classes.addClass) {
  216. target.addClass = classes.addClass;
  217. } else {
  218. target.addClass = null;
  219. }
  220. if (classes.removeClass) {
  221. target.removeClass = classes.removeClass;
  222. } else {
  223. target.removeClass = null;
  224. }
  225. oldAnimation.addClass = target.addClass;
  226. oldAnimation.removeClass = target.removeClass;
  227. return target;
  228. }
  229. function resolveElementClasses(existing, toAdd, toRemove) {
  230. var ADD_CLASS = 1;
  231. var REMOVE_CLASS = -1;
  232. var flags = {};
  233. existing = splitClassesToLookup(existing);
  234. toAdd = splitClassesToLookup(toAdd);
  235. forEach(toAdd, function(value, key) {
  236. flags[key] = ADD_CLASS;
  237. });
  238. toRemove = splitClassesToLookup(toRemove);
  239. forEach(toRemove, function(value, key) {
  240. flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
  241. });
  242. var classes = {
  243. addClass: '',
  244. removeClass: ''
  245. };
  246. forEach(flags, function(val, klass) {
  247. var prop, allow;
  248. if (val === ADD_CLASS) {
  249. prop = 'addClass';
  250. allow = !existing[klass];
  251. } else if (val === REMOVE_CLASS) {
  252. prop = 'removeClass';
  253. allow = existing[klass];
  254. }
  255. if (allow) {
  256. if (classes[prop].length) {
  257. classes[prop] += ' ';
  258. }
  259. classes[prop] += klass;
  260. }
  261. });
  262. function splitClassesToLookup(classes) {
  263. if (isString(classes)) {
  264. classes = classes.split(' ');
  265. }
  266. var obj = {};
  267. forEach(classes, function(klass) {
  268. // sometimes the split leaves empty string values
  269. // incase extra spaces were applied to the options
  270. if (klass.length) {
  271. obj[klass] = true;
  272. }
  273. });
  274. return obj;
  275. }
  276. return classes;
  277. }
  278. function getDomNode(element) {
  279. return (element instanceof angular.element) ? element[0] : element;
  280. }
  281. function applyGeneratedPreparationClasses(element, event, options) {
  282. var classes = '';
  283. if (event) {
  284. classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
  285. }
  286. if (options.addClass) {
  287. classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
  288. }
  289. if (options.removeClass) {
  290. classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
  291. }
  292. if (classes.length) {
  293. options.preparationClasses = classes;
  294. element.addClass(classes);
  295. }
  296. }
  297. function clearGeneratedClasses(element, options) {
  298. if (options.preparationClasses) {
  299. element.removeClass(options.preparationClasses);
  300. options.preparationClasses = null;
  301. }
  302. if (options.activeClasses) {
  303. element.removeClass(options.activeClasses);
  304. options.activeClasses = null;
  305. }
  306. }
  307. function blockTransitions(node, duration) {
  308. // we use a negative delay value since it performs blocking
  309. // yet it doesn't kill any existing transitions running on the
  310. // same element which makes this safe for class-based animations
  311. var value = duration ? '-' + duration + 's' : '';
  312. applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
  313. return [TRANSITION_DELAY_PROP, value];
  314. }
  315. function blockKeyframeAnimations(node, applyBlock) {
  316. var value = applyBlock ? 'paused' : '';
  317. var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
  318. applyInlineStyle(node, [key, value]);
  319. return [key, value];
  320. }
  321. function applyInlineStyle(node, styleTuple) {
  322. var prop = styleTuple[0];
  323. var value = styleTuple[1];
  324. node.style[prop] = value;
  325. }
  326. function concatWithSpace(a,b) {
  327. if (!a) return b;
  328. if (!b) return a;
  329. return a + ' ' + b;
  330. }
  331. var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
  332. var queue, cancelFn;
  333. function scheduler(tasks) {
  334. // we make a copy since RAFScheduler mutates the state
  335. // of the passed in array variable and this would be difficult
  336. // to track down on the outside code
  337. queue = queue.concat(tasks);
  338. nextTick();
  339. }
  340. queue = scheduler.queue = [];
  341. /* waitUntilQuiet does two things:
  342. * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
  343. * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
  344. *
  345. * The motivation here is that animation code can request more time from the scheduler
  346. * before the next wave runs. This allows for certain DOM properties such as classes to
  347. * be resolved in time for the next animation to run.
  348. */
  349. scheduler.waitUntilQuiet = function(fn) {
  350. if (cancelFn) cancelFn();
  351. cancelFn = $$rAF(function() {
  352. cancelFn = null;
  353. fn();
  354. nextTick();
  355. });
  356. };
  357. return scheduler;
  358. function nextTick() {
  359. if (!queue.length) return;
  360. var items = queue.shift();
  361. for (var i = 0; i < items.length; i++) {
  362. items[i]();
  363. }
  364. if (!cancelFn) {
  365. $$rAF(function() {
  366. if (!cancelFn) nextTick();
  367. });
  368. }
  369. }
  370. }];
  371. /**
  372. * @ngdoc directive
  373. * @name ngAnimateChildren
  374. * @restrict AE
  375. * @element ANY
  376. *
  377. * @description
  378. *
  379. * ngAnimateChildren allows you to specify that children of this element should animate even if any
  380. * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
  381. * (structural) animation, child elements that also have an active structural animation are not animated.
  382. *
  383. * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
  384. *
  385. *
  386. * @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
  387. * then child animations are allowed. If the value is `false`, child animations are not allowed.
  388. *
  389. * @example
  390. * <example module="ngAnimateChildren" name="ngAnimateChildren" deps="angular-animate.js" animations="true">
  391. <file name="index.html">
  392. <div ng-controller="mainController as main">
  393. <label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
  394. <label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
  395. <hr>
  396. <div ng-animate-children="{{main.animateChildren}}">
  397. <div ng-if="main.enterElement" class="container">
  398. List of items:
  399. <div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
  400. </div>
  401. </div>
  402. </div>
  403. </file>
  404. <file name="animations.css">
  405. .container.ng-enter,
  406. .container.ng-leave {
  407. transition: all ease 1.5s;
  408. }
  409. .container.ng-enter,
  410. .container.ng-leave-active {
  411. opacity: 0;
  412. }
  413. .container.ng-leave,
  414. .container.ng-enter-active {
  415. opacity: 1;
  416. }
  417. .item {
  418. background: firebrick;
  419. color: #FFF;
  420. margin-bottom: 10px;
  421. }
  422. .item.ng-enter,
  423. .item.ng-leave {
  424. transition: transform 1.5s ease;
  425. }
  426. .item.ng-enter {
  427. transform: translateX(50px);
  428. }
  429. .item.ng-enter-active {
  430. transform: translateX(0);
  431. }
  432. </file>
  433. <file name="script.js">
  434. angular.module('ngAnimateChildren', ['ngAnimate'])
  435. .controller('mainController', function() {
  436. this.animateChildren = false;
  437. this.enterElement = false;
  438. });
  439. </file>
  440. </example>
  441. */
  442. var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
  443. return {
  444. link: function(scope, element, attrs) {
  445. var val = attrs.ngAnimateChildren;
  446. if (angular.isString(val) && val.length === 0) { //empty attribute
  447. element.data(NG_ANIMATE_CHILDREN_DATA, true);
  448. } else {
  449. // Interpolate and set the value, so that it is available to
  450. // animations that run right after compilation
  451. setData($interpolate(val)(scope));
  452. attrs.$observe('ngAnimateChildren', setData);
  453. }
  454. function setData(value) {
  455. value = value === 'on' || value === 'true';
  456. element.data(NG_ANIMATE_CHILDREN_DATA, value);
  457. }
  458. }
  459. };
  460. }];
  461. var ANIMATE_TIMER_KEY = '$$animateCss';
  462. /**
  463. * @ngdoc service
  464. * @name $animateCss
  465. * @kind object
  466. *
  467. * @description
  468. * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
  469. * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
  470. * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
  471. * directives to create more complex animations that can be purely driven using CSS code.
  472. *
  473. * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
  474. * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
  475. *
  476. * ## Usage
  477. * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
  478. * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
  479. * any automatic control over cancelling animations and/or preventing animations from being run on
  480. * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
  481. * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
  482. * the CSS animation.
  483. *
  484. * The example below shows how we can create a folding animation on an element using `ng-if`:
  485. *
  486. * ```html
  487. * <!-- notice the `fold-animation` CSS class -->
  488. * <div ng-if="onOff" class="fold-animation">
  489. * This element will go BOOM
  490. * </div>
  491. * <button ng-click="onOff=true">Fold In</button>
  492. * ```
  493. *
  494. * Now we create the **JavaScript animation** that will trigger the CSS transition:
  495. *
  496. * ```js
  497. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  498. * return {
  499. * enter: function(element, doneFn) {
  500. * var height = element[0].offsetHeight;
  501. * return $animateCss(element, {
  502. * from: { height:'0px' },
  503. * to: { height:height + 'px' },
  504. * duration: 1 // one second
  505. * });
  506. * }
  507. * }
  508. * }]);
  509. * ```
  510. *
  511. * ## More Advanced Uses
  512. *
  513. * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
  514. * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
  515. *
  516. * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
  517. * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
  518. * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
  519. * to provide a working animation that will run in CSS.
  520. *
  521. * The example below showcases a more advanced version of the `.fold-animation` from the example above:
  522. *
  523. * ```js
  524. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  525. * return {
  526. * enter: function(element, doneFn) {
  527. * var height = element[0].offsetHeight;
  528. * return $animateCss(element, {
  529. * addClass: 'red large-text pulse-twice',
  530. * easing: 'ease-out',
  531. * from: { height:'0px' },
  532. * to: { height:height + 'px' },
  533. * duration: 1 // one second
  534. * });
  535. * }
  536. * }
  537. * }]);
  538. * ```
  539. *
  540. * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
  541. *
  542. * ```css
  543. * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
  544. * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
  545. * .red { background:red; }
  546. * .large-text { font-size:20px; }
  547. *
  548. * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
  549. * .pulse-twice {
  550. * animation: 0.5s pulse linear 2;
  551. * -webkit-animation: 0.5s pulse linear 2;
  552. * }
  553. *
  554. * @keyframes pulse {
  555. * from { transform: scale(0.5); }
  556. * to { transform: scale(1.5); }
  557. * }
  558. *
  559. * @-webkit-keyframes pulse {
  560. * from { -webkit-transform: scale(0.5); }
  561. * to { -webkit-transform: scale(1.5); }
  562. * }
  563. * ```
  564. *
  565. * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
  566. *
  567. * ## How the Options are handled
  568. *
  569. * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
  570. * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
  571. * styles using the `from` and `to` properties.
  572. *
  573. * ```js
  574. * var animator = $animateCss(element, {
  575. * from: { background:'red' },
  576. * to: { background:'blue' }
  577. * });
  578. * animator.start();
  579. * ```
  580. *
  581. * ```css
  582. * .rotating-animation {
  583. * animation:0.5s rotate linear;
  584. * -webkit-animation:0.5s rotate linear;
  585. * }
  586. *
  587. * @keyframes rotate {
  588. * from { transform: rotate(0deg); }
  589. * to { transform: rotate(360deg); }
  590. * }
  591. *
  592. * @-webkit-keyframes rotate {
  593. * from { -webkit-transform: rotate(0deg); }
  594. * to { -webkit-transform: rotate(360deg); }
  595. * }
  596. * ```
  597. *
  598. * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
  599. * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
  600. * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
  601. * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
  602. * and spread across the transition and keyframe animation.
  603. *
  604. * ## What is returned
  605. *
  606. * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
  607. * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
  608. * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
  609. *
  610. * ```js
  611. * var animator = $animateCss(element, { ... });
  612. * ```
  613. *
  614. * Now what do the contents of our `animator` variable look like:
  615. *
  616. * ```js
  617. * {
  618. * // starts the animation
  619. * start: Function,
  620. *
  621. * // ends (aborts) the animation
  622. * end: Function
  623. * }
  624. * ```
  625. *
  626. * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
  627. * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been
  628. * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
  629. * and that changing them will not reconfigure the parameters of the animation.
  630. *
  631. * ### runner.done() vs runner.then()
  632. * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
  633. * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
  634. * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
  635. * unless you really need a digest to kick off afterwards.
  636. *
  637. * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
  638. * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
  639. * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
  640. *
  641. * @param {DOMElement} element the element that will be animated
  642. * @param {object} options the animation-related options that will be applied during the animation
  643. *
  644. * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
  645. * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
  646. * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
  647. * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
  648. * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
  649. * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
  650. * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
  651. * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
  652. * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
  653. * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
  654. * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
  655. * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
  656. * is provided then the animation will be skipped entirely.
  657. * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
  658. * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
  659. * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
  660. * CSS delay value.
  661. * * `stagger` - A numeric time value representing the delay between successively animated elements
  662. * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
  663. * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
  664. * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
  665. * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.)
  666. * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
  667. * the animation is closed. This is useful for when the styles are used purely for the sake of
  668. * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
  669. * By default this value is set to `false`.
  670. *
  671. * @return {object} an object with start and end methods and details about the animation.
  672. *
  673. * * `start` - The method to start the animation. This will return a `Promise` when called.
  674. * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
  675. */
  676. var ONE_SECOND = 1000;
  677. var BASE_TEN = 10;
  678. var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
  679. var CLOSING_TIME_BUFFER = 1.5;
  680. var DETECT_CSS_PROPERTIES = {
  681. transitionDuration: TRANSITION_DURATION_PROP,
  682. transitionDelay: TRANSITION_DELAY_PROP,
  683. transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
  684. animationDuration: ANIMATION_DURATION_PROP,
  685. animationDelay: ANIMATION_DELAY_PROP,
  686. animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
  687. };
  688. var DETECT_STAGGER_CSS_PROPERTIES = {
  689. transitionDuration: TRANSITION_DURATION_PROP,
  690. transitionDelay: TRANSITION_DELAY_PROP,
  691. animationDuration: ANIMATION_DURATION_PROP,
  692. animationDelay: ANIMATION_DELAY_PROP
  693. };
  694. function getCssKeyframeDurationStyle(duration) {
  695. return [ANIMATION_DURATION_PROP, duration + 's'];
  696. }
  697. function getCssDelayStyle(delay, isKeyframeAnimation) {
  698. var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
  699. return [prop, delay + 's'];
  700. }
  701. function computeCssStyles($window, element, properties) {
  702. var styles = Object.create(null);
  703. var detectedStyles = $window.getComputedStyle(element) || {};
  704. forEach(properties, function(formalStyleName, actualStyleName) {
  705. var val = detectedStyles[formalStyleName];
  706. if (val) {
  707. var c = val.charAt(0);
  708. // only numerical-based values have a negative sign or digit as the first value
  709. if (c === '-' || c === '+' || c >= 0) {
  710. val = parseMaxTime(val);
  711. }
  712. // by setting this to null in the event that the delay is not set or is set directly as 0
  713. // then we can still allow for negative values to be used later on and not mistake this
  714. // value for being greater than any other negative value.
  715. if (val === 0) {
  716. val = null;
  717. }
  718. styles[actualStyleName] = val;
  719. }
  720. });
  721. return styles;
  722. }
  723. function parseMaxTime(str) {
  724. var maxValue = 0;
  725. var values = str.split(/\s*,\s*/);
  726. forEach(values, function(value) {
  727. // it's always safe to consider only second values and omit `ms` values since
  728. // getComputedStyle will always handle the conversion for us
  729. if (value.charAt(value.length - 1) == 's') {
  730. value = value.substring(0, value.length - 1);
  731. }
  732. value = parseFloat(value) || 0;
  733. maxValue = maxValue ? Math.max(value, maxValue) : value;
  734. });
  735. return maxValue;
  736. }
  737. function truthyTimingValue(val) {
  738. return val === 0 || val != null;
  739. }
  740. function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
  741. var style = TRANSITION_PROP;
  742. var value = duration + 's';
  743. if (applyOnlyDuration) {
  744. style += DURATION_KEY;
  745. } else {
  746. value += ' linear all';
  747. }
  748. return [style, value];
  749. }
  750. function createLocalCacheLookup() {
  751. var cache = Object.create(null);
  752. return {
  753. flush: function() {
  754. cache = Object.create(null);
  755. },
  756. count: function(key) {
  757. var entry = cache[key];
  758. return entry ? entry.total : 0;
  759. },
  760. get: function(key) {
  761. var entry = cache[key];
  762. return entry && entry.value;
  763. },
  764. put: function(key, value) {
  765. if (!cache[key]) {
  766. cache[key] = { total: 1, value: value };
  767. } else {
  768. cache[key].total++;
  769. }
  770. }
  771. };
  772. }
  773. // we do not reassign an already present style value since
  774. // if we detect the style property value again we may be
  775. // detecting styles that were added via the `from` styles.
  776. // We make use of `isDefined` here since an empty string
  777. // or null value (which is what getPropertyValue will return
  778. // for a non-existing style) will still be marked as a valid
  779. // value for the style (a falsy value implies that the style
  780. // is to be removed at the end of the animation). If we had a simple
  781. // "OR" statement then it would not be enough to catch that.
  782. function registerRestorableStyles(backup, node, properties) {
  783. forEach(properties, function(prop) {
  784. backup[prop] = isDefined(backup[prop])
  785. ? backup[prop]
  786. : node.style.getPropertyValue(prop);
  787. });
  788. }
  789. var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
  790. var gcsLookup = createLocalCacheLookup();
  791. var gcsStaggerLookup = createLocalCacheLookup();
  792. this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
  793. '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
  794. function($window, $$jqLite, $$AnimateRunner, $timeout,
  795. $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
  796. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  797. var parentCounter = 0;
  798. function gcsHashFn(node, extraClasses) {
  799. var KEY = "$$ngAnimateParentKey";
  800. var parentNode = node.parentNode;
  801. var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
  802. return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
  803. }
  804. function computeCachedCssStyles(node, className, cacheKey, properties) {
  805. var timings = gcsLookup.get(cacheKey);
  806. if (!timings) {
  807. timings = computeCssStyles($window, node, properties);
  808. if (timings.animationIterationCount === 'infinite') {
  809. timings.animationIterationCount = 1;
  810. }
  811. }
  812. // we keep putting this in multiple times even though the value and the cacheKey are the same
  813. // because we're keeping an internal tally of how many duplicate animations are detected.
  814. gcsLookup.put(cacheKey, timings);
  815. return timings;
  816. }
  817. function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
  818. var stagger;
  819. // if we have one or more existing matches of matching elements
  820. // containing the same parent + CSS styles (which is how cacheKey works)
  821. // then staggering is possible
  822. if (gcsLookup.count(cacheKey) > 0) {
  823. stagger = gcsStaggerLookup.get(cacheKey);
  824. if (!stagger) {
  825. var staggerClassName = pendClasses(className, '-stagger');
  826. $$jqLite.addClass(node, staggerClassName);
  827. stagger = computeCssStyles($window, node, properties);
  828. // force the conversion of a null value to zero incase not set
  829. stagger.animationDuration = Math.max(stagger.animationDuration, 0);
  830. stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
  831. $$jqLite.removeClass(node, staggerClassName);
  832. gcsStaggerLookup.put(cacheKey, stagger);
  833. }
  834. }
  835. return stagger || {};
  836. }
  837. var cancelLastRAFRequest;
  838. var rafWaitQueue = [];
  839. function waitUntilQuiet(callback) {
  840. rafWaitQueue.push(callback);
  841. $$rAFScheduler.waitUntilQuiet(function() {
  842. gcsLookup.flush();
  843. gcsStaggerLookup.flush();
  844. // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
  845. // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
  846. var pageWidth = $$forceReflow();
  847. // we use a for loop to ensure that if the queue is changed
  848. // during this looping then it will consider new requests
  849. for (var i = 0; i < rafWaitQueue.length; i++) {
  850. rafWaitQueue[i](pageWidth);
  851. }
  852. rafWaitQueue.length = 0;
  853. });
  854. }
  855. function computeTimings(node, className, cacheKey) {
  856. var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
  857. var aD = timings.animationDelay;
  858. var tD = timings.transitionDelay;
  859. timings.maxDelay = aD && tD
  860. ? Math.max(aD, tD)
  861. : (aD || tD);
  862. timings.maxDuration = Math.max(
  863. timings.animationDuration * timings.animationIterationCount,
  864. timings.transitionDuration);
  865. return timings;
  866. }
  867. return function init(element, initialOptions) {
  868. // all of the animation functions should create
  869. // a copy of the options data, however, if a
  870. // parent service has already created a copy then
  871. // we should stick to using that
  872. var options = initialOptions || {};
  873. if (!options.$$prepared) {
  874. options = prepareAnimationOptions(copy(options));
  875. }
  876. var restoreStyles = {};
  877. var node = getDomNode(element);
  878. if (!node
  879. || !node.parentNode
  880. || !$$animateQueue.enabled()) {
  881. return closeAndReturnNoopAnimator();
  882. }
  883. var temporaryStyles = [];
  884. var classes = element.attr('class');
  885. var styles = packageStyles(options);
  886. var animationClosed;
  887. var animationPaused;
  888. var animationCompleted;
  889. var runner;
  890. var runnerHost;
  891. var maxDelay;
  892. var maxDelayTime;
  893. var maxDuration;
  894. var maxDurationTime;
  895. var startTime;
  896. var events = [];
  897. if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
  898. return closeAndReturnNoopAnimator();
  899. }
  900. var method = options.event && isArray(options.event)
  901. ? options.event.join(' ')
  902. : options.event;
  903. var isStructural = method && options.structural;
  904. var structuralClassName = '';
  905. var addRemoveClassName = '';
  906. if (isStructural) {
  907. structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
  908. } else if (method) {
  909. structuralClassName = method;
  910. }
  911. if (options.addClass) {
  912. addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
  913. }
  914. if (options.removeClass) {
  915. if (addRemoveClassName.length) {
  916. addRemoveClassName += ' ';
  917. }
  918. addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
  919. }
  920. // there may be a situation where a structural animation is combined together
  921. // with CSS classes that need to resolve before the animation is computed.
  922. // However this means that there is no explicit CSS code to block the animation
  923. // from happening (by setting 0s none in the class name). If this is the case
  924. // we need to apply the classes before the first rAF so we know to continue if
  925. // there actually is a detected transition or keyframe animation
  926. if (options.applyClassesEarly && addRemoveClassName.length) {
  927. applyAnimationClasses(element, options);
  928. }
  929. var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
  930. var fullClassName = classes + ' ' + preparationClasses;
  931. var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
  932. var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
  933. var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
  934. // there is no way we can trigger an animation if no styles and
  935. // no classes are being applied which would then trigger a transition,
  936. // unless there a is raw keyframe value that is applied to the element.
  937. if (!containsKeyframeAnimation
  938. && !hasToStyles
  939. && !preparationClasses) {
  940. return closeAndReturnNoopAnimator();
  941. }
  942. var cacheKey, stagger;
  943. if (options.stagger > 0) {
  944. var staggerVal = parseFloat(options.stagger);
  945. stagger = {
  946. transitionDelay: staggerVal,
  947. animationDelay: staggerVal,
  948. transitionDuration: 0,
  949. animationDuration: 0
  950. };
  951. } else {
  952. cacheKey = gcsHashFn(node, fullClassName);
  953. stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
  954. }
  955. if (!options.$$skipPreparationClasses) {
  956. $$jqLite.addClass(element, preparationClasses);
  957. }
  958. var applyOnlyDuration;
  959. if (options.transitionStyle) {
  960. var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
  961. applyInlineStyle(node, transitionStyle);
  962. temporaryStyles.push(transitionStyle);
  963. }
  964. if (options.duration >= 0) {
  965. applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
  966. var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
  967. // we set the duration so that it will be picked up by getComputedStyle later
  968. applyInlineStyle(node, durationStyle);
  969. temporaryStyles.push(durationStyle);
  970. }
  971. if (options.keyframeStyle) {
  972. var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
  973. applyInlineStyle(node, keyframeStyle);
  974. temporaryStyles.push(keyframeStyle);
  975. }
  976. var itemIndex = stagger
  977. ? options.staggerIndex >= 0
  978. ? options.staggerIndex
  979. : gcsLookup.count(cacheKey)
  980. : 0;
  981. var isFirst = itemIndex === 0;
  982. // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
  983. // without causing any combination of transitions to kick in. By adding a negative delay value
  984. // it forces the setup class' transition to end immediately. We later then remove the negative
  985. // transition delay to allow for the transition to naturally do it's thing. The beauty here is
  986. // that if there is no transition defined then nothing will happen and this will also allow
  987. // other transitions to be stacked on top of each other without any chopping them out.
  988. if (isFirst && !options.skipBlocking) {
  989. blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
  990. }
  991. var timings = computeTimings(node, fullClassName, cacheKey);
  992. var relativeDelay = timings.maxDelay;
  993. maxDelay = Math.max(relativeDelay, 0);
  994. maxDuration = timings.maxDuration;
  995. var flags = {};
  996. flags.hasTransitions = timings.transitionDuration > 0;
  997. flags.hasAnimations = timings.animationDuration > 0;
  998. flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
  999. flags.applyTransitionDuration = hasToStyles && (
  1000. (flags.hasTransitions && !flags.hasTransitionAll)
  1001. || (flags.hasAnimations && !flags.hasTransitions));
  1002. flags.applyAnimationDuration = options.duration && flags.hasAnimations;
  1003. flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
  1004. flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
  1005. flags.recalculateTimingStyles = addRemoveClassName.length > 0;
  1006. if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
  1007. maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
  1008. if (flags.applyTransitionDuration) {
  1009. flags.hasTransitions = true;
  1010. timings.transitionDuration = maxDuration;
  1011. applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
  1012. temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
  1013. }
  1014. if (flags.applyAnimationDuration) {
  1015. flags.hasAnimations = true;
  1016. timings.animationDuration = maxDuration;
  1017. temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
  1018. }
  1019. }
  1020. if (maxDuration === 0 && !flags.recalculateTimingStyles) {
  1021. return closeAndReturnNoopAnimator();
  1022. }
  1023. if (options.delay != null) {
  1024. var delayStyle;
  1025. if (typeof options.delay !== "boolean") {
  1026. delayStyle = parseFloat(options.delay);
  1027. // number in options.delay means we have to recalculate the delay for the closing timeout
  1028. maxDelay = Math.max(delayStyle, 0);
  1029. }
  1030. if (flags.applyTransitionDelay) {
  1031. temporaryStyles.push(getCssDelayStyle(delayStyle));
  1032. }
  1033. if (flags.applyAnimationDelay) {
  1034. temporaryStyles.push(getCssDelayStyle(delayStyle, true));
  1035. }
  1036. }
  1037. // we need to recalculate the delay value since we used a pre-emptive negative
  1038. // delay value and the delay value is required for the final event checking. This
  1039. // property will ensure that this will happen after the RAF phase has passed.
  1040. if (options.duration == null && timings.transitionDuration > 0) {
  1041. flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
  1042. }
  1043. maxDelayTime = maxDelay * ONE_SECOND;
  1044. maxDurationTime = maxDuration * ONE_SECOND;
  1045. if (!options.skipBlocking) {
  1046. flags.blockTransition = timings.transitionDuration > 0;
  1047. flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
  1048. stagger.animationDelay > 0 &&
  1049. stagger.animationDuration === 0;
  1050. }
  1051. if (options.from) {
  1052. if (options.cleanupStyles) {
  1053. registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
  1054. }
  1055. applyAnimationFromStyles(element, options);
  1056. }
  1057. if (flags.blockTransition || flags.blockKeyframeAnimation) {
  1058. applyBlocking(maxDuration);
  1059. } else if (!options.skipBlocking) {
  1060. blockTransitions(node, false);
  1061. }
  1062. // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
  1063. return {
  1064. $$willAnimate: true,
  1065. end: endFn,
  1066. start: function() {
  1067. if (animationClosed) return;
  1068. runnerHost = {
  1069. end: endFn,
  1070. cancel: cancelFn,
  1071. resume: null, //this will be set during the start() phase
  1072. pause: null
  1073. };
  1074. runner = new $$AnimateRunner(runnerHost);
  1075. waitUntilQuiet(start);
  1076. // we don't have access to pause/resume the animation
  1077. // since it hasn't run yet. AnimateRunner will therefore
  1078. // set noop functions for resume and pause and they will
  1079. // later be overridden once the animation is triggered
  1080. return runner;
  1081. }
  1082. };
  1083. function endFn() {
  1084. close();
  1085. }
  1086. function cancelFn() {
  1087. close(true);
  1088. }
  1089. function close(rejected) { // jshint ignore:line
  1090. // if the promise has been called already then we shouldn't close
  1091. // the animation again
  1092. if (animationClosed || (animationCompleted && animationPaused)) return;
  1093. animationClosed = true;
  1094. animationPaused = false;
  1095. if (!options.$$skipPreparationClasses) {
  1096. $$jqLite.removeClass(element, preparationClasses);
  1097. }
  1098. $$jqLite.removeClass(element, activeClasses);
  1099. blockKeyframeAnimations(node, false);
  1100. blockTransitions(node, false);
  1101. forEach(temporaryStyles, function(entry) {
  1102. // There is only one way to remove inline style properties entirely from elements.
  1103. // By using `removeProperty` this works, but we need to convert camel-cased CSS
  1104. // styles down to hyphenated values.
  1105. node.style[entry[0]] = '';
  1106. });
  1107. applyAnimationClasses(element, options);
  1108. applyAnimationStyles(element, options);
  1109. if (Object.keys(restoreStyles).length) {
  1110. forEach(restoreStyles, function(value, prop) {
  1111. value ? node.style.setProperty(prop, value)
  1112. : node.style.removeProperty(prop);
  1113. });
  1114. }
  1115. // the reason why we have this option is to allow a synchronous closing callback
  1116. // that is fired as SOON as the animation ends (when the CSS is removed) or if
  1117. // the animation never takes off at all. A good example is a leave animation since
  1118. // the element must be removed just after the animation is over or else the element
  1119. // will appear on screen for one animation frame causing an overbearing flicker.
  1120. if (options.onDone) {
  1121. options.onDone();
  1122. }
  1123. if (events && events.length) {
  1124. // Remove the transitionend / animationend listener(s)
  1125. element.off(events.join(' '), onAnimationProgress);
  1126. }
  1127. //Cancel the fallback closing timeout and remove the timer data
  1128. var animationTimerData = element.data(ANIMATE_TIMER_KEY);
  1129. if (animationTimerData) {
  1130. $timeout.cancel(animationTimerData[0].timer);
  1131. element.removeData(ANIMATE_TIMER_KEY);
  1132. }
  1133. // if the preparation function fails then the promise is not setup
  1134. if (runner) {
  1135. runner.complete(!rejected);
  1136. }
  1137. }
  1138. function applyBlocking(duration) {
  1139. if (flags.blockTransition) {
  1140. blockTransitions(node, duration);
  1141. }
  1142. if (flags.blockKeyframeAnimation) {
  1143. blockKeyframeAnimations(node, !!duration);
  1144. }
  1145. }
  1146. function closeAndReturnNoopAnimator() {
  1147. runner = new $$AnimateRunner({
  1148. end: endFn,
  1149. cancel: cancelFn
  1150. });
  1151. // should flush the cache animation
  1152. waitUntilQuiet(noop);
  1153. close();
  1154. return {
  1155. $$willAnimate: false,
  1156. start: function() {
  1157. return runner;
  1158. },
  1159. end: endFn
  1160. };
  1161. }
  1162. function onAnimationProgress(event) {
  1163. event.stopPropagation();
  1164. var ev = event.originalEvent || event;
  1165. // we now always use `Date.now()` due to the recent changes with
  1166. // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
  1167. var timeStamp = ev.$manualTimeStamp || Date.now();
  1168. /* Firefox (or possibly just Gecko) likes to not round values up
  1169. * when a ms measurement is used for the animation */
  1170. var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
  1171. /* $manualTimeStamp is a mocked timeStamp value which is set
  1172. * within browserTrigger(). This is only here so that tests can
  1173. * mock animations properly. Real events fallback to event.timeStamp,
  1174. * or, if they don't, then a timeStamp is automatically created for them.
  1175. * We're checking to see if the timeStamp surpasses the expected delay,
  1176. * but we're using elapsedTime instead of the timeStamp on the 2nd
  1177. * pre-condition since animationPauseds sometimes close off early */
  1178. if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
  1179. // we set this flag to ensure that if the transition is paused then, when resumed,
  1180. // the animation will automatically close itself since transitions cannot be paused.
  1181. animationCompleted = true;
  1182. close();
  1183. }
  1184. }
  1185. function start() {
  1186. if (animationClosed) return;
  1187. if (!node.parentNode) {
  1188. close();
  1189. return;
  1190. }
  1191. // even though we only pause keyframe animations here the pause flag
  1192. // will still happen when transitions are used. Only the transition will
  1193. // not be paused since that is not possible. If the animation ends when
  1194. // paused then it will not complete until unpaused or cancelled.
  1195. var playPause = function(playAnimation) {
  1196. if (!animationCompleted) {
  1197. animationPaused = !playAnimation;
  1198. if (timings.animationDuration) {
  1199. var value = blockKeyframeAnimations(node, animationPaused);
  1200. animationPaused
  1201. ? temporaryStyles.push(value)
  1202. : removeFromArray(temporaryStyles, value);
  1203. }
  1204. } else if (animationPaused && playAnimation) {
  1205. animationPaused = false;
  1206. close();
  1207. }
  1208. };
  1209. // checking the stagger duration prevents an accidentally cascade of the CSS delay style
  1210. // being inherited from the parent. If the transition duration is zero then we can safely
  1211. // rely that the delay value is an intentional stagger delay style.
  1212. var maxStagger = itemIndex > 0
  1213. && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
  1214. (timings.animationDuration && stagger.animationDuration === 0))
  1215. && Math.max(stagger.animationDelay, stagger.transitionDelay);
  1216. if (maxStagger) {
  1217. $timeout(triggerAnimationStart,
  1218. Math.floor(maxStagger * itemIndex * ONE_SECOND),
  1219. false);
  1220. } else {
  1221. triggerAnimationStart();
  1222. }
  1223. // this will decorate the existing promise runner with pause/resume methods
  1224. runnerHost.resume = function() {
  1225. playPause(true);
  1226. };
  1227. runnerHost.pause = function() {
  1228. playPause(false);
  1229. };
  1230. function triggerAnimationStart() {
  1231. // just incase a stagger animation kicks in when the animation
  1232. // itself was cancelled entirely
  1233. if (animationClosed) return;
  1234. applyBlocking(false);
  1235. forEach(temporaryStyles, function(entry) {
  1236. var key = entry[0];
  1237. var value = entry[1];
  1238. node.style[key] = value;
  1239. });
  1240. applyAnimationClasses(element, options);
  1241. $$jqLite.addClass(element, activeClasses);
  1242. if (flags.recalculateTimingStyles) {
  1243. fullClassName = node.className + ' ' + preparationClasses;
  1244. cacheKey = gcsHashFn(node, fullClassName);
  1245. timings = computeTimings(node, fullClassName, cacheKey);
  1246. relativeDelay = timings.maxDelay;
  1247. maxDelay = Math.max(relativeDelay, 0);
  1248. maxDuration = timings.maxDuration;
  1249. if (maxDuration === 0) {
  1250. close();
  1251. return;
  1252. }
  1253. flags.hasTransitions = timings.transitionDuration > 0;
  1254. flags.hasAnimations = timings.animationDuration > 0;
  1255. }
  1256. if (flags.applyAnimationDelay) {
  1257. relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
  1258. ? parseFloat(options.delay)
  1259. : relativeDelay;
  1260. maxDelay = Math.max(relativeDelay, 0);
  1261. timings.animationDelay = relativeDelay;
  1262. delayStyle = getCssDelayStyle(relativeDelay, true);
  1263. temporaryStyles.push(delayStyle);
  1264. node.style[delayStyle[0]] = delayStyle[1];
  1265. }
  1266. maxDelayTime = maxDelay * ONE_SECOND;
  1267. maxDurationTime = maxDuration * ONE_SECOND;
  1268. if (options.easing) {
  1269. var easeProp, easeVal = options.easing;
  1270. if (flags.hasTransitions) {
  1271. easeProp = TRANSITION_PROP + TIMING_KEY;
  1272. temporaryStyles.push([easeProp, easeVal]);
  1273. node.style[easeProp] = easeVal;
  1274. }
  1275. if (flags.hasAnimations) {
  1276. easeProp = ANIMATION_PROP + TIMING_KEY;
  1277. temporaryStyles.push([easeProp, easeVal]);
  1278. node.style[easeProp] = easeVal;
  1279. }
  1280. }
  1281. if (timings.transitionDuration) {
  1282. events.push(TRANSITIONEND_EVENT);
  1283. }
  1284. if (timings.animationDuration) {
  1285. events.push(ANIMATIONEND_EVENT);
  1286. }
  1287. startTime = Date.now();
  1288. var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
  1289. var endTime = startTime + timerTime;
  1290. var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
  1291. var setupFallbackTimer = true;
  1292. if (animationsData.length) {
  1293. var currentTimerData = animationsData[0];
  1294. setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
  1295. if (setupFallbackTimer) {
  1296. $timeout.cancel(currentTimerData.timer);
  1297. } else {
  1298. animationsData.push(close);
  1299. }
  1300. }
  1301. if (setupFallbackTimer) {
  1302. var timer = $timeout(onAnimationExpired, timerTime, false);
  1303. animationsData[0] = {
  1304. timer: timer,
  1305. expectedEndTime: endTime
  1306. };
  1307. animationsData.push(close);
  1308. element.data(ANIMATE_TIMER_KEY, animationsData);
  1309. }
  1310. if (events.length) {
  1311. element.on(events.join(' '), onAnimationProgress);
  1312. }
  1313. if (options.to) {
  1314. if (options.cleanupStyles) {
  1315. registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
  1316. }
  1317. applyAnimationToStyles(element, options);
  1318. }
  1319. }
  1320. function onAnimationExpired() {
  1321. var animationsData = element.data(ANIMATE_TIMER_KEY);
  1322. // this will be false in the event that the element was
  1323. // removed from the DOM (via a leave animation or something
  1324. // similar)
  1325. if (animationsData) {
  1326. for (var i = 1; i < animationsData.length; i++) {
  1327. animationsData[i]();
  1328. }
  1329. element.removeData(ANIMATE_TIMER_KEY);
  1330. }
  1331. }
  1332. }
  1333. };
  1334. }];
  1335. }];
  1336. var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
  1337. $$animationProvider.drivers.push('$$animateCssDriver');
  1338. var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
  1339. var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
  1340. var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
  1341. var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
  1342. function isDocumentFragment(node) {
  1343. return node.parentNode && node.parentNode.nodeType === 11;
  1344. }
  1345. this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
  1346. function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
  1347. // only browsers that support these properties can render animations
  1348. if (!$sniffer.animations && !$sniffer.transitions) return noop;
  1349. var bodyNode = $document[0].body;
  1350. var rootNode = getDomNode($rootElement);
  1351. var rootBodyElement = jqLite(
  1352. // this is to avoid using something that exists outside of the body
  1353. // we also special case the doc fragment case because our unit test code
  1354. // appends the $rootElement to the body after the app has been bootstrapped
  1355. isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
  1356. );
  1357. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  1358. return function initDriverFn(animationDetails) {
  1359. return animationDetails.from && animationDetails.to
  1360. ? prepareFromToAnchorAnimation(animationDetails.from,
  1361. animationDetails.to,
  1362. animationDetails.classes,
  1363. animationDetails.anchors)
  1364. : prepareRegularAnimation(animationDetails);
  1365. };
  1366. function filterCssClasses(classes) {
  1367. //remove all the `ng-` stuff
  1368. return classes.replace(/\bng-\S+\b/g, '');
  1369. }
  1370. function getUniqueValues(a, b) {
  1371. if (isString(a)) a = a.split(' ');
  1372. if (isString(b)) b = b.split(' ');
  1373. return a.filter(function(val) {
  1374. return b.indexOf(val) === -1;
  1375. }).join(' ');
  1376. }
  1377. function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
  1378. var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
  1379. var startingClasses = filterCssClasses(getClassVal(clone));
  1380. outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  1381. inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  1382. clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
  1383. rootBodyElement.append(clone);
  1384. var animatorIn, animatorOut = prepareOutAnimation();
  1385. // the user may not end up using the `out` animation and
  1386. // only making use of the `in` animation or vice-versa.
  1387. // In either case we should allow this and not assume the
  1388. // animation is over unless both animations are not used.
  1389. if (!animatorOut) {
  1390. animatorIn = prepareInAnimation();
  1391. if (!animatorIn) {
  1392. return end();
  1393. }
  1394. }
  1395. var startingAnimator = animatorOut || animatorIn;
  1396. return {
  1397. start: function() {
  1398. var runner;
  1399. var currentAnimation = startingAnimator.start();
  1400. currentAnimation.done(function() {
  1401. currentAnimation = null;
  1402. if (!animatorIn) {
  1403. animatorIn = prepareInAnimation();
  1404. if (animatorIn) {
  1405. currentAnimation = animatorIn.start();
  1406. currentAnimation.done(function() {
  1407. currentAnimation = null;
  1408. end();
  1409. runner.complete();
  1410. });
  1411. return currentAnimation;
  1412. }
  1413. }
  1414. // in the event that there is no `in` animation
  1415. end();
  1416. runner.complete();
  1417. });
  1418. runner = new $$AnimateRunner({
  1419. end: endFn,
  1420. cancel: endFn
  1421. });
  1422. return runner;
  1423. function endFn() {
  1424. if (currentAnimation) {
  1425. currentAnimation.end();
  1426. }
  1427. }
  1428. }
  1429. };
  1430. function calculateAnchorStyles(anchor) {
  1431. var styles = {};
  1432. var coords = getDomNode(anchor).getBoundingClientRect();
  1433. // we iterate directly since safari messes up and doesn't return
  1434. // all the keys for the coords object when iterated
  1435. forEach(['width','height','top','left'], function(key) {
  1436. var value = coords[key];
  1437. switch (key) {
  1438. case 'top':
  1439. value += bodyNode.scrollTop;
  1440. break;
  1441. case 'left':
  1442. value += bodyNode.scrollLeft;
  1443. break;
  1444. }
  1445. styles[key] = Math.floor(value) + 'px';
  1446. });
  1447. return styles;
  1448. }
  1449. function prepareOutAnimation() {
  1450. var animator = $animateCss(clone, {
  1451. addClass: NG_OUT_ANCHOR_CLASS_NAME,
  1452. delay: true,
  1453. from: calculateAnchorStyles(outAnchor)
  1454. });
  1455. // read the comment within `prepareRegularAnimation` to understand
  1456. // why this check is necessary
  1457. return animator.$$willAnimate ? animator : null;
  1458. }
  1459. function getClassVal(element) {
  1460. return element.attr('class') || '';
  1461. }
  1462. function prepareInAnimation() {
  1463. var endingClasses = filterCssClasses(getClassVal(inAnchor));
  1464. var toAdd = getUniqueValues(endingClasses, startingClasses);
  1465. var toRemove = getUniqueValues(startingClasses, endingClasses);
  1466. var animator = $animateCss(clone, {
  1467. to: calculateAnchorStyles(inAnchor),
  1468. addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
  1469. removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
  1470. delay: true
  1471. });
  1472. // read the comment within `prepareRegularAnimation` to understand
  1473. // why this check is necessary
  1474. return animator.$$willAnimate ? animator : null;
  1475. }
  1476. function end() {
  1477. clone.remove();
  1478. outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  1479. inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  1480. }
  1481. }
  1482. function prepareFromToAnchorAnimation(from, to, classes, anchors) {
  1483. var fromAnimation = prepareRegularAnimation(from, noop);
  1484. var toAnimation = prepareRegularAnimation(to, noop);
  1485. var anchorAnimations = [];
  1486. forEach(anchors, function(anchor) {
  1487. var outElement = anchor['out'];
  1488. var inElement = anchor['in'];
  1489. var animator = prepareAnchoredAnimation(classes, outElement, inElement);
  1490. if (animator) {
  1491. anchorAnimations.push(animator);
  1492. }
  1493. });
  1494. // no point in doing anything when there are no elements to animate
  1495. if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
  1496. return {
  1497. start: function() {
  1498. var animationRunners = [];
  1499. if (fromAnimation) {
  1500. animationRunners.push(fromAnimation.start());
  1501. }
  1502. if (toAnimation) {
  1503. animationRunners.push(toAnimation.start());
  1504. }
  1505. forEach(anchorAnimations, function(animation) {
  1506. animationRunners.push(animation.start());
  1507. });
  1508. var runner = new $$AnimateRunner({
  1509. end: endFn,
  1510. cancel: endFn // CSS-driven animations cannot be cancelled, only ended
  1511. });
  1512. $$AnimateRunner.all(animationRunners, function(status) {
  1513. runner.complete(status);
  1514. });
  1515. return runner;
  1516. function endFn() {
  1517. forEach(animationRunners, function(runner) {
  1518. runner.end();
  1519. });
  1520. }
  1521. }
  1522. };
  1523. }
  1524. function prepareRegularAnimation(animationDetails) {
  1525. var element = animationDetails.element;
  1526. var options = animationDetails.options || {};
  1527. if (animationDetails.structural) {
  1528. options.event = animationDetails.event;
  1529. options.structural = true;
  1530. options.applyClassesEarly = true;
  1531. // we special case the leave animation since we want to ensure that
  1532. // the element is removed as soon as the animation is over. Otherwise
  1533. // a flicker might appear or the element may not be removed at all
  1534. if (animationDetails.event === 'leave') {
  1535. options.onDone = options.domOperation;
  1536. }
  1537. }
  1538. // We assign the preparationClasses as the actual animation event since
  1539. // the internals of $animateCss will just suffix the event token values
  1540. // with `-active` to trigger the animation.
  1541. if (options.preparationClasses) {
  1542. options.event = concatWithSpace(options.event, options.preparationClasses);
  1543. }
  1544. var animator = $animateCss(element, options);
  1545. // the driver lookup code inside of $$animation attempts to spawn a
  1546. // driver one by one until a driver returns a.$$willAnimate animator object.
  1547. // $animateCss will always return an object, however, it will pass in
  1548. // a flag as a hint as to whether an animation was detected or not
  1549. return animator.$$willAnimate ? animator : null;
  1550. }
  1551. }];
  1552. }];
  1553. // TODO(matsko): use caching here to speed things up for detection
  1554. // TODO(matsko): add documentation
  1555. // by the time...
  1556. var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
  1557. this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
  1558. function($injector, $$AnimateRunner, $$jqLite) {
  1559. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  1560. // $animateJs(element, 'enter');
  1561. return function(element, event, classes, options) {
  1562. var animationClosed = false;
  1563. // the `classes` argument is optional and if it is not used
  1564. // then the classes will be resolved from the element's className
  1565. // property as well as options.addClass/options.removeClass.
  1566. if (arguments.length === 3 && isObject(classes)) {
  1567. options = classes;
  1568. classes = null;
  1569. }
  1570. options = prepareAnimationOptions(options);
  1571. if (!classes) {
  1572. classes = element.attr('class') || '';
  1573. if (options.addClass) {
  1574. classes += ' ' + options.addClass;
  1575. }
  1576. if (options.removeClass) {
  1577. classes += ' ' + options.removeClass;
  1578. }
  1579. }
  1580. var classesToAdd = options.addClass;
  1581. var classesToRemove = options.removeClass;
  1582. // the lookupAnimations function returns a series of animation objects that are
  1583. // matched up with one or more of the CSS classes. These animation objects are
  1584. // defined via the module.animation factory function. If nothing is detected then
  1585. // we don't return anything which then makes $animation query the next driver.
  1586. var animations = lookupAnimations(classes);
  1587. var before, after;
  1588. if (animations.length) {
  1589. var afterFn, beforeFn;
  1590. if (event == 'leave') {
  1591. beforeFn = 'leave';
  1592. afterFn = 'afterLeave'; // TODO(matsko): get rid of this
  1593. } else {
  1594. beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
  1595. afterFn = event;
  1596. }
  1597. if (event !== 'enter' && event !== 'move') {
  1598. before = packageAnimations(element, event, options, animations, beforeFn);
  1599. }
  1600. after = packageAnimations(element, event, options, animations, afterFn);
  1601. }
  1602. // no matching animations
  1603. if (!before && !after) return;
  1604. function applyOptions() {
  1605. options.domOperation();
  1606. applyAnimationClasses(element, options);
  1607. }
  1608. function close() {
  1609. animationClosed = true;
  1610. applyOptions();
  1611. applyAnimationStyles(element, options);
  1612. }
  1613. var runner;
  1614. return {
  1615. $$willAnimate: true,
  1616. end: function() {
  1617. if (runner) {
  1618. runner.end();
  1619. } else {
  1620. close();
  1621. runner = new $$AnimateRunner();
  1622. runner.complete(true);
  1623. }
  1624. return runner;
  1625. },
  1626. start: function() {
  1627. if (runner) {
  1628. return runner;
  1629. }
  1630. runner = new $$AnimateRunner();
  1631. var closeActiveAnimations;
  1632. var chain = [];
  1633. if (before) {
  1634. chain.push(function(fn) {
  1635. closeActiveAnimations = before(fn);
  1636. });
  1637. }
  1638. if (chain.length) {
  1639. chain.push(function(fn) {
  1640. applyOptions();
  1641. fn(true);
  1642. });
  1643. } else {
  1644. applyOptions();
  1645. }
  1646. if (after) {
  1647. chain.push(function(fn) {
  1648. closeActiveAnimations = after(fn);
  1649. });
  1650. }
  1651. runner.setHost({
  1652. end: function() {
  1653. endAnimations();
  1654. },
  1655. cancel: function() {
  1656. endAnimations(true);
  1657. }
  1658. });
  1659. $$AnimateRunner.chain(chain, onComplete);
  1660. return runner;
  1661. function onComplete(success) {
  1662. close(success);
  1663. runner.complete(success);
  1664. }
  1665. function endAnimations(cancelled) {
  1666. if (!animationClosed) {
  1667. (closeActiveAnimations || noop)(cancelled);
  1668. onComplete(cancelled);
  1669. }
  1670. }
  1671. }
  1672. };
  1673. function executeAnimationFn(fn, element, event, options, onDone) {
  1674. var args;
  1675. switch (event) {
  1676. case 'animate':
  1677. args = [element, options.from, options.to, onDone];
  1678. break;
  1679. case 'setClass':
  1680. args = [element, classesToAdd, classesToRemove, onDone];
  1681. break;
  1682. case 'addClass':
  1683. args = [element, classesToAdd, onDone];
  1684. break;
  1685. case 'removeClass':
  1686. args = [element, classesToRemove, onDone];
  1687. break;
  1688. default:
  1689. args = [element, onDone];
  1690. break;
  1691. }
  1692. args.push(options);
  1693. var value = fn.apply(fn, args);
  1694. if (value) {
  1695. if (isFunction(value.start)) {
  1696. value = value.start();
  1697. }
  1698. if (value instanceof $$AnimateRunner) {
  1699. value.done(onDone);
  1700. } else if (isFunction(value)) {
  1701. // optional onEnd / onCancel callback
  1702. return value;
  1703. }
  1704. }
  1705. return noop;
  1706. }
  1707. function groupEventedAnimations(element, event, options, animations, fnName) {
  1708. var operations = [];
  1709. forEach(animations, function(ani) {
  1710. var animation = ani[fnName];
  1711. if (!animation) return;
  1712. // note that all of these animations will run in parallel
  1713. operations.push(function() {
  1714. var runner;
  1715. var endProgressCb;
  1716. var resolved = false;
  1717. var onAnimationComplete = function(rejected) {
  1718. if (!resolved) {
  1719. resolved = true;
  1720. (endProgressCb || noop)(rejected);
  1721. runner.complete(!rejected);
  1722. }
  1723. };
  1724. runner = new $$AnimateRunner({
  1725. end: function() {
  1726. onAnimationComplete();
  1727. },
  1728. cancel: function() {
  1729. onAnimationComplete(true);
  1730. }
  1731. });
  1732. endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
  1733. var cancelled = result === false;
  1734. onAnimationComplete(cancelled);
  1735. });
  1736. return runner;
  1737. });
  1738. });
  1739. return operations;
  1740. }
  1741. function packageAnimations(element, event, options, animations, fnName) {
  1742. var operations = groupEventedAnimations(element, event, options, animations, fnName);
  1743. if (operations.length === 0) {
  1744. var a,b;
  1745. if (fnName === 'beforeSetClass') {
  1746. a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
  1747. b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
  1748. } else if (fnName === 'setClass') {
  1749. a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
  1750. b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
  1751. }
  1752. if (a) {
  1753. operations = operations.concat(a);
  1754. }
  1755. if (b) {
  1756. operations = operations.concat(b);
  1757. }
  1758. }
  1759. if (operations.length === 0) return;
  1760. // TODO(matsko): add documentation
  1761. return function startAnimation(callback) {
  1762. var runners = [];
  1763. if (operations.length) {
  1764. forEach(operations, function(animateFn) {
  1765. runners.push(animateFn());
  1766. });
  1767. }
  1768. runners.length ? $$AnimateRunner.all(runners, callback) : callback();
  1769. return function endFn(reject) {
  1770. forEach(runners, function(runner) {
  1771. reject ? runner.cancel() : runner.end();
  1772. });
  1773. };
  1774. };
  1775. }
  1776. };
  1777. function lookupAnimations(classes) {
  1778. classes = isArray(classes) ? classes : classes.split(' ');
  1779. var matches = [], flagMap = {};
  1780. for (var i=0; i < classes.length; i++) {
  1781. var klass = classes[i],
  1782. animationFactory = $animateProvider.$$registeredAnimations[klass];
  1783. if (animationFactory && !flagMap[klass]) {
  1784. matches.push($injector.get(animationFactory));
  1785. flagMap[klass] = true;
  1786. }
  1787. }
  1788. return matches;
  1789. }
  1790. }];
  1791. }];
  1792. var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
  1793. $$animationProvider.drivers.push('$$animateJsDriver');
  1794. this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
  1795. return function initDriverFn(animationDetails) {
  1796. if (animationDetails.from && animationDetails.to) {
  1797. var fromAnimation = prepareAnimation(animationDetails.from);
  1798. var toAnimation = prepareAnimation(animationDetails.to);
  1799. if (!fromAnimation && !toAnimation) return;
  1800. return {
  1801. start: function() {
  1802. var animationRunners = [];
  1803. if (fromAnimation) {
  1804. animationRunners.push(fromAnimation.start());
  1805. }
  1806. if (toAnimation) {
  1807. animationRunners.push(toAnimation.start());
  1808. }
  1809. $$AnimateRunner.all(animationRunners, done);
  1810. var runner = new $$AnimateRunner({
  1811. end: endFnFactory(),
  1812. cancel: endFnFactory()
  1813. });
  1814. return runner;
  1815. function endFnFactory() {
  1816. return function() {
  1817. forEach(animationRunners, function(runner) {
  1818. // at this point we cannot cancel animations for groups just yet. 1.5+
  1819. runner.end();
  1820. });
  1821. };
  1822. }
  1823. function done(status) {
  1824. runner.complete(status);
  1825. }
  1826. }
  1827. };
  1828. } else {
  1829. return prepareAnimation(animationDetails);
  1830. }
  1831. };
  1832. function prepareAnimation(animationDetails) {
  1833. // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
  1834. var element = animationDetails.element;
  1835. var event = animationDetails.event;
  1836. var options = animationDetails.options;
  1837. var classes = animationDetails.classes;
  1838. return $$animateJs(element, event, classes, options);
  1839. }
  1840. }];
  1841. }];
  1842. var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
  1843. var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
  1844. var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
  1845. var PRE_DIGEST_STATE = 1;
  1846. var RUNNING_STATE = 2;
  1847. var ONE_SPACE = ' ';
  1848. var rules = this.rules = {
  1849. skip: [],
  1850. cancel: [],
  1851. join: []
  1852. };
  1853. function makeTruthyCssClassMap(classString) {
  1854. if (!classString) {
  1855. return null;
  1856. }
  1857. var keys = classString.split(ONE_SPACE);
  1858. var map = Object.create(null);
  1859. forEach(keys, function(key) {
  1860. map[key] = true;
  1861. });
  1862. return map;
  1863. }
  1864. function hasMatchingClasses(newClassString, currentClassString) {
  1865. if (newClassString && currentClassString) {
  1866. var currentClassMap = makeTruthyCssClassMap(currentClassString);
  1867. return newClassString.split(ONE_SPACE).some(function(className) {
  1868. return currentClassMap[className];
  1869. });
  1870. }
  1871. }
  1872. function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
  1873. return rules[ruleType].some(function(fn) {
  1874. return fn(element, currentAnimation, previousAnimation);
  1875. });
  1876. }
  1877. function hasAnimationClasses(animation, and) {
  1878. var a = (animation.addClass || '').length > 0;
  1879. var b = (animation.removeClass || '').length > 0;
  1880. return and ? a && b : a || b;
  1881. }
  1882. rules.join.push(function(element, newAnimation, currentAnimation) {
  1883. // if the new animation is class-based then we can just tack that on
  1884. return !newAnimation.structural && hasAnimationClasses(newAnimation);
  1885. });
  1886. rules.skip.push(function(element, newAnimation, currentAnimation) {
  1887. // there is no need to animate anything if no classes are being added and
  1888. // there is no structural animation that will be triggered
  1889. return !newAnimation.structural && !hasAnimationClasses(newAnimation);
  1890. });
  1891. rules.skip.push(function(element, newAnimation, currentAnimation) {
  1892. // why should we trigger a new structural animation if the element will
  1893. // be removed from the DOM anyway?
  1894. return currentAnimation.event == 'leave' && newAnimation.structural;
  1895. });
  1896. rules.skip.push(function(element, newAnimation, currentAnimation) {
  1897. // if there is an ongoing current animation then don't even bother running the class-based animation
  1898. return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
  1899. });
  1900. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  1901. // there can never be two structural animations running at the same time
  1902. return currentAnimation.structural && newAnimation.structural;
  1903. });
  1904. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  1905. // if the previous animation is already running, but the new animation will
  1906. // be triggered, but the new animation is structural
  1907. return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
  1908. });
  1909. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  1910. // cancel the animation if classes added / removed in both animation cancel each other out,
  1911. // but only if the current animation isn't structural
  1912. if (currentAnimation.structural) return false;
  1913. var nA = newAnimation.addClass;
  1914. var nR = newAnimation.removeClass;
  1915. var cA = currentAnimation.addClass;
  1916. var cR = currentAnimation.removeClass;
  1917. // early detection to save the global CPU shortage :)
  1918. if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
  1919. return false;
  1920. }
  1921. return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
  1922. });
  1923. this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
  1924. '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
  1925. function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
  1926. $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
  1927. var activeAnimationsLookup = new $$HashMap();
  1928. var disabledElementsLookup = new $$HashMap();
  1929. var animationsEnabled = null;
  1930. function postDigestTaskFactory() {
  1931. var postDigestCalled = false;
  1932. return function(fn) {
  1933. // we only issue a call to postDigest before
  1934. // it has first passed. This prevents any callbacks
  1935. // from not firing once the animation has completed
  1936. // since it will be out of the digest cycle.
  1937. if (postDigestCalled) {
  1938. fn();
  1939. } else {
  1940. $rootScope.$$postDigest(function() {
  1941. postDigestCalled = true;
  1942. fn();
  1943. });
  1944. }
  1945. };
  1946. }
  1947. // Wait until all directive and route-related templates are downloaded and
  1948. // compiled. The $templateRequest.totalPendingRequests variable keeps track of
  1949. // all of the remote templates being currently downloaded. If there are no
  1950. // templates currently downloading then the watcher will still fire anyway.
  1951. var deregisterWatch = $rootScope.$watch(
  1952. function() { return $templateRequest.totalPendingRequests === 0; },
  1953. function(isEmpty) {
  1954. if (!isEmpty) return;
  1955. deregisterWatch();
  1956. // Now that all templates have been downloaded, $animate will wait until
  1957. // the post digest queue is empty before enabling animations. By having two
  1958. // calls to $postDigest calls we can ensure that the flag is enabled at the
  1959. // very end of the post digest queue. Since all of the animations in $animate
  1960. // use $postDigest, it's important that the code below executes at the end.
  1961. // This basically means that the page is fully downloaded and compiled before
  1962. // any animations are triggered.
  1963. $rootScope.$$postDigest(function() {
  1964. $rootScope.$$postDigest(function() {
  1965. // we check for null directly in the event that the application already called
  1966. // .enabled() with whatever arguments that it provided it with
  1967. if (animationsEnabled === null) {
  1968. animationsEnabled = true;
  1969. }
  1970. });
  1971. });
  1972. }
  1973. );
  1974. var callbackRegistry = {};
  1975. // remember that the classNameFilter is set during the provider/config
  1976. // stage therefore we can optimize here and setup a helper function
  1977. var classNameFilter = $animateProvider.classNameFilter();
  1978. var isAnimatableClassName = !classNameFilter
  1979. ? function() { return true; }
  1980. : function(className) {
  1981. return classNameFilter.test(className);
  1982. };
  1983. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  1984. function normalizeAnimationDetails(element, animation) {
  1985. return mergeAnimationDetails(element, animation, {});
  1986. }
  1987. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  1988. var contains = Node.prototype.contains || function(arg) {
  1989. // jshint bitwise: false
  1990. return this === arg || !!(this.compareDocumentPosition(arg) & 16);
  1991. // jshint bitwise: true
  1992. };
  1993. function findCallbacks(parent, element, event) {
  1994. var targetNode = getDomNode(element);
  1995. var targetParentNode = getDomNode(parent);
  1996. var matches = [];
  1997. var entries = callbackRegistry[event];
  1998. if (entries) {
  1999. forEach(entries, function(entry) {
  2000. if (contains.call(entry.node, targetNode)) {
  2001. matches.push(entry.callback);
  2002. } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
  2003. matches.push(entry.callback);
  2004. }
  2005. });
  2006. }
  2007. return matches;
  2008. }
  2009. var $animate = {
  2010. on: function(event, container, callback) {
  2011. var node = extractElementNode(container);
  2012. callbackRegistry[event] = callbackRegistry[event] || [];
  2013. callbackRegistry[event].push({
  2014. node: node,
  2015. callback: callback
  2016. });
  2017. // Remove the callback when the element is removed from the DOM
  2018. jqLite(container).on('$destroy', function() {
  2019. $animate.off(event, container, callback);
  2020. });
  2021. },
  2022. off: function(event, container, callback) {
  2023. var entries = callbackRegistry[event];
  2024. if (!entries) return;
  2025. callbackRegistry[event] = arguments.length === 1
  2026. ? null
  2027. : filterFromRegistry(entries, container, callback);
  2028. function filterFromRegistry(list, matchContainer, matchCallback) {
  2029. var containerNode = extractElementNode(matchContainer);
  2030. return list.filter(function(entry) {
  2031. var isMatch = entry.node === containerNode &&
  2032. (!matchCallback || entry.callback === matchCallback);
  2033. return !isMatch;
  2034. });
  2035. }
  2036. },
  2037. pin: function(element, parentElement) {
  2038. assertArg(isElement(element), 'element', 'not an element');
  2039. assertArg(isElement(parentElement), 'parentElement', 'not an element');
  2040. element.data(NG_ANIMATE_PIN_DATA, parentElement);
  2041. },
  2042. push: function(element, event, options, domOperation) {
  2043. options = options || {};
  2044. options.domOperation = domOperation;
  2045. return queueAnimation(element, event, options);
  2046. },
  2047. // this method has four signatures:
  2048. // () - global getter
  2049. // (bool) - global setter
  2050. // (element) - element getter
  2051. // (element, bool) - element setter<F37>
  2052. enabled: function(element, bool) {
  2053. var argCount = arguments.length;
  2054. if (argCount === 0) {
  2055. // () - Global getter
  2056. bool = !!animationsEnabled;
  2057. } else {
  2058. var hasElement = isElement(element);
  2059. if (!hasElement) {
  2060. // (bool) - Global setter
  2061. bool = animationsEnabled = !!element;
  2062. } else {
  2063. var node = getDomNode(element);
  2064. var recordExists = disabledElementsLookup.get(node);
  2065. if (argCount === 1) {
  2066. // (element) - Element getter
  2067. bool = !recordExists;
  2068. } else {
  2069. // (element, bool) - Element setter
  2070. disabledElementsLookup.put(node, !bool);
  2071. }
  2072. }
  2073. }
  2074. return bool;
  2075. }
  2076. };
  2077. return $animate;
  2078. function queueAnimation(element, event, initialOptions) {
  2079. // we always make a copy of the options since
  2080. // there should never be any side effects on
  2081. // the input data when running `$animateCss`.
  2082. var options = copy(initialOptions);
  2083. var node, parent;
  2084. element = stripCommentsFromElement(element);
  2085. if (element) {
  2086. node = getDomNode(element);
  2087. parent = element.parent();
  2088. }
  2089. options = prepareAnimationOptions(options);
  2090. // we create a fake runner with a working promise.
  2091. // These methods will become available after the digest has passed
  2092. var runner = new $$AnimateRunner();
  2093. // this is used to trigger callbacks in postDigest mode
  2094. var runInNextPostDigestOrNow = postDigestTaskFactory();
  2095. if (isArray(options.addClass)) {
  2096. options.addClass = options.addClass.join(' ');
  2097. }
  2098. if (options.addClass && !isString(options.addClass)) {
  2099. options.addClass = null;
  2100. }
  2101. if (isArray(options.removeClass)) {
  2102. options.removeClass = options.removeClass.join(' ');
  2103. }
  2104. if (options.removeClass && !isString(options.removeClass)) {
  2105. options.removeClass = null;
  2106. }
  2107. if (options.from && !isObject(options.from)) {
  2108. options.from = null;
  2109. }
  2110. if (options.to && !isObject(options.to)) {
  2111. options.to = null;
  2112. }
  2113. // there are situations where a directive issues an animation for
  2114. // a jqLite wrapper that contains only comment nodes... If this
  2115. // happens then there is no way we can perform an animation
  2116. if (!node) {
  2117. close();
  2118. return runner;
  2119. }
  2120. var className = [node.className, options.addClass, options.removeClass].join(' ');
  2121. if (!isAnimatableClassName(className)) {
  2122. close();
  2123. return runner;
  2124. }
  2125. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  2126. // this is a hard disable of all animations for the application or on
  2127. // the element itself, therefore there is no need to continue further
  2128. // past this point if not enabled
  2129. // Animations are also disabled if the document is currently hidden (page is not visible
  2130. // to the user), because browsers slow down or do not flush calls to requestAnimationFrame
  2131. var skipAnimations = !animationsEnabled || $document[0].hidden || disabledElementsLookup.get(node);
  2132. var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
  2133. var hasExistingAnimation = !!existingAnimation.state;
  2134. // there is no point in traversing the same collection of parent ancestors if a followup
  2135. // animation will be run on the same element that already did all that checking work
  2136. if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
  2137. skipAnimations = !areAnimationsAllowed(element, parent, event);
  2138. }
  2139. if (skipAnimations) {
  2140. close();
  2141. return runner;
  2142. }
  2143. if (isStructural) {
  2144. closeChildAnimations(element);
  2145. }
  2146. var newAnimation = {
  2147. structural: isStructural,
  2148. element: element,
  2149. event: event,
  2150. addClass: options.addClass,
  2151. removeClass: options.removeClass,
  2152. close: close,
  2153. options: options,
  2154. runner: runner
  2155. };
  2156. if (hasExistingAnimation) {
  2157. var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
  2158. if (skipAnimationFlag) {
  2159. if (existingAnimation.state === RUNNING_STATE) {
  2160. close();
  2161. return runner;
  2162. } else {
  2163. mergeAnimationDetails(element, existingAnimation, newAnimation);
  2164. return existingAnimation.runner;
  2165. }
  2166. }
  2167. var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
  2168. if (cancelAnimationFlag) {
  2169. if (existingAnimation.state === RUNNING_STATE) {
  2170. // this will end the animation right away and it is safe
  2171. // to do so since the animation is already running and the
  2172. // runner callback code will run in async
  2173. existingAnimation.runner.end();
  2174. } else if (existingAnimation.structural) {
  2175. // this means that the animation is queued into a digest, but
  2176. // hasn't started yet. Therefore it is safe to run the close
  2177. // method which will call the runner methods in async.
  2178. existingAnimation.close();
  2179. } else {
  2180. // this will merge the new animation options into existing animation options
  2181. mergeAnimationDetails(element, existingAnimation, newAnimation);
  2182. return existingAnimation.runner;
  2183. }
  2184. } else {
  2185. // a joined animation means that this animation will take over the existing one
  2186. // so an example would involve a leave animation taking over an enter. Then when
  2187. // the postDigest kicks in the enter will be ignored.
  2188. var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
  2189. if (joinAnimationFlag) {
  2190. if (existingAnimation.state === RUNNING_STATE) {
  2191. normalizeAnimationDetails(element, newAnimation);
  2192. } else {
  2193. applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
  2194. event = newAnimation.event = existingAnimation.event;
  2195. options = mergeAnimationDetails(element, existingAnimation, newAnimation);
  2196. //we return the same runner since only the option values of this animation will
  2197. //be fed into the `existingAnimation`.
  2198. return existingAnimation.runner;
  2199. }
  2200. }
  2201. }
  2202. } else {
  2203. // normalization in this case means that it removes redundant CSS classes that
  2204. // already exist (addClass) or do not exist (removeClass) on the element
  2205. normalizeAnimationDetails(element, newAnimation);
  2206. }
  2207. // when the options are merged and cleaned up we may end up not having to do
  2208. // an animation at all, therefore we should check this before issuing a post
  2209. // digest callback. Structural animations will always run no matter what.
  2210. var isValidAnimation = newAnimation.structural;
  2211. if (!isValidAnimation) {
  2212. // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
  2213. isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
  2214. || hasAnimationClasses(newAnimation);
  2215. }
  2216. if (!isValidAnimation) {
  2217. close();
  2218. clearElementAnimationState(element);
  2219. return runner;
  2220. }
  2221. // the counter keeps track of cancelled animations
  2222. var counter = (existingAnimation.counter || 0) + 1;
  2223. newAnimation.counter = counter;
  2224. markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
  2225. $rootScope.$$postDigest(function() {
  2226. var animationDetails = activeAnimationsLookup.get(node);
  2227. var animationCancelled = !animationDetails;
  2228. animationDetails = animationDetails || {};
  2229. // if addClass/removeClass is called before something like enter then the
  2230. // registered parent element may not be present. The code below will ensure
  2231. // that a final value for parent element is obtained
  2232. var parentElement = element.parent() || [];
  2233. // animate/structural/class-based animations all have requirements. Otherwise there
  2234. // is no point in performing an animation. The parent node must also be set.
  2235. var isValidAnimation = parentElement.length > 0
  2236. && (animationDetails.event === 'animate'
  2237. || animationDetails.structural
  2238. || hasAnimationClasses(animationDetails));
  2239. // this means that the previous animation was cancelled
  2240. // even if the follow-up animation is the same event
  2241. if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
  2242. // if another animation did not take over then we need
  2243. // to make sure that the domOperation and options are
  2244. // handled accordingly
  2245. if (animationCancelled) {
  2246. applyAnimationClasses(element, options);
  2247. applyAnimationStyles(element, options);
  2248. }
  2249. // if the event changed from something like enter to leave then we do
  2250. // it, otherwise if it's the same then the end result will be the same too
  2251. if (animationCancelled || (isStructural && animationDetails.event !== event)) {
  2252. options.domOperation();
  2253. runner.end();
  2254. }
  2255. // in the event that the element animation was not cancelled or a follow-up animation
  2256. // isn't allowed to animate from here then we need to clear the state of the element
  2257. // so that any future animations won't read the expired animation data.
  2258. if (!isValidAnimation) {
  2259. clearElementAnimationState(element);
  2260. }
  2261. return;
  2262. }
  2263. // this combined multiple class to addClass / removeClass into a setClass event
  2264. // so long as a structural event did not take over the animation
  2265. event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
  2266. ? 'setClass'
  2267. : animationDetails.event;
  2268. markElementAnimationState(element, RUNNING_STATE);
  2269. var realRunner = $$animation(element, event, animationDetails.options);
  2270. realRunner.done(function(status) {
  2271. close(!status);
  2272. var animationDetails = activeAnimationsLookup.get(node);
  2273. if (animationDetails && animationDetails.counter === counter) {
  2274. clearElementAnimationState(getDomNode(element));
  2275. }
  2276. notifyProgress(runner, event, 'close', {});
  2277. });
  2278. // this will update the runner's flow-control events based on
  2279. // the `realRunner` object.
  2280. runner.setHost(realRunner);
  2281. notifyProgress(runner, event, 'start', {});
  2282. });
  2283. return runner;
  2284. function notifyProgress(runner, event, phase, data) {
  2285. runInNextPostDigestOrNow(function() {
  2286. var callbacks = findCallbacks(parent, element, event);
  2287. if (callbacks.length) {
  2288. // do not optimize this call here to RAF because
  2289. // we don't know how heavy the callback code here will
  2290. // be and if this code is buffered then this can
  2291. // lead to a performance regression.
  2292. $$rAF(function() {
  2293. forEach(callbacks, function(callback) {
  2294. callback(element, phase, data);
  2295. });
  2296. });
  2297. }
  2298. });
  2299. runner.progress(event, phase, data);
  2300. }
  2301. function close(reject) { // jshint ignore:line
  2302. clearGeneratedClasses(element, options);
  2303. applyAnimationClasses(element, options);
  2304. applyAnimationStyles(element, options);
  2305. options.domOperation();
  2306. runner.complete(!reject);
  2307. }
  2308. }
  2309. function closeChildAnimations(element) {
  2310. var node = getDomNode(element);
  2311. var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
  2312. forEach(children, function(child) {
  2313. var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
  2314. var animationDetails = activeAnimationsLookup.get(child);
  2315. if (animationDetails) {
  2316. switch (state) {
  2317. case RUNNING_STATE:
  2318. animationDetails.runner.end();
  2319. /* falls through */
  2320. case PRE_DIGEST_STATE:
  2321. activeAnimationsLookup.remove(child);
  2322. break;
  2323. }
  2324. }
  2325. });
  2326. }
  2327. function clearElementAnimationState(element) {
  2328. var node = getDomNode(element);
  2329. node.removeAttribute(NG_ANIMATE_ATTR_NAME);
  2330. activeAnimationsLookup.remove(node);
  2331. }
  2332. function isMatchingElement(nodeOrElmA, nodeOrElmB) {
  2333. return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
  2334. }
  2335. /**
  2336. * This fn returns false if any of the following is true:
  2337. * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
  2338. * b) a parent element has an ongoing structural animation, and animateChildren is false
  2339. * c) the element is not a child of the body
  2340. * d) the element is not a child of the $rootElement
  2341. */
  2342. function areAnimationsAllowed(element, parentElement, event) {
  2343. var bodyElement = jqLite($document[0].body);
  2344. var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
  2345. var rootElementDetected = isMatchingElement(element, $rootElement);
  2346. var parentAnimationDetected = false;
  2347. var animateChildren;
  2348. var elementDisabled = disabledElementsLookup.get(getDomNode(element));
  2349. var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA);
  2350. if (parentHost) {
  2351. parentElement = parentHost;
  2352. }
  2353. parentElement = getDomNode(parentElement);
  2354. while (parentElement) {
  2355. if (!rootElementDetected) {
  2356. // angular doesn't want to attempt to animate elements outside of the application
  2357. // therefore we need to ensure that the rootElement is an ancestor of the current element
  2358. rootElementDetected = isMatchingElement(parentElement, $rootElement);
  2359. }
  2360. if (parentElement.nodeType !== ELEMENT_NODE) {
  2361. // no point in inspecting the #document element
  2362. break;
  2363. }
  2364. var details = activeAnimationsLookup.get(parentElement) || {};
  2365. // either an enter, leave or move animation will commence
  2366. // therefore we can't allow any animations to take place
  2367. // but if a parent animation is class-based then that's ok
  2368. if (!parentAnimationDetected) {
  2369. var parentElementDisabled = disabledElementsLookup.get(parentElement);
  2370. if (parentElementDisabled === true && elementDisabled !== false) {
  2371. // disable animations if the user hasn't explicitly enabled animations on the
  2372. // current element
  2373. elementDisabled = true;
  2374. // element is disabled via parent element, no need to check anything else
  2375. break;
  2376. } else if (parentElementDisabled === false) {
  2377. elementDisabled = false;
  2378. }
  2379. parentAnimationDetected = details.structural;
  2380. }
  2381. if (isUndefined(animateChildren) || animateChildren === true) {
  2382. var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA);
  2383. if (isDefined(value)) {
  2384. animateChildren = value;
  2385. }
  2386. }
  2387. // there is no need to continue traversing at this point
  2388. if (parentAnimationDetected && animateChildren === false) break;
  2389. if (!bodyElementDetected) {
  2390. // we also need to ensure that the element is or will be a part of the body element
  2391. // otherwise it is pointless to even issue an animation to be rendered
  2392. bodyElementDetected = isMatchingElement(parentElement, bodyElement);
  2393. }
  2394. if (bodyElementDetected && rootElementDetected) {
  2395. // If both body and root have been found, any other checks are pointless,
  2396. // as no animation data should live outside the application
  2397. break;
  2398. }
  2399. if (!rootElementDetected) {
  2400. // If no rootElement is detected, check if the parentElement is pinned to another element
  2401. parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA);
  2402. if (parentHost) {
  2403. // The pin target element becomes the next parent element
  2404. parentElement = getDomNode(parentHost);
  2405. continue;
  2406. }
  2407. }
  2408. parentElement = parentElement.parentNode;
  2409. }
  2410. var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
  2411. return allowAnimation && rootElementDetected && bodyElementDetected;
  2412. }
  2413. function markElementAnimationState(element, state, details) {
  2414. details = details || {};
  2415. details.state = state;
  2416. var node = getDomNode(element);
  2417. node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
  2418. var oldValue = activeAnimationsLookup.get(node);
  2419. var newValue = oldValue
  2420. ? extend(oldValue, details)
  2421. : details;
  2422. activeAnimationsLookup.put(node, newValue);
  2423. }
  2424. }];
  2425. }];
  2426. var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
  2427. var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
  2428. var drivers = this.drivers = [];
  2429. var RUNNER_STORAGE_KEY = '$$animationRunner';
  2430. function setRunner(element, runner) {
  2431. element.data(RUNNER_STORAGE_KEY, runner);
  2432. }
  2433. function removeRunner(element) {
  2434. element.removeData(RUNNER_STORAGE_KEY);
  2435. }
  2436. function getRunner(element) {
  2437. return element.data(RUNNER_STORAGE_KEY);
  2438. }
  2439. this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
  2440. function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
  2441. var animationQueue = [];
  2442. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  2443. function sortAnimations(animations) {
  2444. var tree = { children: [] };
  2445. var i, lookup = new $$HashMap();
  2446. // this is done first beforehand so that the hashmap
  2447. // is filled with a list of the elements that will be animated
  2448. for (i = 0; i < animations.length; i++) {
  2449. var animation = animations[i];
  2450. lookup.put(animation.domNode, animations[i] = {
  2451. domNode: animation.domNode,
  2452. fn: animation.fn,
  2453. children: []
  2454. });
  2455. }
  2456. for (i = 0; i < animations.length; i++) {
  2457. processNode(animations[i]);
  2458. }
  2459. return flatten(tree);
  2460. function processNode(entry) {
  2461. if (entry.processed) return entry;
  2462. entry.processed = true;
  2463. var elementNode = entry.domNode;
  2464. var parentNode = elementNode.parentNode;
  2465. lookup.put(elementNode, entry);
  2466. var parentEntry;
  2467. while (parentNode) {
  2468. parentEntry = lookup.get(parentNode);
  2469. if (parentEntry) {
  2470. if (!parentEntry.processed) {
  2471. parentEntry = processNode(parentEntry);
  2472. }
  2473. break;
  2474. }
  2475. parentNode = parentNode.parentNode;
  2476. }
  2477. (parentEntry || tree).children.push(entry);
  2478. return entry;
  2479. }
  2480. function flatten(tree) {
  2481. var result = [];
  2482. var queue = [];
  2483. var i;
  2484. for (i = 0; i < tree.children.length; i++) {
  2485. queue.push(tree.children[i]);
  2486. }
  2487. var remainingLevelEntries = queue.length;
  2488. var nextLevelEntries = 0;
  2489. var row = [];
  2490. for (i = 0; i < queue.length; i++) {
  2491. var entry = queue[i];
  2492. if (remainingLevelEntries <= 0) {
  2493. remainingLevelEntries = nextLevelEntries;
  2494. nextLevelEntries = 0;
  2495. result.push(row);
  2496. row = [];
  2497. }
  2498. row.push(entry.fn);
  2499. entry.children.forEach(function(childEntry) {
  2500. nextLevelEntries++;
  2501. queue.push(childEntry);
  2502. });
  2503. remainingLevelEntries--;
  2504. }
  2505. if (row.length) {
  2506. result.push(row);
  2507. }
  2508. return result;
  2509. }
  2510. }
  2511. // TODO(matsko): document the signature in a better way
  2512. return function(element, event, options) {
  2513. options = prepareAnimationOptions(options);
  2514. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  2515. // there is no animation at the current moment, however
  2516. // these runner methods will get later updated with the
  2517. // methods leading into the driver's end/cancel methods
  2518. // for now they just stop the animation from starting
  2519. var runner = new $$AnimateRunner({
  2520. end: function() { close(); },
  2521. cancel: function() { close(true); }
  2522. });
  2523. if (!drivers.length) {
  2524. close();
  2525. return runner;
  2526. }
  2527. setRunner(element, runner);
  2528. var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
  2529. var tempClasses = options.tempClasses;
  2530. if (tempClasses) {
  2531. classes += ' ' + tempClasses;
  2532. options.tempClasses = null;
  2533. }
  2534. var prepareClassName;
  2535. if (isStructural) {
  2536. prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX;
  2537. $$jqLite.addClass(element, prepareClassName);
  2538. }
  2539. animationQueue.push({
  2540. // this data is used by the postDigest code and passed into
  2541. // the driver step function
  2542. element: element,
  2543. classes: classes,
  2544. event: event,
  2545. structural: isStructural,
  2546. options: options,
  2547. beforeStart: beforeStart,
  2548. close: close
  2549. });
  2550. element.on('$destroy', handleDestroyedElement);
  2551. // we only want there to be one function called within the post digest
  2552. // block. This way we can group animations for all the animations that
  2553. // were apart of the same postDigest flush call.
  2554. if (animationQueue.length > 1) return runner;
  2555. $rootScope.$$postDigest(function() {
  2556. var animations = [];
  2557. forEach(animationQueue, function(entry) {
  2558. // the element was destroyed early on which removed the runner
  2559. // form its storage. This means we can't animate this element
  2560. // at all and it already has been closed due to destruction.
  2561. if (getRunner(entry.element)) {
  2562. animations.push(entry);
  2563. } else {
  2564. entry.close();
  2565. }
  2566. });
  2567. // now any future animations will be in another postDigest
  2568. animationQueue.length = 0;
  2569. var groupedAnimations = groupAnimations(animations);
  2570. var toBeSortedAnimations = [];
  2571. forEach(groupedAnimations, function(animationEntry) {
  2572. toBeSortedAnimations.push({
  2573. domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
  2574. fn: function triggerAnimationStart() {
  2575. // it's important that we apply the `ng-animate` CSS class and the
  2576. // temporary classes before we do any driver invoking since these
  2577. // CSS classes may be required for proper CSS detection.
  2578. animationEntry.beforeStart();
  2579. var startAnimationFn, closeFn = animationEntry.close;
  2580. // in the event that the element was removed before the digest runs or
  2581. // during the RAF sequencing then we should not trigger the animation.
  2582. var targetElement = animationEntry.anchors
  2583. ? (animationEntry.from.element || animationEntry.to.element)
  2584. : animationEntry.element;
  2585. if (getRunner(targetElement)) {
  2586. var operation = invokeFirstDriver(animationEntry);
  2587. if (operation) {
  2588. startAnimationFn = operation.start;
  2589. }
  2590. }
  2591. if (!startAnimationFn) {
  2592. closeFn();
  2593. } else {
  2594. var animationRunner = startAnimationFn();
  2595. animationRunner.done(function(status) {
  2596. closeFn(!status);
  2597. });
  2598. updateAnimationRunners(animationEntry, animationRunner);
  2599. }
  2600. }
  2601. });
  2602. });
  2603. // we need to sort each of the animations in order of parent to child
  2604. // relationships. This ensures that the child classes are applied at the
  2605. // right time.
  2606. $$rAFScheduler(sortAnimations(toBeSortedAnimations));
  2607. });
  2608. return runner;
  2609. // TODO(matsko): change to reference nodes
  2610. function getAnchorNodes(node) {
  2611. var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
  2612. var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
  2613. ? [node]
  2614. : node.querySelectorAll(SELECTOR);
  2615. var anchors = [];
  2616. forEach(items, function(node) {
  2617. var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
  2618. if (attr && attr.length) {
  2619. anchors.push(node);
  2620. }
  2621. });
  2622. return anchors;
  2623. }
  2624. function groupAnimations(animations) {
  2625. var preparedAnimations = [];
  2626. var refLookup = {};
  2627. forEach(animations, function(animation, index) {
  2628. var element = animation.element;
  2629. var node = getDomNode(element);
  2630. var event = animation.event;
  2631. var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
  2632. var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
  2633. if (anchorNodes.length) {
  2634. var direction = enterOrMove ? 'to' : 'from';
  2635. forEach(anchorNodes, function(anchor) {
  2636. var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
  2637. refLookup[key] = refLookup[key] || {};
  2638. refLookup[key][direction] = {
  2639. animationID: index,
  2640. element: jqLite(anchor)
  2641. };
  2642. });
  2643. } else {
  2644. preparedAnimations.push(animation);
  2645. }
  2646. });
  2647. var usedIndicesLookup = {};
  2648. var anchorGroups = {};
  2649. forEach(refLookup, function(operations, key) {
  2650. var from = operations.from;
  2651. var to = operations.to;
  2652. if (!from || !to) {
  2653. // only one of these is set therefore we can't have an
  2654. // anchor animation since all three pieces are required
  2655. var index = from ? from.animationID : to.animationID;
  2656. var indexKey = index.toString();
  2657. if (!usedIndicesLookup[indexKey]) {
  2658. usedIndicesLookup[indexKey] = true;
  2659. preparedAnimations.push(animations[index]);
  2660. }
  2661. return;
  2662. }
  2663. var fromAnimation = animations[from.animationID];
  2664. var toAnimation = animations[to.animationID];
  2665. var lookupKey = from.animationID.toString();
  2666. if (!anchorGroups[lookupKey]) {
  2667. var group = anchorGroups[lookupKey] = {
  2668. structural: true,
  2669. beforeStart: function() {
  2670. fromAnimation.beforeStart();
  2671. toAnimation.beforeStart();
  2672. },
  2673. close: function() {
  2674. fromAnimation.close();
  2675. toAnimation.close();
  2676. },
  2677. classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
  2678. from: fromAnimation,
  2679. to: toAnimation,
  2680. anchors: [] // TODO(matsko): change to reference nodes
  2681. };
  2682. // the anchor animations require that the from and to elements both have at least
  2683. // one shared CSS class which effectively marries the two elements together to use
  2684. // the same animation driver and to properly sequence the anchor animation.
  2685. if (group.classes.length) {
  2686. preparedAnimations.push(group);
  2687. } else {
  2688. preparedAnimations.push(fromAnimation);
  2689. preparedAnimations.push(toAnimation);
  2690. }
  2691. }
  2692. anchorGroups[lookupKey].anchors.push({
  2693. 'out': from.element, 'in': to.element
  2694. });
  2695. });
  2696. return preparedAnimations;
  2697. }
  2698. function cssClassesIntersection(a,b) {
  2699. a = a.split(' ');
  2700. b = b.split(' ');
  2701. var matches = [];
  2702. for (var i = 0; i < a.length; i++) {
  2703. var aa = a[i];
  2704. if (aa.substring(0,3) === 'ng-') continue;
  2705. for (var j = 0; j < b.length; j++) {
  2706. if (aa === b[j]) {
  2707. matches.push(aa);
  2708. break;
  2709. }
  2710. }
  2711. }
  2712. return matches.join(' ');
  2713. }
  2714. function invokeFirstDriver(animationDetails) {
  2715. // we loop in reverse order since the more general drivers (like CSS and JS)
  2716. // may attempt more elements, but custom drivers are more particular
  2717. for (var i = drivers.length - 1; i >= 0; i--) {
  2718. var driverName = drivers[i];
  2719. if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
  2720. var factory = $injector.get(driverName);
  2721. var driver = factory(animationDetails);
  2722. if (driver) {
  2723. return driver;
  2724. }
  2725. }
  2726. }
  2727. function beforeStart() {
  2728. element.addClass(NG_ANIMATE_CLASSNAME);
  2729. if (tempClasses) {
  2730. $$jqLite.addClass(element, tempClasses);
  2731. }
  2732. if (prepareClassName) {
  2733. $$jqLite.removeClass(element, prepareClassName);
  2734. prepareClassName = null;
  2735. }
  2736. }
  2737. function updateAnimationRunners(animation, newRunner) {
  2738. if (animation.from && animation.to) {
  2739. update(animation.from.element);
  2740. update(animation.to.element);
  2741. } else {
  2742. update(animation.element);
  2743. }
  2744. function update(element) {
  2745. getRunner(element).setHost(newRunner);
  2746. }
  2747. }
  2748. function handleDestroyedElement() {
  2749. var runner = getRunner(element);
  2750. if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
  2751. runner.end();
  2752. }
  2753. }
  2754. function close(rejected) { // jshint ignore:line
  2755. element.off('$destroy', handleDestroyedElement);
  2756. removeRunner(element);
  2757. applyAnimationClasses(element, options);
  2758. applyAnimationStyles(element, options);
  2759. options.domOperation();
  2760. if (tempClasses) {
  2761. $$jqLite.removeClass(element, tempClasses);
  2762. }
  2763. element.removeClass(NG_ANIMATE_CLASSNAME);
  2764. runner.complete(!rejected);
  2765. }
  2766. };
  2767. }];
  2768. }];
  2769. /**
  2770. * @ngdoc directive
  2771. * @name ngAnimateSwap
  2772. * @restrict A
  2773. * @scope
  2774. *
  2775. * @description
  2776. *
  2777. * ngAnimateSwap is a animation-oriented directive that allows for the container to
  2778. * be removed and entered in whenever the associated expression changes. A
  2779. * common usecase for this directive is a rotating banner or slider component which
  2780. * contains one image being present at a time. When the active image changes
  2781. * then the old image will perform a `leave` animation and the new element
  2782. * will be inserted via an `enter` animation.
  2783. *
  2784. * @animations
  2785. * | Animation | Occurs |
  2786. * |----------------------------------|--------------------------------------|
  2787. * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
  2788. * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM |
  2789. *
  2790. * @example
  2791. * <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample"
  2792. * deps="angular-animate.js"
  2793. * animations="true" fixBase="true">
  2794. * <file name="index.html">
  2795. * <div class="container" ng-controller="AppCtrl">
  2796. * <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)">
  2797. * {{ number }}
  2798. * </div>
  2799. * </div>
  2800. * </file>
  2801. * <file name="script.js">
  2802. * angular.module('ngAnimateSwapExample', ['ngAnimate'])
  2803. * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
  2804. * $scope.number = 0;
  2805. * $interval(function() {
  2806. * $scope.number++;
  2807. * }, 1000);
  2808. *
  2809. * var colors = ['red','blue','green','yellow','orange'];
  2810. * $scope.colorClass = function(number) {
  2811. * return colors[number % colors.length];
  2812. * };
  2813. * }]);
  2814. * </file>
  2815. * <file name="animations.css">
  2816. * .container {
  2817. * height:250px;
  2818. * width:250px;
  2819. * position:relative;
  2820. * overflow:hidden;
  2821. * border:2px solid black;
  2822. * }
  2823. * .container .cell {
  2824. * font-size:150px;
  2825. * text-align:center;
  2826. * line-height:250px;
  2827. * position:absolute;
  2828. * top:0;
  2829. * left:0;
  2830. * right:0;
  2831. * border-bottom:2px solid black;
  2832. * }
  2833. * .swap-animation.ng-enter, .swap-animation.ng-leave {
  2834. * transition:0.5s linear all;
  2835. * }
  2836. * .swap-animation.ng-enter {
  2837. * top:-250px;
  2838. * }
  2839. * .swap-animation.ng-enter-active {
  2840. * top:0px;
  2841. * }
  2842. * .swap-animation.ng-leave {
  2843. * top:0px;
  2844. * }
  2845. * .swap-animation.ng-leave-active {
  2846. * top:250px;
  2847. * }
  2848. * .red { background:red; }
  2849. * .green { background:green; }
  2850. * .blue { background:blue; }
  2851. * .yellow { background:yellow; }
  2852. * .orange { background:orange; }
  2853. * </file>
  2854. * </example>
  2855. */
  2856. var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
  2857. return {
  2858. restrict: 'A',
  2859. transclude: 'element',
  2860. terminal: true,
  2861. priority: 600, // we use 600 here to ensure that the directive is caught before others
  2862. link: function(scope, $element, attrs, ctrl, $transclude) {
  2863. var previousElement, previousScope;
  2864. scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
  2865. if (previousElement) {
  2866. $animate.leave(previousElement);
  2867. }
  2868. if (previousScope) {
  2869. previousScope.$destroy();
  2870. previousScope = null;
  2871. }
  2872. if (value || value === 0) {
  2873. previousScope = scope.$new();
  2874. $transclude(previousScope, function(element) {
  2875. previousElement = element;
  2876. $animate.enter(element, null, $element);
  2877. });
  2878. }
  2879. });
  2880. }
  2881. };
  2882. }];
  2883. /* global angularAnimateModule: true,
  2884. ngAnimateSwapDirective,
  2885. $$AnimateAsyncRunFactory,
  2886. $$rAFSchedulerFactory,
  2887. $$AnimateChildrenDirective,
  2888. $$AnimateQueueProvider,
  2889. $$AnimationProvider,
  2890. $AnimateCssProvider,
  2891. $$AnimateCssDriverProvider,
  2892. $$AnimateJsProvider,
  2893. $$AnimateJsDriverProvider,
  2894. */
  2895. /**
  2896. * @ngdoc module
  2897. * @name ngAnimate
  2898. * @description
  2899. *
  2900. * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
  2901. * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
  2902. *
  2903. * <div doc-module-components="ngAnimate"></div>
  2904. *
  2905. * # Usage
  2906. * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
  2907. * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
  2908. * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
  2909. * the HTML element that the animation will be triggered on.
  2910. *
  2911. * ## Directive Support
  2912. * The following directives are "animation aware":
  2913. *
  2914. * | Directive | Supported Animations |
  2915. * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
  2916. * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
  2917. * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
  2918. * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
  2919. * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
  2920. * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
  2921. * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
  2922. * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
  2923. * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
  2924. * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
  2925. * | {@link module:ngMessages#animations ngMessage} | enter and leave |
  2926. *
  2927. * (More information can be found by visiting each the documentation associated with each directive.)
  2928. *
  2929. * ## CSS-based Animations
  2930. *
  2931. * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
  2932. * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
  2933. *
  2934. * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
  2935. *
  2936. * ```html
  2937. * <div ng-if="bool" class="fade">
  2938. * Fade me in out
  2939. * </div>
  2940. * <button ng-click="bool=true">Fade In!</button>
  2941. * <button ng-click="bool=false">Fade Out!</button>
  2942. * ```
  2943. *
  2944. * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
  2945. *
  2946. * ```css
  2947. * /&#42; The starting CSS styles for the enter animation &#42;/
  2948. * .fade.ng-enter {
  2949. * transition:0.5s linear all;
  2950. * opacity:0;
  2951. * }
  2952. *
  2953. * /&#42; The finishing CSS styles for the enter animation &#42;/
  2954. * .fade.ng-enter.ng-enter-active {
  2955. * opacity:1;
  2956. * }
  2957. * ```
  2958. *
  2959. * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
  2960. * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
  2961. * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
  2962. *
  2963. * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
  2964. *
  2965. * ```css
  2966. * /&#42; now the element will fade out before it is removed from the DOM &#42;/
  2967. * .fade.ng-leave {
  2968. * transition:0.5s linear all;
  2969. * opacity:1;
  2970. * }
  2971. * .fade.ng-leave.ng-leave-active {
  2972. * opacity:0;
  2973. * }
  2974. * ```
  2975. *
  2976. * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
  2977. *
  2978. * ```css
  2979. * /&#42; there is no need to define anything inside of the destination
  2980. * CSS class since the keyframe will take charge of the animation &#42;/
  2981. * .fade.ng-leave {
  2982. * animation: my_fade_animation 0.5s linear;
  2983. * -webkit-animation: my_fade_animation 0.5s linear;
  2984. * }
  2985. *
  2986. * @keyframes my_fade_animation {
  2987. * from { opacity:1; }
  2988. * to { opacity:0; }
  2989. * }
  2990. *
  2991. * @-webkit-keyframes my_fade_animation {
  2992. * from { opacity:1; }
  2993. * to { opacity:0; }
  2994. * }
  2995. * ```
  2996. *
  2997. * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
  2998. *
  2999. * ### CSS Class-based Animations
  3000. *
  3001. * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
  3002. * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
  3003. * and removed.
  3004. *
  3005. * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
  3006. *
  3007. * ```html
  3008. * <div ng-show="bool" class="fade">
  3009. * Show and hide me
  3010. * </div>
  3011. * <button ng-click="bool=true">Toggle</button>
  3012. *
  3013. * <style>
  3014. * .fade.ng-hide {
  3015. * transition:0.5s linear all;
  3016. * opacity:0;
  3017. * }
  3018. * </style>
  3019. * ```
  3020. *
  3021. * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
  3022. * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
  3023. *
  3024. * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
  3025. * with CSS styles.
  3026. *
  3027. * ```html
  3028. * <div ng-class="{on:onOff}" class="highlight">
  3029. * Highlight this box
  3030. * </div>
  3031. * <button ng-click="onOff=!onOff">Toggle</button>
  3032. *
  3033. * <style>
  3034. * .highlight {
  3035. * transition:0.5s linear all;
  3036. * }
  3037. * .highlight.on-add {
  3038. * background:white;
  3039. * }
  3040. * .highlight.on {
  3041. * background:yellow;
  3042. * }
  3043. * .highlight.on-remove {
  3044. * background:black;
  3045. * }
  3046. * </style>
  3047. * ```
  3048. *
  3049. * We can also make use of CSS keyframes by placing them within the CSS classes.
  3050. *
  3051. *
  3052. * ### CSS Staggering Animations
  3053. * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
  3054. * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
  3055. * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
  3056. * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
  3057. * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
  3058. *
  3059. * ```css
  3060. * .my-animation.ng-enter {
  3061. * /&#42; standard transition code &#42;/
  3062. * transition: 1s linear all;
  3063. * opacity:0;
  3064. * }
  3065. * .my-animation.ng-enter-stagger {
  3066. * /&#42; this will have a 100ms delay between each successive leave animation &#42;/
  3067. * transition-delay: 0.1s;
  3068. *
  3069. * /&#42; As of 1.4.4, this must always be set: it signals ngAnimate
  3070. * to not accidentally inherit a delay property from another CSS class &#42;/
  3071. * transition-duration: 0s;
  3072. * }
  3073. * .my-animation.ng-enter.ng-enter-active {
  3074. * /&#42; standard transition styles &#42;/
  3075. * opacity:1;
  3076. * }
  3077. * ```
  3078. *
  3079. * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
  3080. * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
  3081. * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
  3082. * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
  3083. *
  3084. * The following code will issue the **ng-leave-stagger** event on the element provided:
  3085. *
  3086. * ```js
  3087. * var kids = parent.children();
  3088. *
  3089. * $animate.leave(kids[0]); //stagger index=0
  3090. * $animate.leave(kids[1]); //stagger index=1
  3091. * $animate.leave(kids[2]); //stagger index=2
  3092. * $animate.leave(kids[3]); //stagger index=3
  3093. * $animate.leave(kids[4]); //stagger index=4
  3094. *
  3095. * window.requestAnimationFrame(function() {
  3096. * //stagger has reset itself
  3097. * $animate.leave(kids[5]); //stagger index=0
  3098. * $animate.leave(kids[6]); //stagger index=1
  3099. *
  3100. * $scope.$digest();
  3101. * });
  3102. * ```
  3103. *
  3104. * Stagger animations are currently only supported within CSS-defined animations.
  3105. *
  3106. * ### The `ng-animate` CSS class
  3107. *
  3108. * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
  3109. * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
  3110. *
  3111. * Therefore, animations can be applied to an element using this temporary class directly via CSS.
  3112. *
  3113. * ```css
  3114. * .zipper.ng-animate {
  3115. * transition:0.5s linear all;
  3116. * }
  3117. * .zipper.ng-enter {
  3118. * opacity:0;
  3119. * }
  3120. * .zipper.ng-enter.ng-enter-active {
  3121. * opacity:1;
  3122. * }
  3123. * .zipper.ng-leave {
  3124. * opacity:1;
  3125. * }
  3126. * .zipper.ng-leave.ng-leave-active {
  3127. * opacity:0;
  3128. * }
  3129. * ```
  3130. *
  3131. * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
  3132. * the CSS class once an animation has completed.)
  3133. *
  3134. *
  3135. * ### The `ng-[event]-prepare` class
  3136. *
  3137. * This is a special class that can be used to prevent unwanted flickering / flash of content before
  3138. * the actual animation starts. The class is added as soon as an animation is initialized, but removed
  3139. * before the actual animation starts (after waiting for a $digest).
  3140. * It is also only added for *structural* animations (`enter`, `move`, and `leave`).
  3141. *
  3142. * In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
  3143. * into elements that have class-based animations such as `ngClass`.
  3144. *
  3145. * ```html
  3146. * <div ng-class="{red: myProp}">
  3147. * <div ng-class="{blue: myProp}">
  3148. * <div class="message" ng-if="myProp"></div>
  3149. * </div>
  3150. * </div>
  3151. * ```
  3152. *
  3153. * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
  3154. * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
  3155. *
  3156. * ```css
  3157. * .message.ng-enter-prepare {
  3158. * opacity: 0;
  3159. * }
  3160. *
  3161. * ```
  3162. *
  3163. * ## JavaScript-based Animations
  3164. *
  3165. * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
  3166. * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
  3167. * `module.animation()` module function we can register the animation.
  3168. *
  3169. * Let's see an example of a enter/leave animation using `ngRepeat`:
  3170. *
  3171. * ```html
  3172. * <div ng-repeat="item in items" class="slide">
  3173. * {{ item }}
  3174. * </div>
  3175. * ```
  3176. *
  3177. * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
  3178. *
  3179. * ```js
  3180. * myModule.animation('.slide', [function() {
  3181. * return {
  3182. * // make note that other events (like addClass/removeClass)
  3183. * // have different function input parameters
  3184. * enter: function(element, doneFn) {
  3185. * jQuery(element).fadeIn(1000, doneFn);
  3186. *
  3187. * // remember to call doneFn so that angular
  3188. * // knows that the animation has concluded
  3189. * },
  3190. *
  3191. * move: function(element, doneFn) {
  3192. * jQuery(element).fadeIn(1000, doneFn);
  3193. * },
  3194. *
  3195. * leave: function(element, doneFn) {
  3196. * jQuery(element).fadeOut(1000, doneFn);
  3197. * }
  3198. * }
  3199. * }]);
  3200. * ```
  3201. *
  3202. * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
  3203. * greensock.js and velocity.js.
  3204. *
  3205. * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
  3206. * our animations inside of the same registered animation, however, the function input arguments are a bit different:
  3207. *
  3208. * ```html
  3209. * <div ng-class="color" class="colorful">
  3210. * this box is moody
  3211. * </div>
  3212. * <button ng-click="color='red'">Change to red</button>
  3213. * <button ng-click="color='blue'">Change to blue</button>
  3214. * <button ng-click="color='green'">Change to green</button>
  3215. * ```
  3216. *
  3217. * ```js
  3218. * myModule.animation('.colorful', [function() {
  3219. * return {
  3220. * addClass: function(element, className, doneFn) {
  3221. * // do some cool animation and call the doneFn
  3222. * },
  3223. * removeClass: function(element, className, doneFn) {
  3224. * // do some cool animation and call the doneFn
  3225. * },
  3226. * setClass: function(element, addedClass, removedClass, doneFn) {
  3227. * // do some cool animation and call the doneFn
  3228. * }
  3229. * }
  3230. * }]);
  3231. * ```
  3232. *
  3233. * ## CSS + JS Animations Together
  3234. *
  3235. * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
  3236. * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
  3237. * charge of the animation**:
  3238. *
  3239. * ```html
  3240. * <div ng-if="bool" class="slide">
  3241. * Slide in and out
  3242. * </div>
  3243. * ```
  3244. *
  3245. * ```js
  3246. * myModule.animation('.slide', [function() {
  3247. * return {
  3248. * enter: function(element, doneFn) {
  3249. * jQuery(element).slideIn(1000, doneFn);
  3250. * }
  3251. * }
  3252. * }]);
  3253. * ```
  3254. *
  3255. * ```css
  3256. * .slide.ng-enter {
  3257. * transition:0.5s linear all;
  3258. * transform:translateY(-100px);
  3259. * }
  3260. * .slide.ng-enter.ng-enter-active {
  3261. * transform:translateY(0);
  3262. * }
  3263. * ```
  3264. *
  3265. * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
  3266. * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
  3267. * our own JS-based animation code:
  3268. *
  3269. * ```js
  3270. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  3271. * return {
  3272. * enter: function(element) {
  3273. * // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
  3274. * return $animateCss(element, {
  3275. * event: 'enter',
  3276. * structural: true
  3277. * });
  3278. * }
  3279. * }
  3280. * }]);
  3281. * ```
  3282. *
  3283. * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
  3284. *
  3285. * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
  3286. * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
  3287. * data into `$animateCss` directly:
  3288. *
  3289. * ```js
  3290. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  3291. * return {
  3292. * enter: function(element) {
  3293. * return $animateCss(element, {
  3294. * event: 'enter',
  3295. * structural: true,
  3296. * addClass: 'maroon-setting',
  3297. * from: { height:0 },
  3298. * to: { height: 200 }
  3299. * });
  3300. * }
  3301. * }
  3302. * }]);
  3303. * ```
  3304. *
  3305. * Now we can fill in the rest via our transition CSS code:
  3306. *
  3307. * ```css
  3308. * /&#42; the transition tells ngAnimate to make the animation happen &#42;/
  3309. * .slide.ng-enter { transition:0.5s linear all; }
  3310. *
  3311. * /&#42; this extra CSS class will be absorbed into the transition
  3312. * since the $animateCss code is adding the class &#42;/
  3313. * .maroon-setting { background:red; }
  3314. * ```
  3315. *
  3316. * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
  3317. *
  3318. * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
  3319. *
  3320. * ## Animation Anchoring (via `ng-animate-ref`)
  3321. *
  3322. * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
  3323. * structural areas of an application (like views) by pairing up elements using an attribute
  3324. * called `ng-animate-ref`.
  3325. *
  3326. * Let's say for example we have two views that are managed by `ng-view` and we want to show
  3327. * that there is a relationship between two components situated in within these views. By using the
  3328. * `ng-animate-ref` attribute we can identify that the two components are paired together and we
  3329. * can then attach an animation, which is triggered when the view changes.
  3330. *
  3331. * Say for example we have the following template code:
  3332. *
  3333. * ```html
  3334. * <!-- index.html -->
  3335. * <div ng-view class="view-animation">
  3336. * </div>
  3337. *
  3338. * <!-- home.html -->
  3339. * <a href="#/banner-page">
  3340. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  3341. * </a>
  3342. *
  3343. * <!-- banner-page.html -->
  3344. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  3345. * ```
  3346. *
  3347. * Now, when the view changes (once the link is clicked), ngAnimate will examine the
  3348. * HTML contents to see if there is a match reference between any components in the view
  3349. * that is leaving and the view that is entering. It will scan both the view which is being
  3350. * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
  3351. * contain a matching ref value.
  3352. *
  3353. * The two images match since they share the same ref value. ngAnimate will now create a
  3354. * transport element (which is a clone of the first image element) and it will then attempt
  3355. * to animate to the position of the second image element in the next view. For the animation to
  3356. * work a special CSS class called `ng-anchor` will be added to the transported element.
  3357. *
  3358. * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
  3359. * ngAnimate will handle the entire transition for us as well as the addition and removal of
  3360. * any changes of CSS classes between the elements:
  3361. *
  3362. * ```css
  3363. * .banner.ng-anchor {
  3364. * /&#42; this animation will last for 1 second since there are
  3365. * two phases to the animation (an `in` and an `out` phase) &#42;/
  3366. * transition:0.5s linear all;
  3367. * }
  3368. * ```
  3369. *
  3370. * We also **must** include animations for the views that are being entered and removed
  3371. * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
  3372. *
  3373. * ```css
  3374. * .view-animation.ng-enter, .view-animation.ng-leave {
  3375. * transition:0.5s linear all;
  3376. * position:fixed;
  3377. * left:0;
  3378. * top:0;
  3379. * width:100%;
  3380. * }
  3381. * .view-animation.ng-enter {
  3382. * transform:translateX(100%);
  3383. * }
  3384. * .view-animation.ng-leave,
  3385. * .view-animation.ng-enter.ng-enter-active {
  3386. * transform:translateX(0%);
  3387. * }
  3388. * .view-animation.ng-leave.ng-leave-active {
  3389. * transform:translateX(-100%);
  3390. * }
  3391. * ```
  3392. *
  3393. * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
  3394. * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
  3395. * from its origin. Once that animation is over then the `in` stage occurs which animates the
  3396. * element to its destination. The reason why there are two animations is to give enough time
  3397. * for the enter animation on the new element to be ready.
  3398. *
  3399. * The example above sets up a transition for both the in and out phases, but we can also target the out or
  3400. * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
  3401. *
  3402. * ```css
  3403. * .banner.ng-anchor-out {
  3404. * transition: 0.5s linear all;
  3405. *
  3406. * /&#42; the scale will be applied during the out animation,
  3407. * but will be animated away when the in animation runs &#42;/
  3408. * transform: scale(1.2);
  3409. * }
  3410. *
  3411. * .banner.ng-anchor-in {
  3412. * transition: 1s linear all;
  3413. * }
  3414. * ```
  3415. *
  3416. *
  3417. *
  3418. *
  3419. * ### Anchoring Demo
  3420. *
  3421. <example module="anchoringExample"
  3422. name="anchoringExample"
  3423. id="anchoringExample"
  3424. deps="angular-animate.js;angular-route.js"
  3425. animations="true">
  3426. <file name="index.html">
  3427. <a href="#/">Home</a>
  3428. <hr />
  3429. <div class="view-container">
  3430. <div ng-view class="view"></div>
  3431. </div>
  3432. </file>
  3433. <file name="script.js">
  3434. angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
  3435. .config(['$routeProvider', function($routeProvider) {
  3436. $routeProvider.when('/', {
  3437. templateUrl: 'home.html',
  3438. controller: 'HomeController as home'
  3439. });
  3440. $routeProvider.when('/profile/:id', {
  3441. templateUrl: 'profile.html',
  3442. controller: 'ProfileController as profile'
  3443. });
  3444. }])
  3445. .run(['$rootScope', function($rootScope) {
  3446. $rootScope.records = [
  3447. { id:1, title: "Miss Beulah Roob" },
  3448. { id:2, title: "Trent Morissette" },
  3449. { id:3, title: "Miss Ava Pouros" },
  3450. { id:4, title: "Rod Pouros" },
  3451. { id:5, title: "Abdul Rice" },
  3452. { id:6, title: "Laurie Rutherford Sr." },
  3453. { id:7, title: "Nakia McLaughlin" },
  3454. { id:8, title: "Jordon Blanda DVM" },
  3455. { id:9, title: "Rhoda Hand" },
  3456. { id:10, title: "Alexandrea Sauer" }
  3457. ];
  3458. }])
  3459. .controller('HomeController', [function() {
  3460. //empty
  3461. }])
  3462. .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
  3463. var index = parseInt($routeParams.id, 10);
  3464. var record = $rootScope.records[index - 1];
  3465. this.title = record.title;
  3466. this.id = record.id;
  3467. }]);
  3468. </file>
  3469. <file name="home.html">
  3470. <h2>Welcome to the home page</h1>
  3471. <p>Please click on an element</p>
  3472. <a class="record"
  3473. ng-href="#/profile/{{ record.id }}"
  3474. ng-animate-ref="{{ record.id }}"
  3475. ng-repeat="record in records">
  3476. {{ record.title }}
  3477. </a>
  3478. </file>
  3479. <file name="profile.html">
  3480. <div class="profile record" ng-animate-ref="{{ profile.id }}">
  3481. {{ profile.title }}
  3482. </div>
  3483. </file>
  3484. <file name="animations.css">
  3485. .record {
  3486. display:block;
  3487. font-size:20px;
  3488. }
  3489. .profile {
  3490. background:black;
  3491. color:white;
  3492. font-size:100px;
  3493. }
  3494. .view-container {
  3495. position:relative;
  3496. }
  3497. .view-container > .view.ng-animate {
  3498. position:absolute;
  3499. top:0;
  3500. left:0;
  3501. width:100%;
  3502. min-height:500px;
  3503. }
  3504. .view.ng-enter, .view.ng-leave,
  3505. .record.ng-anchor {
  3506. transition:0.5s linear all;
  3507. }
  3508. .view.ng-enter {
  3509. transform:translateX(100%);
  3510. }
  3511. .view.ng-enter.ng-enter-active, .view.ng-leave {
  3512. transform:translateX(0%);
  3513. }
  3514. .view.ng-leave.ng-leave-active {
  3515. transform:translateX(-100%);
  3516. }
  3517. .record.ng-anchor-out {
  3518. background:red;
  3519. }
  3520. </file>
  3521. </example>
  3522. *
  3523. * ### How is the element transported?
  3524. *
  3525. * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
  3526. * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
  3527. * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
  3528. * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
  3529. * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
  3530. * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
  3531. * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
  3532. * will become visible since the shim class will be removed.
  3533. *
  3534. * ### How is the morphing handled?
  3535. *
  3536. * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
  3537. * what CSS classes differ between the starting element and the destination element. These different CSS classes
  3538. * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
  3539. * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
  3540. * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
  3541. * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
  3542. * the cloned element is placed inside of root element which is likely close to the body element).
  3543. *
  3544. * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
  3545. *
  3546. *
  3547. * ## Using $animate in your directive code
  3548. *
  3549. * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
  3550. * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
  3551. * imagine we have a greeting box that shows and hides itself when the data changes
  3552. *
  3553. * ```html
  3554. * <greeting-box active="onOrOff">Hi there</greeting-box>
  3555. * ```
  3556. *
  3557. * ```js
  3558. * ngModule.directive('greetingBox', ['$animate', function($animate) {
  3559. * return function(scope, element, attrs) {
  3560. * attrs.$observe('active', function(value) {
  3561. * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
  3562. * });
  3563. * });
  3564. * }]);
  3565. * ```
  3566. *
  3567. * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
  3568. * in our HTML code then we can trigger a CSS or JS animation to happen.
  3569. *
  3570. * ```css
  3571. * /&#42; normally we would create a CSS class to reference on the element &#42;/
  3572. * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
  3573. * ```
  3574. *
  3575. * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
  3576. * possible be sure to visit the {@link ng.$animate $animate service API page}.
  3577. *
  3578. *
  3579. * ## Callbacks and Promises
  3580. *
  3581. * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
  3582. * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
  3583. * ended by chaining onto the returned promise that animation method returns.
  3584. *
  3585. * ```js
  3586. * // somewhere within the depths of the directive
  3587. * $animate.enter(element, parent).then(function() {
  3588. * //the animation has completed
  3589. * });
  3590. * ```
  3591. *
  3592. * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
  3593. * anymore.)
  3594. *
  3595. * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
  3596. * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
  3597. * routing controller to hook into that:
  3598. *
  3599. * ```js
  3600. * ngModule.controller('HomePageController', ['$animate', function($animate) {
  3601. * $animate.on('enter', ngViewElement, function(element) {
  3602. * // the animation for this route has completed
  3603. * }]);
  3604. * }])
  3605. * ```
  3606. *
  3607. * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
  3608. */
  3609. /**
  3610. * @ngdoc service
  3611. * @name $animate
  3612. * @kind object
  3613. *
  3614. * @description
  3615. * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
  3616. *
  3617. * Click here {@link ng.$animate to learn more about animations with `$animate`}.
  3618. */
  3619. angular.module('ngAnimate', [])
  3620. .directive('ngAnimateSwap', ngAnimateSwapDirective)
  3621. .directive('ngAnimateChildren', $$AnimateChildrenDirective)
  3622. .factory('$$rAFScheduler', $$rAFSchedulerFactory)
  3623. .provider('$$animateQueue', $$AnimateQueueProvider)
  3624. .provider('$$animation', $$AnimationProvider)
  3625. .provider('$animateCss', $AnimateCssProvider)
  3626. .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
  3627. .provider('$$animateJs', $$AnimateJsProvider)
  3628. .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
  3629. })(window, window.angular);