angular-animate.js 138KB

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