browser.mjs 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  1. /**
  2. * @license Angular v19.2.13
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import * as i0 from '@angular/core';
  7. import { Injectable } from '@angular/core';
  8. import { validateStyleProperty, containsElement, getParentElement, invokeQuery, dashCaseToCamelCase, invalidCssUnitValue, invalidExpression, invalidTransitionAlias, visitDslNode, invalidTrigger, invalidDefinition, extractStyleParams, invalidState, invalidStyleValue, SUBSTITUTION_EXPR_START, invalidParallelAnimation, validateStyleParams, invalidKeyframes, invalidOffset, keyframeOffsetsOutOfOrder, keyframesMissingOffsets, getOrSetDefaultValue, invalidStagger, resolveTiming, normalizeAnimationEntry, NG_TRIGGER_SELECTOR, NG_ANIMATING_SELECTOR, resolveTimingValue, interpolateParams, invalidQuery, registerFailed, normalizeKeyframes, LEAVE_CLASSNAME, ENTER_CLASSNAME, missingOrDestroyedAnimation, createAnimationFailed, optimizeGroupPlayer, missingPlayer, listenOnPlayer, makeAnimationEvent, triggerTransitionsFailed, eraseStyles, setStyles, transitionFailed, missingTrigger, missingEvent, unsupportedTriggerEvent, unregisteredTrigger, NG_TRIGGER_CLASSNAME, NG_ANIMATING_CLASSNAME, triggerBuildFailed, parseTimelineCommand, computeStyle, camelCaseToDashCase, validateWebAnimatableStyleProperty, allowPreviousPlayerStylesMerge, normalizeKeyframes$1, balancePreviousStylesIntoKeyframes, validationFailed, normalizeStyles, buildingFailed } from './util-D9FfmVnv.mjs';
  9. import { NoopAnimationPlayer, AnimationMetadataType, style, AUTO_STYLE, ɵPRE_STYLE as _PRE_STYLE, AnimationGroupPlayer } from './private_export-faY_wCkZ.mjs';
  10. /**
  11. * @publicApi
  12. *
  13. * `AnimationDriver` implentation for Noop animations
  14. */
  15. class NoopAnimationDriver {
  16. /**
  17. * @returns Whether `prop` is a valid CSS property
  18. */
  19. validateStyleProperty(prop) {
  20. return validateStyleProperty(prop);
  21. }
  22. /**
  23. *
  24. * @returns Whether elm1 contains elm2.
  25. */
  26. containsElement(elm1, elm2) {
  27. return containsElement(elm1, elm2);
  28. }
  29. /**
  30. * @returns Rhe parent of the given element or `null` if the element is the `document`
  31. */
  32. getParentElement(element) {
  33. return getParentElement(element);
  34. }
  35. /**
  36. * @returns The result of the query selector on the element. The array will contain up to 1 item
  37. * if `multi` is `false`.
  38. */
  39. query(element, selector, multi) {
  40. return invokeQuery(element, selector, multi);
  41. }
  42. /**
  43. * @returns The `defaultValue` or empty string
  44. */
  45. computeStyle(element, prop, defaultValue) {
  46. return defaultValue || '';
  47. }
  48. /**
  49. * @returns An `NoopAnimationPlayer`
  50. */
  51. animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
  52. return new NoopAnimationPlayer(duration, delay);
  53. }
  54. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NoopAnimationDriver, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  55. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NoopAnimationDriver });
  56. }
  57. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NoopAnimationDriver, decorators: [{
  58. type: Injectable
  59. }] });
  60. /**
  61. * @publicApi
  62. */
  63. class AnimationDriver {
  64. /**
  65. * @deprecated Use the NoopAnimationDriver class.
  66. */
  67. static NOOP = new NoopAnimationDriver();
  68. }
  69. class AnimationStyleNormalizer {
  70. }
  71. class NoopAnimationStyleNormalizer {
  72. normalizePropertyName(propertyName, errors) {
  73. return propertyName;
  74. }
  75. normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
  76. return value;
  77. }
  78. }
  79. const DIMENSIONAL_PROP_SET = new Set([
  80. 'width',
  81. 'height',
  82. 'minWidth',
  83. 'minHeight',
  84. 'maxWidth',
  85. 'maxHeight',
  86. 'left',
  87. 'top',
  88. 'bottom',
  89. 'right',
  90. 'fontSize',
  91. 'outlineWidth',
  92. 'outlineOffset',
  93. 'paddingTop',
  94. 'paddingLeft',
  95. 'paddingBottom',
  96. 'paddingRight',
  97. 'marginTop',
  98. 'marginLeft',
  99. 'marginBottom',
  100. 'marginRight',
  101. 'borderRadius',
  102. 'borderWidth',
  103. 'borderTopWidth',
  104. 'borderLeftWidth',
  105. 'borderRightWidth',
  106. 'borderBottomWidth',
  107. 'textIndent',
  108. 'perspective',
  109. ]);
  110. class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {
  111. normalizePropertyName(propertyName, errors) {
  112. return dashCaseToCamelCase(propertyName);
  113. }
  114. normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
  115. let unit = '';
  116. const strVal = value.toString().trim();
  117. if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {
  118. if (typeof value === 'number') {
  119. unit = 'px';
  120. }
  121. else {
  122. const valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/);
  123. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  124. errors.push(invalidCssUnitValue(userProvidedProperty, value));
  125. }
  126. }
  127. }
  128. return strVal + unit;
  129. }
  130. }
  131. function createListOfWarnings(warnings) {
  132. const LINE_START = '\n - ';
  133. return `${LINE_START}${warnings
  134. .filter(Boolean)
  135. .map((warning) => warning)
  136. .join(LINE_START)}`;
  137. }
  138. function warnValidation(warnings) {
  139. console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
  140. }
  141. function warnTriggerBuild(name, warnings) {
  142. console.warn(`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(warnings)}`);
  143. }
  144. function warnRegister(warnings) {
  145. console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
  146. }
  147. function pushUnrecognizedPropertiesWarning(warnings, props) {
  148. if (props.length) {
  149. warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);
  150. }
  151. }
  152. const ANY_STATE = '*';
  153. function parseTransitionExpr(transitionValue, errors) {
  154. const expressions = [];
  155. if (typeof transitionValue == 'string') {
  156. transitionValue
  157. .split(/\s*,\s*/)
  158. .forEach((str) => parseInnerTransitionStr(str, expressions, errors));
  159. }
  160. else {
  161. expressions.push(transitionValue);
  162. }
  163. return expressions;
  164. }
  165. function parseInnerTransitionStr(eventStr, expressions, errors) {
  166. if (eventStr[0] == ':') {
  167. const result = parseAnimationAlias(eventStr, errors);
  168. if (typeof result == 'function') {
  169. expressions.push(result);
  170. return;
  171. }
  172. eventStr = result;
  173. }
  174. const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
  175. if (match == null || match.length < 4) {
  176. errors.push(invalidExpression(eventStr));
  177. return expressions;
  178. }
  179. const fromState = match[1];
  180. const separator = match[2];
  181. const toState = match[3];
  182. expressions.push(makeLambdaFromStates(fromState, toState));
  183. const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
  184. if (separator[0] == '<' && !isFullAnyStateExpr) {
  185. expressions.push(makeLambdaFromStates(toState, fromState));
  186. }
  187. return;
  188. }
  189. function parseAnimationAlias(alias, errors) {
  190. switch (alias) {
  191. case ':enter':
  192. return 'void => *';
  193. case ':leave':
  194. return '* => void';
  195. case ':increment':
  196. return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);
  197. case ':decrement':
  198. return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);
  199. default:
  200. errors.push(invalidTransitionAlias(alias));
  201. return '* => *';
  202. }
  203. }
  204. // DO NOT REFACTOR ... keep the follow set instantiations
  205. // with the values intact (closure compiler for some reason
  206. // removes follow-up lines that add the values outside of
  207. // the constructor...
  208. const TRUE_BOOLEAN_VALUES = new Set(['true', '1']);
  209. const FALSE_BOOLEAN_VALUES = new Set(['false', '0']);
  210. function makeLambdaFromStates(lhs, rhs) {
  211. const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
  212. const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
  213. return (fromState, toState) => {
  214. let lhsMatch = lhs == ANY_STATE || lhs == fromState;
  215. let rhsMatch = rhs == ANY_STATE || rhs == toState;
  216. if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
  217. lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
  218. }
  219. if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
  220. rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
  221. }
  222. return lhsMatch && rhsMatch;
  223. };
  224. }
  225. const SELF_TOKEN = ':self';
  226. const SELF_TOKEN_REGEX = /* @__PURE__ */ new RegExp(`s*${SELF_TOKEN}s*,?`, 'g');
  227. /*
  228. * [Validation]
  229. * The visitor code below will traverse the animation AST generated by the animation verb functions
  230. * (the output is a tree of objects) and attempt to perform a series of validations on the data. The
  231. * following corner-cases will be validated:
  232. *
  233. * 1. Overlap of animations
  234. * Given that a CSS property cannot be animated in more than one place at the same time, it's
  235. * important that this behavior is detected and validated. The way in which this occurs is that
  236. * each time a style property is examined, a string-map containing the property will be updated with
  237. * the start and end times for when the property is used within an animation step.
  238. *
  239. * If there are two or more parallel animations that are currently running (these are invoked by the
  240. * group()) on the same element then the validator will throw an error. Since the start/end timing
  241. * values are collected for each property then if the current animation step is animating the same
  242. * property and its timing values fall anywhere into the window of time that the property is
  243. * currently being animated within then this is what causes an error.
  244. *
  245. * 2. Timing values
  246. * The validator will validate to see if a timing value of `duration delay easing` or
  247. * `durationNumber` is valid or not.
  248. *
  249. * (note that upon validation the code below will replace the timing data with an object containing
  250. * {duration,delay,easing}.
  251. *
  252. * 3. Offset Validation
  253. * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().
  254. * Offsets within keyframes() are considered valid when:
  255. *
  256. * - No offsets are used at all
  257. * - Each style() entry contains an offset value
  258. * - Each offset is between 0 and 1
  259. * - Each offset is greater to or equal than the previous one
  260. *
  261. * Otherwise an error will be thrown.
  262. */
  263. function buildAnimationAst(driver, metadata, errors, warnings) {
  264. return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);
  265. }
  266. const ROOT_SELECTOR = '';
  267. class AnimationAstBuilderVisitor {
  268. _driver;
  269. constructor(_driver) {
  270. this._driver = _driver;
  271. }
  272. build(metadata, errors, warnings) {
  273. const context = new AnimationAstBuilderContext(errors);
  274. this._resetContextStyleTimingState(context);
  275. const ast = (visitDslNode(this, normalizeAnimationEntry(metadata), context));
  276. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  277. if (context.unsupportedCSSPropertiesFound.size) {
  278. pushUnrecognizedPropertiesWarning(warnings, [
  279. ...context.unsupportedCSSPropertiesFound.keys(),
  280. ]);
  281. }
  282. }
  283. return ast;
  284. }
  285. _resetContextStyleTimingState(context) {
  286. context.currentQuerySelector = ROOT_SELECTOR;
  287. context.collectedStyles = new Map();
  288. context.collectedStyles.set(ROOT_SELECTOR, new Map());
  289. context.currentTime = 0;
  290. }
  291. visitTrigger(metadata, context) {
  292. let queryCount = (context.queryCount = 0);
  293. let depCount = (context.depCount = 0);
  294. const states = [];
  295. const transitions = [];
  296. if (metadata.name.charAt(0) == '@') {
  297. context.errors.push(invalidTrigger());
  298. }
  299. metadata.definitions.forEach((def) => {
  300. this._resetContextStyleTimingState(context);
  301. if (def.type == AnimationMetadataType.State) {
  302. const stateDef = def;
  303. const name = stateDef.name;
  304. name
  305. .toString()
  306. .split(/\s*,\s*/)
  307. .forEach((n) => {
  308. stateDef.name = n;
  309. states.push(this.visitState(stateDef, context));
  310. });
  311. stateDef.name = name;
  312. }
  313. else if (def.type == AnimationMetadataType.Transition) {
  314. const transition = this.visitTransition(def, context);
  315. queryCount += transition.queryCount;
  316. depCount += transition.depCount;
  317. transitions.push(transition);
  318. }
  319. else {
  320. context.errors.push(invalidDefinition());
  321. }
  322. });
  323. return {
  324. type: AnimationMetadataType.Trigger,
  325. name: metadata.name,
  326. states,
  327. transitions,
  328. queryCount,
  329. depCount,
  330. options: null,
  331. };
  332. }
  333. visitState(metadata, context) {
  334. const styleAst = this.visitStyle(metadata.styles, context);
  335. const astParams = (metadata.options && metadata.options.params) || null;
  336. if (styleAst.containsDynamicStyles) {
  337. const missingSubs = new Set();
  338. const params = astParams || {};
  339. styleAst.styles.forEach((style) => {
  340. if (style instanceof Map) {
  341. style.forEach((value) => {
  342. extractStyleParams(value).forEach((sub) => {
  343. if (!params.hasOwnProperty(sub)) {
  344. missingSubs.add(sub);
  345. }
  346. });
  347. });
  348. }
  349. });
  350. if (missingSubs.size) {
  351. context.errors.push(invalidState(metadata.name, [...missingSubs.values()]));
  352. }
  353. }
  354. return {
  355. type: AnimationMetadataType.State,
  356. name: metadata.name,
  357. style: styleAst,
  358. options: astParams ? { params: astParams } : null,
  359. };
  360. }
  361. visitTransition(metadata, context) {
  362. context.queryCount = 0;
  363. context.depCount = 0;
  364. const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
  365. const matchers = parseTransitionExpr(metadata.expr, context.errors);
  366. return {
  367. type: AnimationMetadataType.Transition,
  368. matchers,
  369. animation,
  370. queryCount: context.queryCount,
  371. depCount: context.depCount,
  372. options: normalizeAnimationOptions(metadata.options),
  373. };
  374. }
  375. visitSequence(metadata, context) {
  376. return {
  377. type: AnimationMetadataType.Sequence,
  378. steps: metadata.steps.map((s) => visitDslNode(this, s, context)),
  379. options: normalizeAnimationOptions(metadata.options),
  380. };
  381. }
  382. visitGroup(metadata, context) {
  383. const currentTime = context.currentTime;
  384. let furthestTime = 0;
  385. const steps = metadata.steps.map((step) => {
  386. context.currentTime = currentTime;
  387. const innerAst = visitDslNode(this, step, context);
  388. furthestTime = Math.max(furthestTime, context.currentTime);
  389. return innerAst;
  390. });
  391. context.currentTime = furthestTime;
  392. return {
  393. type: AnimationMetadataType.Group,
  394. steps,
  395. options: normalizeAnimationOptions(metadata.options),
  396. };
  397. }
  398. visitAnimate(metadata, context) {
  399. const timingAst = constructTimingAst(metadata.timings, context.errors);
  400. context.currentAnimateTimings = timingAst;
  401. let styleAst;
  402. let styleMetadata = metadata.styles
  403. ? metadata.styles
  404. : style({});
  405. if (styleMetadata.type == AnimationMetadataType.Keyframes) {
  406. styleAst = this.visitKeyframes(styleMetadata, context);
  407. }
  408. else {
  409. let styleMetadata = metadata.styles;
  410. let isEmpty = false;
  411. if (!styleMetadata) {
  412. isEmpty = true;
  413. const newStyleData = {};
  414. if (timingAst.easing) {
  415. newStyleData['easing'] = timingAst.easing;
  416. }
  417. styleMetadata = style(newStyleData);
  418. }
  419. context.currentTime += timingAst.duration + timingAst.delay;
  420. const _styleAst = this.visitStyle(styleMetadata, context);
  421. _styleAst.isEmptyStep = isEmpty;
  422. styleAst = _styleAst;
  423. }
  424. context.currentAnimateTimings = null;
  425. return {
  426. type: AnimationMetadataType.Animate,
  427. timings: timingAst,
  428. style: styleAst,
  429. options: null,
  430. };
  431. }
  432. visitStyle(metadata, context) {
  433. const ast = this._makeStyleAst(metadata, context);
  434. this._validateStyleAst(ast, context);
  435. return ast;
  436. }
  437. _makeStyleAst(metadata, context) {
  438. const styles = [];
  439. const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];
  440. for (let styleTuple of metadataStyles) {
  441. if (typeof styleTuple === 'string') {
  442. if (styleTuple === AUTO_STYLE) {
  443. styles.push(styleTuple);
  444. }
  445. else {
  446. context.errors.push(invalidStyleValue(styleTuple));
  447. }
  448. }
  449. else {
  450. styles.push(new Map(Object.entries(styleTuple)));
  451. }
  452. }
  453. let containsDynamicStyles = false;
  454. let collectedEasing = null;
  455. styles.forEach((styleData) => {
  456. if (styleData instanceof Map) {
  457. if (styleData.has('easing')) {
  458. collectedEasing = styleData.get('easing');
  459. styleData.delete('easing');
  460. }
  461. if (!containsDynamicStyles) {
  462. for (let value of styleData.values()) {
  463. if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {
  464. containsDynamicStyles = true;
  465. break;
  466. }
  467. }
  468. }
  469. }
  470. });
  471. return {
  472. type: AnimationMetadataType.Style,
  473. styles,
  474. easing: collectedEasing,
  475. offset: metadata.offset,
  476. containsDynamicStyles,
  477. options: null,
  478. };
  479. }
  480. _validateStyleAst(ast, context) {
  481. const timings = context.currentAnimateTimings;
  482. let endTime = context.currentTime;
  483. let startTime = context.currentTime;
  484. if (timings && startTime > 0) {
  485. startTime -= timings.duration + timings.delay;
  486. }
  487. ast.styles.forEach((tuple) => {
  488. if (typeof tuple === 'string')
  489. return;
  490. tuple.forEach((value, prop) => {
  491. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  492. if (!this._driver.validateStyleProperty(prop)) {
  493. tuple.delete(prop);
  494. context.unsupportedCSSPropertiesFound.add(prop);
  495. return;
  496. }
  497. }
  498. // This is guaranteed to have a defined Map at this querySelector location making it
  499. // safe to add the assertion here. It is set as a default empty map in prior methods.
  500. const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);
  501. const collectedEntry = collectedStyles.get(prop);
  502. let updateCollectedStyle = true;
  503. if (collectedEntry) {
  504. if (startTime != endTime &&
  505. startTime >= collectedEntry.startTime &&
  506. endTime <= collectedEntry.endTime) {
  507. context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));
  508. updateCollectedStyle = false;
  509. }
  510. // we always choose the smaller start time value since we
  511. // want to have a record of the entire animation window where
  512. // the style property is being animated in between
  513. startTime = collectedEntry.startTime;
  514. }
  515. if (updateCollectedStyle) {
  516. collectedStyles.set(prop, { startTime, endTime });
  517. }
  518. if (context.options) {
  519. validateStyleParams(value, context.options, context.errors);
  520. }
  521. });
  522. });
  523. }
  524. visitKeyframes(metadata, context) {
  525. const ast = { type: AnimationMetadataType.Keyframes, styles: [], options: null };
  526. if (!context.currentAnimateTimings) {
  527. context.errors.push(invalidKeyframes());
  528. return ast;
  529. }
  530. const MAX_KEYFRAME_OFFSET = 1;
  531. let totalKeyframesWithOffsets = 0;
  532. const offsets = [];
  533. let offsetsOutOfOrder = false;
  534. let keyframesOutOfRange = false;
  535. let previousOffset = 0;
  536. const keyframes = metadata.steps.map((styles) => {
  537. const style = this._makeStyleAst(styles, context);
  538. let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);
  539. let offset = 0;
  540. if (offsetVal != null) {
  541. totalKeyframesWithOffsets++;
  542. offset = style.offset = offsetVal;
  543. }
  544. keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
  545. offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
  546. previousOffset = offset;
  547. offsets.push(offset);
  548. return style;
  549. });
  550. if (keyframesOutOfRange) {
  551. context.errors.push(invalidOffset());
  552. }
  553. if (offsetsOutOfOrder) {
  554. context.errors.push(keyframeOffsetsOutOfOrder());
  555. }
  556. const length = metadata.steps.length;
  557. let generatedOffset = 0;
  558. if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
  559. context.errors.push(keyframesMissingOffsets());
  560. }
  561. else if (totalKeyframesWithOffsets == 0) {
  562. generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);
  563. }
  564. const limit = length - 1;
  565. const currentTime = context.currentTime;
  566. const currentAnimateTimings = context.currentAnimateTimings;
  567. const animateDuration = currentAnimateTimings.duration;
  568. keyframes.forEach((kf, i) => {
  569. const offset = generatedOffset > 0 ? (i == limit ? 1 : generatedOffset * i) : offsets[i];
  570. const durationUpToThisFrame = offset * animateDuration;
  571. context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;
  572. currentAnimateTimings.duration = durationUpToThisFrame;
  573. this._validateStyleAst(kf, context);
  574. kf.offset = offset;
  575. ast.styles.push(kf);
  576. });
  577. return ast;
  578. }
  579. visitReference(metadata, context) {
  580. return {
  581. type: AnimationMetadataType.Reference,
  582. animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
  583. options: normalizeAnimationOptions(metadata.options),
  584. };
  585. }
  586. visitAnimateChild(metadata, context) {
  587. context.depCount++;
  588. return {
  589. type: AnimationMetadataType.AnimateChild,
  590. options: normalizeAnimationOptions(metadata.options),
  591. };
  592. }
  593. visitAnimateRef(metadata, context) {
  594. return {
  595. type: AnimationMetadataType.AnimateRef,
  596. animation: this.visitReference(metadata.animation, context),
  597. options: normalizeAnimationOptions(metadata.options),
  598. };
  599. }
  600. visitQuery(metadata, context) {
  601. const parentSelector = context.currentQuerySelector;
  602. const options = (metadata.options || {});
  603. context.queryCount++;
  604. context.currentQuery = metadata;
  605. const [selector, includeSelf] = normalizeSelector(metadata.selector);
  606. context.currentQuerySelector = parentSelector.length
  607. ? parentSelector + ' ' + selector
  608. : selector;
  609. getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());
  610. const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
  611. context.currentQuery = null;
  612. context.currentQuerySelector = parentSelector;
  613. return {
  614. type: AnimationMetadataType.Query,
  615. selector,
  616. limit: options.limit || 0,
  617. optional: !!options.optional,
  618. includeSelf,
  619. animation,
  620. originalSelector: metadata.selector,
  621. options: normalizeAnimationOptions(metadata.options),
  622. };
  623. }
  624. visitStagger(metadata, context) {
  625. if (!context.currentQuery) {
  626. context.errors.push(invalidStagger());
  627. }
  628. const timings = metadata.timings === 'full'
  629. ? { duration: 0, delay: 0, easing: 'full' }
  630. : resolveTiming(metadata.timings, context.errors, true);
  631. return {
  632. type: AnimationMetadataType.Stagger,
  633. animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
  634. timings,
  635. options: null,
  636. };
  637. }
  638. }
  639. function normalizeSelector(selector) {
  640. const hasAmpersand = selector.split(/\s*,\s*/).find((token) => token == SELF_TOKEN)
  641. ? true
  642. : false;
  643. if (hasAmpersand) {
  644. selector = selector.replace(SELF_TOKEN_REGEX, '');
  645. }
  646. // Note: the :enter and :leave aren't normalized here since those
  647. // selectors are filled in at runtime during timeline building
  648. selector = selector
  649. .replace(/@\*/g, NG_TRIGGER_SELECTOR)
  650. .replace(/@\w+/g, (match) => NG_TRIGGER_SELECTOR + '-' + match.slice(1))
  651. .replace(/:animating/g, NG_ANIMATING_SELECTOR);
  652. return [selector, hasAmpersand];
  653. }
  654. function normalizeParams(obj) {
  655. return obj ? { ...obj } : null;
  656. }
  657. class AnimationAstBuilderContext {
  658. errors;
  659. queryCount = 0;
  660. depCount = 0;
  661. currentTransition = null;
  662. currentQuery = null;
  663. currentQuerySelector = null;
  664. currentAnimateTimings = null;
  665. currentTime = 0;
  666. collectedStyles = new Map();
  667. options = null;
  668. unsupportedCSSPropertiesFound = new Set();
  669. constructor(errors) {
  670. this.errors = errors;
  671. }
  672. }
  673. function consumeOffset(styles) {
  674. if (typeof styles == 'string')
  675. return null;
  676. let offset = null;
  677. if (Array.isArray(styles)) {
  678. styles.forEach((styleTuple) => {
  679. if (styleTuple instanceof Map && styleTuple.has('offset')) {
  680. const obj = styleTuple;
  681. offset = parseFloat(obj.get('offset'));
  682. obj.delete('offset');
  683. }
  684. });
  685. }
  686. else if (styles instanceof Map && styles.has('offset')) {
  687. const obj = styles;
  688. offset = parseFloat(obj.get('offset'));
  689. obj.delete('offset');
  690. }
  691. return offset;
  692. }
  693. function constructTimingAst(value, errors) {
  694. if (value.hasOwnProperty('duration')) {
  695. return value;
  696. }
  697. if (typeof value == 'number') {
  698. const duration = resolveTiming(value, errors).duration;
  699. return makeTimingAst(duration, 0, '');
  700. }
  701. const strValue = value;
  702. const isDynamic = strValue.split(/\s+/).some((v) => v.charAt(0) == '{' && v.charAt(1) == '{');
  703. if (isDynamic) {
  704. const ast = makeTimingAst(0, 0, '');
  705. ast.dynamic = true;
  706. ast.strValue = strValue;
  707. return ast;
  708. }
  709. const timings = resolveTiming(strValue, errors);
  710. return makeTimingAst(timings.duration, timings.delay, timings.easing);
  711. }
  712. function normalizeAnimationOptions(options) {
  713. if (options) {
  714. options = { ...options };
  715. if (options['params']) {
  716. options['params'] = normalizeParams(options['params']);
  717. }
  718. }
  719. else {
  720. options = {};
  721. }
  722. return options;
  723. }
  724. function makeTimingAst(duration, delay, easing) {
  725. return { duration, delay, easing };
  726. }
  727. function createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {
  728. return {
  729. type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,
  730. element,
  731. keyframes,
  732. preStyleProps,
  733. postStyleProps,
  734. duration,
  735. delay,
  736. totalTime: duration + delay,
  737. easing,
  738. subTimeline,
  739. };
  740. }
  741. class ElementInstructionMap {
  742. _map = new Map();
  743. get(element) {
  744. return this._map.get(element) || [];
  745. }
  746. append(element, instructions) {
  747. let existingInstructions = this._map.get(element);
  748. if (!existingInstructions) {
  749. this._map.set(element, (existingInstructions = []));
  750. }
  751. existingInstructions.push(...instructions);
  752. }
  753. has(element) {
  754. return this._map.has(element);
  755. }
  756. clear() {
  757. this._map.clear();
  758. }
  759. }
  760. const ONE_FRAME_IN_MILLISECONDS = 1;
  761. const ENTER_TOKEN = ':enter';
  762. const ENTER_TOKEN_REGEX = /* @__PURE__ */ new RegExp(ENTER_TOKEN, 'g');
  763. const LEAVE_TOKEN = ':leave';
  764. const LEAVE_TOKEN_REGEX = /* @__PURE__ */ new RegExp(LEAVE_TOKEN, 'g');
  765. /*
  766. * The code within this file aims to generate web-animations-compatible keyframes from Angular's
  767. * animation DSL code.
  768. *
  769. * The code below will be converted from:
  770. *
  771. * ```ts
  772. * sequence([
  773. * style({ opacity: 0 }),
  774. * animate(1000, style({ opacity: 0 }))
  775. * ])
  776. * ```
  777. *
  778. * To:
  779. * ```ts
  780. * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]
  781. * duration = 1000
  782. * delay = 0
  783. * easing = ''
  784. * ```
  785. *
  786. * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a
  787. * combination of AST traversal and merge-sort-like algorithms are used.
  788. *
  789. * [AST Traversal]
  790. * Each of the animation verbs, when executed, will return an string-map object representing what
  791. * type of action it is (style, animate, group, etc...) and the data associated with it. This means
  792. * that when functional composition mix of these functions is evaluated (like in the example above)
  793. * then it will end up producing a tree of objects representing the animation itself.
  794. *
  795. * When this animation object tree is processed by the visitor code below it will visit each of the
  796. * verb statements within the visitor. And during each visit it will build the context of the
  797. * animation keyframes by interacting with the `TimelineBuilder`.
  798. *
  799. * [TimelineBuilder]
  800. * This class is responsible for tracking the styles and building a series of keyframe objects for a
  801. * timeline between a start and end time. The builder starts off with an initial timeline and each
  802. * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a
  803. * `sequence()` then it will generate a sub timeline for each step as well as a new one after
  804. * they are complete.
  805. *
  806. * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub
  807. * timeline was created (based on one of the cases above) then the parent timeline will attempt to
  808. * merge the styles used within the sub timelines into itself (only with group() this will happen).
  809. * This happens with a merge operation (much like how the merge works in mergeSort) and it will only
  810. * copy the most recently used styles from the sub timelines into the parent timeline. This ensures
  811. * that if the styles are used later on in another phase of the animation then they will be the most
  812. * up-to-date values.
  813. *
  814. * [How Missing Styles Are Updated]
  815. * Each timeline has a `backFill` property which is responsible for filling in new styles into
  816. * already processed keyframes if a new style shows up later within the animation sequence.
  817. *
  818. * ```ts
  819. * sequence([
  820. * style({ width: 0 }),
  821. * animate(1000, style({ width: 100 })),
  822. * animate(1000, style({ width: 200 })),
  823. * animate(1000, style({ width: 300 }))
  824. * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere
  825. * else
  826. * ])
  827. * ```
  828. *
  829. * What is happening here is that the `height` value is added later in the sequence, but is missing
  830. * from all previous animation steps. Therefore when a keyframe is created it would also be missing
  831. * from all previous keyframes up until where it is first used. For the timeline keyframe generation
  832. * to properly fill in the style it will place the previous value (the value from the parent
  833. * timeline) or a default value of `*` into the backFill map.
  834. *
  835. * When a sub-timeline is created it will have its own backFill property. This is done so that
  836. * styles present within the sub-timeline do not accidentally seep into the previous/future timeline
  837. * keyframes
  838. *
  839. * [Validation]
  840. * The code in this file is not responsible for validation. That functionality happens with within
  841. * the `AnimationValidatorVisitor` code.
  842. */
  843. function buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {
  844. return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);
  845. }
  846. class AnimationTimelineBuilderVisitor {
  847. buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {
  848. subInstructions = subInstructions || new ElementInstructionMap();
  849. const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);
  850. context.options = options;
  851. const delay = options.delay ? resolveTimingValue(options.delay) : 0;
  852. context.currentTimeline.delayNextStep(delay);
  853. context.currentTimeline.setStyles([startingStyles], null, context.errors, options);
  854. visitDslNode(this, ast, context);
  855. // this checks to see if an actual animation happened
  856. const timelines = context.timelines.filter((timeline) => timeline.containsAnimation());
  857. // note: we just want to apply the final styles for the rootElement, so we do not
  858. // just apply the styles to the last timeline but the last timeline which
  859. // element is the root one (basically `*`-styles are replaced with the actual
  860. // state style values only for the root element)
  861. if (timelines.length && finalStyles.size) {
  862. let lastRootTimeline;
  863. for (let i = timelines.length - 1; i >= 0; i--) {
  864. const timeline = timelines[i];
  865. if (timeline.element === rootElement) {
  866. lastRootTimeline = timeline;
  867. break;
  868. }
  869. }
  870. if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {
  871. lastRootTimeline.setStyles([finalStyles], null, context.errors, options);
  872. }
  873. }
  874. return timelines.length
  875. ? timelines.map((timeline) => timeline.buildKeyframes())
  876. : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];
  877. }
  878. visitTrigger(ast, context) {
  879. // these values are not visited in this AST
  880. }
  881. visitState(ast, context) {
  882. // these values are not visited in this AST
  883. }
  884. visitTransition(ast, context) {
  885. // these values are not visited in this AST
  886. }
  887. visitAnimateChild(ast, context) {
  888. const elementInstructions = context.subInstructions.get(context.element);
  889. if (elementInstructions) {
  890. const innerContext = context.createSubContext(ast.options);
  891. const startTime = context.currentTimeline.currentTime;
  892. const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);
  893. if (startTime != endTime) {
  894. // we do this on the upper context because we created a sub context for
  895. // the sub child animations
  896. context.transformIntoNewTimeline(endTime);
  897. }
  898. }
  899. context.previousNode = ast;
  900. }
  901. visitAnimateRef(ast, context) {
  902. const innerContext = context.createSubContext(ast.options);
  903. innerContext.transformIntoNewTimeline();
  904. this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);
  905. this.visitReference(ast.animation, innerContext);
  906. context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);
  907. context.previousNode = ast;
  908. }
  909. _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {
  910. for (const animationRefOptions of animationsRefsOptions) {
  911. const animationDelay = animationRefOptions?.delay;
  912. if (animationDelay) {
  913. const animationDelayValue = typeof animationDelay === 'number'
  914. ? animationDelay
  915. : resolveTimingValue(interpolateParams(animationDelay, animationRefOptions?.params ?? {}, context.errors));
  916. innerContext.delayNextStep(animationDelayValue);
  917. }
  918. }
  919. }
  920. _visitSubInstructions(instructions, context, options) {
  921. const startTime = context.currentTimeline.currentTime;
  922. let furthestTime = startTime;
  923. // this is a special-case for when a user wants to skip a sub
  924. // animation from being fired entirely.
  925. const duration = options.duration != null ? resolveTimingValue(options.duration) : null;
  926. const delay = options.delay != null ? resolveTimingValue(options.delay) : null;
  927. if (duration !== 0) {
  928. instructions.forEach((instruction) => {
  929. const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);
  930. furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);
  931. });
  932. }
  933. return furthestTime;
  934. }
  935. visitReference(ast, context) {
  936. context.updateOptions(ast.options, true);
  937. visitDslNode(this, ast.animation, context);
  938. context.previousNode = ast;
  939. }
  940. visitSequence(ast, context) {
  941. const subContextCount = context.subContextCount;
  942. let ctx = context;
  943. const options = ast.options;
  944. if (options && (options.params || options.delay)) {
  945. ctx = context.createSubContext(options);
  946. ctx.transformIntoNewTimeline();
  947. if (options.delay != null) {
  948. if (ctx.previousNode.type == AnimationMetadataType.Style) {
  949. ctx.currentTimeline.snapshotCurrentStyles();
  950. ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
  951. }
  952. const delay = resolveTimingValue(options.delay);
  953. ctx.delayNextStep(delay);
  954. }
  955. }
  956. if (ast.steps.length) {
  957. ast.steps.forEach((s) => visitDslNode(this, s, ctx));
  958. // this is here just in case the inner steps only contain or end with a style() call
  959. ctx.currentTimeline.applyStylesToKeyframe();
  960. // this means that some animation function within the sequence
  961. // ended up creating a sub timeline (which means the current
  962. // timeline cannot overlap with the contents of the sequence)
  963. if (ctx.subContextCount > subContextCount) {
  964. ctx.transformIntoNewTimeline();
  965. }
  966. }
  967. context.previousNode = ast;
  968. }
  969. visitGroup(ast, context) {
  970. const innerTimelines = [];
  971. let furthestTime = context.currentTimeline.currentTime;
  972. const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;
  973. ast.steps.forEach((s) => {
  974. const innerContext = context.createSubContext(ast.options);
  975. if (delay) {
  976. innerContext.delayNextStep(delay);
  977. }
  978. visitDslNode(this, s, innerContext);
  979. furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);
  980. innerTimelines.push(innerContext.currentTimeline);
  981. });
  982. // this operation is run after the AST loop because otherwise
  983. // if the parent timeline's collected styles were updated then
  984. // it would pass in invalid data into the new-to-be forked items
  985. innerTimelines.forEach((timeline) => context.currentTimeline.mergeTimelineCollectedStyles(timeline));
  986. context.transformIntoNewTimeline(furthestTime);
  987. context.previousNode = ast;
  988. }
  989. _visitTiming(ast, context) {
  990. if (ast.dynamic) {
  991. const strValue = ast.strValue;
  992. const timingValue = context.params
  993. ? interpolateParams(strValue, context.params, context.errors)
  994. : strValue;
  995. return resolveTiming(timingValue, context.errors);
  996. }
  997. else {
  998. return { duration: ast.duration, delay: ast.delay, easing: ast.easing };
  999. }
  1000. }
  1001. visitAnimate(ast, context) {
  1002. const timings = (context.currentAnimateTimings = this._visitTiming(ast.timings, context));
  1003. const timeline = context.currentTimeline;
  1004. if (timings.delay) {
  1005. context.incrementTime(timings.delay);
  1006. timeline.snapshotCurrentStyles();
  1007. }
  1008. const style = ast.style;
  1009. if (style.type == AnimationMetadataType.Keyframes) {
  1010. this.visitKeyframes(style, context);
  1011. }
  1012. else {
  1013. context.incrementTime(timings.duration);
  1014. this.visitStyle(style, context);
  1015. timeline.applyStylesToKeyframe();
  1016. }
  1017. context.currentAnimateTimings = null;
  1018. context.previousNode = ast;
  1019. }
  1020. visitStyle(ast, context) {
  1021. const timeline = context.currentTimeline;
  1022. const timings = context.currentAnimateTimings;
  1023. // this is a special case for when a style() call
  1024. // directly follows an animate() call (but not inside of an animate() call)
  1025. if (!timings && timeline.hasCurrentStyleProperties()) {
  1026. timeline.forwardFrame();
  1027. }
  1028. const easing = (timings && timings.easing) || ast.easing;
  1029. if (ast.isEmptyStep) {
  1030. timeline.applyEmptyStep(easing);
  1031. }
  1032. else {
  1033. timeline.setStyles(ast.styles, easing, context.errors, context.options);
  1034. }
  1035. context.previousNode = ast;
  1036. }
  1037. visitKeyframes(ast, context) {
  1038. const currentAnimateTimings = context.currentAnimateTimings;
  1039. const startTime = context.currentTimeline.duration;
  1040. const duration = currentAnimateTimings.duration;
  1041. const innerContext = context.createSubContext();
  1042. const innerTimeline = innerContext.currentTimeline;
  1043. innerTimeline.easing = currentAnimateTimings.easing;
  1044. ast.styles.forEach((step) => {
  1045. const offset = step.offset || 0;
  1046. innerTimeline.forwardTime(offset * duration);
  1047. innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);
  1048. innerTimeline.applyStylesToKeyframe();
  1049. });
  1050. // this will ensure that the parent timeline gets all the styles from
  1051. // the child even if the new timeline below is not used
  1052. context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);
  1053. // we do this because the window between this timeline and the sub timeline
  1054. // should ensure that the styles within are exactly the same as they were before
  1055. context.transformIntoNewTimeline(startTime + duration);
  1056. context.previousNode = ast;
  1057. }
  1058. visitQuery(ast, context) {
  1059. // in the event that the first step before this is a style step we need
  1060. // to ensure the styles are applied before the children are animated
  1061. const startTime = context.currentTimeline.currentTime;
  1062. const options = (ast.options || {});
  1063. const delay = options.delay ? resolveTimingValue(options.delay) : 0;
  1064. if (delay &&
  1065. (context.previousNode.type === AnimationMetadataType.Style ||
  1066. (startTime == 0 && context.currentTimeline.hasCurrentStyleProperties()))) {
  1067. context.currentTimeline.snapshotCurrentStyles();
  1068. context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
  1069. }
  1070. let furthestTime = startTime;
  1071. const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);
  1072. context.currentQueryTotal = elms.length;
  1073. let sameElementTimeline = null;
  1074. elms.forEach((element, i) => {
  1075. context.currentQueryIndex = i;
  1076. const innerContext = context.createSubContext(ast.options, element);
  1077. if (delay) {
  1078. innerContext.delayNextStep(delay);
  1079. }
  1080. if (element === context.element) {
  1081. sameElementTimeline = innerContext.currentTimeline;
  1082. }
  1083. visitDslNode(this, ast.animation, innerContext);
  1084. // this is here just incase the inner steps only contain or end
  1085. // with a style() call (which is here to signal that this is a preparatory
  1086. // call to style an element before it is animated again)
  1087. innerContext.currentTimeline.applyStylesToKeyframe();
  1088. const endTime = innerContext.currentTimeline.currentTime;
  1089. furthestTime = Math.max(furthestTime, endTime);
  1090. });
  1091. context.currentQueryIndex = 0;
  1092. context.currentQueryTotal = 0;
  1093. context.transformIntoNewTimeline(furthestTime);
  1094. if (sameElementTimeline) {
  1095. context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);
  1096. context.currentTimeline.snapshotCurrentStyles();
  1097. }
  1098. context.previousNode = ast;
  1099. }
  1100. visitStagger(ast, context) {
  1101. const parentContext = context.parentContext;
  1102. const tl = context.currentTimeline;
  1103. const timings = ast.timings;
  1104. const duration = Math.abs(timings.duration);
  1105. const maxTime = duration * (context.currentQueryTotal - 1);
  1106. let delay = duration * context.currentQueryIndex;
  1107. let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;
  1108. switch (staggerTransformer) {
  1109. case 'reverse':
  1110. delay = maxTime - delay;
  1111. break;
  1112. case 'full':
  1113. delay = parentContext.currentStaggerTime;
  1114. break;
  1115. }
  1116. const timeline = context.currentTimeline;
  1117. if (delay) {
  1118. timeline.delayNextStep(delay);
  1119. }
  1120. const startingTime = timeline.currentTime;
  1121. visitDslNode(this, ast.animation, context);
  1122. context.previousNode = ast;
  1123. // time = duration + delay
  1124. // the reason why this computation is so complex is because
  1125. // the inner timeline may either have a delay value or a stretched
  1126. // keyframe depending on if a subtimeline is not used or is used.
  1127. parentContext.currentStaggerTime =
  1128. tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime);
  1129. }
  1130. }
  1131. const DEFAULT_NOOP_PREVIOUS_NODE = {};
  1132. class AnimationTimelineContext {
  1133. _driver;
  1134. element;
  1135. subInstructions;
  1136. _enterClassName;
  1137. _leaveClassName;
  1138. errors;
  1139. timelines;
  1140. parentContext = null;
  1141. currentTimeline;
  1142. currentAnimateTimings = null;
  1143. previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
  1144. subContextCount = 0;
  1145. options = {};
  1146. currentQueryIndex = 0;
  1147. currentQueryTotal = 0;
  1148. currentStaggerTime = 0;
  1149. constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {
  1150. this._driver = _driver;
  1151. this.element = element;
  1152. this.subInstructions = subInstructions;
  1153. this._enterClassName = _enterClassName;
  1154. this._leaveClassName = _leaveClassName;
  1155. this.errors = errors;
  1156. this.timelines = timelines;
  1157. this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);
  1158. timelines.push(this.currentTimeline);
  1159. }
  1160. get params() {
  1161. return this.options.params;
  1162. }
  1163. updateOptions(options, skipIfExists) {
  1164. if (!options)
  1165. return;
  1166. const newOptions = options;
  1167. let optionsToUpdate = this.options;
  1168. // NOTE: this will get patched up when other animation methods support duration overrides
  1169. if (newOptions.duration != null) {
  1170. optionsToUpdate.duration = resolveTimingValue(newOptions.duration);
  1171. }
  1172. if (newOptions.delay != null) {
  1173. optionsToUpdate.delay = resolveTimingValue(newOptions.delay);
  1174. }
  1175. const newParams = newOptions.params;
  1176. if (newParams) {
  1177. let paramsToUpdate = optionsToUpdate.params;
  1178. if (!paramsToUpdate) {
  1179. paramsToUpdate = this.options.params = {};
  1180. }
  1181. Object.keys(newParams).forEach((name) => {
  1182. if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {
  1183. paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);
  1184. }
  1185. });
  1186. }
  1187. }
  1188. _copyOptions() {
  1189. const options = {};
  1190. if (this.options) {
  1191. const oldParams = this.options.params;
  1192. if (oldParams) {
  1193. const params = (options['params'] = {});
  1194. Object.keys(oldParams).forEach((name) => {
  1195. params[name] = oldParams[name];
  1196. });
  1197. }
  1198. }
  1199. return options;
  1200. }
  1201. createSubContext(options = null, element, newTime) {
  1202. const target = element || this.element;
  1203. const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));
  1204. context.previousNode = this.previousNode;
  1205. context.currentAnimateTimings = this.currentAnimateTimings;
  1206. context.options = this._copyOptions();
  1207. context.updateOptions(options);
  1208. context.currentQueryIndex = this.currentQueryIndex;
  1209. context.currentQueryTotal = this.currentQueryTotal;
  1210. context.parentContext = this;
  1211. this.subContextCount++;
  1212. return context;
  1213. }
  1214. transformIntoNewTimeline(newTime) {
  1215. this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
  1216. this.currentTimeline = this.currentTimeline.fork(this.element, newTime);
  1217. this.timelines.push(this.currentTimeline);
  1218. return this.currentTimeline;
  1219. }
  1220. appendInstructionToTimeline(instruction, duration, delay) {
  1221. const updatedTimings = {
  1222. duration: duration != null ? duration : instruction.duration,
  1223. delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,
  1224. easing: '',
  1225. };
  1226. const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);
  1227. this.timelines.push(builder);
  1228. return updatedTimings;
  1229. }
  1230. incrementTime(time) {
  1231. this.currentTimeline.forwardTime(this.currentTimeline.duration + time);
  1232. }
  1233. delayNextStep(delay) {
  1234. // negative delays are not yet supported
  1235. if (delay > 0) {
  1236. this.currentTimeline.delayNextStep(delay);
  1237. }
  1238. }
  1239. invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {
  1240. let results = [];
  1241. if (includeSelf) {
  1242. results.push(this.element);
  1243. }
  1244. if (selector.length > 0) {
  1245. // only if :self is used then the selector can be empty
  1246. selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);
  1247. selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);
  1248. const multi = limit != 1;
  1249. let elements = this._driver.query(this.element, selector, multi);
  1250. if (limit !== 0) {
  1251. elements =
  1252. limit < 0
  1253. ? elements.slice(elements.length + limit, elements.length)
  1254. : elements.slice(0, limit);
  1255. }
  1256. results.push(...elements);
  1257. }
  1258. if (!optional && results.length == 0) {
  1259. errors.push(invalidQuery(originalSelector));
  1260. }
  1261. return results;
  1262. }
  1263. }
  1264. class TimelineBuilder {
  1265. _driver;
  1266. element;
  1267. startTime;
  1268. _elementTimelineStylesLookup;
  1269. duration = 0;
  1270. easing = null;
  1271. _previousKeyframe = new Map();
  1272. _currentKeyframe = new Map();
  1273. _keyframes = new Map();
  1274. _styleSummary = new Map();
  1275. _localTimelineStyles = new Map();
  1276. _globalTimelineStyles;
  1277. _pendingStyles = new Map();
  1278. _backFill = new Map();
  1279. _currentEmptyStepKeyframe = null;
  1280. constructor(_driver, element, startTime, _elementTimelineStylesLookup) {
  1281. this._driver = _driver;
  1282. this.element = element;
  1283. this.startTime = startTime;
  1284. this._elementTimelineStylesLookup = _elementTimelineStylesLookup;
  1285. if (!this._elementTimelineStylesLookup) {
  1286. this._elementTimelineStylesLookup = new Map();
  1287. }
  1288. this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);
  1289. if (!this._globalTimelineStyles) {
  1290. this._globalTimelineStyles = this._localTimelineStyles;
  1291. this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);
  1292. }
  1293. this._loadKeyframe();
  1294. }
  1295. containsAnimation() {
  1296. switch (this._keyframes.size) {
  1297. case 0:
  1298. return false;
  1299. case 1:
  1300. return this.hasCurrentStyleProperties();
  1301. default:
  1302. return true;
  1303. }
  1304. }
  1305. hasCurrentStyleProperties() {
  1306. return this._currentKeyframe.size > 0;
  1307. }
  1308. get currentTime() {
  1309. return this.startTime + this.duration;
  1310. }
  1311. delayNextStep(delay) {
  1312. // in the event that a style() step is placed right before a stagger()
  1313. // and that style() step is the very first style() value in the animation
  1314. // then we need to make a copy of the keyframe [0, copy, 1] so that the delay
  1315. // properly applies the style() values to work with the stagger...
  1316. const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;
  1317. if (this.duration || hasPreStyleStep) {
  1318. this.forwardTime(this.currentTime + delay);
  1319. if (hasPreStyleStep) {
  1320. this.snapshotCurrentStyles();
  1321. }
  1322. }
  1323. else {
  1324. this.startTime += delay;
  1325. }
  1326. }
  1327. fork(element, currentTime) {
  1328. this.applyStylesToKeyframe();
  1329. return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);
  1330. }
  1331. _loadKeyframe() {
  1332. if (this._currentKeyframe) {
  1333. this._previousKeyframe = this._currentKeyframe;
  1334. }
  1335. this._currentKeyframe = this._keyframes.get(this.duration);
  1336. if (!this._currentKeyframe) {
  1337. this._currentKeyframe = new Map();
  1338. this._keyframes.set(this.duration, this._currentKeyframe);
  1339. }
  1340. }
  1341. forwardFrame() {
  1342. this.duration += ONE_FRAME_IN_MILLISECONDS;
  1343. this._loadKeyframe();
  1344. }
  1345. forwardTime(time) {
  1346. this.applyStylesToKeyframe();
  1347. this.duration = time;
  1348. this._loadKeyframe();
  1349. }
  1350. _updateStyle(prop, value) {
  1351. this._localTimelineStyles.set(prop, value);
  1352. this._globalTimelineStyles.set(prop, value);
  1353. this._styleSummary.set(prop, { time: this.currentTime, value });
  1354. }
  1355. allowOnlyTimelineStyles() {
  1356. return this._currentEmptyStepKeyframe !== this._currentKeyframe;
  1357. }
  1358. applyEmptyStep(easing) {
  1359. if (easing) {
  1360. this._previousKeyframe.set('easing', easing);
  1361. }
  1362. // special case for animate(duration):
  1363. // all missing styles are filled with a `*` value then
  1364. // if any destination styles are filled in later on the same
  1365. // keyframe then they will override the overridden styles
  1366. // We use `_globalTimelineStyles` here because there may be
  1367. // styles in previous keyframes that are not present in this timeline
  1368. for (let [prop, value] of this._globalTimelineStyles) {
  1369. this._backFill.set(prop, value || AUTO_STYLE);
  1370. this._currentKeyframe.set(prop, AUTO_STYLE);
  1371. }
  1372. this._currentEmptyStepKeyframe = this._currentKeyframe;
  1373. }
  1374. setStyles(input, easing, errors, options) {
  1375. if (easing) {
  1376. this._previousKeyframe.set('easing', easing);
  1377. }
  1378. const params = (options && options.params) || {};
  1379. const styles = flattenStyles(input, this._globalTimelineStyles);
  1380. for (let [prop, value] of styles) {
  1381. const val = interpolateParams(value, params, errors);
  1382. this._pendingStyles.set(prop, val);
  1383. if (!this._localTimelineStyles.has(prop)) {
  1384. this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? AUTO_STYLE);
  1385. }
  1386. this._updateStyle(prop, val);
  1387. }
  1388. }
  1389. applyStylesToKeyframe() {
  1390. if (this._pendingStyles.size == 0)
  1391. return;
  1392. this._pendingStyles.forEach((val, prop) => {
  1393. this._currentKeyframe.set(prop, val);
  1394. });
  1395. this._pendingStyles.clear();
  1396. this._localTimelineStyles.forEach((val, prop) => {
  1397. if (!this._currentKeyframe.has(prop)) {
  1398. this._currentKeyframe.set(prop, val);
  1399. }
  1400. });
  1401. }
  1402. snapshotCurrentStyles() {
  1403. for (let [prop, val] of this._localTimelineStyles) {
  1404. this._pendingStyles.set(prop, val);
  1405. this._updateStyle(prop, val);
  1406. }
  1407. }
  1408. getFinalKeyframe() {
  1409. return this._keyframes.get(this.duration);
  1410. }
  1411. get properties() {
  1412. const properties = [];
  1413. for (let prop in this._currentKeyframe) {
  1414. properties.push(prop);
  1415. }
  1416. return properties;
  1417. }
  1418. mergeTimelineCollectedStyles(timeline) {
  1419. timeline._styleSummary.forEach((details1, prop) => {
  1420. const details0 = this._styleSummary.get(prop);
  1421. if (!details0 || details1.time > details0.time) {
  1422. this._updateStyle(prop, details1.value);
  1423. }
  1424. });
  1425. }
  1426. buildKeyframes() {
  1427. this.applyStylesToKeyframe();
  1428. const preStyleProps = new Set();
  1429. const postStyleProps = new Set();
  1430. const isEmpty = this._keyframes.size === 1 && this.duration === 0;
  1431. let finalKeyframes = [];
  1432. this._keyframes.forEach((keyframe, time) => {
  1433. const finalKeyframe = new Map([...this._backFill, ...keyframe]);
  1434. finalKeyframe.forEach((value, prop) => {
  1435. if (value === _PRE_STYLE) {
  1436. preStyleProps.add(prop);
  1437. }
  1438. else if (value === AUTO_STYLE) {
  1439. postStyleProps.add(prop);
  1440. }
  1441. });
  1442. if (!isEmpty) {
  1443. finalKeyframe.set('offset', time / this.duration);
  1444. }
  1445. finalKeyframes.push(finalKeyframe);
  1446. });
  1447. const preProps = [...preStyleProps.values()];
  1448. const postProps = [...postStyleProps.values()];
  1449. // special case for a 0-second animation (which is designed just to place styles onscreen)
  1450. if (isEmpty) {
  1451. const kf0 = finalKeyframes[0];
  1452. const kf1 = new Map(kf0);
  1453. kf0.set('offset', 0);
  1454. kf1.set('offset', 1);
  1455. finalKeyframes = [kf0, kf1];
  1456. }
  1457. return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);
  1458. }
  1459. }
  1460. class SubTimelineBuilder extends TimelineBuilder {
  1461. keyframes;
  1462. preStyleProps;
  1463. postStyleProps;
  1464. _stretchStartingKeyframe;
  1465. timings;
  1466. constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {
  1467. super(driver, element, timings.delay);
  1468. this.keyframes = keyframes;
  1469. this.preStyleProps = preStyleProps;
  1470. this.postStyleProps = postStyleProps;
  1471. this._stretchStartingKeyframe = _stretchStartingKeyframe;
  1472. this.timings = { duration: timings.duration, delay: timings.delay, easing: timings.easing };
  1473. }
  1474. containsAnimation() {
  1475. return this.keyframes.length > 1;
  1476. }
  1477. buildKeyframes() {
  1478. let keyframes = this.keyframes;
  1479. let { delay, duration, easing } = this.timings;
  1480. if (this._stretchStartingKeyframe && delay) {
  1481. const newKeyframes = [];
  1482. const totalTime = duration + delay;
  1483. const startingGap = delay / totalTime;
  1484. // the original starting keyframe now starts once the delay is done
  1485. const newFirstKeyframe = new Map(keyframes[0]);
  1486. newFirstKeyframe.set('offset', 0);
  1487. newKeyframes.push(newFirstKeyframe);
  1488. const oldFirstKeyframe = new Map(keyframes[0]);
  1489. oldFirstKeyframe.set('offset', roundOffset(startingGap));
  1490. newKeyframes.push(oldFirstKeyframe);
  1491. /*
  1492. When the keyframe is stretched then it means that the delay before the animation
  1493. starts is gone. Instead the first keyframe is placed at the start of the animation
  1494. and it is then copied to where it starts when the original delay is over. This basically
  1495. means nothing animates during that delay, but the styles are still rendered. For this
  1496. to work the original offset values that exist in the original keyframes must be "warped"
  1497. so that they can take the new keyframe + delay into account.
  1498. delay=1000, duration=1000, keyframes = 0 .5 1
  1499. turns into
  1500. delay=0, duration=2000, keyframes = 0 .33 .66 1
  1501. */
  1502. // offsets between 1 ... n -1 are all warped by the keyframe stretch
  1503. const limit = keyframes.length - 1;
  1504. for (let i = 1; i <= limit; i++) {
  1505. let kf = new Map(keyframes[i]);
  1506. const oldOffset = kf.get('offset');
  1507. const timeAtKeyframe = delay + oldOffset * duration;
  1508. kf.set('offset', roundOffset(timeAtKeyframe / totalTime));
  1509. newKeyframes.push(kf);
  1510. }
  1511. // the new starting keyframe should be added at the start
  1512. duration = totalTime;
  1513. delay = 0;
  1514. easing = '';
  1515. keyframes = newKeyframes;
  1516. }
  1517. return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);
  1518. }
  1519. }
  1520. function roundOffset(offset, decimalPoints = 3) {
  1521. const mult = Math.pow(10, decimalPoints - 1);
  1522. return Math.round(offset * mult) / mult;
  1523. }
  1524. function flattenStyles(input, allStyles) {
  1525. const styles = new Map();
  1526. let allProperties;
  1527. input.forEach((token) => {
  1528. if (token === '*') {
  1529. allProperties ??= allStyles.keys();
  1530. for (let prop of allProperties) {
  1531. styles.set(prop, AUTO_STYLE);
  1532. }
  1533. }
  1534. else {
  1535. for (let [prop, val] of token) {
  1536. styles.set(prop, val);
  1537. }
  1538. }
  1539. });
  1540. return styles;
  1541. }
  1542. function createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {
  1543. return {
  1544. type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,
  1545. element,
  1546. triggerName,
  1547. isRemovalTransition,
  1548. fromState,
  1549. fromStyles,
  1550. toState,
  1551. toStyles,
  1552. timelines,
  1553. queriedElements,
  1554. preStyleProps,
  1555. postStyleProps,
  1556. totalTime,
  1557. errors,
  1558. };
  1559. }
  1560. const EMPTY_OBJECT = {};
  1561. class AnimationTransitionFactory {
  1562. _triggerName;
  1563. ast;
  1564. _stateStyles;
  1565. constructor(_triggerName, ast, _stateStyles) {
  1566. this._triggerName = _triggerName;
  1567. this.ast = ast;
  1568. this._stateStyles = _stateStyles;
  1569. }
  1570. match(currentState, nextState, element, params) {
  1571. return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);
  1572. }
  1573. buildStyles(stateName, params, errors) {
  1574. let styler = this._stateStyles.get('*');
  1575. if (stateName !== undefined) {
  1576. styler = this._stateStyles.get(stateName?.toString()) || styler;
  1577. }
  1578. return styler ? styler.buildStyles(params, errors) : new Map();
  1579. }
  1580. build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {
  1581. const errors = [];
  1582. const transitionAnimationParams = (this.ast.options && this.ast.options.params) || EMPTY_OBJECT;
  1583. const currentAnimationParams = (currentOptions && currentOptions.params) || EMPTY_OBJECT;
  1584. const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);
  1585. const nextAnimationParams = (nextOptions && nextOptions.params) || EMPTY_OBJECT;
  1586. const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);
  1587. const queriedElements = new Set();
  1588. const preStyleMap = new Map();
  1589. const postStyleMap = new Map();
  1590. const isRemoval = nextState === 'void';
  1591. const animationOptions = {
  1592. params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),
  1593. delay: this.ast.options?.delay,
  1594. };
  1595. const timelines = skipAstBuild
  1596. ? []
  1597. : buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);
  1598. let totalTime = 0;
  1599. timelines.forEach((tl) => {
  1600. totalTime = Math.max(tl.duration + tl.delay, totalTime);
  1601. });
  1602. if (errors.length) {
  1603. return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);
  1604. }
  1605. timelines.forEach((tl) => {
  1606. const elm = tl.element;
  1607. const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());
  1608. tl.preStyleProps.forEach((prop) => preProps.add(prop));
  1609. const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());
  1610. tl.postStyleProps.forEach((prop) => postProps.add(prop));
  1611. if (elm !== element) {
  1612. queriedElements.add(elm);
  1613. }
  1614. });
  1615. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  1616. checkNonAnimatableInTimelines(timelines, this._triggerName, driver);
  1617. }
  1618. return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime);
  1619. }
  1620. }
  1621. /**
  1622. * Checks inside a set of timelines if they try to animate a css property which is not considered
  1623. * animatable, in that case it prints a warning on the console.
  1624. * Besides that the function doesn't have any other effect.
  1625. *
  1626. * Note: this check is done here after the timelines are built instead of doing on a lower level so
  1627. * that we can make sure that the warning appears only once per instruction (we can aggregate here
  1628. * all the issues instead of finding them separately).
  1629. *
  1630. * @param timelines The built timelines for the current instruction.
  1631. * @param triggerName The name of the trigger for the current instruction.
  1632. * @param driver Animation driver used to perform the check.
  1633. *
  1634. */
  1635. function checkNonAnimatableInTimelines(timelines, triggerName, driver) {
  1636. if (!driver.validateAnimatableStyleProperty) {
  1637. return;
  1638. }
  1639. const allowedNonAnimatableProps = new Set([
  1640. // 'easing' is a utility/synthetic prop we use to represent
  1641. // easing functions, it represents a property of the animation
  1642. // which is not animatable but different values can be used
  1643. // in different steps
  1644. 'easing',
  1645. ]);
  1646. const invalidNonAnimatableProps = new Set();
  1647. timelines.forEach(({ keyframes }) => {
  1648. const nonAnimatablePropsInitialValues = new Map();
  1649. keyframes.forEach((keyframe) => {
  1650. const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));
  1651. for (const [prop, value] of entriesToCheck) {
  1652. if (!driver.validateAnimatableStyleProperty(prop)) {
  1653. if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {
  1654. const propInitialValue = nonAnimatablePropsInitialValues.get(prop);
  1655. if (propInitialValue !== value) {
  1656. invalidNonAnimatableProps.add(prop);
  1657. }
  1658. }
  1659. else {
  1660. nonAnimatablePropsInitialValues.set(prop, value);
  1661. }
  1662. }
  1663. }
  1664. });
  1665. });
  1666. if (invalidNonAnimatableProps.size > 0) {
  1667. console.warn(`Warning: The animation trigger "${triggerName}" is attempting to animate the following` +
  1668. ' not animatable properties: ' +
  1669. Array.from(invalidNonAnimatableProps).join(', ') +
  1670. '\n' +
  1671. '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');
  1672. }
  1673. }
  1674. function oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {
  1675. return matchFns.some((fn) => fn(currentState, nextState, element, params));
  1676. }
  1677. function applyParamDefaults(userParams, defaults) {
  1678. const result = { ...defaults };
  1679. Object.entries(userParams).forEach(([key, value]) => {
  1680. if (value != null) {
  1681. result[key] = value;
  1682. }
  1683. });
  1684. return result;
  1685. }
  1686. class AnimationStateStyles {
  1687. styles;
  1688. defaultParams;
  1689. normalizer;
  1690. constructor(styles, defaultParams, normalizer) {
  1691. this.styles = styles;
  1692. this.defaultParams = defaultParams;
  1693. this.normalizer = normalizer;
  1694. }
  1695. buildStyles(params, errors) {
  1696. const finalStyles = new Map();
  1697. const combinedParams = applyParamDefaults(params, this.defaultParams);
  1698. this.styles.styles.forEach((value) => {
  1699. if (typeof value !== 'string') {
  1700. value.forEach((val, prop) => {
  1701. if (val) {
  1702. val = interpolateParams(val, combinedParams, errors);
  1703. }
  1704. const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);
  1705. val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);
  1706. finalStyles.set(prop, val);
  1707. });
  1708. }
  1709. });
  1710. return finalStyles;
  1711. }
  1712. }
  1713. function buildTrigger(name, ast, normalizer) {
  1714. return new AnimationTrigger(name, ast, normalizer);
  1715. }
  1716. class AnimationTrigger {
  1717. name;
  1718. ast;
  1719. _normalizer;
  1720. transitionFactories = [];
  1721. fallbackTransition;
  1722. states = new Map();
  1723. constructor(name, ast, _normalizer) {
  1724. this.name = name;
  1725. this.ast = ast;
  1726. this._normalizer = _normalizer;
  1727. ast.states.forEach((ast) => {
  1728. const defaultParams = (ast.options && ast.options.params) || {};
  1729. this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));
  1730. });
  1731. balanceProperties(this.states, 'true', '1');
  1732. balanceProperties(this.states, 'false', '0');
  1733. ast.transitions.forEach((ast) => {
  1734. this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));
  1735. });
  1736. this.fallbackTransition = createFallbackTransition(name, this.states);
  1737. }
  1738. get containsQueries() {
  1739. return this.ast.queryCount > 0;
  1740. }
  1741. matchTransition(currentState, nextState, element, params) {
  1742. const entry = this.transitionFactories.find((f) => f.match(currentState, nextState, element, params));
  1743. return entry || null;
  1744. }
  1745. matchStyles(currentState, params, errors) {
  1746. return this.fallbackTransition.buildStyles(currentState, params, errors);
  1747. }
  1748. }
  1749. function createFallbackTransition(triggerName, states, normalizer) {
  1750. const matchers = [(fromState, toState) => true];
  1751. const animation = { type: AnimationMetadataType.Sequence, steps: [], options: null };
  1752. const transition = {
  1753. type: AnimationMetadataType.Transition,
  1754. animation,
  1755. matchers,
  1756. options: null,
  1757. queryCount: 0,
  1758. depCount: 0,
  1759. };
  1760. return new AnimationTransitionFactory(triggerName, transition, states);
  1761. }
  1762. function balanceProperties(stateMap, key1, key2) {
  1763. if (stateMap.has(key1)) {
  1764. if (!stateMap.has(key2)) {
  1765. stateMap.set(key2, stateMap.get(key1));
  1766. }
  1767. }
  1768. else if (stateMap.has(key2)) {
  1769. stateMap.set(key1, stateMap.get(key2));
  1770. }
  1771. }
  1772. const EMPTY_INSTRUCTION_MAP = /* @__PURE__ */ new ElementInstructionMap();
  1773. class TimelineAnimationEngine {
  1774. bodyNode;
  1775. _driver;
  1776. _normalizer;
  1777. _animations = new Map();
  1778. _playersById = new Map();
  1779. players = [];
  1780. constructor(bodyNode, _driver, _normalizer) {
  1781. this.bodyNode = bodyNode;
  1782. this._driver = _driver;
  1783. this._normalizer = _normalizer;
  1784. }
  1785. register(id, metadata) {
  1786. const errors = [];
  1787. const warnings = [];
  1788. const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
  1789. if (errors.length) {
  1790. throw registerFailed(errors);
  1791. }
  1792. else {
  1793. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  1794. if (warnings.length) {
  1795. warnRegister(warnings);
  1796. }
  1797. }
  1798. this._animations.set(id, ast);
  1799. }
  1800. }
  1801. _buildPlayer(i, preStyles, postStyles) {
  1802. const element = i.element;
  1803. const keyframes = normalizeKeyframes(this._normalizer, i.keyframes, preStyles, postStyles);
  1804. return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);
  1805. }
  1806. create(id, element, options = {}) {
  1807. const errors = [];
  1808. const ast = this._animations.get(id);
  1809. let instructions;
  1810. const autoStylesMap = new Map();
  1811. if (ast) {
  1812. instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);
  1813. instructions.forEach((inst) => {
  1814. const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());
  1815. inst.postStyleProps.forEach((prop) => styles.set(prop, null));
  1816. });
  1817. }
  1818. else {
  1819. errors.push(missingOrDestroyedAnimation());
  1820. instructions = [];
  1821. }
  1822. if (errors.length) {
  1823. throw createAnimationFailed(errors);
  1824. }
  1825. autoStylesMap.forEach((styles, element) => {
  1826. styles.forEach((_, prop) => {
  1827. styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));
  1828. });
  1829. });
  1830. const players = instructions.map((i) => {
  1831. const styles = autoStylesMap.get(i.element);
  1832. return this._buildPlayer(i, new Map(), styles);
  1833. });
  1834. const player = optimizeGroupPlayer(players);
  1835. this._playersById.set(id, player);
  1836. player.onDestroy(() => this.destroy(id));
  1837. this.players.push(player);
  1838. return player;
  1839. }
  1840. destroy(id) {
  1841. const player = this._getPlayer(id);
  1842. player.destroy();
  1843. this._playersById.delete(id);
  1844. const index = this.players.indexOf(player);
  1845. if (index >= 0) {
  1846. this.players.splice(index, 1);
  1847. }
  1848. }
  1849. _getPlayer(id) {
  1850. const player = this._playersById.get(id);
  1851. if (!player) {
  1852. throw missingPlayer(id);
  1853. }
  1854. return player;
  1855. }
  1856. listen(id, element, eventName, callback) {
  1857. // triggerName, fromState, toState are all ignored for timeline animations
  1858. const baseEvent = makeAnimationEvent(element, '', '', '');
  1859. listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);
  1860. return () => { };
  1861. }
  1862. command(id, element, command, args) {
  1863. if (command == 'register') {
  1864. this.register(id, args[0]);
  1865. return;
  1866. }
  1867. if (command == 'create') {
  1868. const options = (args[0] || {});
  1869. this.create(id, element, options);
  1870. return;
  1871. }
  1872. const player = this._getPlayer(id);
  1873. switch (command) {
  1874. case 'play':
  1875. player.play();
  1876. break;
  1877. case 'pause':
  1878. player.pause();
  1879. break;
  1880. case 'reset':
  1881. player.reset();
  1882. break;
  1883. case 'restart':
  1884. player.restart();
  1885. break;
  1886. case 'finish':
  1887. player.finish();
  1888. break;
  1889. case 'init':
  1890. player.init();
  1891. break;
  1892. case 'setPosition':
  1893. player.setPosition(parseFloat(args[0]));
  1894. break;
  1895. case 'destroy':
  1896. this.destroy(id);
  1897. break;
  1898. }
  1899. }
  1900. }
  1901. const QUEUED_CLASSNAME = 'ng-animate-queued';
  1902. const QUEUED_SELECTOR = '.ng-animate-queued';
  1903. const DISABLED_CLASSNAME = 'ng-animate-disabled';
  1904. const DISABLED_SELECTOR = '.ng-animate-disabled';
  1905. const STAR_CLASSNAME = 'ng-star-inserted';
  1906. const STAR_SELECTOR = '.ng-star-inserted';
  1907. const EMPTY_PLAYER_ARRAY = [];
  1908. const NULL_REMOVAL_STATE = {
  1909. namespaceId: '',
  1910. setForRemoval: false,
  1911. setForMove: false,
  1912. hasAnimation: false,
  1913. removedBeforeQueried: false,
  1914. };
  1915. const NULL_REMOVED_QUERIED_STATE = {
  1916. namespaceId: '',
  1917. setForMove: false,
  1918. setForRemoval: false,
  1919. hasAnimation: false,
  1920. removedBeforeQueried: true,
  1921. };
  1922. const REMOVAL_FLAG = '__ng_removed';
  1923. class StateValue {
  1924. namespaceId;
  1925. value;
  1926. options;
  1927. get params() {
  1928. return this.options.params;
  1929. }
  1930. constructor(input, namespaceId = '') {
  1931. this.namespaceId = namespaceId;
  1932. const isObj = input && input.hasOwnProperty('value');
  1933. const value = isObj ? input['value'] : input;
  1934. this.value = normalizeTriggerValue(value);
  1935. if (isObj) {
  1936. // we drop the value property from options.
  1937. const { value, ...options } = input;
  1938. this.options = options;
  1939. }
  1940. else {
  1941. this.options = {};
  1942. }
  1943. if (!this.options.params) {
  1944. this.options.params = {};
  1945. }
  1946. }
  1947. absorbOptions(options) {
  1948. const newParams = options.params;
  1949. if (newParams) {
  1950. const oldParams = this.options.params;
  1951. Object.keys(newParams).forEach((prop) => {
  1952. if (oldParams[prop] == null) {
  1953. oldParams[prop] = newParams[prop];
  1954. }
  1955. });
  1956. }
  1957. }
  1958. }
  1959. const VOID_VALUE = 'void';
  1960. const DEFAULT_STATE_VALUE = /* @__PURE__ */ new StateValue(VOID_VALUE);
  1961. class AnimationTransitionNamespace {
  1962. id;
  1963. hostElement;
  1964. _engine;
  1965. players = [];
  1966. _triggers = new Map();
  1967. _queue = [];
  1968. _elementListeners = new Map();
  1969. _hostClassName;
  1970. constructor(id, hostElement, _engine) {
  1971. this.id = id;
  1972. this.hostElement = hostElement;
  1973. this._engine = _engine;
  1974. this._hostClassName = 'ng-tns-' + id;
  1975. addClass(hostElement, this._hostClassName);
  1976. }
  1977. listen(element, name, phase, callback) {
  1978. if (!this._triggers.has(name)) {
  1979. throw missingTrigger(phase, name);
  1980. }
  1981. if (phase == null || phase.length == 0) {
  1982. throw missingEvent(name);
  1983. }
  1984. if (!isTriggerEventValid(phase)) {
  1985. throw unsupportedTriggerEvent(phase, name);
  1986. }
  1987. const listeners = getOrSetDefaultValue(this._elementListeners, element, []);
  1988. const data = { name, phase, callback };
  1989. listeners.push(data);
  1990. const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());
  1991. if (!triggersWithStates.has(name)) {
  1992. addClass(element, NG_TRIGGER_CLASSNAME);
  1993. addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
  1994. triggersWithStates.set(name, DEFAULT_STATE_VALUE);
  1995. }
  1996. return () => {
  1997. // the event listener is removed AFTER the flush has occurred such
  1998. // that leave animations callbacks can fire (otherwise if the node
  1999. // is removed in between then the listeners would be deregistered)
  2000. this._engine.afterFlush(() => {
  2001. const index = listeners.indexOf(data);
  2002. if (index >= 0) {
  2003. listeners.splice(index, 1);
  2004. }
  2005. if (!this._triggers.has(name)) {
  2006. triggersWithStates.delete(name);
  2007. }
  2008. });
  2009. };
  2010. }
  2011. register(name, ast) {
  2012. if (this._triggers.has(name)) {
  2013. // throw
  2014. return false;
  2015. }
  2016. else {
  2017. this._triggers.set(name, ast);
  2018. return true;
  2019. }
  2020. }
  2021. _getTrigger(name) {
  2022. const trigger = this._triggers.get(name);
  2023. if (!trigger) {
  2024. throw unregisteredTrigger(name);
  2025. }
  2026. return trigger;
  2027. }
  2028. trigger(element, triggerName, value, defaultToFallback = true) {
  2029. const trigger = this._getTrigger(triggerName);
  2030. const player = new TransitionAnimationPlayer(this.id, triggerName, element);
  2031. let triggersWithStates = this._engine.statesByElement.get(element);
  2032. if (!triggersWithStates) {
  2033. addClass(element, NG_TRIGGER_CLASSNAME);
  2034. addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
  2035. this._engine.statesByElement.set(element, (triggersWithStates = new Map()));
  2036. }
  2037. let fromState = triggersWithStates.get(triggerName);
  2038. const toState = new StateValue(value, this.id);
  2039. const isObj = value && value.hasOwnProperty('value');
  2040. if (!isObj && fromState) {
  2041. toState.absorbOptions(fromState.options);
  2042. }
  2043. triggersWithStates.set(triggerName, toState);
  2044. if (!fromState) {
  2045. fromState = DEFAULT_STATE_VALUE;
  2046. }
  2047. const isRemoval = toState.value === VOID_VALUE;
  2048. // normally this isn't reached by here, however, if an object expression
  2049. // is passed in then it may be a new object each time. Comparing the value
  2050. // is important since that will stay the same despite there being a new object.
  2051. // The removal arc here is special cased because the same element is triggered
  2052. // twice in the event that it contains animations on the outer/inner portions
  2053. // of the host container
  2054. if (!isRemoval && fromState.value === toState.value) {
  2055. // this means that despite the value not changing, some inner params
  2056. // have changed which means that the animation final styles need to be applied
  2057. if (!objEquals(fromState.params, toState.params)) {
  2058. const errors = [];
  2059. const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
  2060. const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
  2061. if (errors.length) {
  2062. this._engine.reportError(errors);
  2063. }
  2064. else {
  2065. this._engine.afterFlush(() => {
  2066. eraseStyles(element, fromStyles);
  2067. setStyles(element, toStyles);
  2068. });
  2069. }
  2070. }
  2071. return;
  2072. }
  2073. const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);
  2074. playersOnElement.forEach((player) => {
  2075. // only remove the player if it is queued on the EXACT same trigger/namespace
  2076. // we only also deal with queued players here because if the animation has
  2077. // started then we want to keep the player alive until the flush happens
  2078. // (which is where the previousPlayers are passed into the new player)
  2079. if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
  2080. player.destroy();
  2081. }
  2082. });
  2083. let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);
  2084. let isFallbackTransition = false;
  2085. if (!transition) {
  2086. if (!defaultToFallback)
  2087. return;
  2088. transition = trigger.fallbackTransition;
  2089. isFallbackTransition = true;
  2090. }
  2091. this._engine.totalQueuedPlayers++;
  2092. this._queue.push({
  2093. element,
  2094. triggerName,
  2095. transition,
  2096. fromState,
  2097. toState,
  2098. player,
  2099. isFallbackTransition,
  2100. });
  2101. if (!isFallbackTransition) {
  2102. addClass(element, QUEUED_CLASSNAME);
  2103. player.onStart(() => {
  2104. removeClass(element, QUEUED_CLASSNAME);
  2105. });
  2106. }
  2107. player.onDone(() => {
  2108. let index = this.players.indexOf(player);
  2109. if (index >= 0) {
  2110. this.players.splice(index, 1);
  2111. }
  2112. const players = this._engine.playersByElement.get(element);
  2113. if (players) {
  2114. let index = players.indexOf(player);
  2115. if (index >= 0) {
  2116. players.splice(index, 1);
  2117. }
  2118. }
  2119. });
  2120. this.players.push(player);
  2121. playersOnElement.push(player);
  2122. return player;
  2123. }
  2124. deregister(name) {
  2125. this._triggers.delete(name);
  2126. this._engine.statesByElement.forEach((stateMap) => stateMap.delete(name));
  2127. this._elementListeners.forEach((listeners, element) => {
  2128. this._elementListeners.set(element, listeners.filter((entry) => {
  2129. return entry.name != name;
  2130. }));
  2131. });
  2132. }
  2133. clearElementCache(element) {
  2134. this._engine.statesByElement.delete(element);
  2135. this._elementListeners.delete(element);
  2136. const elementPlayers = this._engine.playersByElement.get(element);
  2137. if (elementPlayers) {
  2138. elementPlayers.forEach((player) => player.destroy());
  2139. this._engine.playersByElement.delete(element);
  2140. }
  2141. }
  2142. _signalRemovalForInnerTriggers(rootElement, context) {
  2143. const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
  2144. // emulate a leave animation for all inner nodes within this node.
  2145. // If there are no animations found for any of the nodes then clear the cache
  2146. // for the element.
  2147. elements.forEach((elm) => {
  2148. // this means that an inner remove() operation has already kicked off
  2149. // the animation on this element...
  2150. if (elm[REMOVAL_FLAG])
  2151. return;
  2152. const namespaces = this._engine.fetchNamespacesByElement(elm);
  2153. if (namespaces.size) {
  2154. namespaces.forEach((ns) => ns.triggerLeaveAnimation(elm, context, false, true));
  2155. }
  2156. else {
  2157. this.clearElementCache(elm);
  2158. }
  2159. });
  2160. // If the child elements were removed along with the parent, their animations might not
  2161. // have completed. Clear all the elements from the cache so we don't end up with a memory leak.
  2162. this._engine.afterFlushAnimationsDone(() => elements.forEach((elm) => this.clearElementCache(elm)));
  2163. }
  2164. triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {
  2165. const triggerStates = this._engine.statesByElement.get(element);
  2166. const previousTriggersValues = new Map();
  2167. if (triggerStates) {
  2168. const players = [];
  2169. triggerStates.forEach((state, triggerName) => {
  2170. previousTriggersValues.set(triggerName, state.value);
  2171. // this check is here in the event that an element is removed
  2172. // twice (both on the host level and the component level)
  2173. if (this._triggers.has(triggerName)) {
  2174. const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
  2175. if (player) {
  2176. players.push(player);
  2177. }
  2178. }
  2179. });
  2180. if (players.length) {
  2181. this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);
  2182. if (destroyAfterComplete) {
  2183. optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
  2184. }
  2185. return true;
  2186. }
  2187. }
  2188. return false;
  2189. }
  2190. prepareLeaveAnimationListeners(element) {
  2191. const listeners = this._elementListeners.get(element);
  2192. const elementStates = this._engine.statesByElement.get(element);
  2193. // if this statement fails then it means that the element was picked up
  2194. // by an earlier flush (or there are no listeners at all to track the leave).
  2195. if (listeners && elementStates) {
  2196. const visitedTriggers = new Set();
  2197. listeners.forEach((listener) => {
  2198. const triggerName = listener.name;
  2199. if (visitedTriggers.has(triggerName))
  2200. return;
  2201. visitedTriggers.add(triggerName);
  2202. const trigger = this._triggers.get(triggerName);
  2203. const transition = trigger.fallbackTransition;
  2204. const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;
  2205. const toState = new StateValue(VOID_VALUE);
  2206. const player = new TransitionAnimationPlayer(this.id, triggerName, element);
  2207. this._engine.totalQueuedPlayers++;
  2208. this._queue.push({
  2209. element,
  2210. triggerName,
  2211. transition,
  2212. fromState,
  2213. toState,
  2214. player,
  2215. isFallbackTransition: true,
  2216. });
  2217. });
  2218. }
  2219. }
  2220. removeNode(element, context) {
  2221. const engine = this._engine;
  2222. if (element.childElementCount) {
  2223. this._signalRemovalForInnerTriggers(element, context);
  2224. }
  2225. // this means that a * => VOID animation was detected and kicked off
  2226. if (this.triggerLeaveAnimation(element, context, true))
  2227. return;
  2228. // find the player that is animating and make sure that the
  2229. // removal is delayed until that player has completed
  2230. let containsPotentialParentTransition = false;
  2231. if (engine.totalAnimations) {
  2232. const currentPlayers = engine.players.length
  2233. ? engine.playersByQueriedElement.get(element)
  2234. : [];
  2235. // when this `if statement` does not continue forward it means that
  2236. // a previous animation query has selected the current element and
  2237. // is animating it. In this situation want to continue forwards and
  2238. // allow the element to be queued up for animation later.
  2239. if (currentPlayers && currentPlayers.length) {
  2240. containsPotentialParentTransition = true;
  2241. }
  2242. else {
  2243. let parent = element;
  2244. while ((parent = parent.parentNode)) {
  2245. const triggers = engine.statesByElement.get(parent);
  2246. if (triggers) {
  2247. containsPotentialParentTransition = true;
  2248. break;
  2249. }
  2250. }
  2251. }
  2252. }
  2253. // at this stage we know that the element will either get removed
  2254. // during flush or will be picked up by a parent query. Either way
  2255. // we need to fire the listeners for this element when it DOES get
  2256. // removed (once the query parent animation is done or after flush)
  2257. this.prepareLeaveAnimationListeners(element);
  2258. // whether or not a parent has an animation we need to delay the deferral of the leave
  2259. // operation until we have more information (which we do after flush() has been called)
  2260. if (containsPotentialParentTransition) {
  2261. engine.markElementAsRemoved(this.id, element, false, context);
  2262. }
  2263. else {
  2264. const removalFlag = element[REMOVAL_FLAG];
  2265. if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
  2266. // we do this after the flush has occurred such
  2267. // that the callbacks can be fired
  2268. engine.afterFlush(() => this.clearElementCache(element));
  2269. engine.destroyInnerAnimations(element);
  2270. engine._onRemovalComplete(element, context);
  2271. }
  2272. }
  2273. }
  2274. insertNode(element, parent) {
  2275. addClass(element, this._hostClassName);
  2276. }
  2277. drainQueuedTransitions(microtaskId) {
  2278. const instructions = [];
  2279. this._queue.forEach((entry) => {
  2280. const player = entry.player;
  2281. if (player.destroyed)
  2282. return;
  2283. const element = entry.element;
  2284. const listeners = this._elementListeners.get(element);
  2285. if (listeners) {
  2286. listeners.forEach((listener) => {
  2287. if (listener.name == entry.triggerName) {
  2288. const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);
  2289. baseEvent['_data'] = microtaskId;
  2290. listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
  2291. }
  2292. });
  2293. }
  2294. if (player.markedForDestroy) {
  2295. this._engine.afterFlush(() => {
  2296. // now we can destroy the element properly since the event listeners have
  2297. // been bound to the player
  2298. player.destroy();
  2299. });
  2300. }
  2301. else {
  2302. instructions.push(entry);
  2303. }
  2304. });
  2305. this._queue = [];
  2306. return instructions.sort((a, b) => {
  2307. // if depCount == 0 them move to front
  2308. // otherwise if a contains b then move back
  2309. const d0 = a.transition.ast.depCount;
  2310. const d1 = b.transition.ast.depCount;
  2311. if (d0 == 0 || d1 == 0) {
  2312. return d0 - d1;
  2313. }
  2314. return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
  2315. });
  2316. }
  2317. destroy(context) {
  2318. this.players.forEach((p) => p.destroy());
  2319. this._signalRemovalForInnerTriggers(this.hostElement, context);
  2320. }
  2321. }
  2322. class TransitionAnimationEngine {
  2323. bodyNode;
  2324. driver;
  2325. _normalizer;
  2326. players = [];
  2327. newHostElements = new Map();
  2328. playersByElement = new Map();
  2329. playersByQueriedElement = new Map();
  2330. statesByElement = new Map();
  2331. disabledNodes = new Set();
  2332. totalAnimations = 0;
  2333. totalQueuedPlayers = 0;
  2334. _namespaceLookup = {};
  2335. _namespaceList = [];
  2336. _flushFns = [];
  2337. _whenQuietFns = [];
  2338. namespacesByHostElement = new Map();
  2339. collectedEnterElements = [];
  2340. collectedLeaveElements = [];
  2341. // this method is designed to be overridden by the code that uses this engine
  2342. onRemovalComplete = (element, context) => { };
  2343. /** @internal */
  2344. _onRemovalComplete(element, context) {
  2345. this.onRemovalComplete(element, context);
  2346. }
  2347. constructor(bodyNode, driver, _normalizer) {
  2348. this.bodyNode = bodyNode;
  2349. this.driver = driver;
  2350. this._normalizer = _normalizer;
  2351. }
  2352. get queuedPlayers() {
  2353. const players = [];
  2354. this._namespaceList.forEach((ns) => {
  2355. ns.players.forEach((player) => {
  2356. if (player.queued) {
  2357. players.push(player);
  2358. }
  2359. });
  2360. });
  2361. return players;
  2362. }
  2363. createNamespace(namespaceId, hostElement) {
  2364. const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
  2365. if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
  2366. this._balanceNamespaceList(ns, hostElement);
  2367. }
  2368. else {
  2369. // defer this later until flush during when the host element has
  2370. // been inserted so that we know exactly where to place it in
  2371. // the namespace list
  2372. this.newHostElements.set(hostElement, ns);
  2373. // given that this host element is a part of the animation code, it
  2374. // may or may not be inserted by a parent node that is of an
  2375. // animation renderer type. If this happens then we can still have
  2376. // access to this item when we query for :enter nodes. If the parent
  2377. // is a renderer then the set data-structure will normalize the entry
  2378. this.collectEnterElement(hostElement);
  2379. }
  2380. return (this._namespaceLookup[namespaceId] = ns);
  2381. }
  2382. _balanceNamespaceList(ns, hostElement) {
  2383. const namespaceList = this._namespaceList;
  2384. const namespacesByHostElement = this.namespacesByHostElement;
  2385. const limit = namespaceList.length - 1;
  2386. if (limit >= 0) {
  2387. let found = false;
  2388. // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,
  2389. // establishing a top-down ordering of namespaces in `this._namespaceList`.
  2390. let ancestor = this.driver.getParentElement(hostElement);
  2391. while (ancestor) {
  2392. const ancestorNs = namespacesByHostElement.get(ancestor);
  2393. if (ancestorNs) {
  2394. // An animation namespace has been registered for this ancestor, so we insert `ns`
  2395. // right after it to establish top-down ordering of animation namespaces.
  2396. const index = namespaceList.indexOf(ancestorNs);
  2397. namespaceList.splice(index + 1, 0, ns);
  2398. found = true;
  2399. break;
  2400. }
  2401. ancestor = this.driver.getParentElement(ancestor);
  2402. }
  2403. if (!found) {
  2404. // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to
  2405. // ensure that any existing descendants are ordered after `ns`, retaining the desired
  2406. // top-down ordering.
  2407. namespaceList.unshift(ns);
  2408. }
  2409. }
  2410. else {
  2411. namespaceList.push(ns);
  2412. }
  2413. namespacesByHostElement.set(hostElement, ns);
  2414. return ns;
  2415. }
  2416. register(namespaceId, hostElement) {
  2417. let ns = this._namespaceLookup[namespaceId];
  2418. if (!ns) {
  2419. ns = this.createNamespace(namespaceId, hostElement);
  2420. }
  2421. return ns;
  2422. }
  2423. registerTrigger(namespaceId, name, trigger) {
  2424. let ns = this._namespaceLookup[namespaceId];
  2425. if (ns && ns.register(name, trigger)) {
  2426. this.totalAnimations++;
  2427. }
  2428. }
  2429. destroy(namespaceId, context) {
  2430. if (!namespaceId)
  2431. return;
  2432. this.afterFlush(() => { });
  2433. this.afterFlushAnimationsDone(() => {
  2434. const ns = this._fetchNamespace(namespaceId);
  2435. this.namespacesByHostElement.delete(ns.hostElement);
  2436. const index = this._namespaceList.indexOf(ns);
  2437. if (index >= 0) {
  2438. this._namespaceList.splice(index, 1);
  2439. }
  2440. ns.destroy(context);
  2441. delete this._namespaceLookup[namespaceId];
  2442. });
  2443. }
  2444. _fetchNamespace(id) {
  2445. return this._namespaceLookup[id];
  2446. }
  2447. fetchNamespacesByElement(element) {
  2448. // normally there should only be one namespace per element, however
  2449. // if @triggers are placed on both the component element and then
  2450. // its host element (within the component code) then there will be
  2451. // two namespaces returned. We use a set here to simply deduplicate
  2452. // the namespaces in case (for the reason described above) there are multiple triggers
  2453. const namespaces = new Set();
  2454. const elementStates = this.statesByElement.get(element);
  2455. if (elementStates) {
  2456. for (let stateValue of elementStates.values()) {
  2457. if (stateValue.namespaceId) {
  2458. const ns = this._fetchNamespace(stateValue.namespaceId);
  2459. if (ns) {
  2460. namespaces.add(ns);
  2461. }
  2462. }
  2463. }
  2464. }
  2465. return namespaces;
  2466. }
  2467. trigger(namespaceId, element, name, value) {
  2468. if (isElementNode(element)) {
  2469. const ns = this._fetchNamespace(namespaceId);
  2470. if (ns) {
  2471. ns.trigger(element, name, value);
  2472. return true;
  2473. }
  2474. }
  2475. return false;
  2476. }
  2477. insertNode(namespaceId, element, parent, insertBefore) {
  2478. if (!isElementNode(element))
  2479. return;
  2480. // special case for when an element is removed and reinserted (move operation)
  2481. // when this occurs we do not want to use the element for deletion later
  2482. const details = element[REMOVAL_FLAG];
  2483. if (details && details.setForRemoval) {
  2484. details.setForRemoval = false;
  2485. details.setForMove = true;
  2486. const index = this.collectedLeaveElements.indexOf(element);
  2487. if (index >= 0) {
  2488. this.collectedLeaveElements.splice(index, 1);
  2489. }
  2490. }
  2491. // in the event that the namespaceId is blank then the caller
  2492. // code does not contain any animation code in it, but it is
  2493. // just being called so that the node is marked as being inserted
  2494. if (namespaceId) {
  2495. const ns = this._fetchNamespace(namespaceId);
  2496. // This if-statement is a workaround for router issue #21947.
  2497. // The router sometimes hits a race condition where while a route
  2498. // is being instantiated a new navigation arrives, triggering leave
  2499. // animation of DOM that has not been fully initialized, until this
  2500. // is resolved, we need to handle the scenario when DOM is not in a
  2501. // consistent state during the animation.
  2502. if (ns) {
  2503. ns.insertNode(element, parent);
  2504. }
  2505. }
  2506. // only *directives and host elements are inserted before
  2507. if (insertBefore) {
  2508. this.collectEnterElement(element);
  2509. }
  2510. }
  2511. collectEnterElement(element) {
  2512. this.collectedEnterElements.push(element);
  2513. }
  2514. markElementAsDisabled(element, value) {
  2515. if (value) {
  2516. if (!this.disabledNodes.has(element)) {
  2517. this.disabledNodes.add(element);
  2518. addClass(element, DISABLED_CLASSNAME);
  2519. }
  2520. }
  2521. else if (this.disabledNodes.has(element)) {
  2522. this.disabledNodes.delete(element);
  2523. removeClass(element, DISABLED_CLASSNAME);
  2524. }
  2525. }
  2526. removeNode(namespaceId, element, context) {
  2527. if (isElementNode(element)) {
  2528. const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
  2529. if (ns) {
  2530. ns.removeNode(element, context);
  2531. }
  2532. else {
  2533. this.markElementAsRemoved(namespaceId, element, false, context);
  2534. }
  2535. const hostNS = this.namespacesByHostElement.get(element);
  2536. if (hostNS && hostNS.id !== namespaceId) {
  2537. hostNS.removeNode(element, context);
  2538. }
  2539. }
  2540. else {
  2541. this._onRemovalComplete(element, context);
  2542. }
  2543. }
  2544. markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {
  2545. this.collectedLeaveElements.push(element);
  2546. element[REMOVAL_FLAG] = {
  2547. namespaceId,
  2548. setForRemoval: context,
  2549. hasAnimation,
  2550. removedBeforeQueried: false,
  2551. previousTriggersValues,
  2552. };
  2553. }
  2554. listen(namespaceId, element, name, phase, callback) {
  2555. if (isElementNode(element)) {
  2556. return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
  2557. }
  2558. return () => { };
  2559. }
  2560. _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {
  2561. return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);
  2562. }
  2563. destroyInnerAnimations(containerElement) {
  2564. let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
  2565. elements.forEach((element) => this.destroyActiveAnimationsForElement(element));
  2566. if (this.playersByQueriedElement.size == 0)
  2567. return;
  2568. elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
  2569. elements.forEach((element) => this.finishActiveQueriedAnimationOnElement(element));
  2570. }
  2571. destroyActiveAnimationsForElement(element) {
  2572. const players = this.playersByElement.get(element);
  2573. if (players) {
  2574. players.forEach((player) => {
  2575. // special case for when an element is set for destruction, but hasn't started.
  2576. // in this situation we want to delay the destruction until the flush occurs
  2577. // so that any event listeners attached to the player are triggered.
  2578. if (player.queued) {
  2579. player.markedForDestroy = true;
  2580. }
  2581. else {
  2582. player.destroy();
  2583. }
  2584. });
  2585. }
  2586. }
  2587. finishActiveQueriedAnimationOnElement(element) {
  2588. const players = this.playersByQueriedElement.get(element);
  2589. if (players) {
  2590. players.forEach((player) => player.finish());
  2591. }
  2592. }
  2593. whenRenderingDone() {
  2594. return new Promise((resolve) => {
  2595. if (this.players.length) {
  2596. return optimizeGroupPlayer(this.players).onDone(() => resolve());
  2597. }
  2598. else {
  2599. resolve();
  2600. }
  2601. });
  2602. }
  2603. processLeaveNode(element) {
  2604. const details = element[REMOVAL_FLAG];
  2605. if (details && details.setForRemoval) {
  2606. // this will prevent it from removing it twice
  2607. element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
  2608. if (details.namespaceId) {
  2609. this.destroyInnerAnimations(element);
  2610. const ns = this._fetchNamespace(details.namespaceId);
  2611. if (ns) {
  2612. ns.clearElementCache(element);
  2613. }
  2614. }
  2615. this._onRemovalComplete(element, details.setForRemoval);
  2616. }
  2617. if (element.classList?.contains(DISABLED_CLASSNAME)) {
  2618. this.markElementAsDisabled(element, false);
  2619. }
  2620. this.driver.query(element, DISABLED_SELECTOR, true).forEach((node) => {
  2621. this.markElementAsDisabled(node, false);
  2622. });
  2623. }
  2624. flush(microtaskId = -1) {
  2625. let players = [];
  2626. if (this.newHostElements.size) {
  2627. this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
  2628. this.newHostElements.clear();
  2629. }
  2630. if (this.totalAnimations && this.collectedEnterElements.length) {
  2631. for (let i = 0; i < this.collectedEnterElements.length; i++) {
  2632. const elm = this.collectedEnterElements[i];
  2633. addClass(elm, STAR_CLASSNAME);
  2634. }
  2635. }
  2636. if (this._namespaceList.length &&
  2637. (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
  2638. const cleanupFns = [];
  2639. try {
  2640. players = this._flushAnimations(cleanupFns, microtaskId);
  2641. }
  2642. finally {
  2643. for (let i = 0; i < cleanupFns.length; i++) {
  2644. cleanupFns[i]();
  2645. }
  2646. }
  2647. }
  2648. else {
  2649. for (let i = 0; i < this.collectedLeaveElements.length; i++) {
  2650. const element = this.collectedLeaveElements[i];
  2651. this.processLeaveNode(element);
  2652. }
  2653. }
  2654. this.totalQueuedPlayers = 0;
  2655. this.collectedEnterElements.length = 0;
  2656. this.collectedLeaveElements.length = 0;
  2657. this._flushFns.forEach((fn) => fn());
  2658. this._flushFns = [];
  2659. if (this._whenQuietFns.length) {
  2660. // we move these over to a variable so that
  2661. // if any new callbacks are registered in another
  2662. // flush they do not populate the existing set
  2663. const quietFns = this._whenQuietFns;
  2664. this._whenQuietFns = [];
  2665. if (players.length) {
  2666. optimizeGroupPlayer(players).onDone(() => {
  2667. quietFns.forEach((fn) => fn());
  2668. });
  2669. }
  2670. else {
  2671. quietFns.forEach((fn) => fn());
  2672. }
  2673. }
  2674. }
  2675. reportError(errors) {
  2676. throw triggerTransitionsFailed(errors);
  2677. }
  2678. _flushAnimations(cleanupFns, microtaskId) {
  2679. const subTimelines = new ElementInstructionMap();
  2680. const skippedPlayers = [];
  2681. const skippedPlayersMap = new Map();
  2682. const queuedInstructions = [];
  2683. const queriedElements = new Map();
  2684. const allPreStyleElements = new Map();
  2685. const allPostStyleElements = new Map();
  2686. const disabledElementsSet = new Set();
  2687. this.disabledNodes.forEach((node) => {
  2688. disabledElementsSet.add(node);
  2689. const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
  2690. for (let i = 0; i < nodesThatAreDisabled.length; i++) {
  2691. disabledElementsSet.add(nodesThatAreDisabled[i]);
  2692. }
  2693. });
  2694. const bodyNode = this.bodyNode;
  2695. const allTriggerElements = Array.from(this.statesByElement.keys());
  2696. const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
  2697. // this must occur before the instructions are built below such that
  2698. // the :enter queries match the elements (since the timeline queries
  2699. // are fired during instruction building).
  2700. const enterNodeMapIds = new Map();
  2701. let i = 0;
  2702. enterNodeMap.forEach((nodes, root) => {
  2703. const className = ENTER_CLASSNAME + i++;
  2704. enterNodeMapIds.set(root, className);
  2705. nodes.forEach((node) => addClass(node, className));
  2706. });
  2707. const allLeaveNodes = [];
  2708. const mergedLeaveNodes = new Set();
  2709. const leaveNodesWithoutAnimations = new Set();
  2710. for (let i = 0; i < this.collectedLeaveElements.length; i++) {
  2711. const element = this.collectedLeaveElements[i];
  2712. const details = element[REMOVAL_FLAG];
  2713. if (details && details.setForRemoval) {
  2714. allLeaveNodes.push(element);
  2715. mergedLeaveNodes.add(element);
  2716. if (details.hasAnimation) {
  2717. this.driver
  2718. .query(element, STAR_SELECTOR, true)
  2719. .forEach((elm) => mergedLeaveNodes.add(elm));
  2720. }
  2721. else {
  2722. leaveNodesWithoutAnimations.add(element);
  2723. }
  2724. }
  2725. }
  2726. const leaveNodeMapIds = new Map();
  2727. const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
  2728. leaveNodeMap.forEach((nodes, root) => {
  2729. const className = LEAVE_CLASSNAME + i++;
  2730. leaveNodeMapIds.set(root, className);
  2731. nodes.forEach((node) => addClass(node, className));
  2732. });
  2733. cleanupFns.push(() => {
  2734. enterNodeMap.forEach((nodes, root) => {
  2735. const className = enterNodeMapIds.get(root);
  2736. nodes.forEach((node) => removeClass(node, className));
  2737. });
  2738. leaveNodeMap.forEach((nodes, root) => {
  2739. const className = leaveNodeMapIds.get(root);
  2740. nodes.forEach((node) => removeClass(node, className));
  2741. });
  2742. allLeaveNodes.forEach((element) => {
  2743. this.processLeaveNode(element);
  2744. });
  2745. });
  2746. const allPlayers = [];
  2747. const erroneousTransitions = [];
  2748. for (let i = this._namespaceList.length - 1; i >= 0; i--) {
  2749. const ns = this._namespaceList[i];
  2750. ns.drainQueuedTransitions(microtaskId).forEach((entry) => {
  2751. const player = entry.player;
  2752. const element = entry.element;
  2753. allPlayers.push(player);
  2754. if (this.collectedEnterElements.length) {
  2755. const details = element[REMOVAL_FLAG];
  2756. // animations for move operations (elements being removed and reinserted,
  2757. // e.g. when the order of an *ngFor list changes) are currently not supported
  2758. if (details && details.setForMove) {
  2759. if (details.previousTriggersValues &&
  2760. details.previousTriggersValues.has(entry.triggerName)) {
  2761. const previousValue = details.previousTriggersValues.get(entry.triggerName);
  2762. // we need to restore the previous trigger value since the element has
  2763. // only been moved and hasn't actually left the DOM
  2764. const triggersWithStates = this.statesByElement.get(entry.element);
  2765. if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {
  2766. const state = triggersWithStates.get(entry.triggerName);
  2767. state.value = previousValue;
  2768. triggersWithStates.set(entry.triggerName, state);
  2769. }
  2770. }
  2771. player.destroy();
  2772. return;
  2773. }
  2774. }
  2775. const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);
  2776. const leaveClassName = leaveNodeMapIds.get(element);
  2777. const enterClassName = enterNodeMapIds.get(element);
  2778. const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);
  2779. if (instruction.errors && instruction.errors.length) {
  2780. erroneousTransitions.push(instruction);
  2781. return;
  2782. }
  2783. // even though the element may not be in the DOM, it may still
  2784. // be added at a later point (due to the mechanics of content
  2785. // projection and/or dynamic component insertion) therefore it's
  2786. // important to still style the element.
  2787. if (nodeIsOrphaned) {
  2788. player.onStart(() => eraseStyles(element, instruction.fromStyles));
  2789. player.onDestroy(() => setStyles(element, instruction.toStyles));
  2790. skippedPlayers.push(player);
  2791. return;
  2792. }
  2793. // if an unmatched transition is queued and ready to go
  2794. // then it SHOULD NOT render an animation and cancel the
  2795. // previously running animations.
  2796. if (entry.isFallbackTransition) {
  2797. player.onStart(() => eraseStyles(element, instruction.fromStyles));
  2798. player.onDestroy(() => setStyles(element, instruction.toStyles));
  2799. skippedPlayers.push(player);
  2800. return;
  2801. }
  2802. // this means that if a parent animation uses this animation as a sub-trigger
  2803. // then it will instruct the timeline builder not to add a player delay, but
  2804. // instead stretch the first keyframe gap until the animation starts. This is
  2805. // important in order to prevent extra initialization styles from being
  2806. // required by the user for the animation.
  2807. const timelines = [];
  2808. instruction.timelines.forEach((tl) => {
  2809. tl.stretchStartingKeyframe = true;
  2810. if (!this.disabledNodes.has(tl.element)) {
  2811. timelines.push(tl);
  2812. }
  2813. });
  2814. instruction.timelines = timelines;
  2815. subTimelines.append(element, instruction.timelines);
  2816. const tuple = { instruction, player, element };
  2817. queuedInstructions.push(tuple);
  2818. instruction.queriedElements.forEach((element) => getOrSetDefaultValue(queriedElements, element, []).push(player));
  2819. instruction.preStyleProps.forEach((stringMap, element) => {
  2820. if (stringMap.size) {
  2821. let setVal = allPreStyleElements.get(element);
  2822. if (!setVal) {
  2823. allPreStyleElements.set(element, (setVal = new Set()));
  2824. }
  2825. stringMap.forEach((_, prop) => setVal.add(prop));
  2826. }
  2827. });
  2828. instruction.postStyleProps.forEach((stringMap, element) => {
  2829. let setVal = allPostStyleElements.get(element);
  2830. if (!setVal) {
  2831. allPostStyleElements.set(element, (setVal = new Set()));
  2832. }
  2833. stringMap.forEach((_, prop) => setVal.add(prop));
  2834. });
  2835. });
  2836. }
  2837. if (erroneousTransitions.length) {
  2838. const errors = [];
  2839. erroneousTransitions.forEach((instruction) => {
  2840. errors.push(transitionFailed(instruction.triggerName, instruction.errors));
  2841. });
  2842. allPlayers.forEach((player) => player.destroy());
  2843. this.reportError(errors);
  2844. }
  2845. const allPreviousPlayersMap = new Map();
  2846. // this map tells us which element in the DOM tree is contained by
  2847. // which animation. Further down this map will get populated once
  2848. // the players are built and in doing so we can use it to efficiently
  2849. // figure out if a sub player is skipped due to a parent player having priority.
  2850. const animationElementMap = new Map();
  2851. queuedInstructions.forEach((entry) => {
  2852. const element = entry.element;
  2853. if (subTimelines.has(element)) {
  2854. animationElementMap.set(element, element);
  2855. this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);
  2856. }
  2857. });
  2858. skippedPlayers.forEach((player) => {
  2859. const element = player.element;
  2860. const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);
  2861. previousPlayers.forEach((prevPlayer) => {
  2862. getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);
  2863. prevPlayer.destroy();
  2864. });
  2865. });
  2866. // this is a special case for nodes that will be removed either by
  2867. // having their own leave animations or by being queried in a container
  2868. // that will be removed once a parent animation is complete. The idea
  2869. // here is that * styles must be identical to ! styles because of
  2870. // backwards compatibility (* is also filled in by default in many places).
  2871. // Otherwise * styles will return an empty value or "auto" since the element
  2872. // passed to getComputedStyle will not be visible (since * === destination)
  2873. const replaceNodes = allLeaveNodes.filter((node) => {
  2874. return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);
  2875. });
  2876. // POST STAGE: fill the * styles
  2877. const postStylesMap = new Map();
  2878. const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);
  2879. allLeaveQueriedNodes.forEach((node) => {
  2880. if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {
  2881. replaceNodes.push(node);
  2882. }
  2883. });
  2884. // PRE STAGE: fill the ! styles
  2885. const preStylesMap = new Map();
  2886. enterNodeMap.forEach((nodes, root) => {
  2887. cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, _PRE_STYLE);
  2888. });
  2889. replaceNodes.forEach((node) => {
  2890. const post = postStylesMap.get(node);
  2891. const pre = preStylesMap.get(node);
  2892. postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])]));
  2893. });
  2894. const rootPlayers = [];
  2895. const subPlayers = [];
  2896. const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};
  2897. queuedInstructions.forEach((entry) => {
  2898. const { element, player, instruction } = entry;
  2899. // this means that it was never consumed by a parent animation which
  2900. // means that it is independent and therefore should be set for animation
  2901. if (subTimelines.has(element)) {
  2902. if (disabledElementsSet.has(element)) {
  2903. player.onDestroy(() => setStyles(element, instruction.toStyles));
  2904. player.disabled = true;
  2905. player.overrideTotalTime(instruction.totalTime);
  2906. skippedPlayers.push(player);
  2907. return;
  2908. }
  2909. // this will flow up the DOM and query the map to figure out
  2910. // if a parent animation has priority over it. In the situation
  2911. // that a parent is detected then it will cancel the loop. If
  2912. // nothing is detected, or it takes a few hops to find a parent,
  2913. // then it will fill in the missing nodes and signal them as having
  2914. // a detected parent (or a NO_PARENT value via a special constant).
  2915. let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;
  2916. if (animationElementMap.size > 1) {
  2917. let elm = element;
  2918. const parentsToAdd = [];
  2919. while ((elm = elm.parentNode)) {
  2920. const detectedParent = animationElementMap.get(elm);
  2921. if (detectedParent) {
  2922. parentWithAnimation = detectedParent;
  2923. break;
  2924. }
  2925. parentsToAdd.push(elm);
  2926. }
  2927. parentsToAdd.forEach((parent) => animationElementMap.set(parent, parentWithAnimation));
  2928. }
  2929. const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);
  2930. player.setRealPlayer(innerPlayer);
  2931. if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {
  2932. rootPlayers.push(player);
  2933. }
  2934. else {
  2935. const parentPlayers = this.playersByElement.get(parentWithAnimation);
  2936. if (parentPlayers && parentPlayers.length) {
  2937. player.parentPlayer = optimizeGroupPlayer(parentPlayers);
  2938. }
  2939. skippedPlayers.push(player);
  2940. }
  2941. }
  2942. else {
  2943. eraseStyles(element, instruction.fromStyles);
  2944. player.onDestroy(() => setStyles(element, instruction.toStyles));
  2945. // there still might be a ancestor player animating this
  2946. // element therefore we will still add it as a sub player
  2947. // even if its animation may be disabled
  2948. subPlayers.push(player);
  2949. if (disabledElementsSet.has(element)) {
  2950. skippedPlayers.push(player);
  2951. }
  2952. }
  2953. });
  2954. // find all of the sub players' corresponding inner animation players
  2955. subPlayers.forEach((player) => {
  2956. // even if no players are found for a sub animation it
  2957. // will still complete itself after the next tick since it's Noop
  2958. const playersForElement = skippedPlayersMap.get(player.element);
  2959. if (playersForElement && playersForElement.length) {
  2960. const innerPlayer = optimizeGroupPlayer(playersForElement);
  2961. player.setRealPlayer(innerPlayer);
  2962. }
  2963. });
  2964. // the reason why we don't actually play the animation is
  2965. // because all that a skipped player is designed to do is to
  2966. // fire the start/done transition callback events
  2967. skippedPlayers.forEach((player) => {
  2968. if (player.parentPlayer) {
  2969. player.syncPlayerEvents(player.parentPlayer);
  2970. }
  2971. else {
  2972. player.destroy();
  2973. }
  2974. });
  2975. // run through all of the queued removals and see if they
  2976. // were picked up by a query. If not then perform the removal
  2977. // operation right away unless a parent animation is ongoing.
  2978. for (let i = 0; i < allLeaveNodes.length; i++) {
  2979. const element = allLeaveNodes[i];
  2980. const details = element[REMOVAL_FLAG];
  2981. removeClass(element, LEAVE_CLASSNAME);
  2982. // this means the element has a removal animation that is being
  2983. // taken care of and therefore the inner elements will hang around
  2984. // until that animation is over (or the parent queried animation)
  2985. if (details && details.hasAnimation)
  2986. continue;
  2987. let players = [];
  2988. // if this element is queried or if it contains queried children
  2989. // then we want for the element not to be removed from the page
  2990. // until the queried animations have finished
  2991. if (queriedElements.size) {
  2992. let queriedPlayerResults = queriedElements.get(element);
  2993. if (queriedPlayerResults && queriedPlayerResults.length) {
  2994. players.push(...queriedPlayerResults);
  2995. }
  2996. let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);
  2997. for (let j = 0; j < queriedInnerElements.length; j++) {
  2998. let queriedPlayers = queriedElements.get(queriedInnerElements[j]);
  2999. if (queriedPlayers && queriedPlayers.length) {
  3000. players.push(...queriedPlayers);
  3001. }
  3002. }
  3003. }
  3004. const activePlayers = players.filter((p) => !p.destroyed);
  3005. if (activePlayers.length) {
  3006. removeNodesAfterAnimationDone(this, element, activePlayers);
  3007. }
  3008. else {
  3009. this.processLeaveNode(element);
  3010. }
  3011. }
  3012. // this is required so the cleanup method doesn't remove them
  3013. allLeaveNodes.length = 0;
  3014. rootPlayers.forEach((player) => {
  3015. this.players.push(player);
  3016. player.onDone(() => {
  3017. player.destroy();
  3018. const index = this.players.indexOf(player);
  3019. this.players.splice(index, 1);
  3020. });
  3021. player.play();
  3022. });
  3023. return rootPlayers;
  3024. }
  3025. afterFlush(callback) {
  3026. this._flushFns.push(callback);
  3027. }
  3028. afterFlushAnimationsDone(callback) {
  3029. this._whenQuietFns.push(callback);
  3030. }
  3031. _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {
  3032. let players = [];
  3033. if (isQueriedElement) {
  3034. const queriedElementPlayers = this.playersByQueriedElement.get(element);
  3035. if (queriedElementPlayers) {
  3036. players = queriedElementPlayers;
  3037. }
  3038. }
  3039. else {
  3040. const elementPlayers = this.playersByElement.get(element);
  3041. if (elementPlayers) {
  3042. const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;
  3043. elementPlayers.forEach((player) => {
  3044. if (player.queued)
  3045. return;
  3046. if (!isRemovalAnimation && player.triggerName != triggerName)
  3047. return;
  3048. players.push(player);
  3049. });
  3050. }
  3051. }
  3052. if (namespaceId || triggerName) {
  3053. players = players.filter((player) => {
  3054. if (namespaceId && namespaceId != player.namespaceId)
  3055. return false;
  3056. if (triggerName && triggerName != player.triggerName)
  3057. return false;
  3058. return true;
  3059. });
  3060. }
  3061. return players;
  3062. }
  3063. _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {
  3064. const triggerName = instruction.triggerName;
  3065. const rootElement = instruction.element;
  3066. // when a removal animation occurs, ALL previous players are collected
  3067. // and destroyed (even if they are outside of the current namespace)
  3068. const targetNameSpaceId = instruction.isRemovalTransition
  3069. ? undefined
  3070. : namespaceId;
  3071. const targetTriggerName = instruction.isRemovalTransition
  3072. ? undefined
  3073. : triggerName;
  3074. for (const timelineInstruction of instruction.timelines) {
  3075. const element = timelineInstruction.element;
  3076. const isQueriedElement = element !== rootElement;
  3077. const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);
  3078. const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);
  3079. previousPlayers.forEach((player) => {
  3080. const realPlayer = player.getRealPlayer();
  3081. if (realPlayer.beforeDestroy) {
  3082. realPlayer.beforeDestroy();
  3083. }
  3084. player.destroy();
  3085. players.push(player);
  3086. });
  3087. }
  3088. // this needs to be done so that the PRE/POST styles can be
  3089. // computed properly without interfering with the previous animation
  3090. eraseStyles(rootElement, instruction.fromStyles);
  3091. }
  3092. _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {
  3093. const triggerName = instruction.triggerName;
  3094. const rootElement = instruction.element;
  3095. // we first run this so that the previous animation player
  3096. // data can be passed into the successive animation players
  3097. const allQueriedPlayers = [];
  3098. const allConsumedElements = new Set();
  3099. const allSubElements = new Set();
  3100. const allNewPlayers = instruction.timelines.map((timelineInstruction) => {
  3101. const element = timelineInstruction.element;
  3102. allConsumedElements.add(element);
  3103. // FIXME (matsko): make sure to-be-removed animations are removed properly
  3104. const details = element[REMOVAL_FLAG];
  3105. if (details && details.removedBeforeQueried)
  3106. return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);
  3107. const isQueriedElement = element !== rootElement;
  3108. const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map((p) => p.getRealPlayer())).filter((p) => {
  3109. // the `element` is not apart of the AnimationPlayer definition, but
  3110. // Mock/WebAnimations
  3111. // use the element within their implementation. This will be added in Angular5 to
  3112. // AnimationPlayer
  3113. const pp = p;
  3114. return pp.element ? pp.element === element : false;
  3115. });
  3116. const preStyles = preStylesMap.get(element);
  3117. const postStyles = postStylesMap.get(element);
  3118. const keyframes = normalizeKeyframes(this._normalizer, timelineInstruction.keyframes, preStyles, postStyles);
  3119. const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);
  3120. // this means that this particular player belongs to a sub trigger. It is
  3121. // important that we match this player up with the corresponding (@trigger.listener)
  3122. if (timelineInstruction.subTimeline && skippedPlayersMap) {
  3123. allSubElements.add(element);
  3124. }
  3125. if (isQueriedElement) {
  3126. const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);
  3127. wrappedPlayer.setRealPlayer(player);
  3128. allQueriedPlayers.push(wrappedPlayer);
  3129. }
  3130. return player;
  3131. });
  3132. allQueriedPlayers.forEach((player) => {
  3133. getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);
  3134. player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));
  3135. });
  3136. allConsumedElements.forEach((element) => addClass(element, NG_ANIMATING_CLASSNAME));
  3137. const player = optimizeGroupPlayer(allNewPlayers);
  3138. player.onDestroy(() => {
  3139. allConsumedElements.forEach((element) => removeClass(element, NG_ANIMATING_CLASSNAME));
  3140. setStyles(rootElement, instruction.toStyles);
  3141. });
  3142. // this basically makes all of the callbacks for sub element animations
  3143. // be dependent on the upper players for when they finish
  3144. allSubElements.forEach((element) => {
  3145. getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);
  3146. });
  3147. return player;
  3148. }
  3149. _buildPlayer(instruction, keyframes, previousPlayers) {
  3150. if (keyframes.length > 0) {
  3151. return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);
  3152. }
  3153. // special case for when an empty transition|definition is provided
  3154. // ... there is no point in rendering an empty animation
  3155. return new NoopAnimationPlayer(instruction.duration, instruction.delay);
  3156. }
  3157. }
  3158. class TransitionAnimationPlayer {
  3159. namespaceId;
  3160. triggerName;
  3161. element;
  3162. _player = new NoopAnimationPlayer();
  3163. _containsRealPlayer = false;
  3164. _queuedCallbacks = new Map();
  3165. destroyed = false;
  3166. parentPlayer = null;
  3167. markedForDestroy = false;
  3168. disabled = false;
  3169. queued = true;
  3170. totalTime = 0;
  3171. constructor(namespaceId, triggerName, element) {
  3172. this.namespaceId = namespaceId;
  3173. this.triggerName = triggerName;
  3174. this.element = element;
  3175. }
  3176. setRealPlayer(player) {
  3177. if (this._containsRealPlayer)
  3178. return;
  3179. this._player = player;
  3180. this._queuedCallbacks.forEach((callbacks, phase) => {
  3181. callbacks.forEach((callback) => listenOnPlayer(player, phase, undefined, callback));
  3182. });
  3183. this._queuedCallbacks.clear();
  3184. this._containsRealPlayer = true;
  3185. this.overrideTotalTime(player.totalTime);
  3186. this.queued = false;
  3187. }
  3188. getRealPlayer() {
  3189. return this._player;
  3190. }
  3191. overrideTotalTime(totalTime) {
  3192. this.totalTime = totalTime;
  3193. }
  3194. syncPlayerEvents(player) {
  3195. const p = this._player;
  3196. if (p.triggerCallback) {
  3197. player.onStart(() => p.triggerCallback('start'));
  3198. }
  3199. player.onDone(() => this.finish());
  3200. player.onDestroy(() => this.destroy());
  3201. }
  3202. _queueEvent(name, callback) {
  3203. getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);
  3204. }
  3205. onDone(fn) {
  3206. if (this.queued) {
  3207. this._queueEvent('done', fn);
  3208. }
  3209. this._player.onDone(fn);
  3210. }
  3211. onStart(fn) {
  3212. if (this.queued) {
  3213. this._queueEvent('start', fn);
  3214. }
  3215. this._player.onStart(fn);
  3216. }
  3217. onDestroy(fn) {
  3218. if (this.queued) {
  3219. this._queueEvent('destroy', fn);
  3220. }
  3221. this._player.onDestroy(fn);
  3222. }
  3223. init() {
  3224. this._player.init();
  3225. }
  3226. hasStarted() {
  3227. return this.queued ? false : this._player.hasStarted();
  3228. }
  3229. play() {
  3230. !this.queued && this._player.play();
  3231. }
  3232. pause() {
  3233. !this.queued && this._player.pause();
  3234. }
  3235. restart() {
  3236. !this.queued && this._player.restart();
  3237. }
  3238. finish() {
  3239. this._player.finish();
  3240. }
  3241. destroy() {
  3242. this.destroyed = true;
  3243. this._player.destroy();
  3244. }
  3245. reset() {
  3246. !this.queued && this._player.reset();
  3247. }
  3248. setPosition(p) {
  3249. if (!this.queued) {
  3250. this._player.setPosition(p);
  3251. }
  3252. }
  3253. getPosition() {
  3254. return this.queued ? 0 : this._player.getPosition();
  3255. }
  3256. /** @internal */
  3257. triggerCallback(phaseName) {
  3258. const p = this._player;
  3259. if (p.triggerCallback) {
  3260. p.triggerCallback(phaseName);
  3261. }
  3262. }
  3263. }
  3264. function deleteOrUnsetInMap(map, key, value) {
  3265. let currentValues = map.get(key);
  3266. if (currentValues) {
  3267. if (currentValues.length) {
  3268. const index = currentValues.indexOf(value);
  3269. currentValues.splice(index, 1);
  3270. }
  3271. if (currentValues.length == 0) {
  3272. map.delete(key);
  3273. }
  3274. }
  3275. return currentValues;
  3276. }
  3277. function normalizeTriggerValue(value) {
  3278. // we use `!= null` here because it's the most simple
  3279. // way to test against a "falsy" value without mixing
  3280. // in empty strings or a zero value. DO NOT OPTIMIZE.
  3281. return value != null ? value : null;
  3282. }
  3283. function isElementNode(node) {
  3284. return node && node['nodeType'] === 1;
  3285. }
  3286. function isTriggerEventValid(eventName) {
  3287. return eventName == 'start' || eventName == 'done';
  3288. }
  3289. function cloakElement(element, value) {
  3290. const oldValue = element.style.display;
  3291. element.style.display = value != null ? value : 'none';
  3292. return oldValue;
  3293. }
  3294. function cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {
  3295. const cloakVals = [];
  3296. elements.forEach((element) => cloakVals.push(cloakElement(element)));
  3297. const failedElements = [];
  3298. elementPropsMap.forEach((props, element) => {
  3299. const styles = new Map();
  3300. props.forEach((prop) => {
  3301. const value = driver.computeStyle(element, prop, defaultStyle);
  3302. styles.set(prop, value);
  3303. // there is no easy way to detect this because a sub element could be removed
  3304. // by a parent animation element being detached.
  3305. if (!value || value.length == 0) {
  3306. element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;
  3307. failedElements.push(element);
  3308. }
  3309. });
  3310. valuesMap.set(element, styles);
  3311. });
  3312. // we use a index variable here since Set.forEach(a, i) does not return
  3313. // an index value for the closure (but instead just the value)
  3314. let i = 0;
  3315. elements.forEach((element) => cloakElement(element, cloakVals[i++]));
  3316. return failedElements;
  3317. }
  3318. /*
  3319. Since the Angular renderer code will return a collection of inserted
  3320. nodes in all areas of a DOM tree, it's up to this algorithm to figure
  3321. out which nodes are roots for each animation @trigger.
  3322. By placing each inserted node into a Set and traversing upwards, it
  3323. is possible to find the @trigger elements and well any direct *star
  3324. insertion nodes, if a @trigger root is found then the enter element
  3325. is placed into the Map[@trigger] spot.
  3326. */
  3327. function buildRootMap(roots, nodes) {
  3328. const rootMap = new Map();
  3329. roots.forEach((root) => rootMap.set(root, []));
  3330. if (nodes.length == 0)
  3331. return rootMap;
  3332. const NULL_NODE = 1;
  3333. const nodeSet = new Set(nodes);
  3334. const localRootMap = new Map();
  3335. function getRoot(node) {
  3336. if (!node)
  3337. return NULL_NODE;
  3338. let root = localRootMap.get(node);
  3339. if (root)
  3340. return root;
  3341. const parent = node.parentNode;
  3342. if (rootMap.has(parent)) {
  3343. // ngIf inside @trigger
  3344. root = parent;
  3345. }
  3346. else if (nodeSet.has(parent)) {
  3347. // ngIf inside ngIf
  3348. root = NULL_NODE;
  3349. }
  3350. else {
  3351. // recurse upwards
  3352. root = getRoot(parent);
  3353. }
  3354. localRootMap.set(node, root);
  3355. return root;
  3356. }
  3357. nodes.forEach((node) => {
  3358. const root = getRoot(node);
  3359. if (root !== NULL_NODE) {
  3360. rootMap.get(root).push(node);
  3361. }
  3362. });
  3363. return rootMap;
  3364. }
  3365. function addClass(element, className) {
  3366. element.classList?.add(className);
  3367. }
  3368. function removeClass(element, className) {
  3369. element.classList?.remove(className);
  3370. }
  3371. function removeNodesAfterAnimationDone(engine, element, players) {
  3372. optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
  3373. }
  3374. function flattenGroupPlayers(players) {
  3375. const finalPlayers = [];
  3376. _flattenGroupPlayersRecur(players, finalPlayers);
  3377. return finalPlayers;
  3378. }
  3379. function _flattenGroupPlayersRecur(players, finalPlayers) {
  3380. for (let i = 0; i < players.length; i++) {
  3381. const player = players[i];
  3382. if (player instanceof AnimationGroupPlayer) {
  3383. _flattenGroupPlayersRecur(player.players, finalPlayers);
  3384. }
  3385. else {
  3386. finalPlayers.push(player);
  3387. }
  3388. }
  3389. }
  3390. function objEquals(a, b) {
  3391. const k1 = Object.keys(a);
  3392. const k2 = Object.keys(b);
  3393. if (k1.length != k2.length)
  3394. return false;
  3395. for (let i = 0; i < k1.length; i++) {
  3396. const prop = k1[i];
  3397. if (!b.hasOwnProperty(prop) || a[prop] !== b[prop])
  3398. return false;
  3399. }
  3400. return true;
  3401. }
  3402. function replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {
  3403. const postEntry = allPostStyleElements.get(element);
  3404. if (!postEntry)
  3405. return false;
  3406. let preEntry = allPreStyleElements.get(element);
  3407. if (preEntry) {
  3408. postEntry.forEach((data) => preEntry.add(data));
  3409. }
  3410. else {
  3411. allPreStyleElements.set(element, postEntry);
  3412. }
  3413. allPostStyleElements.delete(element);
  3414. return true;
  3415. }
  3416. class AnimationEngine {
  3417. _driver;
  3418. _normalizer;
  3419. _transitionEngine;
  3420. _timelineEngine;
  3421. _triggerCache = {};
  3422. // this method is designed to be overridden by the code that uses this engine
  3423. onRemovalComplete = (element, context) => { };
  3424. constructor(doc, _driver, _normalizer) {
  3425. this._driver = _driver;
  3426. this._normalizer = _normalizer;
  3427. this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer);
  3428. this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);
  3429. this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);
  3430. }
  3431. registerTrigger(componentId, namespaceId, hostElement, name, metadata) {
  3432. const cacheKey = componentId + '-' + name;
  3433. let trigger = this._triggerCache[cacheKey];
  3434. if (!trigger) {
  3435. const errors = [];
  3436. const warnings = [];
  3437. const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
  3438. if (errors.length) {
  3439. throw triggerBuildFailed(name, errors);
  3440. }
  3441. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3442. if (warnings.length) {
  3443. warnTriggerBuild(name, warnings);
  3444. }
  3445. }
  3446. trigger = buildTrigger(name, ast, this._normalizer);
  3447. this._triggerCache[cacheKey] = trigger;
  3448. }
  3449. this._transitionEngine.registerTrigger(namespaceId, name, trigger);
  3450. }
  3451. register(namespaceId, hostElement) {
  3452. this._transitionEngine.register(namespaceId, hostElement);
  3453. }
  3454. destroy(namespaceId, context) {
  3455. this._transitionEngine.destroy(namespaceId, context);
  3456. }
  3457. onInsert(namespaceId, element, parent, insertBefore) {
  3458. this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
  3459. }
  3460. onRemove(namespaceId, element, context) {
  3461. this._transitionEngine.removeNode(namespaceId, element, context);
  3462. }
  3463. disableAnimations(element, disable) {
  3464. this._transitionEngine.markElementAsDisabled(element, disable);
  3465. }
  3466. process(namespaceId, element, property, value) {
  3467. if (property.charAt(0) == '@') {
  3468. const [id, action] = parseTimelineCommand(property);
  3469. const args = value;
  3470. this._timelineEngine.command(id, element, action, args);
  3471. }
  3472. else {
  3473. this._transitionEngine.trigger(namespaceId, element, property, value);
  3474. }
  3475. }
  3476. listen(namespaceId, element, eventName, eventPhase, callback) {
  3477. // @@listen
  3478. if (eventName.charAt(0) == '@') {
  3479. const [id, action] = parseTimelineCommand(eventName);
  3480. return this._timelineEngine.listen(id, element, action, callback);
  3481. }
  3482. return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
  3483. }
  3484. flush(microtaskId = -1) {
  3485. this._transitionEngine.flush(microtaskId);
  3486. }
  3487. get players() {
  3488. return [...this._transitionEngine.players, ...this._timelineEngine.players];
  3489. }
  3490. whenRenderingDone() {
  3491. return this._transitionEngine.whenRenderingDone();
  3492. }
  3493. afterFlushAnimationsDone(cb) {
  3494. this._transitionEngine.afterFlushAnimationsDone(cb);
  3495. }
  3496. }
  3497. /**
  3498. * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are
  3499. * detected.
  3500. *
  3501. * In CSS there exist properties that cannot be animated within a keyframe animation
  3502. * (whether it be via CSS keyframes or web-animations) and the animation implementation
  3503. * will ignore them. This function is designed to detect those special cased styles and
  3504. * return a container that will be executed at the start and end of the animation.
  3505. *
  3506. * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`
  3507. */
  3508. function packageNonAnimatableStyles(element, styles) {
  3509. let startStyles = null;
  3510. let endStyles = null;
  3511. if (Array.isArray(styles) && styles.length) {
  3512. startStyles = filterNonAnimatableStyles(styles[0]);
  3513. if (styles.length > 1) {
  3514. endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);
  3515. }
  3516. }
  3517. else if (styles instanceof Map) {
  3518. startStyles = filterNonAnimatableStyles(styles);
  3519. }
  3520. return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;
  3521. }
  3522. /**
  3523. * Designed to be executed during a keyframe-based animation to apply any special-cased styles.
  3524. *
  3525. * When started (when the `start()` method is run) then the provided `startStyles`
  3526. * will be applied. When finished (when the `finish()` method is called) the
  3527. * `endStyles` will be applied as well any any starting styles. Finally when
  3528. * `destroy()` is called then all styles will be removed.
  3529. */
  3530. class SpecialCasedStyles {
  3531. _element;
  3532. _startStyles;
  3533. _endStyles;
  3534. static initialStylesByElement = /* @__PURE__ */ new WeakMap();
  3535. _state = 0 /* SpecialCasedStylesState.Pending */;
  3536. _initialStyles;
  3537. constructor(_element, _startStyles, _endStyles) {
  3538. this._element = _element;
  3539. this._startStyles = _startStyles;
  3540. this._endStyles = _endStyles;
  3541. let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);
  3542. if (!initialStyles) {
  3543. SpecialCasedStyles.initialStylesByElement.set(_element, (initialStyles = new Map()));
  3544. }
  3545. this._initialStyles = initialStyles;
  3546. }
  3547. start() {
  3548. if (this._state < 1 /* SpecialCasedStylesState.Started */) {
  3549. if (this._startStyles) {
  3550. setStyles(this._element, this._startStyles, this._initialStyles);
  3551. }
  3552. this._state = 1 /* SpecialCasedStylesState.Started */;
  3553. }
  3554. }
  3555. finish() {
  3556. this.start();
  3557. if (this._state < 2 /* SpecialCasedStylesState.Finished */) {
  3558. setStyles(this._element, this._initialStyles);
  3559. if (this._endStyles) {
  3560. setStyles(this._element, this._endStyles);
  3561. this._endStyles = null;
  3562. }
  3563. this._state = 1 /* SpecialCasedStylesState.Started */;
  3564. }
  3565. }
  3566. destroy() {
  3567. this.finish();
  3568. if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {
  3569. SpecialCasedStyles.initialStylesByElement.delete(this._element);
  3570. if (this._startStyles) {
  3571. eraseStyles(this._element, this._startStyles);
  3572. this._endStyles = null;
  3573. }
  3574. if (this._endStyles) {
  3575. eraseStyles(this._element, this._endStyles);
  3576. this._endStyles = null;
  3577. }
  3578. setStyles(this._element, this._initialStyles);
  3579. this._state = 3 /* SpecialCasedStylesState.Destroyed */;
  3580. }
  3581. }
  3582. }
  3583. function filterNonAnimatableStyles(styles) {
  3584. let result = null;
  3585. styles.forEach((val, prop) => {
  3586. if (isNonAnimatableStyle(prop)) {
  3587. result = result || new Map();
  3588. result.set(prop, val);
  3589. }
  3590. });
  3591. return result;
  3592. }
  3593. function isNonAnimatableStyle(prop) {
  3594. return prop === 'display' || prop === 'position';
  3595. }
  3596. class WebAnimationsPlayer {
  3597. element;
  3598. keyframes;
  3599. options;
  3600. _specialStyles;
  3601. _onDoneFns = [];
  3602. _onStartFns = [];
  3603. _onDestroyFns = [];
  3604. _duration;
  3605. _delay;
  3606. _initialized = false;
  3607. _finished = false;
  3608. _started = false;
  3609. _destroyed = false;
  3610. _finalKeyframe;
  3611. // the following original fns are persistent copies of the _onStartFns and _onDoneFns
  3612. // and are used to reset the fns to their original values upon reset()
  3613. // (since the _onStartFns and _onDoneFns get deleted after they are called)
  3614. _originalOnDoneFns = [];
  3615. _originalOnStartFns = [];
  3616. // using non-null assertion because it's re(set) by init();
  3617. domPlayer;
  3618. time = 0;
  3619. parentPlayer = null;
  3620. currentSnapshot = new Map();
  3621. constructor(element, keyframes, options, _specialStyles) {
  3622. this.element = element;
  3623. this.keyframes = keyframes;
  3624. this.options = options;
  3625. this._specialStyles = _specialStyles;
  3626. this._duration = options['duration'];
  3627. this._delay = options['delay'] || 0;
  3628. this.time = this._duration + this._delay;
  3629. }
  3630. _onFinish() {
  3631. if (!this._finished) {
  3632. this._finished = true;
  3633. this._onDoneFns.forEach((fn) => fn());
  3634. this._onDoneFns = [];
  3635. }
  3636. }
  3637. init() {
  3638. this._buildPlayer();
  3639. this._preparePlayerBeforeStart();
  3640. }
  3641. _buildPlayer() {
  3642. if (this._initialized)
  3643. return;
  3644. this._initialized = true;
  3645. const keyframes = this.keyframes;
  3646. // @ts-expect-error overwriting a readonly property
  3647. this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);
  3648. this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();
  3649. const onFinish = () => this._onFinish();
  3650. this.domPlayer.addEventListener('finish', onFinish);
  3651. this.onDestroy(() => {
  3652. // We must remove the `finish` event listener once an animation has completed all its
  3653. // iterations. This action is necessary to prevent a memory leak since the listener captures
  3654. // `this`, creating a closure that prevents `this` from being garbage collected.
  3655. this.domPlayer.removeEventListener('finish', onFinish);
  3656. });
  3657. }
  3658. _preparePlayerBeforeStart() {
  3659. // this is required so that the player doesn't start to animate right away
  3660. if (this._delay) {
  3661. this._resetDomPlayerState();
  3662. }
  3663. else {
  3664. this.domPlayer.pause();
  3665. }
  3666. }
  3667. _convertKeyframesToObject(keyframes) {
  3668. const kfs = [];
  3669. keyframes.forEach((frame) => {
  3670. kfs.push(Object.fromEntries(frame));
  3671. });
  3672. return kfs;
  3673. }
  3674. /** @internal */
  3675. _triggerWebAnimation(element, keyframes, options) {
  3676. return element.animate(this._convertKeyframesToObject(keyframes), options);
  3677. }
  3678. onStart(fn) {
  3679. this._originalOnStartFns.push(fn);
  3680. this._onStartFns.push(fn);
  3681. }
  3682. onDone(fn) {
  3683. this._originalOnDoneFns.push(fn);
  3684. this._onDoneFns.push(fn);
  3685. }
  3686. onDestroy(fn) {
  3687. this._onDestroyFns.push(fn);
  3688. }
  3689. play() {
  3690. this._buildPlayer();
  3691. if (!this.hasStarted()) {
  3692. this._onStartFns.forEach((fn) => fn());
  3693. this._onStartFns = [];
  3694. this._started = true;
  3695. if (this._specialStyles) {
  3696. this._specialStyles.start();
  3697. }
  3698. }
  3699. this.domPlayer.play();
  3700. }
  3701. pause() {
  3702. this.init();
  3703. this.domPlayer.pause();
  3704. }
  3705. finish() {
  3706. this.init();
  3707. if (this._specialStyles) {
  3708. this._specialStyles.finish();
  3709. }
  3710. this._onFinish();
  3711. this.domPlayer.finish();
  3712. }
  3713. reset() {
  3714. this._resetDomPlayerState();
  3715. this._destroyed = false;
  3716. this._finished = false;
  3717. this._started = false;
  3718. this._onStartFns = this._originalOnStartFns;
  3719. this._onDoneFns = this._originalOnDoneFns;
  3720. }
  3721. _resetDomPlayerState() {
  3722. if (this.domPlayer) {
  3723. this.domPlayer.cancel();
  3724. }
  3725. }
  3726. restart() {
  3727. this.reset();
  3728. this.play();
  3729. }
  3730. hasStarted() {
  3731. return this._started;
  3732. }
  3733. destroy() {
  3734. if (!this._destroyed) {
  3735. this._destroyed = true;
  3736. this._resetDomPlayerState();
  3737. this._onFinish();
  3738. if (this._specialStyles) {
  3739. this._specialStyles.destroy();
  3740. }
  3741. this._onDestroyFns.forEach((fn) => fn());
  3742. this._onDestroyFns = [];
  3743. }
  3744. }
  3745. setPosition(p) {
  3746. if (this.domPlayer === undefined) {
  3747. this.init();
  3748. }
  3749. this.domPlayer.currentTime = p * this.time;
  3750. }
  3751. getPosition() {
  3752. // tsc is complaining with TS2362 without the conversion to number
  3753. return +(this.domPlayer.currentTime ?? 0) / this.time;
  3754. }
  3755. get totalTime() {
  3756. return this._delay + this._duration;
  3757. }
  3758. beforeDestroy() {
  3759. const styles = new Map();
  3760. if (this.hasStarted()) {
  3761. // note: this code is invoked only when the `play` function was called prior to this
  3762. // (thus `hasStarted` returns true), this implies that the code that initializes
  3763. // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here
  3764. const finalKeyframe = this._finalKeyframe;
  3765. finalKeyframe.forEach((val, prop) => {
  3766. if (prop !== 'offset') {
  3767. styles.set(prop, this._finished ? val : computeStyle(this.element, prop));
  3768. }
  3769. });
  3770. }
  3771. this.currentSnapshot = styles;
  3772. }
  3773. /** @internal */
  3774. triggerCallback(phaseName) {
  3775. const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;
  3776. methods.forEach((fn) => fn());
  3777. methods.length = 0;
  3778. }
  3779. }
  3780. class WebAnimationsDriver {
  3781. validateStyleProperty(prop) {
  3782. // Perform actual validation in dev mode only, in prod mode this check is a noop.
  3783. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3784. return validateStyleProperty(prop);
  3785. }
  3786. return true;
  3787. }
  3788. validateAnimatableStyleProperty(prop) {
  3789. // Perform actual validation in dev mode only, in prod mode this check is a noop.
  3790. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3791. const cssProp = camelCaseToDashCase(prop);
  3792. return validateWebAnimatableStyleProperty(cssProp);
  3793. }
  3794. return true;
  3795. }
  3796. containsElement(elm1, elm2) {
  3797. return containsElement(elm1, elm2);
  3798. }
  3799. getParentElement(element) {
  3800. return getParentElement(element);
  3801. }
  3802. query(element, selector, multi) {
  3803. return invokeQuery(element, selector, multi);
  3804. }
  3805. computeStyle(element, prop, defaultValue) {
  3806. return computeStyle(element, prop);
  3807. }
  3808. animate(element, keyframes, duration, delay, easing, previousPlayers = []) {
  3809. const fill = delay == 0 ? 'both' : 'forwards';
  3810. const playerOptions = { duration, delay, fill };
  3811. // we check for this to avoid having a null|undefined value be present
  3812. // for the easing (which results in an error for certain browsers #9752)
  3813. if (easing) {
  3814. playerOptions['easing'] = easing;
  3815. }
  3816. const previousStyles = new Map();
  3817. const previousWebAnimationPlayers = (previousPlayers.filter((player) => player instanceof WebAnimationsPlayer));
  3818. if (allowPreviousPlayerStylesMerge(duration, delay)) {
  3819. previousWebAnimationPlayers.forEach((player) => {
  3820. player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));
  3821. });
  3822. }
  3823. let _keyframes = normalizeKeyframes$1(keyframes).map((styles) => new Map(styles));
  3824. _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);
  3825. const specialStyles = packageNonAnimatableStyles(element, _keyframes);
  3826. return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);
  3827. }
  3828. }
  3829. function createEngine(type, doc) {
  3830. // TODO: find a way to make this tree shakable.
  3831. if (type === 'noop') {
  3832. return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer());
  3833. }
  3834. return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer());
  3835. }
  3836. class Animation {
  3837. _driver;
  3838. _animationAst;
  3839. constructor(_driver, input) {
  3840. this._driver = _driver;
  3841. const errors = [];
  3842. const warnings = [];
  3843. const ast = buildAnimationAst(_driver, input, errors, warnings);
  3844. if (errors.length) {
  3845. throw validationFailed(errors);
  3846. }
  3847. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3848. if (warnings.length) {
  3849. warnValidation(warnings);
  3850. }
  3851. }
  3852. this._animationAst = ast;
  3853. }
  3854. buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {
  3855. const start = Array.isArray(startingStyles)
  3856. ? normalizeStyles(startingStyles)
  3857. : startingStyles;
  3858. const dest = Array.isArray(destinationStyles)
  3859. ? normalizeStyles(destinationStyles)
  3860. : destinationStyles;
  3861. const errors = [];
  3862. subInstructions = subInstructions || new ElementInstructionMap();
  3863. const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);
  3864. if (errors.length) {
  3865. throw buildingFailed(errors);
  3866. }
  3867. return result;
  3868. }
  3869. }
  3870. const ANIMATION_PREFIX = '@';
  3871. const DISABLE_ANIMATIONS_FLAG = '@.disabled';
  3872. class BaseAnimationRenderer {
  3873. namespaceId;
  3874. delegate;
  3875. engine;
  3876. _onDestroy;
  3877. // We need to explicitly type this property because of an api-extractor bug
  3878. // See https://github.com/microsoft/rushstack/issues/4390
  3879. ɵtype = 0 /* AnimationRendererType.Regular */;
  3880. constructor(namespaceId, delegate, engine, _onDestroy) {
  3881. this.namespaceId = namespaceId;
  3882. this.delegate = delegate;
  3883. this.engine = engine;
  3884. this._onDestroy = _onDestroy;
  3885. }
  3886. get data() {
  3887. return this.delegate.data;
  3888. }
  3889. destroyNode(node) {
  3890. this.delegate.destroyNode?.(node);
  3891. }
  3892. destroy() {
  3893. this.engine.destroy(this.namespaceId, this.delegate);
  3894. this.engine.afterFlushAnimationsDone(() => {
  3895. // Call the renderer destroy method after the animations has finished as otherwise
  3896. // styles will be removed too early which will cause an unstyled animation.
  3897. queueMicrotask(() => {
  3898. this.delegate.destroy();
  3899. });
  3900. });
  3901. this._onDestroy?.();
  3902. }
  3903. createElement(name, namespace) {
  3904. return this.delegate.createElement(name, namespace);
  3905. }
  3906. createComment(value) {
  3907. return this.delegate.createComment(value);
  3908. }
  3909. createText(value) {
  3910. return this.delegate.createText(value);
  3911. }
  3912. appendChild(parent, newChild) {
  3913. this.delegate.appendChild(parent, newChild);
  3914. this.engine.onInsert(this.namespaceId, newChild, parent, false);
  3915. }
  3916. insertBefore(parent, newChild, refChild, isMove = true) {
  3917. this.delegate.insertBefore(parent, newChild, refChild);
  3918. // If `isMove` true than we should animate this insert.
  3919. this.engine.onInsert(this.namespaceId, newChild, parent, isMove);
  3920. }
  3921. removeChild(parent, oldChild, isHostElement) {
  3922. // Prior to the changes in #57203, this method wasn't being called at all by `core` if the child
  3923. // doesn't have a parent. There appears to be some animation-specific downstream logic that
  3924. // depends on the null check happening before the animation engine. This check keeps the old
  3925. // behavior while allowing `core` to not have to check for the parent element anymore.
  3926. if (this.parentNode(oldChild)) {
  3927. this.engine.onRemove(this.namespaceId, oldChild, this.delegate);
  3928. }
  3929. }
  3930. selectRootElement(selectorOrNode, preserveContent) {
  3931. return this.delegate.selectRootElement(selectorOrNode, preserveContent);
  3932. }
  3933. parentNode(node) {
  3934. return this.delegate.parentNode(node);
  3935. }
  3936. nextSibling(node) {
  3937. return this.delegate.nextSibling(node);
  3938. }
  3939. setAttribute(el, name, value, namespace) {
  3940. this.delegate.setAttribute(el, name, value, namespace);
  3941. }
  3942. removeAttribute(el, name, namespace) {
  3943. this.delegate.removeAttribute(el, name, namespace);
  3944. }
  3945. addClass(el, name) {
  3946. this.delegate.addClass(el, name);
  3947. }
  3948. removeClass(el, name) {
  3949. this.delegate.removeClass(el, name);
  3950. }
  3951. setStyle(el, style, value, flags) {
  3952. this.delegate.setStyle(el, style, value, flags);
  3953. }
  3954. removeStyle(el, style, flags) {
  3955. this.delegate.removeStyle(el, style, flags);
  3956. }
  3957. setProperty(el, name, value) {
  3958. if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) {
  3959. this.disableAnimations(el, !!value);
  3960. }
  3961. else {
  3962. this.delegate.setProperty(el, name, value);
  3963. }
  3964. }
  3965. setValue(node, value) {
  3966. this.delegate.setValue(node, value);
  3967. }
  3968. listen(target, eventName, callback, options) {
  3969. return this.delegate.listen(target, eventName, callback, options);
  3970. }
  3971. disableAnimations(element, value) {
  3972. this.engine.disableAnimations(element, value);
  3973. }
  3974. }
  3975. class AnimationRenderer extends BaseAnimationRenderer {
  3976. factory;
  3977. constructor(factory, namespaceId, delegate, engine, onDestroy) {
  3978. super(namespaceId, delegate, engine, onDestroy);
  3979. this.factory = factory;
  3980. this.namespaceId = namespaceId;
  3981. }
  3982. setProperty(el, name, value) {
  3983. if (name.charAt(0) == ANIMATION_PREFIX) {
  3984. if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) {
  3985. value = value === undefined ? true : !!value;
  3986. this.disableAnimations(el, value);
  3987. }
  3988. else {
  3989. this.engine.process(this.namespaceId, el, name.slice(1), value);
  3990. }
  3991. }
  3992. else {
  3993. this.delegate.setProperty(el, name, value);
  3994. }
  3995. }
  3996. listen(target, eventName, callback, options) {
  3997. if (eventName.charAt(0) == ANIMATION_PREFIX) {
  3998. const element = resolveElementFromTarget(target);
  3999. let name = eventName.slice(1);
  4000. let phase = '';
  4001. // @listener.phase is for trigger animation callbacks
  4002. // @@listener is for animation builder callbacks
  4003. if (name.charAt(0) != ANIMATION_PREFIX) {
  4004. [name, phase] = parseTriggerCallbackName(name);
  4005. }
  4006. return this.engine.listen(this.namespaceId, element, name, phase, (event) => {
  4007. const countId = event['_data'] || -1;
  4008. this.factory.scheduleListenerCallback(countId, callback, event);
  4009. });
  4010. }
  4011. return this.delegate.listen(target, eventName, callback, options);
  4012. }
  4013. }
  4014. function resolveElementFromTarget(target) {
  4015. switch (target) {
  4016. case 'body':
  4017. return document.body;
  4018. case 'document':
  4019. return document;
  4020. case 'window':
  4021. return window;
  4022. default:
  4023. return target;
  4024. }
  4025. }
  4026. function parseTriggerCallbackName(triggerName) {
  4027. const dotIndex = triggerName.indexOf('.');
  4028. const trigger = triggerName.substring(0, dotIndex);
  4029. const phase = triggerName.slice(dotIndex + 1);
  4030. return [trigger, phase];
  4031. }
  4032. class AnimationRendererFactory {
  4033. delegate;
  4034. engine;
  4035. _zone;
  4036. _currentId = 0;
  4037. _microtaskId = 1;
  4038. _animationCallbacksBuffer = [];
  4039. _rendererCache = new Map();
  4040. _cdRecurDepth = 0;
  4041. constructor(delegate, engine, _zone) {
  4042. this.delegate = delegate;
  4043. this.engine = engine;
  4044. this._zone = _zone;
  4045. engine.onRemovalComplete = (element, delegate) => {
  4046. delegate?.removeChild(null, element);
  4047. };
  4048. }
  4049. createRenderer(hostElement, type) {
  4050. const EMPTY_NAMESPACE_ID = '';
  4051. // cache the delegates to find out which cached delegate can
  4052. // be used by which cached renderer
  4053. const delegate = this.delegate.createRenderer(hostElement, type);
  4054. if (!hostElement || !type?.data?.['animation']) {
  4055. const cache = this._rendererCache;
  4056. let renderer = cache.get(delegate);
  4057. if (!renderer) {
  4058. // Ensure that the renderer is removed from the cache on destroy
  4059. // since it may contain references to detached DOM nodes.
  4060. const onRendererDestroy = () => cache.delete(delegate);
  4061. renderer = new BaseAnimationRenderer(EMPTY_NAMESPACE_ID, delegate, this.engine, onRendererDestroy);
  4062. // only cache this result when the base renderer is used
  4063. cache.set(delegate, renderer);
  4064. }
  4065. return renderer;
  4066. }
  4067. const componentId = type.id;
  4068. const namespaceId = type.id + '-' + this._currentId;
  4069. this._currentId++;
  4070. this.engine.register(namespaceId, hostElement);
  4071. const registerTrigger = (trigger) => {
  4072. if (Array.isArray(trigger)) {
  4073. trigger.forEach(registerTrigger);
  4074. }
  4075. else {
  4076. this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);
  4077. }
  4078. };
  4079. const animationTriggers = type.data['animation'];
  4080. animationTriggers.forEach(registerTrigger);
  4081. return new AnimationRenderer(this, namespaceId, delegate, this.engine);
  4082. }
  4083. begin() {
  4084. this._cdRecurDepth++;
  4085. if (this.delegate.begin) {
  4086. this.delegate.begin();
  4087. }
  4088. }
  4089. _scheduleCountTask() {
  4090. queueMicrotask(() => {
  4091. this._microtaskId++;
  4092. });
  4093. }
  4094. /** @internal */
  4095. scheduleListenerCallback(count, fn, data) {
  4096. if (count >= 0 && count < this._microtaskId) {
  4097. this._zone.run(() => fn(data));
  4098. return;
  4099. }
  4100. const animationCallbacksBuffer = this._animationCallbacksBuffer;
  4101. if (animationCallbacksBuffer.length == 0) {
  4102. queueMicrotask(() => {
  4103. this._zone.run(() => {
  4104. animationCallbacksBuffer.forEach((tuple) => {
  4105. const [fn, data] = tuple;
  4106. fn(data);
  4107. });
  4108. this._animationCallbacksBuffer = [];
  4109. });
  4110. });
  4111. }
  4112. animationCallbacksBuffer.push([fn, data]);
  4113. }
  4114. end() {
  4115. this._cdRecurDepth--;
  4116. // this is to prevent animations from running twice when an inner
  4117. // component does CD when a parent component instead has inserted it
  4118. if (this._cdRecurDepth == 0) {
  4119. this._zone.runOutsideAngular(() => {
  4120. this._scheduleCountTask();
  4121. this.engine.flush(this._microtaskId);
  4122. });
  4123. }
  4124. if (this.delegate.end) {
  4125. this.delegate.end();
  4126. }
  4127. }
  4128. whenRenderingDone() {
  4129. return this.engine.whenRenderingDone();
  4130. }
  4131. /**
  4132. * Used during HMR to clear any cached data about a component.
  4133. * @param componentId ID of the component that is being replaced.
  4134. */
  4135. componentReplaced(componentId) {
  4136. // Flush the engine since the renderer destruction waits for animations to be done.
  4137. this.engine.flush();
  4138. this.delegate.componentReplaced?.(componentId);
  4139. }
  4140. }
  4141. export { AnimationDriver, NoopAnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationRenderer as ɵAnimationRenderer, AnimationRendererFactory as ɵAnimationRendererFactory, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, BaseAnimationRenderer as ɵBaseAnimationRenderer, ENTER_CLASSNAME as ɵENTER_CLASSNAME, LEAVE_CLASSNAME as ɵLEAVE_CLASSNAME, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, TransitionAnimationPlayer as ɵTransitionAnimationPlayer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, camelCaseToDashCase as ɵcamelCaseToDashCase, containsElement as ɵcontainsElement, createEngine as ɵcreateEngine, getParentElement as ɵgetParentElement, invokeQuery as ɵinvokeQuery, normalizeKeyframes$1 as ɵnormalizeKeyframes, validateStyleProperty as ɵvalidateStyleProperty, validateWebAnimatableStyleProperty as ɵvalidateWebAnimatableStyleProperty };
  4142. //# sourceMappingURL=browser.mjs.map