common.mjs 289 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711
  1. /**
  2. * @license Angular v16.2.9
  3. * (c) 2010-2022 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import * as i0 from '@angular/core';
  7. import { InjectionToken, inject, Injectable, Optional, Inject, EventEmitter, ɵɵinject, ɵfindLocaleData, ɵLocaleDataIndex, ɵgetLocaleCurrencyCode, ɵgetLocalePluralCase, LOCALE_ID, ɵregisterLocaleData, ɵstringify, Directive, Input, createNgModule, NgModuleRef, ɵRuntimeError, Host, Attribute, RendererStyleFlags2, untracked, ɵisPromise, ɵisSubscribable, Pipe, DEFAULT_CURRENCY_CODE, NgModule, Version, ɵɵdefineInjectable, ɵformatRuntimeError, Renderer2, ElementRef, Injector, PLATFORM_ID, NgZone, numberAttribute, booleanAttribute, ɵunwrapSafeValue } from '@angular/core';
  8. let _DOM = null;
  9. function getDOM() {
  10. return _DOM;
  11. }
  12. function setRootDomAdapter(adapter) {
  13. if (!_DOM) {
  14. _DOM = adapter;
  15. }
  16. }
  17. /* tslint:disable:requireParameterType */
  18. /**
  19. * Provides DOM operations in an environment-agnostic way.
  20. *
  21. * @security Tread carefully! Interacting with the DOM directly is dangerous and
  22. * can introduce XSS risks.
  23. */
  24. class DomAdapter {
  25. }
  26. /**
  27. * A DI Token representing the main rendering context.
  28. * In a browser and SSR this is the DOM Document.
  29. * When using SSR, that document is created by [Domino](https://github.com/angular/domino).
  30. *
  31. * @publicApi
  32. */
  33. const DOCUMENT = new InjectionToken('DocumentToken');
  34. /**
  35. * This class should not be used directly by an application developer. Instead, use
  36. * {@link Location}.
  37. *
  38. * `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be
  39. * platform-agnostic.
  40. * This means that we can have different implementation of `PlatformLocation` for the different
  41. * platforms that Angular supports. For example, `@angular/platform-browser` provides an
  42. * implementation specific to the browser environment, while `@angular/platform-server` provides
  43. * one suitable for use with server-side rendering.
  44. *
  45. * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy}
  46. * when they need to interact with the DOM APIs like pushState, popState, etc.
  47. *
  48. * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly
  49. * by the {@link Router} in order to navigate between routes. Since all interactions between {@link
  50. * Router} /
  51. * {@link Location} / {@link LocationStrategy} and DOM APIs flow through the `PlatformLocation`
  52. * class, they are all platform-agnostic.
  53. *
  54. * @publicApi
  55. */
  56. class PlatformLocation {
  57. historyGo(relativePosition) {
  58. throw new Error('Not implemented');
  59. }
  60. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PlatformLocation, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  61. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PlatformLocation, providedIn: 'platform', useFactory: () => inject(BrowserPlatformLocation) }); }
  62. }
  63. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PlatformLocation, decorators: [{
  64. type: Injectable,
  65. args: [{ providedIn: 'platform', useFactory: () => inject(BrowserPlatformLocation) }]
  66. }] });
  67. /**
  68. * @description
  69. * Indicates when a location is initialized.
  70. *
  71. * @publicApi
  72. */
  73. const LOCATION_INITIALIZED = new InjectionToken('Location Initialized');
  74. /**
  75. * `PlatformLocation` encapsulates all of the direct calls to platform APIs.
  76. * This class should not be used directly by an application developer. Instead, use
  77. * {@link Location}.
  78. *
  79. * @publicApi
  80. */
  81. class BrowserPlatformLocation extends PlatformLocation {
  82. constructor() {
  83. super();
  84. this._doc = inject(DOCUMENT);
  85. this._location = window.location;
  86. this._history = window.history;
  87. }
  88. getBaseHrefFromDOM() {
  89. return getDOM().getBaseHref(this._doc);
  90. }
  91. onPopState(fn) {
  92. const window = getDOM().getGlobalEventTarget(this._doc, 'window');
  93. window.addEventListener('popstate', fn, false);
  94. return () => window.removeEventListener('popstate', fn);
  95. }
  96. onHashChange(fn) {
  97. const window = getDOM().getGlobalEventTarget(this._doc, 'window');
  98. window.addEventListener('hashchange', fn, false);
  99. return () => window.removeEventListener('hashchange', fn);
  100. }
  101. get href() {
  102. return this._location.href;
  103. }
  104. get protocol() {
  105. return this._location.protocol;
  106. }
  107. get hostname() {
  108. return this._location.hostname;
  109. }
  110. get port() {
  111. return this._location.port;
  112. }
  113. get pathname() {
  114. return this._location.pathname;
  115. }
  116. get search() {
  117. return this._location.search;
  118. }
  119. get hash() {
  120. return this._location.hash;
  121. }
  122. set pathname(newPath) {
  123. this._location.pathname = newPath;
  124. }
  125. pushState(state, title, url) {
  126. this._history.pushState(state, title, url);
  127. }
  128. replaceState(state, title, url) {
  129. this._history.replaceState(state, title, url);
  130. }
  131. forward() {
  132. this._history.forward();
  133. }
  134. back() {
  135. this._history.back();
  136. }
  137. historyGo(relativePosition = 0) {
  138. this._history.go(relativePosition);
  139. }
  140. getState() {
  141. return this._history.state;
  142. }
  143. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: BrowserPlatformLocation, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  144. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: BrowserPlatformLocation, providedIn: 'platform', useFactory: () => new BrowserPlatformLocation() }); }
  145. }
  146. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: BrowserPlatformLocation, decorators: [{
  147. type: Injectable,
  148. args: [{
  149. providedIn: 'platform',
  150. useFactory: () => new BrowserPlatformLocation(),
  151. }]
  152. }], ctorParameters: function () { return []; } });
  153. /**
  154. * Joins two parts of a URL with a slash if needed.
  155. *
  156. * @param start URL string
  157. * @param end URL string
  158. *
  159. *
  160. * @returns The joined URL string.
  161. */
  162. function joinWithSlash(start, end) {
  163. if (start.length == 0) {
  164. return end;
  165. }
  166. if (end.length == 0) {
  167. return start;
  168. }
  169. let slashes = 0;
  170. if (start.endsWith('/')) {
  171. slashes++;
  172. }
  173. if (end.startsWith('/')) {
  174. slashes++;
  175. }
  176. if (slashes == 2) {
  177. return start + end.substring(1);
  178. }
  179. if (slashes == 1) {
  180. return start + end;
  181. }
  182. return start + '/' + end;
  183. }
  184. /**
  185. * Removes a trailing slash from a URL string if needed.
  186. * Looks for the first occurrence of either `#`, `?`, or the end of the
  187. * line as `/` characters and removes the trailing slash if one exists.
  188. *
  189. * @param url URL string.
  190. *
  191. * @returns The URL string, modified if needed.
  192. */
  193. function stripTrailingSlash(url) {
  194. const match = url.match(/#|\?|$/);
  195. const pathEndIdx = match && match.index || url.length;
  196. const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
  197. return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx);
  198. }
  199. /**
  200. * Normalizes URL parameters by prepending with `?` if needed.
  201. *
  202. * @param params String of URL parameters.
  203. *
  204. * @returns The normalized URL parameters string.
  205. */
  206. function normalizeQueryParams(params) {
  207. return params && params[0] !== '?' ? '?' + params : params;
  208. }
  209. /**
  210. * Enables the `Location` service to read route state from the browser's URL.
  211. * Angular provides two strategies:
  212. * `HashLocationStrategy` and `PathLocationStrategy`.
  213. *
  214. * Applications should use the `Router` or `Location` services to
  215. * interact with application route state.
  216. *
  217. * For instance, `HashLocationStrategy` produces URLs like
  218. * <code class="no-auto-link">http://example.com#/foo</code>,
  219. * and `PathLocationStrategy` produces
  220. * <code class="no-auto-link">http://example.com/foo</code> as an equivalent URL.
  221. *
  222. * See these two classes for more.
  223. *
  224. * @publicApi
  225. */
  226. class LocationStrategy {
  227. historyGo(relativePosition) {
  228. throw new Error('Not implemented');
  229. }
  230. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LocationStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  231. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LocationStrategy, providedIn: 'root', useFactory: () => inject(PathLocationStrategy) }); }
  232. }
  233. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LocationStrategy, decorators: [{
  234. type: Injectable,
  235. args: [{ providedIn: 'root', useFactory: () => inject(PathLocationStrategy) }]
  236. }] });
  237. /**
  238. * A predefined [DI token](guide/glossary#di-token) for the base href
  239. * to be used with the `PathLocationStrategy`.
  240. * The base href is the URL prefix that should be preserved when generating
  241. * and recognizing URLs.
  242. *
  243. * @usageNotes
  244. *
  245. * The following example shows how to use this token to configure the root app injector
  246. * with a base href value, so that the DI framework can supply the dependency anywhere in the app.
  247. *
  248. * ```typescript
  249. * import {Component, NgModule} from '@angular/core';
  250. * import {APP_BASE_HREF} from '@angular/common';
  251. *
  252. * @NgModule({
  253. * providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
  254. * })
  255. * class AppModule {}
  256. * ```
  257. *
  258. * @publicApi
  259. */
  260. const APP_BASE_HREF = new InjectionToken('appBaseHref');
  261. /**
  262. * @description
  263. * A {@link LocationStrategy} used to configure the {@link Location} service to
  264. * represent its state in the
  265. * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
  266. * browser's URL.
  267. *
  268. * If you're using `PathLocationStrategy`, you may provide a {@link APP_BASE_HREF}
  269. * or add a `<base href>` element to the document to override the default.
  270. *
  271. * For instance, if you provide an `APP_BASE_HREF` of `'/my/app/'` and call
  272. * `location.go('/foo')`, the browser's URL will become
  273. * `example.com/my/app/foo`. To ensure all relative URIs resolve correctly,
  274. * the `<base href>` and/or `APP_BASE_HREF` should end with a `/`.
  275. *
  276. * Similarly, if you add `<base href='/my/app/'/>` to the document and call
  277. * `location.go('/foo')`, the browser's URL will become
  278. * `example.com/my/app/foo`.
  279. *
  280. * Note that when using `PathLocationStrategy`, neither the query nor
  281. * the fragment in the `<base href>` will be preserved, as outlined
  282. * by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2).
  283. *
  284. * @usageNotes
  285. *
  286. * ### Example
  287. *
  288. * {@example common/location/ts/path_location_component.ts region='LocationComponent'}
  289. *
  290. * @publicApi
  291. */
  292. class PathLocationStrategy extends LocationStrategy {
  293. constructor(_platformLocation, href) {
  294. super();
  295. this._platformLocation = _platformLocation;
  296. this._removeListenerFns = [];
  297. this._baseHref = href ?? this._platformLocation.getBaseHrefFromDOM() ??
  298. inject(DOCUMENT).location?.origin ?? '';
  299. }
  300. /** @nodoc */
  301. ngOnDestroy() {
  302. while (this._removeListenerFns.length) {
  303. this._removeListenerFns.pop()();
  304. }
  305. }
  306. onPopState(fn) {
  307. this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn));
  308. }
  309. getBaseHref() {
  310. return this._baseHref;
  311. }
  312. prepareExternalUrl(internal) {
  313. return joinWithSlash(this._baseHref, internal);
  314. }
  315. path(includeHash = false) {
  316. const pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search);
  317. const hash = this._platformLocation.hash;
  318. return hash && includeHash ? `${pathname}${hash}` : pathname;
  319. }
  320. pushState(state, title, url, queryParams) {
  321. const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
  322. this._platformLocation.pushState(state, title, externalUrl);
  323. }
  324. replaceState(state, title, url, queryParams) {
  325. const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
  326. this._platformLocation.replaceState(state, title, externalUrl);
  327. }
  328. forward() {
  329. this._platformLocation.forward();
  330. }
  331. back() {
  332. this._platformLocation.back();
  333. }
  334. getState() {
  335. return this._platformLocation.getState();
  336. }
  337. historyGo(relativePosition = 0) {
  338. this._platformLocation.historyGo?.(relativePosition);
  339. }
  340. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PathLocationStrategy, deps: [{ token: PlatformLocation }, { token: APP_BASE_HREF, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
  341. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PathLocationStrategy, providedIn: 'root' }); }
  342. }
  343. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PathLocationStrategy, decorators: [{
  344. type: Injectable,
  345. args: [{ providedIn: 'root' }]
  346. }], ctorParameters: function () { return [{ type: PlatformLocation }, { type: undefined, decorators: [{
  347. type: Optional
  348. }, {
  349. type: Inject,
  350. args: [APP_BASE_HREF]
  351. }] }]; } });
  352. /**
  353. * @description
  354. * A {@link LocationStrategy} used to configure the {@link Location} service to
  355. * represent its state in the
  356. * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
  357. * of the browser's URL.
  358. *
  359. * For instance, if you call `location.go('/foo')`, the browser's URL will become
  360. * `example.com#/foo`.
  361. *
  362. * @usageNotes
  363. *
  364. * ### Example
  365. *
  366. * {@example common/location/ts/hash_location_component.ts region='LocationComponent'}
  367. *
  368. * @publicApi
  369. */
  370. class HashLocationStrategy extends LocationStrategy {
  371. constructor(_platformLocation, _baseHref) {
  372. super();
  373. this._platformLocation = _platformLocation;
  374. this._baseHref = '';
  375. this._removeListenerFns = [];
  376. if (_baseHref != null) {
  377. this._baseHref = _baseHref;
  378. }
  379. }
  380. /** @nodoc */
  381. ngOnDestroy() {
  382. while (this._removeListenerFns.length) {
  383. this._removeListenerFns.pop()();
  384. }
  385. }
  386. onPopState(fn) {
  387. this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn));
  388. }
  389. getBaseHref() {
  390. return this._baseHref;
  391. }
  392. path(includeHash = false) {
  393. // the hash value is always prefixed with a `#`
  394. // and if it is empty then it will stay empty
  395. let path = this._platformLocation.hash;
  396. if (path == null)
  397. path = '#';
  398. return path.length > 0 ? path.substring(1) : path;
  399. }
  400. prepareExternalUrl(internal) {
  401. const url = joinWithSlash(this._baseHref, internal);
  402. return url.length > 0 ? ('#' + url) : url;
  403. }
  404. pushState(state, title, path, queryParams) {
  405. let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
  406. if (url.length == 0) {
  407. url = this._platformLocation.pathname;
  408. }
  409. this._platformLocation.pushState(state, title, url);
  410. }
  411. replaceState(state, title, path, queryParams) {
  412. let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
  413. if (url.length == 0) {
  414. url = this._platformLocation.pathname;
  415. }
  416. this._platformLocation.replaceState(state, title, url);
  417. }
  418. forward() {
  419. this._platformLocation.forward();
  420. }
  421. back() {
  422. this._platformLocation.back();
  423. }
  424. getState() {
  425. return this._platformLocation.getState();
  426. }
  427. historyGo(relativePosition = 0) {
  428. this._platformLocation.historyGo?.(relativePosition);
  429. }
  430. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: HashLocationStrategy, deps: [{ token: PlatformLocation }, { token: APP_BASE_HREF, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
  431. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: HashLocationStrategy }); }
  432. }
  433. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: HashLocationStrategy, decorators: [{
  434. type: Injectable
  435. }], ctorParameters: function () { return [{ type: PlatformLocation }, { type: undefined, decorators: [{
  436. type: Optional
  437. }, {
  438. type: Inject,
  439. args: [APP_BASE_HREF]
  440. }] }]; } });
  441. /**
  442. * @description
  443. *
  444. * A service that applications can use to interact with a browser's URL.
  445. *
  446. * Depending on the `LocationStrategy` used, `Location` persists
  447. * to the URL's path or the URL's hash segment.
  448. *
  449. * @usageNotes
  450. *
  451. * It's better to use the `Router.navigate()` service to trigger route changes. Use
  452. * `Location` only if you need to interact with or create normalized URLs outside of
  453. * routing.
  454. *
  455. * `Location` is responsible for normalizing the URL against the application's base href.
  456. * A normalized URL is absolute from the URL host, includes the application's base href, and has no
  457. * trailing slash:
  458. * - `/my/app/user/123` is normalized
  459. * - `my/app/user/123` **is not** normalized
  460. * - `/my/app/user/123/` **is not** normalized
  461. *
  462. * ### Example
  463. *
  464. * <code-example path='common/location/ts/path_location_component.ts'
  465. * region='LocationComponent'></code-example>
  466. *
  467. * @publicApi
  468. */
  469. class Location {
  470. constructor(locationStrategy) {
  471. /** @internal */
  472. this._subject = new EventEmitter();
  473. /** @internal */
  474. this._urlChangeListeners = [];
  475. /** @internal */
  476. this._urlChangeSubscription = null;
  477. this._locationStrategy = locationStrategy;
  478. const baseHref = this._locationStrategy.getBaseHref();
  479. // Note: This class's interaction with base HREF does not fully follow the rules
  480. // outlined in the spec https://www.freesoft.org/CIE/RFC/1808/18.htm.
  481. // Instead of trying to fix individual bugs with more and more code, we should
  482. // investigate using the URL constructor and providing the base as a second
  483. // argument.
  484. // https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#parameters
  485. this._basePath = _stripOrigin(stripTrailingSlash(_stripIndexHtml(baseHref)));
  486. this._locationStrategy.onPopState((ev) => {
  487. this._subject.emit({
  488. 'url': this.path(true),
  489. 'pop': true,
  490. 'state': ev.state,
  491. 'type': ev.type,
  492. });
  493. });
  494. }
  495. /** @nodoc */
  496. ngOnDestroy() {
  497. this._urlChangeSubscription?.unsubscribe();
  498. this._urlChangeListeners = [];
  499. }
  500. /**
  501. * Normalizes the URL path for this location.
  502. *
  503. * @param includeHash True to include an anchor fragment in the path.
  504. *
  505. * @returns The normalized URL path.
  506. */
  507. // TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is
  508. // removed.
  509. path(includeHash = false) {
  510. return this.normalize(this._locationStrategy.path(includeHash));
  511. }
  512. /**
  513. * Reports the current state of the location history.
  514. * @returns The current value of the `history.state` object.
  515. */
  516. getState() {
  517. return this._locationStrategy.getState();
  518. }
  519. /**
  520. * Normalizes the given path and compares to the current normalized path.
  521. *
  522. * @param path The given URL path.
  523. * @param query Query parameters.
  524. *
  525. * @returns True if the given URL path is equal to the current normalized path, false
  526. * otherwise.
  527. */
  528. isCurrentPathEqualTo(path, query = '') {
  529. return this.path() == this.normalize(path + normalizeQueryParams(query));
  530. }
  531. /**
  532. * Normalizes a URL path by stripping any trailing slashes.
  533. *
  534. * @param url String representing a URL.
  535. *
  536. * @returns The normalized URL string.
  537. */
  538. normalize(url) {
  539. return Location.stripTrailingSlash(_stripBasePath(this._basePath, _stripIndexHtml(url)));
  540. }
  541. /**
  542. * Normalizes an external URL path.
  543. * If the given URL doesn't begin with a leading slash (`'/'`), adds one
  544. * before normalizing. Adds a hash if `HashLocationStrategy` is
  545. * in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
  546. *
  547. * @param url String representing a URL.
  548. *
  549. * @returns A normalized platform-specific URL.
  550. */
  551. prepareExternalUrl(url) {
  552. if (url && url[0] !== '/') {
  553. url = '/' + url;
  554. }
  555. return this._locationStrategy.prepareExternalUrl(url);
  556. }
  557. // TODO: rename this method to pushState
  558. /**
  559. * Changes the browser's URL to a normalized version of a given URL, and pushes a
  560. * new item onto the platform's history.
  561. *
  562. * @param path URL path to normalize.
  563. * @param query Query parameters.
  564. * @param state Location history state.
  565. *
  566. */
  567. go(path, query = '', state = null) {
  568. this._locationStrategy.pushState(state, '', path, query);
  569. this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
  570. }
  571. /**
  572. * Changes the browser's URL to a normalized version of the given URL, and replaces
  573. * the top item on the platform's history stack.
  574. *
  575. * @param path URL path to normalize.
  576. * @param query Query parameters.
  577. * @param state Location history state.
  578. */
  579. replaceState(path, query = '', state = null) {
  580. this._locationStrategy.replaceState(state, '', path, query);
  581. this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
  582. }
  583. /**
  584. * Navigates forward in the platform's history.
  585. */
  586. forward() {
  587. this._locationStrategy.forward();
  588. }
  589. /**
  590. * Navigates back in the platform's history.
  591. */
  592. back() {
  593. this._locationStrategy.back();
  594. }
  595. /**
  596. * Navigate to a specific page from session history, identified by its relative position to the
  597. * current page.
  598. *
  599. * @param relativePosition Position of the target page in the history relative to the current
  600. * page.
  601. * A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)`
  602. * moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go
  603. * beyond what's stored in the history session, we stay in the current page. Same behaviour occurs
  604. * when `relativePosition` equals 0.
  605. * @see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history
  606. */
  607. historyGo(relativePosition = 0) {
  608. this._locationStrategy.historyGo?.(relativePosition);
  609. }
  610. /**
  611. * Registers a URL change listener. Use to catch updates performed by the Angular
  612. * framework that are not detectible through "popstate" or "hashchange" events.
  613. *
  614. * @param fn The change handler function, which take a URL and a location history state.
  615. * @returns A function that, when executed, unregisters a URL change listener.
  616. */
  617. onUrlChange(fn) {
  618. this._urlChangeListeners.push(fn);
  619. if (!this._urlChangeSubscription) {
  620. this._urlChangeSubscription = this.subscribe(v => {
  621. this._notifyUrlChangeListeners(v.url, v.state);
  622. });
  623. }
  624. return () => {
  625. const fnIndex = this._urlChangeListeners.indexOf(fn);
  626. this._urlChangeListeners.splice(fnIndex, 1);
  627. if (this._urlChangeListeners.length === 0) {
  628. this._urlChangeSubscription?.unsubscribe();
  629. this._urlChangeSubscription = null;
  630. }
  631. };
  632. }
  633. /** @internal */
  634. _notifyUrlChangeListeners(url = '', state) {
  635. this._urlChangeListeners.forEach(fn => fn(url, state));
  636. }
  637. /**
  638. * Subscribes to the platform's `popState` events.
  639. *
  640. * Note: `Location.go()` does not trigger the `popState` event in the browser. Use
  641. * `Location.onUrlChange()` to subscribe to URL changes instead.
  642. *
  643. * @param value Event that is triggered when the state history changes.
  644. * @param exception The exception to throw.
  645. *
  646. * @see [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate)
  647. *
  648. * @returns Subscribed events.
  649. */
  650. subscribe(onNext, onThrow, onReturn) {
  651. return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
  652. }
  653. /**
  654. * Normalizes URL parameters by prepending with `?` if needed.
  655. *
  656. * @param params String of URL parameters.
  657. *
  658. * @returns The normalized URL parameters string.
  659. */
  660. static { this.normalizeQueryParams = normalizeQueryParams; }
  661. /**
  662. * Joins two parts of a URL with a slash if needed.
  663. *
  664. * @param start URL string
  665. * @param end URL string
  666. *
  667. *
  668. * @returns The joined URL string.
  669. */
  670. static { this.joinWithSlash = joinWithSlash; }
  671. /**
  672. * Removes a trailing slash from a URL string if needed.
  673. * Looks for the first occurrence of either `#`, `?`, or the end of the
  674. * line as `/` characters and removes the trailing slash if one exists.
  675. *
  676. * @param url URL string.
  677. *
  678. * @returns The URL string, modified if needed.
  679. */
  680. static { this.stripTrailingSlash = stripTrailingSlash; }
  681. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: Location, deps: [{ token: LocationStrategy }], target: i0.ɵɵFactoryTarget.Injectable }); }
  682. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: Location, providedIn: 'root', useFactory: createLocation }); }
  683. }
  684. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: Location, decorators: [{
  685. type: Injectable,
  686. args: [{
  687. providedIn: 'root',
  688. // See #23917
  689. useFactory: createLocation,
  690. }]
  691. }], ctorParameters: function () { return [{ type: LocationStrategy }]; } });
  692. function createLocation() {
  693. return new Location(ɵɵinject(LocationStrategy));
  694. }
  695. function _stripBasePath(basePath, url) {
  696. if (!basePath || !url.startsWith(basePath)) {
  697. return url;
  698. }
  699. const strippedUrl = url.substring(basePath.length);
  700. if (strippedUrl === '' || ['/', ';', '?', '#'].includes(strippedUrl[0])) {
  701. return strippedUrl;
  702. }
  703. return url;
  704. }
  705. function _stripIndexHtml(url) {
  706. return url.replace(/\/index.html$/, '');
  707. }
  708. function _stripOrigin(baseHref) {
  709. // DO NOT REFACTOR! Previously, this check looked like this:
  710. // `/^(https?:)?\/\//.test(baseHref)`, but that resulted in
  711. // syntactically incorrect code after Closure Compiler minification.
  712. // This was likely caused by a bug in Closure Compiler, but
  713. // for now, the check is rewritten to use `new RegExp` instead.
  714. const isAbsoluteUrl = (new RegExp('^(https?:)?//')).test(baseHref);
  715. if (isAbsoluteUrl) {
  716. const [, pathname] = baseHref.split(/\/\/[^\/]+/);
  717. return pathname;
  718. }
  719. return baseHref;
  720. }
  721. /** @internal */
  722. const CURRENCIES_EN = { "ADP": [undefined, undefined, 0], "AFN": [undefined, "؋", 0], "ALL": [undefined, undefined, 0], "AMD": [undefined, "֏", 2], "AOA": [undefined, "Kz"], "ARS": [undefined, "$"], "AUD": ["A$", "$"], "AZN": [undefined, "₼"], "BAM": [undefined, "KM"], "BBD": [undefined, "$"], "BDT": [undefined, "৳"], "BHD": [undefined, undefined, 3], "BIF": [undefined, undefined, 0], "BMD": [undefined, "$"], "BND": [undefined, "$"], "BOB": [undefined, "Bs"], "BRL": ["R$"], "BSD": [undefined, "$"], "BWP": [undefined, "P"], "BYN": [undefined, undefined, 2], "BYR": [undefined, undefined, 0], "BZD": [undefined, "$"], "CAD": ["CA$", "$", 2], "CHF": [undefined, undefined, 2], "CLF": [undefined, undefined, 4], "CLP": [undefined, "$", 0], "CNY": ["CN¥", "¥"], "COP": [undefined, "$", 2], "CRC": [undefined, "₡", 2], "CUC": [undefined, "$"], "CUP": [undefined, "$"], "CZK": [undefined, "Kč", 2], "DJF": [undefined, undefined, 0], "DKK": [undefined, "kr", 2], "DOP": [undefined, "$"], "EGP": [undefined, "E£"], "ESP": [undefined, "₧", 0], "EUR": ["€"], "FJD": [undefined, "$"], "FKP": [undefined, "£"], "GBP": ["£"], "GEL": [undefined, "₾"], "GHS": [undefined, "GH₵"], "GIP": [undefined, "£"], "GNF": [undefined, "FG", 0], "GTQ": [undefined, "Q"], "GYD": [undefined, "$", 2], "HKD": ["HK$", "$"], "HNL": [undefined, "L"], "HRK": [undefined, "kn"], "HUF": [undefined, "Ft", 2], "IDR": [undefined, "Rp", 2], "ILS": ["₪"], "INR": ["₹"], "IQD": [undefined, undefined, 0], "IRR": [undefined, undefined, 0], "ISK": [undefined, "kr", 0], "ITL": [undefined, undefined, 0], "JMD": [undefined, "$"], "JOD": [undefined, undefined, 3], "JPY": ["¥", undefined, 0], "KHR": [undefined, "៛"], "KMF": [undefined, "CF", 0], "KPW": [undefined, "₩", 0], "KRW": ["₩", undefined, 0], "KWD": [undefined, undefined, 3], "KYD": [undefined, "$"], "KZT": [undefined, "₸"], "LAK": [undefined, "₭", 0], "LBP": [undefined, "L£", 0], "LKR": [undefined, "Rs"], "LRD": [undefined, "$"], "LTL": [undefined, "Lt"], "LUF": [undefined, undefined, 0], "LVL": [undefined, "Ls"], "LYD": [undefined, undefined, 3], "MGA": [undefined, "Ar", 0], "MGF": [undefined, undefined, 0], "MMK": [undefined, "K", 0], "MNT": [undefined, "₮", 2], "MRO": [undefined, undefined, 0], "MUR": [undefined, "Rs", 2], "MXN": ["MX$", "$"], "MYR": [undefined, "RM"], "NAD": [undefined, "$"], "NGN": [undefined, "₦"], "NIO": [undefined, "C$"], "NOK": [undefined, "kr", 2], "NPR": [undefined, "Rs"], "NZD": ["NZ$", "$"], "OMR": [undefined, undefined, 3], "PHP": ["₱"], "PKR": [undefined, "Rs", 2], "PLN": [undefined, "zł"], "PYG": [undefined, "₲", 0], "RON": [undefined, "lei"], "RSD": [undefined, undefined, 0], "RUB": [undefined, "₽"], "RWF": [undefined, "RF", 0], "SBD": [undefined, "$"], "SEK": [undefined, "kr", 2], "SGD": [undefined, "$"], "SHP": [undefined, "£"], "SLE": [undefined, undefined, 2], "SLL": [undefined, undefined, 0], "SOS": [undefined, undefined, 0], "SRD": [undefined, "$"], "SSP": [undefined, "£"], "STD": [undefined, undefined, 0], "STN": [undefined, "Db"], "SYP": [undefined, "£", 0], "THB": [undefined, "฿"], "TMM": [undefined, undefined, 0], "TND": [undefined, undefined, 3], "TOP": [undefined, "T$"], "TRL": [undefined, undefined, 0], "TRY": [undefined, "₺"], "TTD": [undefined, "$"], "TWD": ["NT$", "$", 2], "TZS": [undefined, undefined, 2], "UAH": [undefined, "₴"], "UGX": [undefined, undefined, 0], "USD": ["$"], "UYI": [undefined, undefined, 0], "UYU": [undefined, "$"], "UYW": [undefined, undefined, 4], "UZS": [undefined, undefined, 2], "VEF": [undefined, "Bs", 2], "VND": ["₫", undefined, 0], "VUV": [undefined, undefined, 0], "XAF": ["FCFA", undefined, 0], "XCD": ["EC$", "$"], "XOF": ["F CFA", undefined, 0], "XPF": ["CFPF", undefined, 0], "XXX": ["¤"], "YER": [undefined, undefined, 0], "ZAR": [undefined, "R"], "ZMK": [undefined, undefined, 0], "ZMW": [undefined, "ZK"], "ZWD": [undefined, undefined, 0] };
  723. /**
  724. * Format styles that can be used to represent numbers.
  725. * @see {@link getLocaleNumberFormat}
  726. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  727. *
  728. * @publicApi
  729. */
  730. var NumberFormatStyle;
  731. (function (NumberFormatStyle) {
  732. NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal";
  733. NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent";
  734. NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency";
  735. NumberFormatStyle[NumberFormatStyle["Scientific"] = 3] = "Scientific";
  736. })(NumberFormatStyle || (NumberFormatStyle = {}));
  737. /**
  738. * Plurality cases used for translating plurals to different languages.
  739. *
  740. * @see {@link NgPlural}
  741. * @see {@link NgPluralCase}
  742. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  743. *
  744. * @publicApi
  745. */
  746. var Plural;
  747. (function (Plural) {
  748. Plural[Plural["Zero"] = 0] = "Zero";
  749. Plural[Plural["One"] = 1] = "One";
  750. Plural[Plural["Two"] = 2] = "Two";
  751. Plural[Plural["Few"] = 3] = "Few";
  752. Plural[Plural["Many"] = 4] = "Many";
  753. Plural[Plural["Other"] = 5] = "Other";
  754. })(Plural || (Plural = {}));
  755. /**
  756. * Context-dependant translation forms for strings.
  757. * Typically the standalone version is for the nominative form of the word,
  758. * and the format version is used for the genitive case.
  759. * @see [CLDR website](http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles)
  760. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  761. *
  762. * @publicApi
  763. */
  764. var FormStyle;
  765. (function (FormStyle) {
  766. FormStyle[FormStyle["Format"] = 0] = "Format";
  767. FormStyle[FormStyle["Standalone"] = 1] = "Standalone";
  768. })(FormStyle || (FormStyle = {}));
  769. /**
  770. * String widths available for translations.
  771. * The specific character widths are locale-specific.
  772. * Examples are given for the word "Sunday" in English.
  773. *
  774. * @publicApi
  775. */
  776. var TranslationWidth;
  777. (function (TranslationWidth) {
  778. /** 1 character for `en-US`. For example: 'S' */
  779. TranslationWidth[TranslationWidth["Narrow"] = 0] = "Narrow";
  780. /** 3 characters for `en-US`. For example: 'Sun' */
  781. TranslationWidth[TranslationWidth["Abbreviated"] = 1] = "Abbreviated";
  782. /** Full length for `en-US`. For example: "Sunday" */
  783. TranslationWidth[TranslationWidth["Wide"] = 2] = "Wide";
  784. /** 2 characters for `en-US`, For example: "Su" */
  785. TranslationWidth[TranslationWidth["Short"] = 3] = "Short";
  786. })(TranslationWidth || (TranslationWidth = {}));
  787. /**
  788. * String widths available for date-time formats.
  789. * The specific character widths are locale-specific.
  790. * Examples are given for `en-US`.
  791. *
  792. * @see {@link getLocaleDateFormat}
  793. * @see {@link getLocaleTimeFormat}
  794. * @see {@link getLocaleDateTimeFormat}
  795. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  796. * @publicApi
  797. */
  798. var FormatWidth;
  799. (function (FormatWidth) {
  800. /**
  801. * For `en-US`, 'M/d/yy, h:mm a'`
  802. * (Example: `6/15/15, 9:03 AM`)
  803. */
  804. FormatWidth[FormatWidth["Short"] = 0] = "Short";
  805. /**
  806. * For `en-US`, `'MMM d, y, h:mm:ss a'`
  807. * (Example: `Jun 15, 2015, 9:03:01 AM`)
  808. */
  809. FormatWidth[FormatWidth["Medium"] = 1] = "Medium";
  810. /**
  811. * For `en-US`, `'MMMM d, y, h:mm:ss a z'`
  812. * (Example: `June 15, 2015 at 9:03:01 AM GMT+1`)
  813. */
  814. FormatWidth[FormatWidth["Long"] = 2] = "Long";
  815. /**
  816. * For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'`
  817. * (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`)
  818. */
  819. FormatWidth[FormatWidth["Full"] = 3] = "Full";
  820. })(FormatWidth || (FormatWidth = {}));
  821. /**
  822. * Symbols that can be used to replace placeholders in number patterns.
  823. * Examples are based on `en-US` values.
  824. *
  825. * @see {@link getLocaleNumberSymbol}
  826. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  827. *
  828. * @publicApi
  829. */
  830. var NumberSymbol;
  831. (function (NumberSymbol) {
  832. /**
  833. * Decimal separator.
  834. * For `en-US`, the dot character.
  835. * Example: 2,345`.`67
  836. */
  837. NumberSymbol[NumberSymbol["Decimal"] = 0] = "Decimal";
  838. /**
  839. * Grouping separator, typically for thousands.
  840. * For `en-US`, the comma character.
  841. * Example: 2`,`345.67
  842. */
  843. NumberSymbol[NumberSymbol["Group"] = 1] = "Group";
  844. /**
  845. * List-item separator.
  846. * Example: "one, two, and three"
  847. */
  848. NumberSymbol[NumberSymbol["List"] = 2] = "List";
  849. /**
  850. * Sign for percentage (out of 100).
  851. * Example: 23.4%
  852. */
  853. NumberSymbol[NumberSymbol["PercentSign"] = 3] = "PercentSign";
  854. /**
  855. * Sign for positive numbers.
  856. * Example: +23
  857. */
  858. NumberSymbol[NumberSymbol["PlusSign"] = 4] = "PlusSign";
  859. /**
  860. * Sign for negative numbers.
  861. * Example: -23
  862. */
  863. NumberSymbol[NumberSymbol["MinusSign"] = 5] = "MinusSign";
  864. /**
  865. * Computer notation for exponential value (n times a power of 10).
  866. * Example: 1.2E3
  867. */
  868. NumberSymbol[NumberSymbol["Exponential"] = 6] = "Exponential";
  869. /**
  870. * Human-readable format of exponential.
  871. * Example: 1.2x103
  872. */
  873. NumberSymbol[NumberSymbol["SuperscriptingExponent"] = 7] = "SuperscriptingExponent";
  874. /**
  875. * Sign for permille (out of 1000).
  876. * Example: 23.4‰
  877. */
  878. NumberSymbol[NumberSymbol["PerMille"] = 8] = "PerMille";
  879. /**
  880. * Infinity, can be used with plus and minus.
  881. * Example: ∞, +∞, -∞
  882. */
  883. NumberSymbol[NumberSymbol["Infinity"] = 9] = "Infinity";
  884. /**
  885. * Not a number.
  886. * Example: NaN
  887. */
  888. NumberSymbol[NumberSymbol["NaN"] = 10] = "NaN";
  889. /**
  890. * Symbol used between time units.
  891. * Example: 10:52
  892. */
  893. NumberSymbol[NumberSymbol["TimeSeparator"] = 11] = "TimeSeparator";
  894. /**
  895. * Decimal separator for currency values (fallback to `Decimal`).
  896. * Example: $2,345.67
  897. */
  898. NumberSymbol[NumberSymbol["CurrencyDecimal"] = 12] = "CurrencyDecimal";
  899. /**
  900. * Group separator for currency values (fallback to `Group`).
  901. * Example: $2,345.67
  902. */
  903. NumberSymbol[NumberSymbol["CurrencyGroup"] = 13] = "CurrencyGroup";
  904. })(NumberSymbol || (NumberSymbol = {}));
  905. /**
  906. * The value for each day of the week, based on the `en-US` locale
  907. *
  908. * @publicApi
  909. */
  910. var WeekDay;
  911. (function (WeekDay) {
  912. WeekDay[WeekDay["Sunday"] = 0] = "Sunday";
  913. WeekDay[WeekDay["Monday"] = 1] = "Monday";
  914. WeekDay[WeekDay["Tuesday"] = 2] = "Tuesday";
  915. WeekDay[WeekDay["Wednesday"] = 3] = "Wednesday";
  916. WeekDay[WeekDay["Thursday"] = 4] = "Thursday";
  917. WeekDay[WeekDay["Friday"] = 5] = "Friday";
  918. WeekDay[WeekDay["Saturday"] = 6] = "Saturday";
  919. })(WeekDay || (WeekDay = {}));
  920. /**
  921. * Retrieves the locale ID from the currently loaded locale.
  922. * The loaded locale could be, for example, a global one rather than a regional one.
  923. * @param locale A locale code, such as `fr-FR`.
  924. * @returns The locale code. For example, `fr`.
  925. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  926. *
  927. * @publicApi
  928. */
  929. function getLocaleId(locale) {
  930. return ɵfindLocaleData(locale)[ɵLocaleDataIndex.LocaleId];
  931. }
  932. /**
  933. * Retrieves day period strings for the given locale.
  934. *
  935. * @param locale A locale code for the locale format rules to use.
  936. * @param formStyle The required grammatical form.
  937. * @param width The required character width.
  938. * @returns An array of localized period strings. For example, `[AM, PM]` for `en-US`.
  939. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  940. *
  941. * @publicApi
  942. */
  943. function getLocaleDayPeriods(locale, formStyle, width) {
  944. const data = ɵfindLocaleData(locale);
  945. const amPmData = [
  946. data[ɵLocaleDataIndex.DayPeriodsFormat], data[ɵLocaleDataIndex.DayPeriodsStandalone]
  947. ];
  948. const amPm = getLastDefinedValue(amPmData, formStyle);
  949. return getLastDefinedValue(amPm, width);
  950. }
  951. /**
  952. * Retrieves days of the week for the given locale, using the Gregorian calendar.
  953. *
  954. * @param locale A locale code for the locale format rules to use.
  955. * @param formStyle The required grammatical form.
  956. * @param width The required character width.
  957. * @returns An array of localized name strings.
  958. * For example,`[Sunday, Monday, ... Saturday]` for `en-US`.
  959. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  960. *
  961. * @publicApi
  962. */
  963. function getLocaleDayNames(locale, formStyle, width) {
  964. const data = ɵfindLocaleData(locale);
  965. const daysData = [data[ɵLocaleDataIndex.DaysFormat], data[ɵLocaleDataIndex.DaysStandalone]];
  966. const days = getLastDefinedValue(daysData, formStyle);
  967. return getLastDefinedValue(days, width);
  968. }
  969. /**
  970. * Retrieves months of the year for the given locale, using the Gregorian calendar.
  971. *
  972. * @param locale A locale code for the locale format rules to use.
  973. * @param formStyle The required grammatical form.
  974. * @param width The required character width.
  975. * @returns An array of localized name strings.
  976. * For example, `[January, February, ...]` for `en-US`.
  977. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  978. *
  979. * @publicApi
  980. */
  981. function getLocaleMonthNames(locale, formStyle, width) {
  982. const data = ɵfindLocaleData(locale);
  983. const monthsData = [data[ɵLocaleDataIndex.MonthsFormat], data[ɵLocaleDataIndex.MonthsStandalone]];
  984. const months = getLastDefinedValue(monthsData, formStyle);
  985. return getLastDefinedValue(months, width);
  986. }
  987. /**
  988. * Retrieves Gregorian-calendar eras for the given locale.
  989. * @param locale A locale code for the locale format rules to use.
  990. * @param width The required character width.
  991. * @returns An array of localized era strings.
  992. * For example, `[AD, BC]` for `en-US`.
  993. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  994. *
  995. * @publicApi
  996. */
  997. function getLocaleEraNames(locale, width) {
  998. const data = ɵfindLocaleData(locale);
  999. const erasData = data[ɵLocaleDataIndex.Eras];
  1000. return getLastDefinedValue(erasData, width);
  1001. }
  1002. /**
  1003. * Retrieves the first day of the week for the given locale.
  1004. *
  1005. * @param locale A locale code for the locale format rules to use.
  1006. * @returns A day index number, using the 0-based week-day index for `en-US`
  1007. * (Sunday = 0, Monday = 1, ...).
  1008. * For example, for `fr-FR`, returns 1 to indicate that the first day is Monday.
  1009. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1010. *
  1011. * @publicApi
  1012. */
  1013. function getLocaleFirstDayOfWeek(locale) {
  1014. const data = ɵfindLocaleData(locale);
  1015. return data[ɵLocaleDataIndex.FirstDayOfWeek];
  1016. }
  1017. /**
  1018. * Range of week days that are considered the week-end for the given locale.
  1019. *
  1020. * @param locale A locale code for the locale format rules to use.
  1021. * @returns The range of day values, `[startDay, endDay]`.
  1022. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1023. *
  1024. * @publicApi
  1025. */
  1026. function getLocaleWeekEndRange(locale) {
  1027. const data = ɵfindLocaleData(locale);
  1028. return data[ɵLocaleDataIndex.WeekendRange];
  1029. }
  1030. /**
  1031. * Retrieves a localized date-value formatting string.
  1032. *
  1033. * @param locale A locale code for the locale format rules to use.
  1034. * @param width The format type.
  1035. * @returns The localized formatting string.
  1036. * @see {@link FormatWidth}
  1037. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1038. *
  1039. * @publicApi
  1040. */
  1041. function getLocaleDateFormat(locale, width) {
  1042. const data = ɵfindLocaleData(locale);
  1043. return getLastDefinedValue(data[ɵLocaleDataIndex.DateFormat], width);
  1044. }
  1045. /**
  1046. * Retrieves a localized time-value formatting string.
  1047. *
  1048. * @param locale A locale code for the locale format rules to use.
  1049. * @param width The format type.
  1050. * @returns The localized formatting string.
  1051. * @see {@link FormatWidth}
  1052. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1053. * @publicApi
  1054. */
  1055. function getLocaleTimeFormat(locale, width) {
  1056. const data = ɵfindLocaleData(locale);
  1057. return getLastDefinedValue(data[ɵLocaleDataIndex.TimeFormat], width);
  1058. }
  1059. /**
  1060. * Retrieves a localized date-time formatting string.
  1061. *
  1062. * @param locale A locale code for the locale format rules to use.
  1063. * @param width The format type.
  1064. * @returns The localized formatting string.
  1065. * @see {@link FormatWidth}
  1066. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1067. *
  1068. * @publicApi
  1069. */
  1070. function getLocaleDateTimeFormat(locale, width) {
  1071. const data = ɵfindLocaleData(locale);
  1072. const dateTimeFormatData = data[ɵLocaleDataIndex.DateTimeFormat];
  1073. return getLastDefinedValue(dateTimeFormatData, width);
  1074. }
  1075. /**
  1076. * Retrieves a localized number symbol that can be used to replace placeholders in number formats.
  1077. * @param locale The locale code.
  1078. * @param symbol The symbol to localize.
  1079. * @returns The character for the localized symbol.
  1080. * @see {@link NumberSymbol}
  1081. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1082. *
  1083. * @publicApi
  1084. */
  1085. function getLocaleNumberSymbol(locale, symbol) {
  1086. const data = ɵfindLocaleData(locale);
  1087. const res = data[ɵLocaleDataIndex.NumberSymbols][symbol];
  1088. if (typeof res === 'undefined') {
  1089. if (symbol === NumberSymbol.CurrencyDecimal) {
  1090. return data[ɵLocaleDataIndex.NumberSymbols][NumberSymbol.Decimal];
  1091. }
  1092. else if (symbol === NumberSymbol.CurrencyGroup) {
  1093. return data[ɵLocaleDataIndex.NumberSymbols][NumberSymbol.Group];
  1094. }
  1095. }
  1096. return res;
  1097. }
  1098. /**
  1099. * Retrieves a number format for a given locale.
  1100. *
  1101. * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00`
  1102. * when used to format the number 12345.678 could result in "12'345,678". That would happen if the
  1103. * grouping separator for your language is an apostrophe, and the decimal separator is a comma.
  1104. *
  1105. * <b>Important:</b> The characters `.` `,` `0` `#` (and others below) are special placeholders
  1106. * that stand for the decimal separator, and so on, and are NOT real characters.
  1107. * You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in
  1108. * your language the decimal point is written with a comma. The symbols should be replaced by the
  1109. * local equivalents, using the appropriate `NumberSymbol` for your language.
  1110. *
  1111. * Here are the special characters used in number patterns:
  1112. *
  1113. * | Symbol | Meaning |
  1114. * |--------|---------|
  1115. * | . | Replaced automatically by the character used for the decimal point. |
  1116. * | , | Replaced by the "grouping" (thousands) separator. |
  1117. * | 0 | Replaced by a digit (or zero if there aren't enough digits). |
  1118. * | # | Replaced by a digit (or nothing if there aren't enough). |
  1119. * | ¤ | Replaced by a currency symbol, such as $ or USD. |
  1120. * | % | Marks a percent format. The % symbol may change position, but must be retained. |
  1121. * | E | Marks a scientific format. The E symbol may change position, but must be retained. |
  1122. * | ' | Special characters used as literal characters are quoted with ASCII single quotes. |
  1123. *
  1124. * @param locale A locale code for the locale format rules to use.
  1125. * @param type The type of numeric value to be formatted (such as `Decimal` or `Currency`.)
  1126. * @returns The localized format string.
  1127. * @see {@link NumberFormatStyle}
  1128. * @see [CLDR website](http://cldr.unicode.org/translation/number-patterns)
  1129. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1130. *
  1131. * @publicApi
  1132. */
  1133. function getLocaleNumberFormat(locale, type) {
  1134. const data = ɵfindLocaleData(locale);
  1135. return data[ɵLocaleDataIndex.NumberFormats][type];
  1136. }
  1137. /**
  1138. * Retrieves the symbol used to represent the currency for the main country
  1139. * corresponding to a given locale. For example, '$' for `en-US`.
  1140. *
  1141. * @param locale A locale code for the locale format rules to use.
  1142. * @returns The localized symbol character,
  1143. * or `null` if the main country cannot be determined.
  1144. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1145. *
  1146. * @publicApi
  1147. */
  1148. function getLocaleCurrencySymbol(locale) {
  1149. const data = ɵfindLocaleData(locale);
  1150. return data[ɵLocaleDataIndex.CurrencySymbol] || null;
  1151. }
  1152. /**
  1153. * Retrieves the name of the currency for the main country corresponding
  1154. * to a given locale. For example, 'US Dollar' for `en-US`.
  1155. * @param locale A locale code for the locale format rules to use.
  1156. * @returns The currency name,
  1157. * or `null` if the main country cannot be determined.
  1158. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1159. *
  1160. * @publicApi
  1161. */
  1162. function getLocaleCurrencyName(locale) {
  1163. const data = ɵfindLocaleData(locale);
  1164. return data[ɵLocaleDataIndex.CurrencyName] || null;
  1165. }
  1166. /**
  1167. * Retrieves the default currency code for the given locale.
  1168. *
  1169. * The default is defined as the first currency which is still in use.
  1170. *
  1171. * @param locale The code of the locale whose currency code we want.
  1172. * @returns The code of the default currency for the given locale.
  1173. *
  1174. * @publicApi
  1175. */
  1176. function getLocaleCurrencyCode(locale) {
  1177. return ɵgetLocaleCurrencyCode(locale);
  1178. }
  1179. /**
  1180. * Retrieves the currency values for a given locale.
  1181. * @param locale A locale code for the locale format rules to use.
  1182. * @returns The currency values.
  1183. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1184. */
  1185. function getLocaleCurrencies(locale) {
  1186. const data = ɵfindLocaleData(locale);
  1187. return data[ɵLocaleDataIndex.Currencies];
  1188. }
  1189. /**
  1190. * @alias core/ɵgetLocalePluralCase
  1191. * @publicApi
  1192. */
  1193. const getLocalePluralCase = ɵgetLocalePluralCase;
  1194. function checkFullData(data) {
  1195. if (!data[ɵLocaleDataIndex.ExtraData]) {
  1196. throw new Error(`Missing extra locale data for the locale "${data[ɵLocaleDataIndex
  1197. .LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`);
  1198. }
  1199. }
  1200. /**
  1201. * Retrieves locale-specific rules used to determine which day period to use
  1202. * when more than one period is defined for a locale.
  1203. *
  1204. * There is a rule for each defined day period. The
  1205. * first rule is applied to the first day period and so on.
  1206. * Fall back to AM/PM when no rules are available.
  1207. *
  1208. * A rule can specify a period as time range, or as a single time value.
  1209. *
  1210. * This functionality is only available when you have loaded the full locale data.
  1211. * See the ["I18n guide"](guide/i18n-common-format-data-locale).
  1212. *
  1213. * @param locale A locale code for the locale format rules to use.
  1214. * @returns The rules for the locale, a single time value or array of *from-time, to-time*,
  1215. * or null if no periods are available.
  1216. *
  1217. * @see {@link getLocaleExtraDayPeriods}
  1218. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1219. *
  1220. * @publicApi
  1221. */
  1222. function getLocaleExtraDayPeriodRules(locale) {
  1223. const data = ɵfindLocaleData(locale);
  1224. checkFullData(data);
  1225. const rules = data[ɵLocaleDataIndex.ExtraData][2 /* ɵExtraLocaleDataIndex.ExtraDayPeriodsRules */] || [];
  1226. return rules.map((rule) => {
  1227. if (typeof rule === 'string') {
  1228. return extractTime(rule);
  1229. }
  1230. return [extractTime(rule[0]), extractTime(rule[1])];
  1231. });
  1232. }
  1233. /**
  1234. * Retrieves locale-specific day periods, which indicate roughly how a day is broken up
  1235. * in different languages.
  1236. * For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight.
  1237. *
  1238. * This functionality is only available when you have loaded the full locale data.
  1239. * See the ["I18n guide"](guide/i18n-common-format-data-locale).
  1240. *
  1241. * @param locale A locale code for the locale format rules to use.
  1242. * @param formStyle The required grammatical form.
  1243. * @param width The required character width.
  1244. * @returns The translated day-period strings.
  1245. * @see {@link getLocaleExtraDayPeriodRules}
  1246. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1247. *
  1248. * @publicApi
  1249. */
  1250. function getLocaleExtraDayPeriods(locale, formStyle, width) {
  1251. const data = ɵfindLocaleData(locale);
  1252. checkFullData(data);
  1253. const dayPeriodsData = [
  1254. data[ɵLocaleDataIndex.ExtraData][0 /* ɵExtraLocaleDataIndex.ExtraDayPeriodFormats */],
  1255. data[ɵLocaleDataIndex.ExtraData][1 /* ɵExtraLocaleDataIndex.ExtraDayPeriodStandalone */]
  1256. ];
  1257. const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || [];
  1258. return getLastDefinedValue(dayPeriods, width) || [];
  1259. }
  1260. /**
  1261. * Retrieves the writing direction of a specified locale
  1262. * @param locale A locale code for the locale format rules to use.
  1263. * @publicApi
  1264. * @returns 'rtl' or 'ltr'
  1265. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1266. */
  1267. function getLocaleDirection(locale) {
  1268. const data = ɵfindLocaleData(locale);
  1269. return data[ɵLocaleDataIndex.Directionality];
  1270. }
  1271. /**
  1272. * Retrieves the first value that is defined in an array, going backwards from an index position.
  1273. *
  1274. * To avoid repeating the same data (as when the "format" and "standalone" forms are the same)
  1275. * add the first value to the locale data arrays, and add other values only if they are different.
  1276. *
  1277. * @param data The data array to retrieve from.
  1278. * @param index A 0-based index into the array to start from.
  1279. * @returns The value immediately before the given index position.
  1280. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1281. *
  1282. * @publicApi
  1283. */
  1284. function getLastDefinedValue(data, index) {
  1285. for (let i = index; i > -1; i--) {
  1286. if (typeof data[i] !== 'undefined') {
  1287. return data[i];
  1288. }
  1289. }
  1290. throw new Error('Locale data API: locale data undefined');
  1291. }
  1292. /**
  1293. * Extracts the hours and minutes from a string like "15:45"
  1294. */
  1295. function extractTime(time) {
  1296. const [h, m] = time.split(':');
  1297. return { hours: +h, minutes: +m };
  1298. }
  1299. /**
  1300. * Retrieves the currency symbol for a given currency code.
  1301. *
  1302. * For example, for the default `en-US` locale, the code `USD` can
  1303. * be represented by the narrow symbol `$` or the wide symbol `US$`.
  1304. *
  1305. * @param code The currency code.
  1306. * @param format The format, `wide` or `narrow`.
  1307. * @param locale A locale code for the locale format rules to use.
  1308. *
  1309. * @returns The symbol, or the currency code if no symbol is available.
  1310. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1311. *
  1312. * @publicApi
  1313. */
  1314. function getCurrencySymbol(code, format, locale = 'en') {
  1315. const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || [];
  1316. const symbolNarrow = currency[1 /* ɵCurrencyIndex.SymbolNarrow */];
  1317. if (format === 'narrow' && typeof symbolNarrow === 'string') {
  1318. return symbolNarrow;
  1319. }
  1320. return currency[0 /* ɵCurrencyIndex.Symbol */] || code;
  1321. }
  1322. // Most currencies have cents, that's why the default is 2
  1323. const DEFAULT_NB_OF_CURRENCY_DIGITS = 2;
  1324. /**
  1325. * Reports the number of decimal digits for a given currency.
  1326. * The value depends upon the presence of cents in that particular currency.
  1327. *
  1328. * @param code The currency code.
  1329. * @returns The number of decimal digits, typically 0 or 2.
  1330. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1331. *
  1332. * @publicApi
  1333. */
  1334. function getNumberOfCurrencyDigits(code) {
  1335. let digits;
  1336. const currency = CURRENCIES_EN[code];
  1337. if (currency) {
  1338. digits = currency[2 /* ɵCurrencyIndex.NbOfDigits */];
  1339. }
  1340. return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS;
  1341. }
  1342. const ISO8601_DATE_REGEX = /^(\d{4,})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  1343. // 1 2 3 4 5 6 7 8 9 10 11
  1344. const NAMED_FORMATS = {};
  1345. const DATE_FORMATS_SPLIT = /((?:[^BEGHLMOSWYZabcdhmswyz']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|Y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|c{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/;
  1346. var ZoneWidth;
  1347. (function (ZoneWidth) {
  1348. ZoneWidth[ZoneWidth["Short"] = 0] = "Short";
  1349. ZoneWidth[ZoneWidth["ShortGMT"] = 1] = "ShortGMT";
  1350. ZoneWidth[ZoneWidth["Long"] = 2] = "Long";
  1351. ZoneWidth[ZoneWidth["Extended"] = 3] = "Extended";
  1352. })(ZoneWidth || (ZoneWidth = {}));
  1353. var DateType;
  1354. (function (DateType) {
  1355. DateType[DateType["FullYear"] = 0] = "FullYear";
  1356. DateType[DateType["Month"] = 1] = "Month";
  1357. DateType[DateType["Date"] = 2] = "Date";
  1358. DateType[DateType["Hours"] = 3] = "Hours";
  1359. DateType[DateType["Minutes"] = 4] = "Minutes";
  1360. DateType[DateType["Seconds"] = 5] = "Seconds";
  1361. DateType[DateType["FractionalSeconds"] = 6] = "FractionalSeconds";
  1362. DateType[DateType["Day"] = 7] = "Day";
  1363. })(DateType || (DateType = {}));
  1364. var TranslationType;
  1365. (function (TranslationType) {
  1366. TranslationType[TranslationType["DayPeriods"] = 0] = "DayPeriods";
  1367. TranslationType[TranslationType["Days"] = 1] = "Days";
  1368. TranslationType[TranslationType["Months"] = 2] = "Months";
  1369. TranslationType[TranslationType["Eras"] = 3] = "Eras";
  1370. })(TranslationType || (TranslationType = {}));
  1371. /**
  1372. * @ngModule CommonModule
  1373. * @description
  1374. *
  1375. * Formats a date according to locale rules.
  1376. *
  1377. * @param value The date to format, as a Date, or a number (milliseconds since UTC epoch)
  1378. * or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime).
  1379. * @param format The date-time components to include. See `DatePipe` for details.
  1380. * @param locale A locale code for the locale format rules to use.
  1381. * @param timezone The time zone. A time zone offset from GMT (such as `'+0430'`),
  1382. * or a standard UTC/GMT or continental US time zone abbreviation.
  1383. * If not specified, uses host system settings.
  1384. *
  1385. * @returns The formatted date string.
  1386. *
  1387. * @see {@link DatePipe}
  1388. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  1389. *
  1390. * @publicApi
  1391. */
  1392. function formatDate(value, format, locale, timezone) {
  1393. let date = toDate(value);
  1394. const namedFormat = getNamedFormat(locale, format);
  1395. format = namedFormat || format;
  1396. let parts = [];
  1397. let match;
  1398. while (format) {
  1399. match = DATE_FORMATS_SPLIT.exec(format);
  1400. if (match) {
  1401. parts = parts.concat(match.slice(1));
  1402. const part = parts.pop();
  1403. if (!part) {
  1404. break;
  1405. }
  1406. format = part;
  1407. }
  1408. else {
  1409. parts.push(format);
  1410. break;
  1411. }
  1412. }
  1413. let dateTimezoneOffset = date.getTimezoneOffset();
  1414. if (timezone) {
  1415. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1416. date = convertTimezoneToLocal(date, timezone, true);
  1417. }
  1418. let text = '';
  1419. parts.forEach(value => {
  1420. const dateFormatter = getDateFormatter(value);
  1421. text += dateFormatter ? dateFormatter(date, locale, dateTimezoneOffset) :
  1422. value === '\'\'' ? '\'' :
  1423. value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  1424. });
  1425. return text;
  1426. }
  1427. /**
  1428. * Create a new Date object with the given date value, and the time set to midnight.
  1429. *
  1430. * We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999.
  1431. * See: https://github.com/angular/angular/issues/40377
  1432. *
  1433. * Note that this function returns a Date object whose time is midnight in the current locale's
  1434. * timezone. In the future we might want to change this to be midnight in UTC, but this would be a
  1435. * considerable breaking change.
  1436. */
  1437. function createDate(year, month, date) {
  1438. // The `newDate` is set to midnight (UTC) on January 1st 1970.
  1439. // - In PST this will be December 31st 1969 at 4pm.
  1440. // - In GMT this will be January 1st 1970 at 1am.
  1441. // Note that they even have different years, dates and months!
  1442. const newDate = new Date(0);
  1443. // `setFullYear()` allows years like 0001 to be set correctly. This function does not
  1444. // change the internal time of the date.
  1445. // Consider calling `setFullYear(2019, 8, 20)` (September 20, 2019).
  1446. // - In PST this will now be September 20, 2019 at 4pm
  1447. // - In GMT this will now be September 20, 2019 at 1am
  1448. newDate.setFullYear(year, month, date);
  1449. // We want the final date to be at local midnight, so we reset the time.
  1450. // - In PST this will now be September 20, 2019 at 12am
  1451. // - In GMT this will now be September 20, 2019 at 12am
  1452. newDate.setHours(0, 0, 0);
  1453. return newDate;
  1454. }
  1455. function getNamedFormat(locale, format) {
  1456. const localeId = getLocaleId(locale);
  1457. NAMED_FORMATS[localeId] = NAMED_FORMATS[localeId] || {};
  1458. if (NAMED_FORMATS[localeId][format]) {
  1459. return NAMED_FORMATS[localeId][format];
  1460. }
  1461. let formatValue = '';
  1462. switch (format) {
  1463. case 'shortDate':
  1464. formatValue = getLocaleDateFormat(locale, FormatWidth.Short);
  1465. break;
  1466. case 'mediumDate':
  1467. formatValue = getLocaleDateFormat(locale, FormatWidth.Medium);
  1468. break;
  1469. case 'longDate':
  1470. formatValue = getLocaleDateFormat(locale, FormatWidth.Long);
  1471. break;
  1472. case 'fullDate':
  1473. formatValue = getLocaleDateFormat(locale, FormatWidth.Full);
  1474. break;
  1475. case 'shortTime':
  1476. formatValue = getLocaleTimeFormat(locale, FormatWidth.Short);
  1477. break;
  1478. case 'mediumTime':
  1479. formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium);
  1480. break;
  1481. case 'longTime':
  1482. formatValue = getLocaleTimeFormat(locale, FormatWidth.Long);
  1483. break;
  1484. case 'fullTime':
  1485. formatValue = getLocaleTimeFormat(locale, FormatWidth.Full);
  1486. break;
  1487. case 'short':
  1488. const shortTime = getNamedFormat(locale, 'shortTime');
  1489. const shortDate = getNamedFormat(locale, 'shortDate');
  1490. formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [shortTime, shortDate]);
  1491. break;
  1492. case 'medium':
  1493. const mediumTime = getNamedFormat(locale, 'mediumTime');
  1494. const mediumDate = getNamedFormat(locale, 'mediumDate');
  1495. formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [mediumTime, mediumDate]);
  1496. break;
  1497. case 'long':
  1498. const longTime = getNamedFormat(locale, 'longTime');
  1499. const longDate = getNamedFormat(locale, 'longDate');
  1500. formatValue =
  1501. formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [longTime, longDate]);
  1502. break;
  1503. case 'full':
  1504. const fullTime = getNamedFormat(locale, 'fullTime');
  1505. const fullDate = getNamedFormat(locale, 'fullDate');
  1506. formatValue =
  1507. formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [fullTime, fullDate]);
  1508. break;
  1509. }
  1510. if (formatValue) {
  1511. NAMED_FORMATS[localeId][format] = formatValue;
  1512. }
  1513. return formatValue;
  1514. }
  1515. function formatDateTime(str, opt_values) {
  1516. if (opt_values) {
  1517. str = str.replace(/\{([^}]+)}/g, function (match, key) {
  1518. return (opt_values != null && key in opt_values) ? opt_values[key] : match;
  1519. });
  1520. }
  1521. return str;
  1522. }
  1523. function padNumber(num, digits, minusSign = '-', trim, negWrap) {
  1524. let neg = '';
  1525. if (num < 0 || (negWrap && num <= 0)) {
  1526. if (negWrap) {
  1527. num = -num + 1;
  1528. }
  1529. else {
  1530. num = -num;
  1531. neg = minusSign;
  1532. }
  1533. }
  1534. let strNum = String(num);
  1535. while (strNum.length < digits) {
  1536. strNum = '0' + strNum;
  1537. }
  1538. if (trim) {
  1539. strNum = strNum.slice(strNum.length - digits);
  1540. }
  1541. return neg + strNum;
  1542. }
  1543. function formatFractionalSeconds(milliseconds, digits) {
  1544. const strMs = padNumber(milliseconds, 3);
  1545. return strMs.substring(0, digits);
  1546. }
  1547. /**
  1548. * Returns a date formatter that transforms a date into its locale digit representation
  1549. */
  1550. function dateGetter(name, size, offset = 0, trim = false, negWrap = false) {
  1551. return function (date, locale) {
  1552. let part = getDatePart(name, date);
  1553. if (offset > 0 || part > -offset) {
  1554. part += offset;
  1555. }
  1556. if (name === DateType.Hours) {
  1557. if (part === 0 && offset === -12) {
  1558. part = 12;
  1559. }
  1560. }
  1561. else if (name === DateType.FractionalSeconds) {
  1562. return formatFractionalSeconds(part, size);
  1563. }
  1564. const localeMinus = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
  1565. return padNumber(part, size, localeMinus, trim, negWrap);
  1566. };
  1567. }
  1568. function getDatePart(part, date) {
  1569. switch (part) {
  1570. case DateType.FullYear:
  1571. return date.getFullYear();
  1572. case DateType.Month:
  1573. return date.getMonth();
  1574. case DateType.Date:
  1575. return date.getDate();
  1576. case DateType.Hours:
  1577. return date.getHours();
  1578. case DateType.Minutes:
  1579. return date.getMinutes();
  1580. case DateType.Seconds:
  1581. return date.getSeconds();
  1582. case DateType.FractionalSeconds:
  1583. return date.getMilliseconds();
  1584. case DateType.Day:
  1585. return date.getDay();
  1586. default:
  1587. throw new Error(`Unknown DateType value "${part}".`);
  1588. }
  1589. }
  1590. /**
  1591. * Returns a date formatter that transforms a date into its locale string representation
  1592. */
  1593. function dateStrGetter(name, width, form = FormStyle.Format, extended = false) {
  1594. return function (date, locale) {
  1595. return getDateTranslation(date, locale, name, width, form, extended);
  1596. };
  1597. }
  1598. /**
  1599. * Returns the locale translation of a date for a given form, type and width
  1600. */
  1601. function getDateTranslation(date, locale, name, width, form, extended) {
  1602. switch (name) {
  1603. case TranslationType.Months:
  1604. return getLocaleMonthNames(locale, form, width)[date.getMonth()];
  1605. case TranslationType.Days:
  1606. return getLocaleDayNames(locale, form, width)[date.getDay()];
  1607. case TranslationType.DayPeriods:
  1608. const currentHours = date.getHours();
  1609. const currentMinutes = date.getMinutes();
  1610. if (extended) {
  1611. const rules = getLocaleExtraDayPeriodRules(locale);
  1612. const dayPeriods = getLocaleExtraDayPeriods(locale, form, width);
  1613. const index = rules.findIndex(rule => {
  1614. if (Array.isArray(rule)) {
  1615. // morning, afternoon, evening, night
  1616. const [from, to] = rule;
  1617. const afterFrom = currentHours >= from.hours && currentMinutes >= from.minutes;
  1618. const beforeTo = (currentHours < to.hours ||
  1619. (currentHours === to.hours && currentMinutes < to.minutes));
  1620. // We must account for normal rules that span a period during the day (e.g. 6am-9am)
  1621. // where `from` is less (earlier) than `to`. But also rules that span midnight (e.g.
  1622. // 10pm - 5am) where `from` is greater (later!) than `to`.
  1623. //
  1624. // In the first case the current time must be BOTH after `from` AND before `to`
  1625. // (e.g. 8am is after 6am AND before 10am).
  1626. //
  1627. // In the second case the current time must be EITHER after `from` OR before `to`
  1628. // (e.g. 4am is before 5am but not after 10pm; and 11pm is not before 5am but it is
  1629. // after 10pm).
  1630. if (from.hours < to.hours) {
  1631. if (afterFrom && beforeTo) {
  1632. return true;
  1633. }
  1634. }
  1635. else if (afterFrom || beforeTo) {
  1636. return true;
  1637. }
  1638. }
  1639. else { // noon or midnight
  1640. if (rule.hours === currentHours && rule.minutes === currentMinutes) {
  1641. return true;
  1642. }
  1643. }
  1644. return false;
  1645. });
  1646. if (index !== -1) {
  1647. return dayPeriods[index];
  1648. }
  1649. }
  1650. // if no rules for the day periods, we use am/pm by default
  1651. return getLocaleDayPeriods(locale, form, width)[currentHours < 12 ? 0 : 1];
  1652. case TranslationType.Eras:
  1653. return getLocaleEraNames(locale, width)[date.getFullYear() <= 0 ? 0 : 1];
  1654. default:
  1655. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  1656. // However Closure Compiler does not understand that and reports an error in typed mode.
  1657. // The `throw new Error` below works around the problem, and the unexpected: never variable
  1658. // makes sure tsc still checks this code is unreachable.
  1659. const unexpected = name;
  1660. throw new Error(`unexpected translation type ${unexpected}`);
  1661. }
  1662. }
  1663. /**
  1664. * Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or
  1665. * GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30,
  1666. * extended = +04:30)
  1667. */
  1668. function timeZoneGetter(width) {
  1669. return function (date, locale, offset) {
  1670. const zone = -1 * offset;
  1671. const minusSign = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
  1672. const hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60);
  1673. switch (width) {
  1674. case ZoneWidth.Short:
  1675. return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) +
  1676. padNumber(Math.abs(zone % 60), 2, minusSign);
  1677. case ZoneWidth.ShortGMT:
  1678. return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 1, minusSign);
  1679. case ZoneWidth.Long:
  1680. return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' +
  1681. padNumber(Math.abs(zone % 60), 2, minusSign);
  1682. case ZoneWidth.Extended:
  1683. if (offset === 0) {
  1684. return 'Z';
  1685. }
  1686. else {
  1687. return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' +
  1688. padNumber(Math.abs(zone % 60), 2, minusSign);
  1689. }
  1690. default:
  1691. throw new Error(`Unknown zone width "${width}"`);
  1692. }
  1693. };
  1694. }
  1695. const JANUARY = 0;
  1696. const THURSDAY = 4;
  1697. function getFirstThursdayOfYear(year) {
  1698. const firstDayOfYear = createDate(year, JANUARY, 1).getDay();
  1699. return createDate(year, 0, 1 + ((firstDayOfYear <= THURSDAY) ? THURSDAY : THURSDAY + 7) - firstDayOfYear);
  1700. }
  1701. function getThursdayThisWeek(datetime) {
  1702. return createDate(datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + (THURSDAY - datetime.getDay()));
  1703. }
  1704. function weekGetter(size, monthBased = false) {
  1705. return function (date, locale) {
  1706. let result;
  1707. if (monthBased) {
  1708. const nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1;
  1709. const today = date.getDate();
  1710. result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7);
  1711. }
  1712. else {
  1713. const thisThurs = getThursdayThisWeek(date);
  1714. // Some days of a year are part of next year according to ISO 8601.
  1715. // Compute the firstThurs from the year of this week's Thursday
  1716. const firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear());
  1717. const diff = thisThurs.getTime() - firstThurs.getTime();
  1718. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  1719. }
  1720. return padNumber(result, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  1721. };
  1722. }
  1723. /**
  1724. * Returns a date formatter that provides the week-numbering year for the input date.
  1725. */
  1726. function weekNumberingYearGetter(size, trim = false) {
  1727. return function (date, locale) {
  1728. const thisThurs = getThursdayThisWeek(date);
  1729. const weekNumberingYear = thisThurs.getFullYear();
  1730. return padNumber(weekNumberingYear, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim);
  1731. };
  1732. }
  1733. const DATE_FORMATS = {};
  1734. // Based on CLDR formats:
  1735. // See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  1736. // See also explanations: http://cldr.unicode.org/translation/date-time
  1737. // TODO(ocombe): support all missing cldr formats: U, Q, D, F, e, j, J, C, A, v, V, X, x
  1738. function getDateFormatter(format) {
  1739. if (DATE_FORMATS[format]) {
  1740. return DATE_FORMATS[format];
  1741. }
  1742. let formatter;
  1743. switch (format) {
  1744. // Era name (AD/BC)
  1745. case 'G':
  1746. case 'GG':
  1747. case 'GGG':
  1748. formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Abbreviated);
  1749. break;
  1750. case 'GGGG':
  1751. formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Wide);
  1752. break;
  1753. case 'GGGGG':
  1754. formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Narrow);
  1755. break;
  1756. // 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199)
  1757. case 'y':
  1758. formatter = dateGetter(DateType.FullYear, 1, 0, false, true);
  1759. break;
  1760. // 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  1761. case 'yy':
  1762. formatter = dateGetter(DateType.FullYear, 2, 0, true, true);
  1763. break;
  1764. // 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10)
  1765. case 'yyy':
  1766. formatter = dateGetter(DateType.FullYear, 3, 0, false, true);
  1767. break;
  1768. // 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010)
  1769. case 'yyyy':
  1770. formatter = dateGetter(DateType.FullYear, 4, 0, false, true);
  1771. break;
  1772. // 1 digit representation of the week-numbering year, e.g. (AD 1 => 1, AD 199 => 199)
  1773. case 'Y':
  1774. formatter = weekNumberingYearGetter(1);
  1775. break;
  1776. // 2 digit representation of the week-numbering year, padded (00-99). (e.g. AD 2001 => 01, AD
  1777. // 2010 => 10)
  1778. case 'YY':
  1779. formatter = weekNumberingYearGetter(2, true);
  1780. break;
  1781. // 3 digit representation of the week-numbering year, padded (000-999). (e.g. AD 1 => 001, AD
  1782. // 2010 => 2010)
  1783. case 'YYY':
  1784. formatter = weekNumberingYearGetter(3);
  1785. break;
  1786. // 4 digit representation of the week-numbering year (e.g. AD 1 => 0001, AD 2010 => 2010)
  1787. case 'YYYY':
  1788. formatter = weekNumberingYearGetter(4);
  1789. break;
  1790. // Month of the year (1-12), numeric
  1791. case 'M':
  1792. case 'L':
  1793. formatter = dateGetter(DateType.Month, 1, 1);
  1794. break;
  1795. case 'MM':
  1796. case 'LL':
  1797. formatter = dateGetter(DateType.Month, 2, 1);
  1798. break;
  1799. // Month of the year (January, ...), string, format
  1800. case 'MMM':
  1801. formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated);
  1802. break;
  1803. case 'MMMM':
  1804. formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide);
  1805. break;
  1806. case 'MMMMM':
  1807. formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow);
  1808. break;
  1809. // Month of the year (January, ...), string, standalone
  1810. case 'LLL':
  1811. formatter =
  1812. dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated, FormStyle.Standalone);
  1813. break;
  1814. case 'LLLL':
  1815. formatter =
  1816. dateStrGetter(TranslationType.Months, TranslationWidth.Wide, FormStyle.Standalone);
  1817. break;
  1818. case 'LLLLL':
  1819. formatter =
  1820. dateStrGetter(TranslationType.Months, TranslationWidth.Narrow, FormStyle.Standalone);
  1821. break;
  1822. // Week of the year (1, ... 52)
  1823. case 'w':
  1824. formatter = weekGetter(1);
  1825. break;
  1826. case 'ww':
  1827. formatter = weekGetter(2);
  1828. break;
  1829. // Week of the month (1, ...)
  1830. case 'W':
  1831. formatter = weekGetter(1, true);
  1832. break;
  1833. // Day of the month (1-31)
  1834. case 'd':
  1835. formatter = dateGetter(DateType.Date, 1);
  1836. break;
  1837. case 'dd':
  1838. formatter = dateGetter(DateType.Date, 2);
  1839. break;
  1840. // Day of the Week StandAlone (1, 1, Mon, Monday, M, Mo)
  1841. case 'c':
  1842. case 'cc':
  1843. formatter = dateGetter(DateType.Day, 1);
  1844. break;
  1845. case 'ccc':
  1846. formatter =
  1847. dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated, FormStyle.Standalone);
  1848. break;
  1849. case 'cccc':
  1850. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide, FormStyle.Standalone);
  1851. break;
  1852. case 'ccccc':
  1853. formatter =
  1854. dateStrGetter(TranslationType.Days, TranslationWidth.Narrow, FormStyle.Standalone);
  1855. break;
  1856. case 'cccccc':
  1857. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short, FormStyle.Standalone);
  1858. break;
  1859. // Day of the Week
  1860. case 'E':
  1861. case 'EE':
  1862. case 'EEE':
  1863. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated);
  1864. break;
  1865. case 'EEEE':
  1866. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide);
  1867. break;
  1868. case 'EEEEE':
  1869. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow);
  1870. break;
  1871. case 'EEEEEE':
  1872. formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short);
  1873. break;
  1874. // Generic period of the day (am-pm)
  1875. case 'a':
  1876. case 'aa':
  1877. case 'aaa':
  1878. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated);
  1879. break;
  1880. case 'aaaa':
  1881. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide);
  1882. break;
  1883. case 'aaaaa':
  1884. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow);
  1885. break;
  1886. // Extended period of the day (midnight, at night, ...), standalone
  1887. case 'b':
  1888. case 'bb':
  1889. case 'bbb':
  1890. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Standalone, true);
  1891. break;
  1892. case 'bbbb':
  1893. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Standalone, true);
  1894. break;
  1895. case 'bbbbb':
  1896. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Standalone, true);
  1897. break;
  1898. // Extended period of the day (midnight, night, ...), standalone
  1899. case 'B':
  1900. case 'BB':
  1901. case 'BBB':
  1902. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Format, true);
  1903. break;
  1904. case 'BBBB':
  1905. formatter =
  1906. dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Format, true);
  1907. break;
  1908. case 'BBBBB':
  1909. formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Format, true);
  1910. break;
  1911. // Hour in AM/PM, (1-12)
  1912. case 'h':
  1913. formatter = dateGetter(DateType.Hours, 1, -12);
  1914. break;
  1915. case 'hh':
  1916. formatter = dateGetter(DateType.Hours, 2, -12);
  1917. break;
  1918. // Hour of the day (0-23)
  1919. case 'H':
  1920. formatter = dateGetter(DateType.Hours, 1);
  1921. break;
  1922. // Hour in day, padded (00-23)
  1923. case 'HH':
  1924. formatter = dateGetter(DateType.Hours, 2);
  1925. break;
  1926. // Minute of the hour (0-59)
  1927. case 'm':
  1928. formatter = dateGetter(DateType.Minutes, 1);
  1929. break;
  1930. case 'mm':
  1931. formatter = dateGetter(DateType.Minutes, 2);
  1932. break;
  1933. // Second of the minute (0-59)
  1934. case 's':
  1935. formatter = dateGetter(DateType.Seconds, 1);
  1936. break;
  1937. case 'ss':
  1938. formatter = dateGetter(DateType.Seconds, 2);
  1939. break;
  1940. // Fractional second
  1941. case 'S':
  1942. formatter = dateGetter(DateType.FractionalSeconds, 1);
  1943. break;
  1944. case 'SS':
  1945. formatter = dateGetter(DateType.FractionalSeconds, 2);
  1946. break;
  1947. case 'SSS':
  1948. formatter = dateGetter(DateType.FractionalSeconds, 3);
  1949. break;
  1950. // Timezone ISO8601 short format (-0430)
  1951. case 'Z':
  1952. case 'ZZ':
  1953. case 'ZZZ':
  1954. formatter = timeZoneGetter(ZoneWidth.Short);
  1955. break;
  1956. // Timezone ISO8601 extended format (-04:30)
  1957. case 'ZZZZZ':
  1958. formatter = timeZoneGetter(ZoneWidth.Extended);
  1959. break;
  1960. // Timezone GMT short format (GMT+4)
  1961. case 'O':
  1962. case 'OO':
  1963. case 'OOO':
  1964. // Should be location, but fallback to format O instead because we don't have the data yet
  1965. case 'z':
  1966. case 'zz':
  1967. case 'zzz':
  1968. formatter = timeZoneGetter(ZoneWidth.ShortGMT);
  1969. break;
  1970. // Timezone GMT long format (GMT+0430)
  1971. case 'OOOO':
  1972. case 'ZZZZ':
  1973. // Should be location, but fallback to format O instead because we don't have the data yet
  1974. case 'zzzz':
  1975. formatter = timeZoneGetter(ZoneWidth.Long);
  1976. break;
  1977. default:
  1978. return null;
  1979. }
  1980. DATE_FORMATS[format] = formatter;
  1981. return formatter;
  1982. }
  1983. function timezoneToOffset(timezone, fallback) {
  1984. // Support: IE 11 only, Edge 13-15+
  1985. // IE/Edge do not "understand" colon (`:`) in timezone
  1986. timezone = timezone.replace(/:/g, '');
  1987. const requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1988. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1989. }
  1990. function addDateMinutes(date, minutes) {
  1991. date = new Date(date.getTime());
  1992. date.setMinutes(date.getMinutes() + minutes);
  1993. return date;
  1994. }
  1995. function convertTimezoneToLocal(date, timezone, reverse) {
  1996. const reverseValue = reverse ? -1 : 1;
  1997. const dateTimezoneOffset = date.getTimezoneOffset();
  1998. const timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1999. return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset));
  2000. }
  2001. /**
  2002. * Converts a value to date.
  2003. *
  2004. * Supported input formats:
  2005. * - `Date`
  2006. * - number: timestamp
  2007. * - string: numeric (e.g. "1234"), ISO and date strings in a format supported by
  2008. * [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse).
  2009. * Note: ISO strings without time return a date without timeoffset.
  2010. *
  2011. * Throws if unable to convert to a date.
  2012. */
  2013. function toDate(value) {
  2014. if (isDate(value)) {
  2015. return value;
  2016. }
  2017. if (typeof value === 'number' && !isNaN(value)) {
  2018. return new Date(value);
  2019. }
  2020. if (typeof value === 'string') {
  2021. value = value.trim();
  2022. if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) {
  2023. /* For ISO Strings without time the day, month and year must be extracted from the ISO String
  2024. before Date creation to avoid time offset and errors in the new Date.
  2025. If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new
  2026. date, some browsers (e.g. IE 9) will throw an invalid Date error.
  2027. If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset
  2028. is applied.
  2029. Note: ISO months are 0 for January, 1 for February, ... */
  2030. const [y, m = 1, d = 1] = value.split('-').map((val) => +val);
  2031. return createDate(y, m - 1, d);
  2032. }
  2033. const parsedNb = parseFloat(value);
  2034. // any string that only contains numbers, like "1234" but not like "1234hello"
  2035. if (!isNaN(value - parsedNb)) {
  2036. return new Date(parsedNb);
  2037. }
  2038. let match;
  2039. if (match = value.match(ISO8601_DATE_REGEX)) {
  2040. return isoStringToDate(match);
  2041. }
  2042. }
  2043. const date = new Date(value);
  2044. if (!isDate(date)) {
  2045. throw new Error(`Unable to convert "${value}" into a date`);
  2046. }
  2047. return date;
  2048. }
  2049. /**
  2050. * Converts a date in ISO8601 to a Date.
  2051. * Used instead of `Date.parse` because of browser discrepancies.
  2052. */
  2053. function isoStringToDate(match) {
  2054. const date = new Date(0);
  2055. let tzHour = 0;
  2056. let tzMin = 0;
  2057. // match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100"
  2058. const dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear;
  2059. const timeSetter = match[8] ? date.setUTCHours : date.setHours;
  2060. // if there is a timezone defined like "+01:00" or "+0100"
  2061. if (match[9]) {
  2062. tzHour = Number(match[9] + match[10]);
  2063. tzMin = Number(match[9] + match[11]);
  2064. }
  2065. dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3]));
  2066. const h = Number(match[4] || 0) - tzHour;
  2067. const m = Number(match[5] || 0) - tzMin;
  2068. const s = Number(match[6] || 0);
  2069. // The ECMAScript specification (https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.11)
  2070. // defines that `DateTime` milliseconds should always be rounded down, so that `999.9ms`
  2071. // becomes `999ms`.
  2072. const ms = Math.floor(parseFloat('0.' + (match[7] || 0)) * 1000);
  2073. timeSetter.call(date, h, m, s, ms);
  2074. return date;
  2075. }
  2076. function isDate(value) {
  2077. return value instanceof Date && !isNaN(value.valueOf());
  2078. }
  2079. const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
  2080. const MAX_DIGITS = 22;
  2081. const DECIMAL_SEP = '.';
  2082. const ZERO_CHAR = '0';
  2083. const PATTERN_SEP = ';';
  2084. const GROUP_SEP = ',';
  2085. const DIGIT_CHAR = '#';
  2086. const CURRENCY_CHAR = '¤';
  2087. const PERCENT_CHAR = '%';
  2088. /**
  2089. * Transforms a number to a locale string based on a style and a format.
  2090. */
  2091. function formatNumberToLocaleString(value, pattern, locale, groupSymbol, decimalSymbol, digitsInfo, isPercent = false) {
  2092. let formattedText = '';
  2093. let isZero = false;
  2094. if (!isFinite(value)) {
  2095. formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity);
  2096. }
  2097. else {
  2098. let parsedNumber = parseNumber(value);
  2099. if (isPercent) {
  2100. parsedNumber = toPercent(parsedNumber);
  2101. }
  2102. let minInt = pattern.minInt;
  2103. let minFraction = pattern.minFrac;
  2104. let maxFraction = pattern.maxFrac;
  2105. if (digitsInfo) {
  2106. const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP);
  2107. if (parts === null) {
  2108. throw new Error(`${digitsInfo} is not a valid digit info`);
  2109. }
  2110. const minIntPart = parts[1];
  2111. const minFractionPart = parts[3];
  2112. const maxFractionPart = parts[5];
  2113. if (minIntPart != null) {
  2114. minInt = parseIntAutoRadix(minIntPart);
  2115. }
  2116. if (minFractionPart != null) {
  2117. minFraction = parseIntAutoRadix(minFractionPart);
  2118. }
  2119. if (maxFractionPart != null) {
  2120. maxFraction = parseIntAutoRadix(maxFractionPart);
  2121. }
  2122. else if (minFractionPart != null && minFraction > maxFraction) {
  2123. maxFraction = minFraction;
  2124. }
  2125. }
  2126. roundNumber(parsedNumber, minFraction, maxFraction);
  2127. let digits = parsedNumber.digits;
  2128. let integerLen = parsedNumber.integerLen;
  2129. const exponent = parsedNumber.exponent;
  2130. let decimals = [];
  2131. isZero = digits.every(d => !d);
  2132. // pad zeros for small numbers
  2133. for (; integerLen < minInt; integerLen++) {
  2134. digits.unshift(0);
  2135. }
  2136. // pad zeros for small numbers
  2137. for (; integerLen < 0; integerLen++) {
  2138. digits.unshift(0);
  2139. }
  2140. // extract decimals digits
  2141. if (integerLen > 0) {
  2142. decimals = digits.splice(integerLen, digits.length);
  2143. }
  2144. else {
  2145. decimals = digits;
  2146. digits = [0];
  2147. }
  2148. // format the integer digits with grouping separators
  2149. const groups = [];
  2150. if (digits.length >= pattern.lgSize) {
  2151. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  2152. }
  2153. while (digits.length > pattern.gSize) {
  2154. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  2155. }
  2156. if (digits.length) {
  2157. groups.unshift(digits.join(''));
  2158. }
  2159. formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol));
  2160. // append the decimal digits
  2161. if (decimals.length) {
  2162. formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join('');
  2163. }
  2164. if (exponent) {
  2165. formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent;
  2166. }
  2167. }
  2168. if (value < 0 && !isZero) {
  2169. formattedText = pattern.negPre + formattedText + pattern.negSuf;
  2170. }
  2171. else {
  2172. formattedText = pattern.posPre + formattedText + pattern.posSuf;
  2173. }
  2174. return formattedText;
  2175. }
  2176. /**
  2177. * @ngModule CommonModule
  2178. * @description
  2179. *
  2180. * Formats a number as currency using locale rules.
  2181. *
  2182. * @param value The number to format.
  2183. * @param locale A locale code for the locale format rules to use.
  2184. * @param currency A string containing the currency symbol or its name,
  2185. * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation
  2186. * of the function.
  2187. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)
  2188. * currency code, such as `USD` for the US dollar and `EUR` for the euro.
  2189. * Used to determine the number of digits in the decimal part.
  2190. * @param digitsInfo Decimal representation options, specified by a string in the following format:
  2191. * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
  2192. *
  2193. * @returns The formatted currency value.
  2194. *
  2195. * @see {@link formatNumber}
  2196. * @see {@link DecimalPipe}
  2197. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  2198. *
  2199. * @publicApi
  2200. */
  2201. function formatCurrency(value, locale, currency, currencyCode, digitsInfo) {
  2202. const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency);
  2203. const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  2204. pattern.minFrac = getNumberOfCurrencyDigits(currencyCode);
  2205. pattern.maxFrac = pattern.minFrac;
  2206. const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo);
  2207. return res
  2208. .replace(CURRENCY_CHAR, currency)
  2209. // if we have 2 time the currency character, the second one is ignored
  2210. .replace(CURRENCY_CHAR, '')
  2211. // If there is a spacing between currency character and the value and
  2212. // the currency character is suppressed by passing an empty string, the
  2213. // spacing character would remain as part of the string. Then we
  2214. // should remove it.
  2215. .trim();
  2216. }
  2217. /**
  2218. * @ngModule CommonModule
  2219. * @description
  2220. *
  2221. * Formats a number as a percentage according to locale rules.
  2222. *
  2223. * @param value The number to format.
  2224. * @param locale A locale code for the locale format rules to use.
  2225. * @param digitsInfo Decimal representation options, specified by a string in the following format:
  2226. * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
  2227. *
  2228. * @returns The formatted percentage value.
  2229. *
  2230. * @see {@link formatNumber}
  2231. * @see {@link DecimalPipe}
  2232. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  2233. * @publicApi
  2234. *
  2235. */
  2236. function formatPercent(value, locale, digitsInfo) {
  2237. const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent);
  2238. const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  2239. const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true);
  2240. return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign));
  2241. }
  2242. /**
  2243. * @ngModule CommonModule
  2244. * @description
  2245. *
  2246. * Formats a number as text, with group sizing, separator, and other
  2247. * parameters based on the locale.
  2248. *
  2249. * @param value The number to format.
  2250. * @param locale A locale code for the locale format rules to use.
  2251. * @param digitsInfo Decimal representation options, specified by a string in the following format:
  2252. * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
  2253. *
  2254. * @returns The formatted text string.
  2255. * @see [Internationalization (i18n) Guide](/guide/i18n-overview)
  2256. *
  2257. * @publicApi
  2258. */
  2259. function formatNumber(value, locale, digitsInfo) {
  2260. const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal);
  2261. const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  2262. return formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo);
  2263. }
  2264. function parseNumberFormat(format, minusSign = '-') {
  2265. const p = {
  2266. minInt: 1,
  2267. minFrac: 0,
  2268. maxFrac: 0,
  2269. posPre: '',
  2270. posSuf: '',
  2271. negPre: '',
  2272. negSuf: '',
  2273. gSize: 0,
  2274. lgSize: 0
  2275. };
  2276. const patternParts = format.split(PATTERN_SEP);
  2277. const positive = patternParts[0];
  2278. const negative = patternParts[1];
  2279. const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ?
  2280. positive.split(DECIMAL_SEP) :
  2281. [
  2282. positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1),
  2283. positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1)
  2284. ], integer = positiveParts[0], fraction = positiveParts[1] || '';
  2285. p.posPre = integer.substring(0, integer.indexOf(DIGIT_CHAR));
  2286. for (let i = 0; i < fraction.length; i++) {
  2287. const ch = fraction.charAt(i);
  2288. if (ch === ZERO_CHAR) {
  2289. p.minFrac = p.maxFrac = i + 1;
  2290. }
  2291. else if (ch === DIGIT_CHAR) {
  2292. p.maxFrac = i + 1;
  2293. }
  2294. else {
  2295. p.posSuf += ch;
  2296. }
  2297. }
  2298. const groups = integer.split(GROUP_SEP);
  2299. p.gSize = groups[1] ? groups[1].length : 0;
  2300. p.lgSize = (groups[2] || groups[1]) ? (groups[2] || groups[1]).length : 0;
  2301. if (negative) {
  2302. const trunkLen = positive.length - p.posPre.length - p.posSuf.length, pos = negative.indexOf(DIGIT_CHAR);
  2303. p.negPre = negative.substring(0, pos).replace(/'/g, '');
  2304. p.negSuf = negative.slice(pos + trunkLen).replace(/'/g, '');
  2305. }
  2306. else {
  2307. p.negPre = minusSign + p.posPre;
  2308. p.negSuf = p.posSuf;
  2309. }
  2310. return p;
  2311. }
  2312. // Transforms a parsed number into a percentage by multiplying it by 100
  2313. function toPercent(parsedNumber) {
  2314. // if the number is 0, don't do anything
  2315. if (parsedNumber.digits[0] === 0) {
  2316. return parsedNumber;
  2317. }
  2318. // Getting the current number of decimals
  2319. const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen;
  2320. if (parsedNumber.exponent) {
  2321. parsedNumber.exponent += 2;
  2322. }
  2323. else {
  2324. if (fractionLen === 0) {
  2325. parsedNumber.digits.push(0, 0);
  2326. }
  2327. else if (fractionLen === 1) {
  2328. parsedNumber.digits.push(0);
  2329. }
  2330. parsedNumber.integerLen += 2;
  2331. }
  2332. return parsedNumber;
  2333. }
  2334. /**
  2335. * Parses a number.
  2336. * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/
  2337. */
  2338. function parseNumber(num) {
  2339. let numStr = Math.abs(num) + '';
  2340. let exponent = 0, digits, integerLen;
  2341. let i, j, zeros;
  2342. // Decimal point?
  2343. if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) {
  2344. numStr = numStr.replace(DECIMAL_SEP, '');
  2345. }
  2346. // Exponential form?
  2347. if ((i = numStr.search(/e/i)) > 0) {
  2348. // Work out the exponent.
  2349. if (integerLen < 0)
  2350. integerLen = i;
  2351. integerLen += +numStr.slice(i + 1);
  2352. numStr = numStr.substring(0, i);
  2353. }
  2354. else if (integerLen < 0) {
  2355. // There was no decimal point or exponent so it is an integer.
  2356. integerLen = numStr.length;
  2357. }
  2358. // Count the number of leading zeros.
  2359. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */
  2360. }
  2361. if (i === (zeros = numStr.length)) {
  2362. // The digits are all zero.
  2363. digits = [0];
  2364. integerLen = 1;
  2365. }
  2366. else {
  2367. // Count the number of trailing zeros
  2368. zeros--;
  2369. while (numStr.charAt(zeros) === ZERO_CHAR)
  2370. zeros--;
  2371. // Trailing zeros are insignificant so ignore them
  2372. integerLen -= i;
  2373. digits = [];
  2374. // Convert string to array of digits without leading/trailing zeros.
  2375. for (j = 0; i <= zeros; i++, j++) {
  2376. digits[j] = Number(numStr.charAt(i));
  2377. }
  2378. }
  2379. // If the number overflows the maximum allowed digits then use an exponent.
  2380. if (integerLen > MAX_DIGITS) {
  2381. digits = digits.splice(0, MAX_DIGITS - 1);
  2382. exponent = integerLen - 1;
  2383. integerLen = 1;
  2384. }
  2385. return { digits, exponent, integerLen };
  2386. }
  2387. /**
  2388. * Round the parsed number to the specified number of decimal places
  2389. * This function changes the parsedNumber in-place
  2390. */
  2391. function roundNumber(parsedNumber, minFrac, maxFrac) {
  2392. if (minFrac > maxFrac) {
  2393. throw new Error(`The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`);
  2394. }
  2395. let digits = parsedNumber.digits;
  2396. let fractionLen = digits.length - parsedNumber.integerLen;
  2397. const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac);
  2398. // The index of the digit to where rounding is to occur
  2399. let roundAt = fractionSize + parsedNumber.integerLen;
  2400. let digit = digits[roundAt];
  2401. if (roundAt > 0) {
  2402. // Drop fractional digits beyond `roundAt`
  2403. digits.splice(Math.max(parsedNumber.integerLen, roundAt));
  2404. // Set non-fractional digits beyond `roundAt` to 0
  2405. for (let j = roundAt; j < digits.length; j++) {
  2406. digits[j] = 0;
  2407. }
  2408. }
  2409. else {
  2410. // We rounded to zero so reset the parsedNumber
  2411. fractionLen = Math.max(0, fractionLen);
  2412. parsedNumber.integerLen = 1;
  2413. digits.length = Math.max(1, roundAt = fractionSize + 1);
  2414. digits[0] = 0;
  2415. for (let i = 1; i < roundAt; i++)
  2416. digits[i] = 0;
  2417. }
  2418. if (digit >= 5) {
  2419. if (roundAt - 1 < 0) {
  2420. for (let k = 0; k > roundAt; k--) {
  2421. digits.unshift(0);
  2422. parsedNumber.integerLen++;
  2423. }
  2424. digits.unshift(1);
  2425. parsedNumber.integerLen++;
  2426. }
  2427. else {
  2428. digits[roundAt - 1]++;
  2429. }
  2430. }
  2431. // Pad out with zeros to get the required fraction length
  2432. for (; fractionLen < Math.max(0, fractionSize); fractionLen++)
  2433. digits.push(0);
  2434. let dropTrailingZeros = fractionSize !== 0;
  2435. // Minimal length = nb of decimals required + current nb of integers
  2436. // Any number besides that is optional and can be removed if it's a trailing 0
  2437. const minLen = minFrac + parsedNumber.integerLen;
  2438. // Do any carrying, e.g. a digit was rounded up to 10
  2439. const carry = digits.reduceRight(function (carry, d, i, digits) {
  2440. d = d + carry;
  2441. digits[i] = d < 10 ? d : d - 10; // d % 10
  2442. if (dropTrailingZeros) {
  2443. // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52)
  2444. if (digits[i] === 0 && i >= minLen) {
  2445. digits.pop();
  2446. }
  2447. else {
  2448. dropTrailingZeros = false;
  2449. }
  2450. }
  2451. return d >= 10 ? 1 : 0; // Math.floor(d / 10);
  2452. }, 0);
  2453. if (carry) {
  2454. digits.unshift(carry);
  2455. parsedNumber.integerLen++;
  2456. }
  2457. }
  2458. function parseIntAutoRadix(text) {
  2459. const result = parseInt(text);
  2460. if (isNaN(result)) {
  2461. throw new Error('Invalid integer literal when parsing ' + text);
  2462. }
  2463. return result;
  2464. }
  2465. /**
  2466. * @publicApi
  2467. */
  2468. class NgLocalization {
  2469. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocalization, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  2470. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocalization, providedIn: 'root', useFactory: (locale) => new NgLocaleLocalization(locale), deps: [{ token: LOCALE_ID }] }); }
  2471. }
  2472. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocalization, decorators: [{
  2473. type: Injectable,
  2474. args: [{
  2475. providedIn: 'root',
  2476. useFactory: (locale) => new NgLocaleLocalization(locale),
  2477. deps: [LOCALE_ID],
  2478. }]
  2479. }] });
  2480. /**
  2481. * Returns the plural category for a given value.
  2482. * - "=value" when the case exists,
  2483. * - the plural category otherwise
  2484. */
  2485. function getPluralCategory(value, cases, ngLocalization, locale) {
  2486. let key = `=${value}`;
  2487. if (cases.indexOf(key) > -1) {
  2488. return key;
  2489. }
  2490. key = ngLocalization.getPluralCategory(value, locale);
  2491. if (cases.indexOf(key) > -1) {
  2492. return key;
  2493. }
  2494. if (cases.indexOf('other') > -1) {
  2495. return 'other';
  2496. }
  2497. throw new Error(`No plural message found for value "${value}"`);
  2498. }
  2499. /**
  2500. * Returns the plural case based on the locale
  2501. *
  2502. * @publicApi
  2503. */
  2504. class NgLocaleLocalization extends NgLocalization {
  2505. constructor(locale) {
  2506. super();
  2507. this.locale = locale;
  2508. }
  2509. getPluralCategory(value, locale) {
  2510. const plural = getLocalePluralCase(locale || this.locale)(value);
  2511. switch (plural) {
  2512. case Plural.Zero:
  2513. return 'zero';
  2514. case Plural.One:
  2515. return 'one';
  2516. case Plural.Two:
  2517. return 'two';
  2518. case Plural.Few:
  2519. return 'few';
  2520. case Plural.Many:
  2521. return 'many';
  2522. default:
  2523. return 'other';
  2524. }
  2525. }
  2526. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocaleLocalization, deps: [{ token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Injectable }); }
  2527. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocaleLocalization }); }
  2528. }
  2529. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgLocaleLocalization, decorators: [{
  2530. type: Injectable
  2531. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  2532. type: Inject,
  2533. args: [LOCALE_ID]
  2534. }] }]; } });
  2535. /**
  2536. * Register global data to be used internally by Angular. See the
  2537. * ["I18n guide"](guide/i18n-common-format-data-locale) to know how to import additional locale
  2538. * data.
  2539. *
  2540. * The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
  2541. *
  2542. * @publicApi
  2543. */
  2544. function registerLocaleData(data, localeId, extraData) {
  2545. return ɵregisterLocaleData(data, localeId, extraData);
  2546. }
  2547. function parseCookieValue(cookieStr, name) {
  2548. name = encodeURIComponent(name);
  2549. for (const cookie of cookieStr.split(';')) {
  2550. const eqIndex = cookie.indexOf('=');
  2551. const [cookieName, cookieValue] = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)];
  2552. if (cookieName.trim() === name) {
  2553. return decodeURIComponent(cookieValue);
  2554. }
  2555. }
  2556. return null;
  2557. }
  2558. const WS_REGEXP = /\s+/;
  2559. const EMPTY_ARRAY = [];
  2560. /**
  2561. * @ngModule CommonModule
  2562. *
  2563. * @usageNotes
  2564. * ```
  2565. * <some-element [ngClass]="'first second'">...</some-element>
  2566. *
  2567. * <some-element [ngClass]="['first', 'second']">...</some-element>
  2568. *
  2569. * <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
  2570. *
  2571. * <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
  2572. *
  2573. * <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
  2574. * ```
  2575. *
  2576. * @description
  2577. *
  2578. * Adds and removes CSS classes on an HTML element.
  2579. *
  2580. * The CSS classes are updated as follows, depending on the type of the expression evaluation:
  2581. * - `string` - the CSS classes listed in the string (space delimited) are added,
  2582. * - `Array` - the CSS classes declared as Array elements are added,
  2583. * - `Object` - keys are CSS classes that get added when the expression given in the value
  2584. * evaluates to a truthy value, otherwise they are removed.
  2585. *
  2586. * @publicApi
  2587. */
  2588. class NgClass {
  2589. constructor(
  2590. // leaving references to differs in place since flex layout is extending NgClass...
  2591. _iterableDiffers, _keyValueDiffers, _ngEl, _renderer) {
  2592. this._iterableDiffers = _iterableDiffers;
  2593. this._keyValueDiffers = _keyValueDiffers;
  2594. this._ngEl = _ngEl;
  2595. this._renderer = _renderer;
  2596. this.initialClasses = EMPTY_ARRAY;
  2597. this.stateMap = new Map();
  2598. }
  2599. set klass(value) {
  2600. this.initialClasses = value != null ? value.trim().split(WS_REGEXP) : EMPTY_ARRAY;
  2601. }
  2602. set ngClass(value) {
  2603. this.rawClass = typeof value === 'string' ? value.trim().split(WS_REGEXP) : value;
  2604. }
  2605. /*
  2606. The NgClass directive uses the custom change detection algorithm for its inputs. The custom
  2607. algorithm is necessary since inputs are represented as complex object or arrays that need to be
  2608. deeply-compared.
  2609. This algorithm is perf-sensitive since NgClass is used very frequently and its poor performance
  2610. might negatively impact runtime performance of the entire change detection cycle. The design of
  2611. this algorithm is making sure that:
  2612. - there is no unnecessary DOM manipulation (CSS classes are added / removed from the DOM only when
  2613. needed), even if references to bound objects change;
  2614. - there is no memory allocation if nothing changes (even relatively modest memory allocation
  2615. during the change detection cycle can result in GC pauses for some of the CD cycles).
  2616. The algorithm works by iterating over the set of bound classes, staring with [class] binding and
  2617. then going over [ngClass] binding. For each CSS class name:
  2618. - check if it was seen before (this information is tracked in the state map) and if its value
  2619. changed;
  2620. - mark it as "touched" - names that are not marked are not present in the latest set of binding
  2621. and we can remove such class name from the internal data structures;
  2622. After iteration over all the CSS class names we've got data structure with all the information
  2623. necessary to synchronize changes to the DOM - it is enough to iterate over the state map, flush
  2624. changes to the DOM and reset internal data structures so those are ready for the next change
  2625. detection cycle.
  2626. */
  2627. ngDoCheck() {
  2628. // classes from the [class] binding
  2629. for (const klass of this.initialClasses) {
  2630. this._updateState(klass, true);
  2631. }
  2632. // classes from the [ngClass] binding
  2633. const rawClass = this.rawClass;
  2634. if (Array.isArray(rawClass) || rawClass instanceof Set) {
  2635. for (const klass of rawClass) {
  2636. this._updateState(klass, true);
  2637. }
  2638. }
  2639. else if (rawClass != null) {
  2640. for (const klass of Object.keys(rawClass)) {
  2641. this._updateState(klass, Boolean(rawClass[klass]));
  2642. }
  2643. }
  2644. this._applyStateDiff();
  2645. }
  2646. _updateState(klass, nextEnabled) {
  2647. const state = this.stateMap.get(klass);
  2648. if (state !== undefined) {
  2649. if (state.enabled !== nextEnabled) {
  2650. state.changed = true;
  2651. state.enabled = nextEnabled;
  2652. }
  2653. state.touched = true;
  2654. }
  2655. else {
  2656. this.stateMap.set(klass, { enabled: nextEnabled, changed: true, touched: true });
  2657. }
  2658. }
  2659. _applyStateDiff() {
  2660. for (const stateEntry of this.stateMap) {
  2661. const klass = stateEntry[0];
  2662. const state = stateEntry[1];
  2663. if (state.changed) {
  2664. this._toggleClass(klass, state.enabled);
  2665. state.changed = false;
  2666. }
  2667. else if (!state.touched) {
  2668. // A class that was previously active got removed from the new collection of classes -
  2669. // remove from the DOM as well.
  2670. if (state.enabled) {
  2671. this._toggleClass(klass, false);
  2672. }
  2673. this.stateMap.delete(klass);
  2674. }
  2675. state.touched = false;
  2676. }
  2677. }
  2678. _toggleClass(klass, enabled) {
  2679. if (ngDevMode) {
  2680. if (typeof klass !== 'string') {
  2681. throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${ɵstringify(klass)}`);
  2682. }
  2683. }
  2684. klass = klass.trim();
  2685. if (klass.length > 0) {
  2686. klass.split(WS_REGEXP).forEach(klass => {
  2687. if (enabled) {
  2688. this._renderer.addClass(this._ngEl.nativeElement, klass);
  2689. }
  2690. else {
  2691. this._renderer.removeClass(this._ngEl.nativeElement, klass);
  2692. }
  2693. });
  2694. }
  2695. }
  2696. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgClass, deps: [{ token: i0.IterableDiffers }, { token: i0.KeyValueDiffers }, { token: i0.ElementRef }, { token: i0.Renderer2 }], target: i0.ɵɵFactoryTarget.Directive }); }
  2697. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgClass, isStandalone: true, selector: "[ngClass]", inputs: { klass: ["class", "klass"], ngClass: "ngClass" }, ngImport: i0 }); }
  2698. }
  2699. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgClass, decorators: [{
  2700. type: Directive,
  2701. args: [{
  2702. selector: '[ngClass]',
  2703. standalone: true,
  2704. }]
  2705. }], ctorParameters: function () { return [{ type: i0.IterableDiffers }, { type: i0.KeyValueDiffers }, { type: i0.ElementRef }, { type: i0.Renderer2 }]; }, propDecorators: { klass: [{
  2706. type: Input,
  2707. args: ['class']
  2708. }], ngClass: [{
  2709. type: Input,
  2710. args: ['ngClass']
  2711. }] } });
  2712. /**
  2713. * Instantiates a {@link Component} type and inserts its Host View into the current View.
  2714. * `NgComponentOutlet` provides a declarative approach for dynamic component creation.
  2715. *
  2716. * `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and
  2717. * any existing component will be destroyed.
  2718. *
  2719. * @usageNotes
  2720. *
  2721. * ### Fine tune control
  2722. *
  2723. * You can control the component creation process by using the following optional attributes:
  2724. *
  2725. * * `ngComponentOutletInputs`: Optional component inputs object, which will be bind to the
  2726. * component.
  2727. *
  2728. * * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for
  2729. * the Component. Defaults to the injector of the current view container.
  2730. *
  2731. * * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content
  2732. * section of the component, if it exists.
  2733. *
  2734. * * `ngComponentOutletNgModule`: Optional NgModule class reference to allow loading another
  2735. * module dynamically, then loading a component from that module.
  2736. *
  2737. * * `ngComponentOutletNgModuleFactory`: Deprecated config option that allows providing optional
  2738. * NgModule factory to allow loading another module dynamically, then loading a component from that
  2739. * module. Use `ngComponentOutletNgModule` instead.
  2740. *
  2741. * ### Syntax
  2742. *
  2743. * Simple
  2744. * ```
  2745. * <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
  2746. * ```
  2747. *
  2748. * With inputs
  2749. * ```
  2750. * <ng-container *ngComponentOutlet="componentTypeExpression;
  2751. * inputs: inputsExpression;">
  2752. * </ng-container>
  2753. * ```
  2754. *
  2755. * Customized injector/content
  2756. * ```
  2757. * <ng-container *ngComponentOutlet="componentTypeExpression;
  2758. * injector: injectorExpression;
  2759. * content: contentNodesExpression;">
  2760. * </ng-container>
  2761. * ```
  2762. *
  2763. * Customized NgModule reference
  2764. * ```
  2765. * <ng-container *ngComponentOutlet="componentTypeExpression;
  2766. * ngModule: ngModuleClass;">
  2767. * </ng-container>
  2768. * ```
  2769. *
  2770. * ### A simple example
  2771. *
  2772. * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'}
  2773. *
  2774. * A more complete example with additional options:
  2775. *
  2776. * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'}
  2777. *
  2778. * @publicApi
  2779. * @ngModule CommonModule
  2780. */
  2781. class NgComponentOutlet {
  2782. constructor(_viewContainerRef) {
  2783. this._viewContainerRef = _viewContainerRef;
  2784. this.ngComponentOutlet = null;
  2785. /**
  2786. * A helper data structure that allows us to track inputs that were part of the
  2787. * ngComponentOutletInputs expression. Tracking inputs is necessary for proper removal of ones
  2788. * that are no longer referenced.
  2789. */
  2790. this._inputsUsed = new Map();
  2791. }
  2792. _needToReCreateNgModuleInstance(changes) {
  2793. // Note: square brackets property accessor is safe for Closure compiler optimizations (the
  2794. // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
  2795. // were changed).
  2796. return changes['ngComponentOutletNgModule'] !== undefined ||
  2797. changes['ngComponentOutletNgModuleFactory'] !== undefined;
  2798. }
  2799. _needToReCreateComponentInstance(changes) {
  2800. // Note: square brackets property accessor is safe for Closure compiler optimizations (the
  2801. // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
  2802. // were changed).
  2803. return changes['ngComponentOutlet'] !== undefined ||
  2804. changes['ngComponentOutletContent'] !== undefined ||
  2805. changes['ngComponentOutletInjector'] !== undefined ||
  2806. this._needToReCreateNgModuleInstance(changes);
  2807. }
  2808. /** @nodoc */
  2809. ngOnChanges(changes) {
  2810. if (this._needToReCreateComponentInstance(changes)) {
  2811. this._viewContainerRef.clear();
  2812. this._inputsUsed.clear();
  2813. this._componentRef = undefined;
  2814. if (this.ngComponentOutlet) {
  2815. const injector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;
  2816. if (this._needToReCreateNgModuleInstance(changes)) {
  2817. this._moduleRef?.destroy();
  2818. if (this.ngComponentOutletNgModule) {
  2819. this._moduleRef =
  2820. createNgModule(this.ngComponentOutletNgModule, getParentInjector(injector));
  2821. }
  2822. else if (this.ngComponentOutletNgModuleFactory) {
  2823. this._moduleRef =
  2824. this.ngComponentOutletNgModuleFactory.create(getParentInjector(injector));
  2825. }
  2826. else {
  2827. this._moduleRef = undefined;
  2828. }
  2829. }
  2830. this._componentRef = this._viewContainerRef.createComponent(this.ngComponentOutlet, {
  2831. injector,
  2832. ngModuleRef: this._moduleRef,
  2833. projectableNodes: this.ngComponentOutletContent,
  2834. });
  2835. }
  2836. }
  2837. }
  2838. /** @nodoc */
  2839. ngDoCheck() {
  2840. if (this._componentRef) {
  2841. if (this.ngComponentOutletInputs) {
  2842. for (const inputName of Object.keys(this.ngComponentOutletInputs)) {
  2843. this._inputsUsed.set(inputName, true);
  2844. }
  2845. }
  2846. this._applyInputStateDiff(this._componentRef);
  2847. }
  2848. }
  2849. /** @nodoc */
  2850. ngOnDestroy() {
  2851. this._moduleRef?.destroy();
  2852. }
  2853. _applyInputStateDiff(componentRef) {
  2854. for (const [inputName, touched] of this._inputsUsed) {
  2855. if (!touched) {
  2856. // The input that was previously active no longer exists and needs to be set to undefined.
  2857. componentRef.setInput(inputName, undefined);
  2858. this._inputsUsed.delete(inputName);
  2859. }
  2860. else {
  2861. // Since touched is true, it can be asserted that the inputs object is not empty.
  2862. componentRef.setInput(inputName, this.ngComponentOutletInputs[inputName]);
  2863. this._inputsUsed.set(inputName, false);
  2864. }
  2865. }
  2866. }
  2867. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgComponentOutlet, deps: [{ token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Directive }); }
  2868. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgComponentOutlet, isStandalone: true, selector: "[ngComponentOutlet]", inputs: { ngComponentOutlet: "ngComponentOutlet", ngComponentOutletInputs: "ngComponentOutletInputs", ngComponentOutletInjector: "ngComponentOutletInjector", ngComponentOutletContent: "ngComponentOutletContent", ngComponentOutletNgModule: "ngComponentOutletNgModule", ngComponentOutletNgModuleFactory: "ngComponentOutletNgModuleFactory" }, usesOnChanges: true, ngImport: i0 }); }
  2869. }
  2870. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgComponentOutlet, decorators: [{
  2871. type: Directive,
  2872. args: [{
  2873. selector: '[ngComponentOutlet]',
  2874. standalone: true,
  2875. }]
  2876. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }]; }, propDecorators: { ngComponentOutlet: [{
  2877. type: Input
  2878. }], ngComponentOutletInputs: [{
  2879. type: Input
  2880. }], ngComponentOutletInjector: [{
  2881. type: Input
  2882. }], ngComponentOutletContent: [{
  2883. type: Input
  2884. }], ngComponentOutletNgModule: [{
  2885. type: Input
  2886. }], ngComponentOutletNgModuleFactory: [{
  2887. type: Input
  2888. }] } });
  2889. // Helper function that returns an Injector instance of a parent NgModule.
  2890. function getParentInjector(injector) {
  2891. const parentNgModule = injector.get(NgModuleRef);
  2892. return parentNgModule.injector;
  2893. }
  2894. /**
  2895. * @publicApi
  2896. */
  2897. class NgForOfContext {
  2898. constructor($implicit, ngForOf, index, count) {
  2899. this.$implicit = $implicit;
  2900. this.ngForOf = ngForOf;
  2901. this.index = index;
  2902. this.count = count;
  2903. }
  2904. get first() {
  2905. return this.index === 0;
  2906. }
  2907. get last() {
  2908. return this.index === this.count - 1;
  2909. }
  2910. get even() {
  2911. return this.index % 2 === 0;
  2912. }
  2913. get odd() {
  2914. return !this.even;
  2915. }
  2916. }
  2917. /**
  2918. * A [structural directive](guide/structural-directives) that renders
  2919. * a template for each item in a collection.
  2920. * The directive is placed on an element, which becomes the parent
  2921. * of the cloned templates.
  2922. *
  2923. * The `ngForOf` directive is generally used in the
  2924. * [shorthand form](guide/structural-directives#asterisk) `*ngFor`.
  2925. * In this form, the template to be rendered for each iteration is the content
  2926. * of an anchor element containing the directive.
  2927. *
  2928. * The following example shows the shorthand syntax with some options,
  2929. * contained in an `<li>` element.
  2930. *
  2931. * ```
  2932. * <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
  2933. * ```
  2934. *
  2935. * The shorthand form expands into a long form that uses the `ngForOf` selector
  2936. * on an `<ng-template>` element.
  2937. * The content of the `<ng-template>` element is the `<li>` element that held the
  2938. * short-form directive.
  2939. *
  2940. * Here is the expanded version of the short-form example.
  2941. *
  2942. * ```
  2943. * <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
  2944. * <li>...</li>
  2945. * </ng-template>
  2946. * ```
  2947. *
  2948. * Angular automatically expands the shorthand syntax as it compiles the template.
  2949. * The context for each embedded view is logically merged to the current component
  2950. * context according to its lexical position.
  2951. *
  2952. * When using the shorthand syntax, Angular allows only [one structural directive
  2953. * on an element](guide/structural-directives#one-per-element).
  2954. * If you want to iterate conditionally, for example,
  2955. * put the `*ngIf` on a container element that wraps the `*ngFor` element.
  2956. * For further discussion, see
  2957. * [Structural Directives](guide/structural-directives#one-per-element).
  2958. *
  2959. * @usageNotes
  2960. *
  2961. * ### Local variables
  2962. *
  2963. * `NgForOf` provides exported values that can be aliased to local variables.
  2964. * For example:
  2965. *
  2966. * ```
  2967. * <li *ngFor="let user of users; index as i; first as isFirst">
  2968. * {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
  2969. * </li>
  2970. * ```
  2971. *
  2972. * The following exported values can be aliased to local variables:
  2973. *
  2974. * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`).
  2975. * - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is
  2976. * more complex then a property access, for example when using the async pipe (`userStreams |
  2977. * async`).
  2978. * - `index: number`: The index of the current item in the iterable.
  2979. * - `count: number`: The length of the iterable.
  2980. * - `first: boolean`: True when the item is the first item in the iterable.
  2981. * - `last: boolean`: True when the item is the last item in the iterable.
  2982. * - `even: boolean`: True when the item has an even index in the iterable.
  2983. * - `odd: boolean`: True when the item has an odd index in the iterable.
  2984. *
  2985. * ### Change propagation
  2986. *
  2987. * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM:
  2988. *
  2989. * * When an item is added, a new instance of the template is added to the DOM.
  2990. * * When an item is removed, its template instance is removed from the DOM.
  2991. * * When items are reordered, their respective templates are reordered in the DOM.
  2992. *
  2993. * Angular uses object identity to track insertions and deletions within the iterator and reproduce
  2994. * those changes in the DOM. This has important implications for animations and any stateful
  2995. * controls that are present, such as `<input>` elements that accept user input. Inserted rows can
  2996. * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state
  2997. * such as user input.
  2998. * For more on animations, see [Transitions and Triggers](guide/transition-and-triggers).
  2999. *
  3000. * The identities of elements in the iterator can change while the data does not.
  3001. * This can happen, for example, if the iterator is produced from an RPC to the server, and that
  3002. * RPC is re-run. Even if the data hasn't changed, the second response produces objects with
  3003. * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old
  3004. * elements were deleted and all new elements inserted).
  3005. *
  3006. * To avoid this expensive operation, you can customize the default tracking algorithm.
  3007. * by supplying the `trackBy` option to `NgForOf`.
  3008. * `trackBy` takes a function that has two arguments: `index` and `item`.
  3009. * If `trackBy` is given, Angular tracks changes by the return value of the function.
  3010. *
  3011. * @see [Structural Directives](guide/structural-directives)
  3012. * @ngModule CommonModule
  3013. * @publicApi
  3014. */
  3015. class NgForOf {
  3016. /**
  3017. * The value of the iterable expression, which can be used as a
  3018. * [template input variable](guide/structural-directives#shorthand).
  3019. */
  3020. set ngForOf(ngForOf) {
  3021. this._ngForOf = ngForOf;
  3022. this._ngForOfDirty = true;
  3023. }
  3024. /**
  3025. * Specifies a custom `TrackByFunction` to compute the identity of items in an iterable.
  3026. *
  3027. * If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object
  3028. * identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
  3029. * as the key.
  3030. *
  3031. * `NgForOf` uses the computed key to associate items in an iterable with DOM elements
  3032. * it produces for these items.
  3033. *
  3034. * A custom `TrackByFunction` is useful to provide good user experience in cases when items in an
  3035. * iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a
  3036. * primary key), and this iterable could be updated with new object instances that still
  3037. * represent the same underlying entity (for example, when data is re-fetched from the server,
  3038. * and the iterable is recreated and re-rendered, but most of the data is still the same).
  3039. *
  3040. * @see {@link TrackByFunction}
  3041. */
  3042. set ngForTrackBy(fn) {
  3043. if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
  3044. console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
  3045. `See https://angular.io/api/common/NgForOf#change-propagation for more information.`);
  3046. }
  3047. this._trackByFn = fn;
  3048. }
  3049. get ngForTrackBy() {
  3050. return this._trackByFn;
  3051. }
  3052. constructor(_viewContainer, _template, _differs) {
  3053. this._viewContainer = _viewContainer;
  3054. this._template = _template;
  3055. this._differs = _differs;
  3056. this._ngForOf = null;
  3057. this._ngForOfDirty = true;
  3058. this._differ = null;
  3059. }
  3060. /**
  3061. * A reference to the template that is stamped out for each item in the iterable.
  3062. * @see [template reference variable](guide/template-reference-variables)
  3063. */
  3064. set ngForTemplate(value) {
  3065. // TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1
  3066. // The current type is too restrictive; a template that just uses index, for example,
  3067. // should be acceptable.
  3068. if (value) {
  3069. this._template = value;
  3070. }
  3071. }
  3072. /**
  3073. * Applies the changes when needed.
  3074. * @nodoc
  3075. */
  3076. ngDoCheck() {
  3077. if (this._ngForOfDirty) {
  3078. this._ngForOfDirty = false;
  3079. // React on ngForOf changes only once all inputs have been initialized
  3080. const value = this._ngForOf;
  3081. if (!this._differ && value) {
  3082. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3083. try {
  3084. // CAUTION: this logic is duplicated for production mode below, as the try-catch
  3085. // is only present in development builds.
  3086. this._differ = this._differs.find(value).create(this.ngForTrackBy);
  3087. }
  3088. catch {
  3089. let errorMessage = `Cannot find a differ supporting object '${value}' of type '` +
  3090. `${getTypeName(value)}'. NgFor only supports binding to Iterables, such as Arrays.`;
  3091. if (typeof value === 'object') {
  3092. errorMessage += ' Did you mean to use the keyvalue pipe?';
  3093. }
  3094. throw new ɵRuntimeError(-2200 /* RuntimeErrorCode.NG_FOR_MISSING_DIFFER */, errorMessage);
  3095. }
  3096. }
  3097. else {
  3098. // CAUTION: this logic is duplicated for development mode above, as the try-catch
  3099. // is only present in development builds.
  3100. this._differ = this._differs.find(value).create(this.ngForTrackBy);
  3101. }
  3102. }
  3103. }
  3104. if (this._differ) {
  3105. const changes = this._differ.diff(this._ngForOf);
  3106. if (changes)
  3107. this._applyChanges(changes);
  3108. }
  3109. }
  3110. _applyChanges(changes) {
  3111. const viewContainer = this._viewContainer;
  3112. changes.forEachOperation((item, adjustedPreviousIndex, currentIndex) => {
  3113. if (item.previousIndex == null) {
  3114. // NgForOf is never "null" or "undefined" here because the differ detected
  3115. // that a new item needs to be inserted from the iterable. This implies that
  3116. // there is an iterable value for "_ngForOf".
  3117. viewContainer.createEmbeddedView(this._template, new NgForOfContext(item.item, this._ngForOf, -1, -1), currentIndex === null ? undefined : currentIndex);
  3118. }
  3119. else if (currentIndex == null) {
  3120. viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex);
  3121. }
  3122. else if (adjustedPreviousIndex !== null) {
  3123. const view = viewContainer.get(adjustedPreviousIndex);
  3124. viewContainer.move(view, currentIndex);
  3125. applyViewChange(view, item);
  3126. }
  3127. });
  3128. for (let i = 0, ilen = viewContainer.length; i < ilen; i++) {
  3129. const viewRef = viewContainer.get(i);
  3130. const context = viewRef.context;
  3131. context.index = i;
  3132. context.count = ilen;
  3133. context.ngForOf = this._ngForOf;
  3134. }
  3135. changes.forEachIdentityChange((record) => {
  3136. const viewRef = viewContainer.get(record.currentIndex);
  3137. applyViewChange(viewRef, record);
  3138. });
  3139. }
  3140. /**
  3141. * Asserts the correct type of the context for the template that `NgForOf` will render.
  3142. *
  3143. * The presence of this method is a signal to the Ivy template type-check compiler that the
  3144. * `NgForOf` structural directive renders its template with a specific context type.
  3145. */
  3146. static ngTemplateContextGuard(dir, ctx) {
  3147. return true;
  3148. }
  3149. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgForOf, deps: [{ token: i0.ViewContainerRef }, { token: i0.TemplateRef }, { token: i0.IterableDiffers }], target: i0.ɵɵFactoryTarget.Directive }); }
  3150. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgForOf, isStandalone: true, selector: "[ngFor][ngForOf]", inputs: { ngForOf: "ngForOf", ngForTrackBy: "ngForTrackBy", ngForTemplate: "ngForTemplate" }, ngImport: i0 }); }
  3151. }
  3152. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgForOf, decorators: [{
  3153. type: Directive,
  3154. args: [{
  3155. selector: '[ngFor][ngForOf]',
  3156. standalone: true,
  3157. }]
  3158. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: i0.IterableDiffers }]; }, propDecorators: { ngForOf: [{
  3159. type: Input
  3160. }], ngForTrackBy: [{
  3161. type: Input
  3162. }], ngForTemplate: [{
  3163. type: Input
  3164. }] } });
  3165. function applyViewChange(view, record) {
  3166. view.context.$implicit = record.item;
  3167. }
  3168. function getTypeName(type) {
  3169. return type['name'] || typeof type;
  3170. }
  3171. /**
  3172. * A structural directive that conditionally includes a template based on the value of
  3173. * an expression coerced to Boolean.
  3174. * When the expression evaluates to true, Angular renders the template
  3175. * provided in a `then` clause, and when false or null,
  3176. * Angular renders the template provided in an optional `else` clause. The default
  3177. * template for the `else` clause is blank.
  3178. *
  3179. * A [shorthand form](guide/structural-directives#asterisk) of the directive,
  3180. * `*ngIf="condition"`, is generally used, provided
  3181. * as an attribute of the anchor element for the inserted template.
  3182. * Angular expands this into a more explicit version, in which the anchor element
  3183. * is contained in an `<ng-template>` element.
  3184. *
  3185. * Simple form with shorthand syntax:
  3186. *
  3187. * ```
  3188. * <div *ngIf="condition">Content to render when condition is true.</div>
  3189. * ```
  3190. *
  3191. * Simple form with expanded syntax:
  3192. *
  3193. * ```
  3194. * <ng-template [ngIf]="condition"><div>Content to render when condition is
  3195. * true.</div></ng-template>
  3196. * ```
  3197. *
  3198. * Form with an "else" block:
  3199. *
  3200. * ```
  3201. * <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
  3202. * <ng-template #elseBlock>Content to render when condition is false.</ng-template>
  3203. * ```
  3204. *
  3205. * Shorthand form with "then" and "else" blocks:
  3206. *
  3207. * ```
  3208. * <div *ngIf="condition; then thenBlock else elseBlock"></div>
  3209. * <ng-template #thenBlock>Content to render when condition is true.</ng-template>
  3210. * <ng-template #elseBlock>Content to render when condition is false.</ng-template>
  3211. * ```
  3212. *
  3213. * Form with storing the value locally:
  3214. *
  3215. * ```
  3216. * <div *ngIf="condition as value; else elseBlock">{{value}}</div>
  3217. * <ng-template #elseBlock>Content to render when value is null.</ng-template>
  3218. * ```
  3219. *
  3220. * @usageNotes
  3221. *
  3222. * The `*ngIf` directive is most commonly used to conditionally show an inline template,
  3223. * as seen in the following example.
  3224. * The default `else` template is blank.
  3225. *
  3226. * {@example common/ngIf/ts/module.ts region='NgIfSimple'}
  3227. *
  3228. * ### Showing an alternative template using `else`
  3229. *
  3230. * To display a template when `expression` evaluates to false, use an `else` template
  3231. * binding as shown in the following example.
  3232. * The `else` binding points to an `<ng-template>` element labeled `#elseBlock`.
  3233. * The template can be defined anywhere in the component view, but is typically placed right after
  3234. * `ngIf` for readability.
  3235. *
  3236. * {@example common/ngIf/ts/module.ts region='NgIfElse'}
  3237. *
  3238. * ### Using an external `then` template
  3239. *
  3240. * In the previous example, the then-clause template is specified inline, as the content of the
  3241. * tag that contains the `ngIf` directive. You can also specify a template that is defined
  3242. * externally, by referencing a labeled `<ng-template>` element. When you do this, you can
  3243. * change which template to use at runtime, as shown in the following example.
  3244. *
  3245. * {@example common/ngIf/ts/module.ts region='NgIfThenElse'}
  3246. *
  3247. * ### Storing a conditional result in a variable
  3248. *
  3249. * You might want to show a set of properties from the same object. If you are waiting
  3250. * for asynchronous data, the object can be undefined.
  3251. * In this case, you can use `ngIf` and store the result of the condition in a local
  3252. * variable as shown in the following example.
  3253. *
  3254. * {@example common/ngIf/ts/module.ts region='NgIfAs'}
  3255. *
  3256. * This code uses only one `AsyncPipe`, so only one subscription is created.
  3257. * The conditional statement stores the result of `userStream|async` in the local variable `user`.
  3258. * You can then bind the local `user` repeatedly.
  3259. *
  3260. * The conditional displays the data only if `userStream` returns a value,
  3261. * so you don't need to use the
  3262. * safe-navigation-operator (`?.`)
  3263. * to guard against null values when accessing properties.
  3264. * You can display an alternative template while waiting for the data.
  3265. *
  3266. * ### Shorthand syntax
  3267. *
  3268. * The shorthand syntax `*ngIf` expands into two separate template specifications
  3269. * for the "then" and "else" clauses. For example, consider the following shorthand statement,
  3270. * that is meant to show a loading page while waiting for data to be loaded.
  3271. *
  3272. * ```
  3273. * <div class="hero-list" *ngIf="heroes else loading">
  3274. * ...
  3275. * </div>
  3276. *
  3277. * <ng-template #loading>
  3278. * <div>Loading...</div>
  3279. * </ng-template>
  3280. * ```
  3281. *
  3282. * You can see that the "else" clause references the `<ng-template>`
  3283. * with the `#loading` label, and the template for the "then" clause
  3284. * is provided as the content of the anchor element.
  3285. *
  3286. * However, when Angular expands the shorthand syntax, it creates
  3287. * another `<ng-template>` tag, with `ngIf` and `ngIfElse` directives.
  3288. * The anchor element containing the template for the "then" clause becomes
  3289. * the content of this unlabeled `<ng-template>` tag.
  3290. *
  3291. * ```
  3292. * <ng-template [ngIf]="heroes" [ngIfElse]="loading">
  3293. * <div class="hero-list">
  3294. * ...
  3295. * </div>
  3296. * </ng-template>
  3297. *
  3298. * <ng-template #loading>
  3299. * <div>Loading...</div>
  3300. * </ng-template>
  3301. * ```
  3302. *
  3303. * The presence of the implicit template object has implications for the nesting of
  3304. * structural directives. For more on this subject, see
  3305. * [Structural Directives](guide/structural-directives#one-per-element).
  3306. *
  3307. * @ngModule CommonModule
  3308. * @publicApi
  3309. */
  3310. class NgIf {
  3311. constructor(_viewContainer, templateRef) {
  3312. this._viewContainer = _viewContainer;
  3313. this._context = new NgIfContext();
  3314. this._thenTemplateRef = null;
  3315. this._elseTemplateRef = null;
  3316. this._thenViewRef = null;
  3317. this._elseViewRef = null;
  3318. this._thenTemplateRef = templateRef;
  3319. }
  3320. /**
  3321. * The Boolean expression to evaluate as the condition for showing a template.
  3322. */
  3323. set ngIf(condition) {
  3324. this._context.$implicit = this._context.ngIf = condition;
  3325. this._updateView();
  3326. }
  3327. /**
  3328. * A template to show if the condition expression evaluates to true.
  3329. */
  3330. set ngIfThen(templateRef) {
  3331. assertTemplate('ngIfThen', templateRef);
  3332. this._thenTemplateRef = templateRef;
  3333. this._thenViewRef = null; // clear previous view if any.
  3334. this._updateView();
  3335. }
  3336. /**
  3337. * A template to show if the condition expression evaluates to false.
  3338. */
  3339. set ngIfElse(templateRef) {
  3340. assertTemplate('ngIfElse', templateRef);
  3341. this._elseTemplateRef = templateRef;
  3342. this._elseViewRef = null; // clear previous view if any.
  3343. this._updateView();
  3344. }
  3345. _updateView() {
  3346. if (this._context.$implicit) {
  3347. if (!this._thenViewRef) {
  3348. this._viewContainer.clear();
  3349. this._elseViewRef = null;
  3350. if (this._thenTemplateRef) {
  3351. this._thenViewRef =
  3352. this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
  3353. }
  3354. }
  3355. }
  3356. else {
  3357. if (!this._elseViewRef) {
  3358. this._viewContainer.clear();
  3359. this._thenViewRef = null;
  3360. if (this._elseTemplateRef) {
  3361. this._elseViewRef =
  3362. this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
  3363. }
  3364. }
  3365. }
  3366. }
  3367. /**
  3368. * Asserts the correct type of the context for the template that `NgIf` will render.
  3369. *
  3370. * The presence of this method is a signal to the Ivy template type-check compiler that the
  3371. * `NgIf` structural directive renders its template with a specific context type.
  3372. */
  3373. static ngTemplateContextGuard(dir, ctx) {
  3374. return true;
  3375. }
  3376. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgIf, deps: [{ token: i0.ViewContainerRef }, { token: i0.TemplateRef }], target: i0.ɵɵFactoryTarget.Directive }); }
  3377. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgIf, isStandalone: true, selector: "[ngIf]", inputs: { ngIf: "ngIf", ngIfThen: "ngIfThen", ngIfElse: "ngIfElse" }, ngImport: i0 }); }
  3378. }
  3379. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgIf, decorators: [{
  3380. type: Directive,
  3381. args: [{
  3382. selector: '[ngIf]',
  3383. standalone: true,
  3384. }]
  3385. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }, { type: i0.TemplateRef }]; }, propDecorators: { ngIf: [{
  3386. type: Input
  3387. }], ngIfThen: [{
  3388. type: Input
  3389. }], ngIfElse: [{
  3390. type: Input
  3391. }] } });
  3392. /**
  3393. * @publicApi
  3394. */
  3395. class NgIfContext {
  3396. constructor() {
  3397. this.$implicit = null;
  3398. this.ngIf = null;
  3399. }
  3400. }
  3401. function assertTemplate(property, templateRef) {
  3402. const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView);
  3403. if (!isTemplateRefOrNull) {
  3404. throw new Error(`${property} must be a TemplateRef, but received '${ɵstringify(templateRef)}'.`);
  3405. }
  3406. }
  3407. class SwitchView {
  3408. constructor(_viewContainerRef, _templateRef) {
  3409. this._viewContainerRef = _viewContainerRef;
  3410. this._templateRef = _templateRef;
  3411. this._created = false;
  3412. }
  3413. create() {
  3414. this._created = true;
  3415. this._viewContainerRef.createEmbeddedView(this._templateRef);
  3416. }
  3417. destroy() {
  3418. this._created = false;
  3419. this._viewContainerRef.clear();
  3420. }
  3421. enforceState(created) {
  3422. if (created && !this._created) {
  3423. this.create();
  3424. }
  3425. else if (!created && this._created) {
  3426. this.destroy();
  3427. }
  3428. }
  3429. }
  3430. /**
  3431. * @ngModule CommonModule
  3432. *
  3433. * @description
  3434. * The `[ngSwitch]` directive on a container specifies an expression to match against.
  3435. * The expressions to match are provided by `ngSwitchCase` directives on views within the container.
  3436. * - Every view that matches is rendered.
  3437. * - If there are no matches, a view with the `ngSwitchDefault` directive is rendered.
  3438. * - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase`
  3439. * or `ngSwitchDefault` directive are preserved at the location.
  3440. *
  3441. * @usageNotes
  3442. * Define a container element for the directive, and specify the switch expression
  3443. * to match against as an attribute:
  3444. *
  3445. * ```
  3446. * <container-element [ngSwitch]="switch_expression">
  3447. * ```
  3448. *
  3449. * Within the container, `*ngSwitchCase` statements specify the match expressions
  3450. * as attributes. Include `*ngSwitchDefault` as the final case.
  3451. *
  3452. * ```
  3453. * <container-element [ngSwitch]="switch_expression">
  3454. * <some-element *ngSwitchCase="match_expression_1">...</some-element>
  3455. * ...
  3456. * <some-element *ngSwitchDefault>...</some-element>
  3457. * </container-element>
  3458. * ```
  3459. *
  3460. * ### Usage Examples
  3461. *
  3462. * The following example shows how to use more than one case to display the same view:
  3463. *
  3464. * ```
  3465. * <container-element [ngSwitch]="switch_expression">
  3466. * <!-- the same view can be shown in more than one case -->
  3467. * <some-element *ngSwitchCase="match_expression_1">...</some-element>
  3468. * <some-element *ngSwitchCase="match_expression_2">...</some-element>
  3469. * <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  3470. * <!--default case when there are no matches -->
  3471. * <some-element *ngSwitchDefault>...</some-element>
  3472. * </container-element>
  3473. * ```
  3474. *
  3475. * The following example shows how cases can be nested:
  3476. * ```
  3477. * <container-element [ngSwitch]="switch_expression">
  3478. * <some-element *ngSwitchCase="match_expression_1">...</some-element>
  3479. * <some-element *ngSwitchCase="match_expression_2">...</some-element>
  3480. * <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  3481. * <ng-container *ngSwitchCase="match_expression_3">
  3482. * <!-- use a ng-container to group multiple root nodes -->
  3483. * <inner-element></inner-element>
  3484. * <inner-other-element></inner-other-element>
  3485. * </ng-container>
  3486. * <some-element *ngSwitchDefault>...</some-element>
  3487. * </container-element>
  3488. * ```
  3489. *
  3490. * @publicApi
  3491. * @see {@link NgSwitchCase}
  3492. * @see {@link NgSwitchDefault}
  3493. * @see [Structural Directives](guide/structural-directives)
  3494. *
  3495. */
  3496. class NgSwitch {
  3497. constructor() {
  3498. this._defaultViews = [];
  3499. this._defaultUsed = false;
  3500. this._caseCount = 0;
  3501. this._lastCaseCheckIndex = 0;
  3502. this._lastCasesMatched = false;
  3503. }
  3504. set ngSwitch(newValue) {
  3505. this._ngSwitch = newValue;
  3506. if (this._caseCount === 0) {
  3507. this._updateDefaultCases(true);
  3508. }
  3509. }
  3510. /** @internal */
  3511. _addCase() {
  3512. return this._caseCount++;
  3513. }
  3514. /** @internal */
  3515. _addDefault(view) {
  3516. this._defaultViews.push(view);
  3517. }
  3518. /** @internal */
  3519. _matchCase(value) {
  3520. const matched = value == this._ngSwitch;
  3521. this._lastCasesMatched = this._lastCasesMatched || matched;
  3522. this._lastCaseCheckIndex++;
  3523. if (this._lastCaseCheckIndex === this._caseCount) {
  3524. this._updateDefaultCases(!this._lastCasesMatched);
  3525. this._lastCaseCheckIndex = 0;
  3526. this._lastCasesMatched = false;
  3527. }
  3528. return matched;
  3529. }
  3530. _updateDefaultCases(useDefault) {
  3531. if (this._defaultViews.length > 0 && useDefault !== this._defaultUsed) {
  3532. this._defaultUsed = useDefault;
  3533. for (const defaultView of this._defaultViews) {
  3534. defaultView.enforceState(useDefault);
  3535. }
  3536. }
  3537. }
  3538. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitch, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
  3539. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgSwitch, isStandalone: true, selector: "[ngSwitch]", inputs: { ngSwitch: "ngSwitch" }, ngImport: i0 }); }
  3540. }
  3541. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitch, decorators: [{
  3542. type: Directive,
  3543. args: [{
  3544. selector: '[ngSwitch]',
  3545. standalone: true,
  3546. }]
  3547. }], propDecorators: { ngSwitch: [{
  3548. type: Input
  3549. }] } });
  3550. /**
  3551. * @ngModule CommonModule
  3552. *
  3553. * @description
  3554. * Provides a switch case expression to match against an enclosing `ngSwitch` expression.
  3555. * When the expressions match, the given `NgSwitchCase` template is rendered.
  3556. * If multiple match expressions match the switch expression value, all of them are displayed.
  3557. *
  3558. * @usageNotes
  3559. *
  3560. * Within a switch container, `*ngSwitchCase` statements specify the match expressions
  3561. * as attributes. Include `*ngSwitchDefault` as the final case.
  3562. *
  3563. * ```
  3564. * <container-element [ngSwitch]="switch_expression">
  3565. * <some-element *ngSwitchCase="match_expression_1">...</some-element>
  3566. * ...
  3567. * <some-element *ngSwitchDefault>...</some-element>
  3568. * </container-element>
  3569. * ```
  3570. *
  3571. * Each switch-case statement contains an in-line HTML template or template reference
  3572. * that defines the subtree to be selected if the value of the match expression
  3573. * matches the value of the switch expression.
  3574. *
  3575. * Unlike JavaScript, which uses strict equality, Angular uses loose equality.
  3576. * This means that the empty string, `""` matches 0.
  3577. *
  3578. * @publicApi
  3579. * @see {@link NgSwitch}
  3580. * @see {@link NgSwitchDefault}
  3581. *
  3582. */
  3583. class NgSwitchCase {
  3584. constructor(viewContainer, templateRef, ngSwitch) {
  3585. this.ngSwitch = ngSwitch;
  3586. if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
  3587. throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase');
  3588. }
  3589. ngSwitch._addCase();
  3590. this._view = new SwitchView(viewContainer, templateRef);
  3591. }
  3592. /**
  3593. * Performs case matching. For internal use only.
  3594. * @nodoc
  3595. */
  3596. ngDoCheck() {
  3597. this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase));
  3598. }
  3599. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitchCase, deps: [{ token: i0.ViewContainerRef }, { token: i0.TemplateRef }, { token: NgSwitch, host: true, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3600. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgSwitchCase, isStandalone: true, selector: "[ngSwitchCase]", inputs: { ngSwitchCase: "ngSwitchCase" }, ngImport: i0 }); }
  3601. }
  3602. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitchCase, decorators: [{
  3603. type: Directive,
  3604. args: [{
  3605. selector: '[ngSwitchCase]',
  3606. standalone: true,
  3607. }]
  3608. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: NgSwitch, decorators: [{
  3609. type: Optional
  3610. }, {
  3611. type: Host
  3612. }] }]; }, propDecorators: { ngSwitchCase: [{
  3613. type: Input
  3614. }] } });
  3615. /**
  3616. * @ngModule CommonModule
  3617. *
  3618. * @description
  3619. *
  3620. * Creates a view that is rendered when no `NgSwitchCase` expressions
  3621. * match the `NgSwitch` expression.
  3622. * This statement should be the final case in an `NgSwitch`.
  3623. *
  3624. * @publicApi
  3625. * @see {@link NgSwitch}
  3626. * @see {@link NgSwitchCase}
  3627. *
  3628. */
  3629. class NgSwitchDefault {
  3630. constructor(viewContainer, templateRef, ngSwitch) {
  3631. if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
  3632. throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault');
  3633. }
  3634. ngSwitch._addDefault(new SwitchView(viewContainer, templateRef));
  3635. }
  3636. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitchDefault, deps: [{ token: i0.ViewContainerRef }, { token: i0.TemplateRef }, { token: NgSwitch, host: true, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3637. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgSwitchDefault, isStandalone: true, selector: "[ngSwitchDefault]", ngImport: i0 }); }
  3638. }
  3639. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgSwitchDefault, decorators: [{
  3640. type: Directive,
  3641. args: [{
  3642. selector: '[ngSwitchDefault]',
  3643. standalone: true,
  3644. }]
  3645. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: NgSwitch, decorators: [{
  3646. type: Optional
  3647. }, {
  3648. type: Host
  3649. }] }]; } });
  3650. function throwNgSwitchProviderNotFoundError(attrName, directiveName) {
  3651. throw new ɵRuntimeError(2000 /* RuntimeErrorCode.PARENT_NG_SWITCH_NOT_FOUND */, `An element with the "${attrName}" attribute ` +
  3652. `(matching the "${directiveName}" directive) must be located inside an element with the "ngSwitch" attribute ` +
  3653. `(matching "NgSwitch" directive)`);
  3654. }
  3655. /**
  3656. * @ngModule CommonModule
  3657. *
  3658. * @usageNotes
  3659. * ```
  3660. * <some-element [ngPlural]="value">
  3661. * <ng-template ngPluralCase="=0">there is nothing</ng-template>
  3662. * <ng-template ngPluralCase="=1">there is one</ng-template>
  3663. * <ng-template ngPluralCase="few">there are a few</ng-template>
  3664. * </some-element>
  3665. * ```
  3666. *
  3667. * @description
  3668. *
  3669. * Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization.
  3670. *
  3671. * Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees
  3672. * that match the switch expression's pluralization category.
  3673. *
  3674. * To use this directive you must provide a container element that sets the `[ngPlural]` attribute
  3675. * to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their
  3676. * expression:
  3677. * - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value
  3678. * matches the switch expression exactly,
  3679. * - otherwise, the view will be treated as a "category match", and will only display if exact
  3680. * value matches aren't found and the value maps to its category for the defined locale.
  3681. *
  3682. * See http://cldr.unicode.org/index/cldr-spec/plural-rules
  3683. *
  3684. * @publicApi
  3685. */
  3686. class NgPlural {
  3687. constructor(_localization) {
  3688. this._localization = _localization;
  3689. this._caseViews = {};
  3690. }
  3691. set ngPlural(value) {
  3692. this._updateView(value);
  3693. }
  3694. addCase(value, switchView) {
  3695. this._caseViews[value] = switchView;
  3696. }
  3697. _updateView(switchValue) {
  3698. this._clearViews();
  3699. const cases = Object.keys(this._caseViews);
  3700. const key = getPluralCategory(switchValue, cases, this._localization);
  3701. this._activateView(this._caseViews[key]);
  3702. }
  3703. _clearViews() {
  3704. if (this._activeView)
  3705. this._activeView.destroy();
  3706. }
  3707. _activateView(view) {
  3708. if (view) {
  3709. this._activeView = view;
  3710. this._activeView.create();
  3711. }
  3712. }
  3713. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgPlural, deps: [{ token: NgLocalization }], target: i0.ɵɵFactoryTarget.Directive }); }
  3714. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgPlural, isStandalone: true, selector: "[ngPlural]", inputs: { ngPlural: "ngPlural" }, ngImport: i0 }); }
  3715. }
  3716. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgPlural, decorators: [{
  3717. type: Directive,
  3718. args: [{
  3719. selector: '[ngPlural]',
  3720. standalone: true,
  3721. }]
  3722. }], ctorParameters: function () { return [{ type: NgLocalization }]; }, propDecorators: { ngPlural: [{
  3723. type: Input
  3724. }] } });
  3725. /**
  3726. * @ngModule CommonModule
  3727. *
  3728. * @description
  3729. *
  3730. * Creates a view that will be added/removed from the parent {@link NgPlural} when the
  3731. * given expression matches the plural expression according to CLDR rules.
  3732. *
  3733. * @usageNotes
  3734. * ```
  3735. * <some-element [ngPlural]="value">
  3736. * <ng-template ngPluralCase="=0">...</ng-template>
  3737. * <ng-template ngPluralCase="other">...</ng-template>
  3738. * </some-element>
  3739. *```
  3740. *
  3741. * See {@link NgPlural} for more details and example.
  3742. *
  3743. * @publicApi
  3744. */
  3745. class NgPluralCase {
  3746. constructor(value, template, viewContainer, ngPlural) {
  3747. this.value = value;
  3748. const isANumber = !isNaN(Number(value));
  3749. ngPlural.addCase(isANumber ? `=${value}` : value, new SwitchView(viewContainer, template));
  3750. }
  3751. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgPluralCase, deps: [{ token: 'ngPluralCase', attribute: true }, { token: i0.TemplateRef }, { token: i0.ViewContainerRef }, { token: NgPlural, host: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3752. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgPluralCase, isStandalone: true, selector: "[ngPluralCase]", ngImport: i0 }); }
  3753. }
  3754. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgPluralCase, decorators: [{
  3755. type: Directive,
  3756. args: [{
  3757. selector: '[ngPluralCase]',
  3758. standalone: true,
  3759. }]
  3760. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  3761. type: Attribute,
  3762. args: ['ngPluralCase']
  3763. }] }, { type: i0.TemplateRef }, { type: i0.ViewContainerRef }, { type: NgPlural, decorators: [{
  3764. type: Host
  3765. }] }]; } });
  3766. /**
  3767. * @ngModule CommonModule
  3768. *
  3769. * @usageNotes
  3770. *
  3771. * Set the font of the containing element to the result of an expression.
  3772. *
  3773. * ```
  3774. * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
  3775. * ```
  3776. *
  3777. * Set the width of the containing element to a pixel value returned by an expression.
  3778. *
  3779. * ```
  3780. * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
  3781. * ```
  3782. *
  3783. * Set a collection of style values using an expression that returns key-value pairs.
  3784. *
  3785. * ```
  3786. * <some-element [ngStyle]="objExp">...</some-element>
  3787. * ```
  3788. *
  3789. * @description
  3790. *
  3791. * An attribute directive that updates styles for the containing HTML element.
  3792. * Sets one or more style properties, specified as colon-separated key-value pairs.
  3793. * The key is a style name, with an optional `.<unit>` suffix
  3794. * (such as 'top.px', 'font-style.em').
  3795. * The value is an expression to be evaluated.
  3796. * The resulting non-null value, expressed in the given unit,
  3797. * is assigned to the given style property.
  3798. * If the result of evaluation is null, the corresponding style is removed.
  3799. *
  3800. * @publicApi
  3801. */
  3802. class NgStyle {
  3803. constructor(_ngEl, _differs, _renderer) {
  3804. this._ngEl = _ngEl;
  3805. this._differs = _differs;
  3806. this._renderer = _renderer;
  3807. this._ngStyle = null;
  3808. this._differ = null;
  3809. }
  3810. set ngStyle(values) {
  3811. this._ngStyle = values;
  3812. if (!this._differ && values) {
  3813. this._differ = this._differs.find(values).create();
  3814. }
  3815. }
  3816. ngDoCheck() {
  3817. if (this._differ) {
  3818. const changes = this._differ.diff(this._ngStyle);
  3819. if (changes) {
  3820. this._applyChanges(changes);
  3821. }
  3822. }
  3823. }
  3824. _setStyle(nameAndUnit, value) {
  3825. const [name, unit] = nameAndUnit.split('.');
  3826. const flags = name.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase;
  3827. if (value != null) {
  3828. this._renderer.setStyle(this._ngEl.nativeElement, name, unit ? `${value}${unit}` : value, flags);
  3829. }
  3830. else {
  3831. this._renderer.removeStyle(this._ngEl.nativeElement, name, flags);
  3832. }
  3833. }
  3834. _applyChanges(changes) {
  3835. changes.forEachRemovedItem((record) => this._setStyle(record.key, null));
  3836. changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue));
  3837. changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue));
  3838. }
  3839. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgStyle, deps: [{ token: i0.ElementRef }, { token: i0.KeyValueDiffers }, { token: i0.Renderer2 }], target: i0.ɵɵFactoryTarget.Directive }); }
  3840. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgStyle, isStandalone: true, selector: "[ngStyle]", inputs: { ngStyle: "ngStyle" }, ngImport: i0 }); }
  3841. }
  3842. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgStyle, decorators: [{
  3843. type: Directive,
  3844. args: [{
  3845. selector: '[ngStyle]',
  3846. standalone: true,
  3847. }]
  3848. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.KeyValueDiffers }, { type: i0.Renderer2 }]; }, propDecorators: { ngStyle: [{
  3849. type: Input,
  3850. args: ['ngStyle']
  3851. }] } });
  3852. /**
  3853. * @ngModule CommonModule
  3854. *
  3855. * @description
  3856. *
  3857. * Inserts an embedded view from a prepared `TemplateRef`.
  3858. *
  3859. * You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`.
  3860. * `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding
  3861. * by the local template `let` declarations.
  3862. *
  3863. * @usageNotes
  3864. * ```
  3865. * <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>
  3866. * ```
  3867. *
  3868. * Using the key `$implicit` in the context object will set its value as default.
  3869. *
  3870. * ### Example
  3871. *
  3872. * {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'}
  3873. *
  3874. * @publicApi
  3875. */
  3876. class NgTemplateOutlet {
  3877. constructor(_viewContainerRef) {
  3878. this._viewContainerRef = _viewContainerRef;
  3879. this._viewRef = null;
  3880. /**
  3881. * A context object to attach to the {@link EmbeddedViewRef}. This should be an
  3882. * object, the object's keys will be available for binding by the local template `let`
  3883. * declarations.
  3884. * Using the key `$implicit` in the context object will set its value as default.
  3885. */
  3886. this.ngTemplateOutletContext = null;
  3887. /**
  3888. * A string defining the template reference and optionally the context object for the template.
  3889. */
  3890. this.ngTemplateOutlet = null;
  3891. /** Injector to be used within the embedded view. */
  3892. this.ngTemplateOutletInjector = null;
  3893. }
  3894. /** @nodoc */
  3895. ngOnChanges(changes) {
  3896. if (changes['ngTemplateOutlet'] || changes['ngTemplateOutletInjector']) {
  3897. const viewContainerRef = this._viewContainerRef;
  3898. if (this._viewRef) {
  3899. viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef));
  3900. }
  3901. if (this.ngTemplateOutlet) {
  3902. const { ngTemplateOutlet: template, ngTemplateOutletContext: context, ngTemplateOutletInjector: injector, } = this;
  3903. this._viewRef =
  3904. viewContainerRef.createEmbeddedView(template, context, injector ? { injector } : undefined);
  3905. }
  3906. else {
  3907. this._viewRef = null;
  3908. }
  3909. }
  3910. else if (this._viewRef && changes['ngTemplateOutletContext'] && this.ngTemplateOutletContext) {
  3911. this._viewRef.context = this.ngTemplateOutletContext;
  3912. }
  3913. }
  3914. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgTemplateOutlet, deps: [{ token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Directive }); }
  3915. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.9", type: NgTemplateOutlet, isStandalone: true, selector: "[ngTemplateOutlet]", inputs: { ngTemplateOutletContext: "ngTemplateOutletContext", ngTemplateOutlet: "ngTemplateOutlet", ngTemplateOutletInjector: "ngTemplateOutletInjector" }, usesOnChanges: true, ngImport: i0 }); }
  3916. }
  3917. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgTemplateOutlet, decorators: [{
  3918. type: Directive,
  3919. args: [{
  3920. selector: '[ngTemplateOutlet]',
  3921. standalone: true,
  3922. }]
  3923. }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }]; }, propDecorators: { ngTemplateOutletContext: [{
  3924. type: Input
  3925. }], ngTemplateOutlet: [{
  3926. type: Input
  3927. }], ngTemplateOutletInjector: [{
  3928. type: Input
  3929. }] } });
  3930. /**
  3931. * A collection of Angular directives that are likely to be used in each and every Angular
  3932. * application.
  3933. */
  3934. const COMMON_DIRECTIVES = [
  3935. NgClass,
  3936. NgComponentOutlet,
  3937. NgForOf,
  3938. NgIf,
  3939. NgTemplateOutlet,
  3940. NgStyle,
  3941. NgSwitch,
  3942. NgSwitchCase,
  3943. NgSwitchDefault,
  3944. NgPlural,
  3945. NgPluralCase,
  3946. ];
  3947. function invalidPipeArgumentError(type, value) {
  3948. return new ɵRuntimeError(2100 /* RuntimeErrorCode.INVALID_PIPE_ARGUMENT */, ngDevMode && `InvalidPipeArgument: '${value}' for pipe '${ɵstringify(type)}'`);
  3949. }
  3950. class SubscribableStrategy {
  3951. createSubscription(async, updateLatestValue) {
  3952. // Subscription can be side-effectful, and we don't want any signal reads which happen in the
  3953. // side effect of the subscription to be tracked by a component's template when that
  3954. // subscription is triggered via the async pipe. So we wrap the subscription in `untracked` to
  3955. // decouple from the current reactive context.
  3956. //
  3957. // `untracked` also prevents signal _writes_ which happen in the subscription side effect from
  3958. // being treated as signal writes during the template evaluation (which throws errors).
  3959. return untracked(() => async.subscribe({
  3960. next: updateLatestValue,
  3961. error: (e) => {
  3962. throw e;
  3963. }
  3964. }));
  3965. }
  3966. dispose(subscription) {
  3967. // See the comment in `createSubscription` above on the use of `untracked`.
  3968. untracked(() => subscription.unsubscribe());
  3969. }
  3970. }
  3971. class PromiseStrategy {
  3972. createSubscription(async, updateLatestValue) {
  3973. return async.then(updateLatestValue, e => {
  3974. throw e;
  3975. });
  3976. }
  3977. dispose(subscription) { }
  3978. }
  3979. const _promiseStrategy = new PromiseStrategy();
  3980. const _subscribableStrategy = new SubscribableStrategy();
  3981. /**
  3982. * @ngModule CommonModule
  3983. * @description
  3984. *
  3985. * Unwraps a value from an asynchronous primitive.
  3986. *
  3987. * The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
  3988. * emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
  3989. * changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
  3990. * potential memory leaks. When the reference of the expression changes, the `async` pipe
  3991. * automatically unsubscribes from the old `Observable` or `Promise` and subscribes to the new one.
  3992. *
  3993. * @usageNotes
  3994. *
  3995. * ### Examples
  3996. *
  3997. * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
  3998. * promise.
  3999. *
  4000. * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
  4001. *
  4002. * It's also possible to use `async` with Observables. The example below binds the `time` Observable
  4003. * to the view. The Observable continuously updates the view with the current time.
  4004. *
  4005. * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
  4006. *
  4007. * @publicApi
  4008. */
  4009. class AsyncPipe {
  4010. constructor(ref) {
  4011. this._latestValue = null;
  4012. this._subscription = null;
  4013. this._obj = null;
  4014. this._strategy = null;
  4015. // Assign `ref` into `this._ref` manually instead of declaring `_ref` in the constructor
  4016. // parameter list, as the type of `this._ref` includes `null` unlike the type of `ref`.
  4017. this._ref = ref;
  4018. }
  4019. ngOnDestroy() {
  4020. if (this._subscription) {
  4021. this._dispose();
  4022. }
  4023. // Clear the `ChangeDetectorRef` and its association with the view data, to mitigate
  4024. // potential memory leaks in Observables that could otherwise cause the view data to
  4025. // be retained.
  4026. // https://github.com/angular/angular/issues/17624
  4027. this._ref = null;
  4028. }
  4029. transform(obj) {
  4030. if (!this._obj) {
  4031. if (obj) {
  4032. this._subscribe(obj);
  4033. }
  4034. return this._latestValue;
  4035. }
  4036. if (obj !== this._obj) {
  4037. this._dispose();
  4038. return this.transform(obj);
  4039. }
  4040. return this._latestValue;
  4041. }
  4042. _subscribe(obj) {
  4043. this._obj = obj;
  4044. this._strategy = this._selectStrategy(obj);
  4045. this._subscription = this._strategy.createSubscription(obj, (value) => this._updateLatestValue(obj, value));
  4046. }
  4047. _selectStrategy(obj) {
  4048. if (ɵisPromise(obj)) {
  4049. return _promiseStrategy;
  4050. }
  4051. if (ɵisSubscribable(obj)) {
  4052. return _subscribableStrategy;
  4053. }
  4054. throw invalidPipeArgumentError(AsyncPipe, obj);
  4055. }
  4056. _dispose() {
  4057. // Note: `dispose` is only called if a subscription has been initialized before, indicating
  4058. // that `this._strategy` is also available.
  4059. this._strategy.dispose(this._subscription);
  4060. this._latestValue = null;
  4061. this._subscription = null;
  4062. this._obj = null;
  4063. }
  4064. _updateLatestValue(async, value) {
  4065. if (async === this._obj) {
  4066. this._latestValue = value;
  4067. // Note: `this._ref` is only cleared in `ngOnDestroy` so is known to be available when a
  4068. // value is being updated.
  4069. this._ref.markForCheck();
  4070. }
  4071. }
  4072. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: AsyncPipe, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4073. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: AsyncPipe, isStandalone: true, name: "async", pure: false }); }
  4074. }
  4075. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: AsyncPipe, decorators: [{
  4076. type: Pipe,
  4077. args: [{
  4078. name: 'async',
  4079. pure: false,
  4080. standalone: true,
  4081. }]
  4082. }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }]; } });
  4083. /**
  4084. * Transforms text to all lower case.
  4085. *
  4086. * @see {@link UpperCasePipe}
  4087. * @see {@link TitleCasePipe}
  4088. * @usageNotes
  4089. *
  4090. * The following example defines a view that allows the user to enter
  4091. * text, and then uses the pipe to convert the input text to all lower case.
  4092. *
  4093. * <code-example path="common/pipes/ts/lowerupper_pipe.ts" region='LowerUpperPipe'></code-example>
  4094. *
  4095. * @ngModule CommonModule
  4096. * @publicApi
  4097. */
  4098. class LowerCasePipe {
  4099. transform(value) {
  4100. if (value == null)
  4101. return null;
  4102. if (typeof value !== 'string') {
  4103. throw invalidPipeArgumentError(LowerCasePipe, value);
  4104. }
  4105. return value.toLowerCase();
  4106. }
  4107. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LowerCasePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4108. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: LowerCasePipe, isStandalone: true, name: "lowercase" }); }
  4109. }
  4110. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LowerCasePipe, decorators: [{
  4111. type: Pipe,
  4112. args: [{
  4113. name: 'lowercase',
  4114. standalone: true,
  4115. }]
  4116. }] });
  4117. //
  4118. // Regex below matches any Unicode word and number compatible with ES5. In ES2018 the same result
  4119. // can be achieved by using /[0-9\p{L}]\S*/gu and also known as Unicode Property Escapes
  4120. // (https://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no
  4121. // transpilation of this functionality down to ES5 without external tool, the only solution is
  4122. // to use already transpiled form. Example can be found here -
  4123. // https://mothereff.in/regexpu#input=var+regex+%3D+%2F%5B0-9%5Cp%7BL%7D%5D%5CS*%2Fgu%3B%0A%0A&unicodePropertyEscape=1
  4124. //
  4125. const unicodeWordMatch = /(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])\S*/g;
  4126. /**
  4127. * Transforms text to title case.
  4128. * Capitalizes the first letter of each word and transforms the
  4129. * rest of the word to lower case.
  4130. * Words are delimited by any whitespace character, such as a space, tab, or line-feed character.
  4131. *
  4132. * @see {@link LowerCasePipe}
  4133. * @see {@link UpperCasePipe}
  4134. *
  4135. * @usageNotes
  4136. * The following example shows the result of transforming various strings into title case.
  4137. *
  4138. * <code-example path="common/pipes/ts/titlecase_pipe.ts" region='TitleCasePipe'></code-example>
  4139. *
  4140. * @ngModule CommonModule
  4141. * @publicApi
  4142. */
  4143. class TitleCasePipe {
  4144. transform(value) {
  4145. if (value == null)
  4146. return null;
  4147. if (typeof value !== 'string') {
  4148. throw invalidPipeArgumentError(TitleCasePipe, value);
  4149. }
  4150. return value.replace(unicodeWordMatch, (txt => txt[0].toUpperCase() + txt.slice(1).toLowerCase()));
  4151. }
  4152. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: TitleCasePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4153. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: TitleCasePipe, isStandalone: true, name: "titlecase" }); }
  4154. }
  4155. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: TitleCasePipe, decorators: [{
  4156. type: Pipe,
  4157. args: [{
  4158. name: 'titlecase',
  4159. standalone: true,
  4160. }]
  4161. }] });
  4162. /**
  4163. * Transforms text to all upper case.
  4164. * @see {@link LowerCasePipe}
  4165. * @see {@link TitleCasePipe}
  4166. *
  4167. * @ngModule CommonModule
  4168. * @publicApi
  4169. */
  4170. class UpperCasePipe {
  4171. transform(value) {
  4172. if (value == null)
  4173. return null;
  4174. if (typeof value !== 'string') {
  4175. throw invalidPipeArgumentError(UpperCasePipe, value);
  4176. }
  4177. return value.toUpperCase();
  4178. }
  4179. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: UpperCasePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4180. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: UpperCasePipe, isStandalone: true, name: "uppercase" }); }
  4181. }
  4182. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: UpperCasePipe, decorators: [{
  4183. type: Pipe,
  4184. args: [{
  4185. name: 'uppercase',
  4186. standalone: true,
  4187. }]
  4188. }] });
  4189. /**
  4190. * The default date format of Angular date pipe, which corresponds to the following format:
  4191. * `'MMM d,y'` (e.g. `Jun 15, 2015`)
  4192. */
  4193. const DEFAULT_DATE_FORMAT = 'mediumDate';
  4194. /**
  4195. * Optionally-provided default timezone to use for all instances of `DatePipe` (such as `'+0430'`).
  4196. * If the value isn't provided, the `DatePipe` will use the end-user's local system timezone.
  4197. *
  4198. * @deprecated use DATE_PIPE_DEFAULT_OPTIONS token to configure DatePipe
  4199. */
  4200. const DATE_PIPE_DEFAULT_TIMEZONE = new InjectionToken('DATE_PIPE_DEFAULT_TIMEZONE');
  4201. /**
  4202. * DI token that allows to provide default configuration for the `DatePipe` instances in an
  4203. * application. The value is an object which can include the following fields:
  4204. * - `dateFormat`: configures the default date format. If not provided, the `DatePipe`
  4205. * will use the 'mediumDate' as a value.
  4206. * - `timezone`: configures the default timezone. If not provided, the `DatePipe` will
  4207. * use the end-user's local system timezone.
  4208. *
  4209. * @see {@link DatePipeConfig}
  4210. *
  4211. * @usageNotes
  4212. *
  4213. * Various date pipe default values can be overwritten by providing this token with
  4214. * the value that has this interface.
  4215. *
  4216. * For example:
  4217. *
  4218. * Override the default date format by providing a value using the token:
  4219. * ```typescript
  4220. * providers: [
  4221. * {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}}
  4222. * ]
  4223. * ```
  4224. *
  4225. * Override the default timezone by providing a value using the token:
  4226. * ```typescript
  4227. * providers: [
  4228. * {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}}
  4229. * ]
  4230. * ```
  4231. */
  4232. const DATE_PIPE_DEFAULT_OPTIONS = new InjectionToken('DATE_PIPE_DEFAULT_OPTIONS');
  4233. // clang-format off
  4234. /**
  4235. * @ngModule CommonModule
  4236. * @description
  4237. *
  4238. * Formats a date value according to locale rules.
  4239. *
  4240. * `DatePipe` is executed only when it detects a pure change to the input value.
  4241. * A pure change is either a change to a primitive input value
  4242. * (such as `String`, `Number`, `Boolean`, or `Symbol`),
  4243. * or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`).
  4244. *
  4245. * Note that mutating a `Date` object does not cause the pipe to be rendered again.
  4246. * To ensure that the pipe is executed, you must create a new `Date` object.
  4247. *
  4248. * Only the `en-US` locale data comes with Angular. To localize dates
  4249. * in another language, you must import the corresponding locale data.
  4250. * See the [I18n guide](guide/i18n-common-format-data-locale) for more information.
  4251. *
  4252. * The time zone of the formatted value can be specified either by passing it in as the second
  4253. * parameter of the pipe, or by setting the default through the `DATE_PIPE_DEFAULT_OPTIONS`
  4254. * injection token. The value that is passed in as the second parameter takes precedence over
  4255. * the one defined using the injection token.
  4256. *
  4257. * @see {@link formatDate}
  4258. *
  4259. *
  4260. * @usageNotes
  4261. *
  4262. * The result of this pipe is not reevaluated when the input is mutated. To avoid the need to
  4263. * reformat the date on every change-detection cycle, treat the date as an immutable object
  4264. * and change the reference when the pipe needs to run again.
  4265. *
  4266. * ### Pre-defined format options
  4267. *
  4268. * | Option | Equivalent to | Examples (given in `en-US` locale) |
  4269. * |---------------|-------------------------------------|-------------------------------------------------|
  4270. * | `'short'` | `'M/d/yy, h:mm a'` | `6/15/15, 9:03 AM` |
  4271. * | `'medium'` | `'MMM d, y, h:mm:ss a'` | `Jun 15, 2015, 9:03:01 AM` |
  4272. * | `'long'` | `'MMMM d, y, h:mm:ss a z'` | `June 15, 2015 at 9:03:01 AM GMT+1` |
  4273. * | `'full'` | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` |
  4274. * | `'shortDate'` | `'M/d/yy'` | `6/15/15` |
  4275. * | `'mediumDate'`| `'MMM d, y'` | `Jun 15, 2015` |
  4276. * | `'longDate'` | `'MMMM d, y'` | `June 15, 2015` |
  4277. * | `'fullDate'` | `'EEEE, MMMM d, y'` | `Monday, June 15, 2015` |
  4278. * | `'shortTime'` | `'h:mm a'` | `9:03 AM` |
  4279. * | `'mediumTime'`| `'h:mm:ss a'` | `9:03:01 AM` |
  4280. * | `'longTime'` | `'h:mm:ss a z'` | `9:03:01 AM GMT+1` |
  4281. * | `'fullTime'` | `'h:mm:ss a zzzz'` | `9:03:01 AM GMT+01:00` |
  4282. *
  4283. * ### Custom format options
  4284. *
  4285. * You can construct a format string using symbols to specify the components
  4286. * of a date-time value, as described in the following table.
  4287. * Format details depend on the locale.
  4288. * Fields marked with (*) are only available in the extra data set for the given locale.
  4289. *
  4290. * | Field type | Format | Description | Example Value |
  4291. * |-------------------- |-------------|---------------------------------------------------------------|------------------------------------------------------------|
  4292. * | Era | G, GG & GGG | Abbreviated | AD |
  4293. * | | GGGG | Wide | Anno Domini |
  4294. * | | GGGGG | Narrow | A |
  4295. * | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 |
  4296. * | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 |
  4297. * | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 |
  4298. * | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 |
  4299. * | Week-numbering year | Y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 |
  4300. * | | YY | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 |
  4301. * | | YYY | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 |
  4302. * | | YYYY | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 |
  4303. * | Month | M | Numeric: 1 digit | 9, 12 |
  4304. * | | MM | Numeric: 2 digits + zero padded | 09, 12 |
  4305. * | | MMM | Abbreviated | Sep |
  4306. * | | MMMM | Wide | September |
  4307. * | | MMMMM | Narrow | S |
  4308. * | Month standalone | L | Numeric: 1 digit | 9, 12 |
  4309. * | | LL | Numeric: 2 digits + zero padded | 09, 12 |
  4310. * | | LLL | Abbreviated | Sep |
  4311. * | | LLLL | Wide | September |
  4312. * | | LLLLL | Narrow | S |
  4313. * | Week of year | w | Numeric: minimum digits | 1... 53 |
  4314. * | | ww | Numeric: 2 digits + zero padded | 01... 53 |
  4315. * | Week of month | W | Numeric: 1 digit | 1... 5 |
  4316. * | Day of month | d | Numeric: minimum digits | 1 |
  4317. * | | dd | Numeric: 2 digits + zero padded | 01 |
  4318. * | Week day | E, EE & EEE | Abbreviated | Tue |
  4319. * | | EEEE | Wide | Tuesday |
  4320. * | | EEEEE | Narrow | T |
  4321. * | | EEEEEE | Short | Tu |
  4322. * | Week day standalone | c, cc | Numeric: 1 digit | 2 |
  4323. * | | ccc | Abbreviated | Tue |
  4324. * | | cccc | Wide | Tuesday |
  4325. * | | ccccc | Narrow | T |
  4326. * | | cccccc | Short | Tu |
  4327. * | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM |
  4328. * | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem |
  4329. * | | aaaaa | Narrow | a/p |
  4330. * | Period* | B, BB & BBB | Abbreviated | mid. |
  4331. * | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
  4332. * | | BBBBB | Narrow | md |
  4333. * | Period standalone* | b, bb & bbb | Abbreviated | mid. |
  4334. * | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
  4335. * | | bbbbb | Narrow | md |
  4336. * | Hour 1-12 | h | Numeric: minimum digits | 1, 12 |
  4337. * | | hh | Numeric: 2 digits + zero padded | 01, 12 |
  4338. * | Hour 0-23 | H | Numeric: minimum digits | 0, 23 |
  4339. * | | HH | Numeric: 2 digits + zero padded | 00, 23 |
  4340. * | Minute | m | Numeric: minimum digits | 8, 59 |
  4341. * | | mm | Numeric: 2 digits + zero padded | 08, 59 |
  4342. * | Second | s | Numeric: minimum digits | 0... 59 |
  4343. * | | ss | Numeric: 2 digits + zero padded | 00... 59 |
  4344. * | Fractional seconds | S | Numeric: 1 digit | 0... 9 |
  4345. * | | SS | Numeric: 2 digits + zero padded | 00... 99 |
  4346. * | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 |
  4347. * | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 |
  4348. * | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 |
  4349. * | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 |
  4350. * | | ZZZZ | Long localized GMT format | GMT-8:00 |
  4351. * | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 |
  4352. * | | O, OO & OOO | Short localized GMT format | GMT-8 |
  4353. * | | OOOO | Long localized GMT format | GMT-08:00 |
  4354. *
  4355. *
  4356. * ### Format examples
  4357. *
  4358. * These examples transform a date into various formats,
  4359. * assuming that `dateObj` is a JavaScript `Date` object for
  4360. * year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11,
  4361. * given in the local time for the `en-US` locale.
  4362. *
  4363. * ```
  4364. * {{ dateObj | date }} // output is 'Jun 15, 2015'
  4365. * {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
  4366. * {{ dateObj | date:'shortTime' }} // output is '9:43 PM'
  4367. * {{ dateObj | date:'mm:ss' }} // output is '43:11'
  4368. * {{ dateObj | date:"MMM dd, yyyy 'at' hh:mm a" }} // output is 'Jun 15, 2015 at 09:43 PM'
  4369. * ```
  4370. *
  4371. * ### Usage example
  4372. *
  4373. * The following component uses a date pipe to display the current date in different formats.
  4374. *
  4375. * ```
  4376. * @Component({
  4377. * selector: 'date-pipe',
  4378. * template: `<div>
  4379. * <p>Today is {{today | date}}</p>
  4380. * <p>Or if you prefer, {{today | date:'fullDate'}}</p>
  4381. * <p>The time is {{today | date:'h:mm a z'}}</p>
  4382. * </div>`
  4383. * })
  4384. * // Get the current date and time as a date-time value.
  4385. * export class DatePipeComponent {
  4386. * today: number = Date.now();
  4387. * }
  4388. * ```
  4389. *
  4390. * @publicApi
  4391. */
  4392. // clang-format on
  4393. class DatePipe {
  4394. constructor(locale, defaultTimezone, defaultOptions) {
  4395. this.locale = locale;
  4396. this.defaultTimezone = defaultTimezone;
  4397. this.defaultOptions = defaultOptions;
  4398. }
  4399. transform(value, format, timezone, locale) {
  4400. if (value == null || value === '' || value !== value)
  4401. return null;
  4402. try {
  4403. const _format = format ?? this.defaultOptions?.dateFormat ?? DEFAULT_DATE_FORMAT;
  4404. const _timezone = timezone ?? this.defaultOptions?.timezone ?? this.defaultTimezone ?? undefined;
  4405. return formatDate(value, _format, locale || this.locale, _timezone);
  4406. }
  4407. catch (error) {
  4408. throw invalidPipeArgumentError(DatePipe, error.message);
  4409. }
  4410. }
  4411. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: DatePipe, deps: [{ token: LOCALE_ID }, { token: DATE_PIPE_DEFAULT_TIMEZONE, optional: true }, { token: DATE_PIPE_DEFAULT_OPTIONS, optional: true }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4412. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: DatePipe, isStandalone: true, name: "date" }); }
  4413. }
  4414. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: DatePipe, decorators: [{
  4415. type: Pipe,
  4416. args: [{
  4417. name: 'date',
  4418. pure: true,
  4419. standalone: true,
  4420. }]
  4421. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  4422. type: Inject,
  4423. args: [LOCALE_ID]
  4424. }] }, { type: undefined, decorators: [{
  4425. type: Inject,
  4426. args: [DATE_PIPE_DEFAULT_TIMEZONE]
  4427. }, {
  4428. type: Optional
  4429. }] }, { type: undefined, decorators: [{
  4430. type: Inject,
  4431. args: [DATE_PIPE_DEFAULT_OPTIONS]
  4432. }, {
  4433. type: Optional
  4434. }] }]; } });
  4435. const _INTERPOLATION_REGEXP = /#/g;
  4436. /**
  4437. * @ngModule CommonModule
  4438. * @description
  4439. *
  4440. * Maps a value to a string that pluralizes the value according to locale rules.
  4441. *
  4442. * @usageNotes
  4443. *
  4444. * ### Example
  4445. *
  4446. * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
  4447. *
  4448. * @publicApi
  4449. */
  4450. class I18nPluralPipe {
  4451. constructor(_localization) {
  4452. this._localization = _localization;
  4453. }
  4454. /**
  4455. * @param value the number to be formatted
  4456. * @param pluralMap an object that mimics the ICU format, see
  4457. * https://unicode-org.github.io/icu/userguide/format_parse/messages/.
  4458. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
  4459. * default).
  4460. */
  4461. transform(value, pluralMap, locale) {
  4462. if (value == null)
  4463. return '';
  4464. if (typeof pluralMap !== 'object' || pluralMap === null) {
  4465. throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
  4466. }
  4467. const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale);
  4468. return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
  4469. }
  4470. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: I18nPluralPipe, deps: [{ token: NgLocalization }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4471. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: I18nPluralPipe, isStandalone: true, name: "i18nPlural" }); }
  4472. }
  4473. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: I18nPluralPipe, decorators: [{
  4474. type: Pipe,
  4475. args: [{
  4476. name: 'i18nPlural',
  4477. pure: true,
  4478. standalone: true,
  4479. }]
  4480. }], ctorParameters: function () { return [{ type: NgLocalization }]; } });
  4481. /**
  4482. * @ngModule CommonModule
  4483. * @description
  4484. *
  4485. * Generic selector that displays the string that matches the current value.
  4486. *
  4487. * If none of the keys of the `mapping` match the `value`, then the content
  4488. * of the `other` key is returned when present, otherwise an empty string is returned.
  4489. *
  4490. * @usageNotes
  4491. *
  4492. * ### Example
  4493. *
  4494. * {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
  4495. *
  4496. * @publicApi
  4497. */
  4498. class I18nSelectPipe {
  4499. /**
  4500. * @param value a string to be internationalized.
  4501. * @param mapping an object that indicates the text that should be displayed
  4502. * for different values of the provided `value`.
  4503. */
  4504. transform(value, mapping) {
  4505. if (value == null)
  4506. return '';
  4507. if (typeof mapping !== 'object' || typeof value !== 'string') {
  4508. throw invalidPipeArgumentError(I18nSelectPipe, mapping);
  4509. }
  4510. if (mapping.hasOwnProperty(value)) {
  4511. return mapping[value];
  4512. }
  4513. if (mapping.hasOwnProperty('other')) {
  4514. return mapping['other'];
  4515. }
  4516. return '';
  4517. }
  4518. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: I18nSelectPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4519. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: I18nSelectPipe, isStandalone: true, name: "i18nSelect" }); }
  4520. }
  4521. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: I18nSelectPipe, decorators: [{
  4522. type: Pipe,
  4523. args: [{
  4524. name: 'i18nSelect',
  4525. pure: true,
  4526. standalone: true,
  4527. }]
  4528. }] });
  4529. /**
  4530. * @ngModule CommonModule
  4531. * @description
  4532. *
  4533. * Converts a value into its JSON-format representation. Useful for debugging.
  4534. *
  4535. * @usageNotes
  4536. *
  4537. * The following component uses a JSON pipe to convert an object
  4538. * to JSON format, and displays the string in both formats for comparison.
  4539. *
  4540. * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'}
  4541. *
  4542. * @publicApi
  4543. */
  4544. class JsonPipe {
  4545. /**
  4546. * @param value A value of any type to convert into a JSON-format string.
  4547. */
  4548. transform(value) {
  4549. return JSON.stringify(value, null, 2);
  4550. }
  4551. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: JsonPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4552. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: JsonPipe, isStandalone: true, name: "json", pure: false }); }
  4553. }
  4554. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: JsonPipe, decorators: [{
  4555. type: Pipe,
  4556. args: [{
  4557. name: 'json',
  4558. pure: false,
  4559. standalone: true,
  4560. }]
  4561. }] });
  4562. function makeKeyValuePair(key, value) {
  4563. return { key: key, value: value };
  4564. }
  4565. /**
  4566. * @ngModule CommonModule
  4567. * @description
  4568. *
  4569. * Transforms Object or Map into an array of key value pairs.
  4570. *
  4571. * The output array will be ordered by keys.
  4572. * By default the comparator will be by Unicode point value.
  4573. * You can optionally pass a compareFn if your keys are complex types.
  4574. *
  4575. * @usageNotes
  4576. * ### Examples
  4577. *
  4578. * This examples show how an Object or a Map can be iterated by ngFor with the use of this
  4579. * keyvalue pipe.
  4580. *
  4581. * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'}
  4582. *
  4583. * @publicApi
  4584. */
  4585. class KeyValuePipe {
  4586. constructor(differs) {
  4587. this.differs = differs;
  4588. this.keyValues = [];
  4589. this.compareFn = defaultComparator;
  4590. }
  4591. transform(input, compareFn = defaultComparator) {
  4592. if (!input || (!(input instanceof Map) && typeof input !== 'object')) {
  4593. return null;
  4594. }
  4595. if (!this.differ) {
  4596. // make a differ for whatever type we've been passed in
  4597. this.differ = this.differs.find(input).create();
  4598. }
  4599. const differChanges = this.differ.diff(input);
  4600. const compareFnChanged = compareFn !== this.compareFn;
  4601. if (differChanges) {
  4602. this.keyValues = [];
  4603. differChanges.forEachItem((r) => {
  4604. this.keyValues.push(makeKeyValuePair(r.key, r.currentValue));
  4605. });
  4606. }
  4607. if (differChanges || compareFnChanged) {
  4608. this.keyValues.sort(compareFn);
  4609. this.compareFn = compareFn;
  4610. }
  4611. return this.keyValues;
  4612. }
  4613. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: KeyValuePipe, deps: [{ token: i0.KeyValueDiffers }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4614. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: KeyValuePipe, isStandalone: true, name: "keyvalue", pure: false }); }
  4615. }
  4616. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: KeyValuePipe, decorators: [{
  4617. type: Pipe,
  4618. args: [{
  4619. name: 'keyvalue',
  4620. pure: false,
  4621. standalone: true,
  4622. }]
  4623. }], ctorParameters: function () { return [{ type: i0.KeyValueDiffers }]; } });
  4624. function defaultComparator(keyValueA, keyValueB) {
  4625. const a = keyValueA.key;
  4626. const b = keyValueB.key;
  4627. // if same exit with 0;
  4628. if (a === b)
  4629. return 0;
  4630. // make sure that undefined are at the end of the sort.
  4631. if (a === undefined)
  4632. return 1;
  4633. if (b === undefined)
  4634. return -1;
  4635. // make sure that nulls are at the end of the sort.
  4636. if (a === null)
  4637. return 1;
  4638. if (b === null)
  4639. return -1;
  4640. if (typeof a == 'string' && typeof b == 'string') {
  4641. return a < b ? -1 : 1;
  4642. }
  4643. if (typeof a == 'number' && typeof b == 'number') {
  4644. return a - b;
  4645. }
  4646. if (typeof a == 'boolean' && typeof b == 'boolean') {
  4647. return a < b ? -1 : 1;
  4648. }
  4649. // `a` and `b` are of different types. Compare their string values.
  4650. const aString = String(a);
  4651. const bString = String(b);
  4652. return aString == bString ? 0 : aString < bString ? -1 : 1;
  4653. }
  4654. /**
  4655. * @ngModule CommonModule
  4656. * @description
  4657. *
  4658. * Formats a value according to digit options and locale rules.
  4659. * Locale determines group sizing and separator,
  4660. * decimal point character, and other locale-specific configurations.
  4661. *
  4662. * @see {@link formatNumber}
  4663. *
  4664. * @usageNotes
  4665. *
  4666. * ### digitsInfo
  4667. *
  4668. * The value's decimal representation is specified by the `digitsInfo`
  4669. * parameter, written in the following format:<br>
  4670. *
  4671. * ```
  4672. * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  4673. * ```
  4674. *
  4675. * - `minIntegerDigits`:
  4676. * The minimum number of integer digits before the decimal point.
  4677. * Default is 1.
  4678. *
  4679. * - `minFractionDigits`:
  4680. * The minimum number of digits after the decimal point.
  4681. * Default is 0.
  4682. *
  4683. * - `maxFractionDigits`:
  4684. * The maximum number of digits after the decimal point.
  4685. * Default is 3.
  4686. *
  4687. * If the formatted value is truncated it will be rounded using the "to-nearest" method:
  4688. *
  4689. * ```
  4690. * {{3.6 | number: '1.0-0'}}
  4691. * <!--will output '4'-->
  4692. *
  4693. * {{-3.6 | number:'1.0-0'}}
  4694. * <!--will output '-4'-->
  4695. * ```
  4696. *
  4697. * ### locale
  4698. *
  4699. * `locale` will format a value according to locale rules.
  4700. * Locale determines group sizing and separator,
  4701. * decimal point character, and other locale-specific configurations.
  4702. *
  4703. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
  4704. *
  4705. * See [Setting your app locale](guide/i18n-common-locale-id).
  4706. *
  4707. * ### Example
  4708. *
  4709. * The following code shows how the pipe transforms values
  4710. * according to various format specifications,
  4711. * where the caller's default locale is `en-US`.
  4712. *
  4713. * <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example>
  4714. *
  4715. * @publicApi
  4716. */
  4717. class DecimalPipe {
  4718. constructor(_locale) {
  4719. this._locale = _locale;
  4720. }
  4721. /**
  4722. * @param value The value to be formatted.
  4723. * @param digitsInfo Sets digit and decimal representation.
  4724. * [See more](#digitsinfo).
  4725. * @param locale Specifies what locale format rules to use.
  4726. * [See more](#locale).
  4727. */
  4728. transform(value, digitsInfo, locale) {
  4729. if (!isValue(value))
  4730. return null;
  4731. locale = locale || this._locale;
  4732. try {
  4733. const num = strToNumber(value);
  4734. return formatNumber(num, locale, digitsInfo);
  4735. }
  4736. catch (error) {
  4737. throw invalidPipeArgumentError(DecimalPipe, error.message);
  4738. }
  4739. }
  4740. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: DecimalPipe, deps: [{ token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4741. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: DecimalPipe, isStandalone: true, name: "number" }); }
  4742. }
  4743. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: DecimalPipe, decorators: [{
  4744. type: Pipe,
  4745. args: [{
  4746. name: 'number',
  4747. standalone: true,
  4748. }]
  4749. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  4750. type: Inject,
  4751. args: [LOCALE_ID]
  4752. }] }]; } });
  4753. /**
  4754. * @ngModule CommonModule
  4755. * @description
  4756. *
  4757. * Transforms a number to a percentage
  4758. * string, formatted according to locale rules that determine group sizing and
  4759. * separator, decimal-point character, and other locale-specific
  4760. * configurations.
  4761. *
  4762. * @see {@link formatPercent}
  4763. *
  4764. * @usageNotes
  4765. * The following code shows how the pipe transforms numbers
  4766. * into text strings, according to various format specifications,
  4767. * where the caller's default locale is `en-US`.
  4768. *
  4769. * <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example>
  4770. *
  4771. * @publicApi
  4772. */
  4773. class PercentPipe {
  4774. constructor(_locale) {
  4775. this._locale = _locale;
  4776. }
  4777. /**
  4778. *
  4779. * @param value The number to be formatted as a percentage.
  4780. * @param digitsInfo Decimal representation options, specified by a string
  4781. * in the following format:<br>
  4782. * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
  4783. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
  4784. * Default is `1`.
  4785. * - `minFractionDigits`: The minimum number of digits after the decimal point.
  4786. * Default is `0`.
  4787. * - `maxFractionDigits`: The maximum number of digits after the decimal point.
  4788. * Default is `0`.
  4789. * @param locale A locale code for the locale format rules to use.
  4790. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
  4791. * See [Setting your app locale](guide/i18n-common-locale-id).
  4792. */
  4793. transform(value, digitsInfo, locale) {
  4794. if (!isValue(value))
  4795. return null;
  4796. locale = locale || this._locale;
  4797. try {
  4798. const num = strToNumber(value);
  4799. return formatPercent(num, locale, digitsInfo);
  4800. }
  4801. catch (error) {
  4802. throw invalidPipeArgumentError(PercentPipe, error.message);
  4803. }
  4804. }
  4805. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PercentPipe, deps: [{ token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4806. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: PercentPipe, isStandalone: true, name: "percent" }); }
  4807. }
  4808. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PercentPipe, decorators: [{
  4809. type: Pipe,
  4810. args: [{
  4811. name: 'percent',
  4812. standalone: true,
  4813. }]
  4814. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  4815. type: Inject,
  4816. args: [LOCALE_ID]
  4817. }] }]; } });
  4818. /**
  4819. * @ngModule CommonModule
  4820. * @description
  4821. *
  4822. * Transforms a number to a currency string, formatted according to locale rules
  4823. * that determine group sizing and separator, decimal-point character,
  4824. * and other locale-specific configurations.
  4825. *
  4826. *
  4827. * @see {@link getCurrencySymbol}
  4828. * @see {@link formatCurrency}
  4829. *
  4830. * @usageNotes
  4831. * The following code shows how the pipe transforms numbers
  4832. * into text strings, according to various format specifications,
  4833. * where the caller's default locale is `en-US`.
  4834. *
  4835. * <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example>
  4836. *
  4837. * @publicApi
  4838. */
  4839. class CurrencyPipe {
  4840. constructor(_locale, _defaultCurrencyCode = 'USD') {
  4841. this._locale = _locale;
  4842. this._defaultCurrencyCode = _defaultCurrencyCode;
  4843. }
  4844. /**
  4845. *
  4846. * @param value The number to be formatted as currency.
  4847. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code,
  4848. * such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be
  4849. * configured using the `DEFAULT_CURRENCY_CODE` injection token.
  4850. * @param display The format for the currency indicator. One of the following:
  4851. * - `code`: Show the code (such as `USD`).
  4852. * - `symbol`(default): Show the symbol (such as `$`).
  4853. * - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their
  4854. * currency.
  4855. * For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the
  4856. * locale has no narrow symbol, uses the standard symbol for the locale.
  4857. * - String: Use the given string value instead of a code or a symbol.
  4858. * For example, an empty string will suppress the currency & symbol.
  4859. * - Boolean (marked deprecated in v5): `true` for symbol and false for `code`.
  4860. *
  4861. * @param digitsInfo Decimal representation options, specified by a string
  4862. * in the following format:<br>
  4863. * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
  4864. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
  4865. * Default is `1`.
  4866. * - `minFractionDigits`: The minimum number of digits after the decimal point.
  4867. * Default is `2`.
  4868. * - `maxFractionDigits`: The maximum number of digits after the decimal point.
  4869. * Default is `2`.
  4870. * If not provided, the number will be formatted with the proper amount of digits,
  4871. * depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies.
  4872. * For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none.
  4873. * @param locale A locale code for the locale format rules to use.
  4874. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
  4875. * See [Setting your app locale](guide/i18n-common-locale-id).
  4876. */
  4877. transform(value, currencyCode = this._defaultCurrencyCode, display = 'symbol', digitsInfo, locale) {
  4878. if (!isValue(value))
  4879. return null;
  4880. locale = locale || this._locale;
  4881. if (typeof display === 'boolean') {
  4882. if ((typeof ngDevMode === 'undefined' || ngDevMode) && console && console.warn) {
  4883. console.warn(`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`);
  4884. }
  4885. display = display ? 'symbol' : 'code';
  4886. }
  4887. let currency = currencyCode || this._defaultCurrencyCode;
  4888. if (display !== 'code') {
  4889. if (display === 'symbol' || display === 'symbol-narrow') {
  4890. currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);
  4891. }
  4892. else {
  4893. currency = display;
  4894. }
  4895. }
  4896. try {
  4897. const num = strToNumber(value);
  4898. return formatCurrency(num, locale, currency, currencyCode, digitsInfo);
  4899. }
  4900. catch (error) {
  4901. throw invalidPipeArgumentError(CurrencyPipe, error.message);
  4902. }
  4903. }
  4904. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: CurrencyPipe, deps: [{ token: LOCALE_ID }, { token: DEFAULT_CURRENCY_CODE }], target: i0.ɵɵFactoryTarget.Pipe }); }
  4905. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: CurrencyPipe, isStandalone: true, name: "currency" }); }
  4906. }
  4907. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: CurrencyPipe, decorators: [{
  4908. type: Pipe,
  4909. args: [{
  4910. name: 'currency',
  4911. standalone: true,
  4912. }]
  4913. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  4914. type: Inject,
  4915. args: [LOCALE_ID]
  4916. }] }, { type: undefined, decorators: [{
  4917. type: Inject,
  4918. args: [DEFAULT_CURRENCY_CODE]
  4919. }] }]; } });
  4920. function isValue(value) {
  4921. return !(value == null || value === '' || value !== value);
  4922. }
  4923. /**
  4924. * Transforms a string into a number (if needed).
  4925. */
  4926. function strToNumber(value) {
  4927. // Convert strings to numbers
  4928. if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
  4929. return Number(value);
  4930. }
  4931. if (typeof value !== 'number') {
  4932. throw new Error(`${value} is not a number`);
  4933. }
  4934. return value;
  4935. }
  4936. /**
  4937. * @ngModule CommonModule
  4938. * @description
  4939. *
  4940. * Creates a new `Array` or `String` containing a subset (slice) of the elements.
  4941. *
  4942. * @usageNotes
  4943. *
  4944. * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`
  4945. * and `String.prototype.slice()`.
  4946. *
  4947. * When operating on an `Array`, the returned `Array` is always a copy even when all
  4948. * the elements are being returned.
  4949. *
  4950. * When operating on a blank value, the pipe returns the blank value.
  4951. *
  4952. * ### List Example
  4953. *
  4954. * This `ngFor` example:
  4955. *
  4956. * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}
  4957. *
  4958. * produces the following:
  4959. *
  4960. * ```html
  4961. * <li>b</li>
  4962. * <li>c</li>
  4963. * ```
  4964. *
  4965. * ### String Examples
  4966. *
  4967. * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'}
  4968. *
  4969. * @publicApi
  4970. */
  4971. class SlicePipe {
  4972. transform(value, start, end) {
  4973. if (value == null)
  4974. return null;
  4975. if (!this.supports(value)) {
  4976. throw invalidPipeArgumentError(SlicePipe, value);
  4977. }
  4978. return value.slice(start, end);
  4979. }
  4980. supports(obj) {
  4981. return typeof obj === 'string' || Array.isArray(obj);
  4982. }
  4983. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: SlicePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
  4984. static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: SlicePipe, isStandalone: true, name: "slice", pure: false }); }
  4985. }
  4986. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: SlicePipe, decorators: [{
  4987. type: Pipe,
  4988. args: [{
  4989. name: 'slice',
  4990. pure: false,
  4991. standalone: true,
  4992. }]
  4993. }] });
  4994. /**
  4995. * @module
  4996. * @description
  4997. * This module provides a set of common Pipes.
  4998. */
  4999. /**
  5000. * A collection of Angular pipes that are likely to be used in each and every application.
  5001. */
  5002. const COMMON_PIPES = [
  5003. AsyncPipe,
  5004. UpperCasePipe,
  5005. LowerCasePipe,
  5006. JsonPipe,
  5007. SlicePipe,
  5008. DecimalPipe,
  5009. PercentPipe,
  5010. TitleCasePipe,
  5011. CurrencyPipe,
  5012. DatePipe,
  5013. I18nPluralPipe,
  5014. I18nSelectPipe,
  5015. KeyValuePipe,
  5016. ];
  5017. // Note: This does not contain the location providers,
  5018. // as they need some platform specific implementations to work.
  5019. /**
  5020. * Exports all the basic Angular directives and pipes,
  5021. * such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on.
  5022. * Re-exported by `BrowserModule`, which is included automatically in the root
  5023. * `AppModule` when you create a new app with the CLI `new` command.
  5024. *
  5025. * @publicApi
  5026. */
  5027. class CommonModule {
  5028. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: CommonModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
  5029. static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.2.9", ngImport: i0, type: CommonModule, imports: [NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe], exports: [NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe] }); }
  5030. static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: CommonModule }); }
  5031. }
  5032. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: CommonModule, decorators: [{
  5033. type: NgModule,
  5034. args: [{
  5035. imports: [COMMON_DIRECTIVES, COMMON_PIPES],
  5036. exports: [COMMON_DIRECTIVES, COMMON_PIPES],
  5037. }]
  5038. }] });
  5039. const PLATFORM_BROWSER_ID = 'browser';
  5040. const PLATFORM_SERVER_ID = 'server';
  5041. const PLATFORM_WORKER_APP_ID = 'browserWorkerApp';
  5042. const PLATFORM_WORKER_UI_ID = 'browserWorkerUi';
  5043. /**
  5044. * Returns whether a platform id represents a browser platform.
  5045. * @publicApi
  5046. */
  5047. function isPlatformBrowser(platformId) {
  5048. return platformId === PLATFORM_BROWSER_ID;
  5049. }
  5050. /**
  5051. * Returns whether a platform id represents a server platform.
  5052. * @publicApi
  5053. */
  5054. function isPlatformServer(platformId) {
  5055. return platformId === PLATFORM_SERVER_ID;
  5056. }
  5057. /**
  5058. * Returns whether a platform id represents a web worker app platform.
  5059. * @publicApi
  5060. * @deprecated This function serves no purpose since the removal of the Webworker platform. It will
  5061. * always return `false`.
  5062. */
  5063. function isPlatformWorkerApp(platformId) {
  5064. return platformId === PLATFORM_WORKER_APP_ID;
  5065. }
  5066. /**
  5067. * Returns whether a platform id represents a web worker UI platform.
  5068. * @publicApi
  5069. * @deprecated This function serves no purpose since the removal of the Webworker platform. It will
  5070. * always return `false`.
  5071. */
  5072. function isPlatformWorkerUi(platformId) {
  5073. return platformId === PLATFORM_WORKER_UI_ID;
  5074. }
  5075. /**
  5076. * @module
  5077. * @description
  5078. * Entry point for all public APIs of the common package.
  5079. */
  5080. /**
  5081. * @publicApi
  5082. */
  5083. const VERSION = new Version('16.2.9');
  5084. /**
  5085. * Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
  5086. *
  5087. * @publicApi
  5088. */
  5089. class ViewportScroller {
  5090. // De-sugared tree-shakable injection
  5091. // See #23917
  5092. /** @nocollapse */
  5093. static { this.ɵprov = ɵɵdefineInjectable({
  5094. token: ViewportScroller,
  5095. providedIn: 'root',
  5096. factory: () => new BrowserViewportScroller(ɵɵinject(DOCUMENT), window)
  5097. }); }
  5098. }
  5099. /**
  5100. * Manages the scroll position for a browser window.
  5101. */
  5102. class BrowserViewportScroller {
  5103. constructor(document, window) {
  5104. this.document = document;
  5105. this.window = window;
  5106. this.offset = () => [0, 0];
  5107. }
  5108. /**
  5109. * Configures the top offset used when scrolling to an anchor.
  5110. * @param offset A position in screen coordinates (a tuple with x and y values)
  5111. * or a function that returns the top offset position.
  5112. *
  5113. */
  5114. setOffset(offset) {
  5115. if (Array.isArray(offset)) {
  5116. this.offset = () => offset;
  5117. }
  5118. else {
  5119. this.offset = offset;
  5120. }
  5121. }
  5122. /**
  5123. * Retrieves the current scroll position.
  5124. * @returns The position in screen coordinates.
  5125. */
  5126. getScrollPosition() {
  5127. if (this.supportsScrolling()) {
  5128. return [this.window.pageXOffset, this.window.pageYOffset];
  5129. }
  5130. else {
  5131. return [0, 0];
  5132. }
  5133. }
  5134. /**
  5135. * Sets the scroll position.
  5136. * @param position The new position in screen coordinates.
  5137. */
  5138. scrollToPosition(position) {
  5139. if (this.supportsScrolling()) {
  5140. this.window.scrollTo(position[0], position[1]);
  5141. }
  5142. }
  5143. /**
  5144. * Scrolls to an element and attempts to focus the element.
  5145. *
  5146. * Note that the function name here is misleading in that the target string may be an ID for a
  5147. * non-anchor element.
  5148. *
  5149. * @param target The ID of an element or name of the anchor.
  5150. *
  5151. * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document
  5152. * @see https://html.spec.whatwg.org/#scroll-to-fragid
  5153. */
  5154. scrollToAnchor(target) {
  5155. if (!this.supportsScrolling()) {
  5156. return;
  5157. }
  5158. const elSelected = findAnchorFromDocument(this.document, target);
  5159. if (elSelected) {
  5160. this.scrollToElement(elSelected);
  5161. // After scrolling to the element, the spec dictates that we follow the focus steps for the
  5162. // target. Rather than following the robust steps, simply attempt focus.
  5163. //
  5164. // @see https://html.spec.whatwg.org/#get-the-focusable-area
  5165. // @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus
  5166. // @see https://html.spec.whatwg.org/#focusable-area
  5167. elSelected.focus();
  5168. }
  5169. }
  5170. /**
  5171. * Disables automatic scroll restoration provided by the browser.
  5172. */
  5173. setHistoryScrollRestoration(scrollRestoration) {
  5174. if (this.supportsScrolling()) {
  5175. this.window.history.scrollRestoration = scrollRestoration;
  5176. }
  5177. }
  5178. /**
  5179. * Scrolls to an element using the native offset and the specified offset set on this scroller.
  5180. *
  5181. * The offset can be used when we know that there is a floating header and scrolling naively to an
  5182. * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header.
  5183. */
  5184. scrollToElement(el) {
  5185. const rect = el.getBoundingClientRect();
  5186. const left = rect.left + this.window.pageXOffset;
  5187. const top = rect.top + this.window.pageYOffset;
  5188. const offset = this.offset();
  5189. this.window.scrollTo(left - offset[0], top - offset[1]);
  5190. }
  5191. supportsScrolling() {
  5192. try {
  5193. return !!this.window && !!this.window.scrollTo && 'pageXOffset' in this.window;
  5194. }
  5195. catch {
  5196. return false;
  5197. }
  5198. }
  5199. }
  5200. function findAnchorFromDocument(document, target) {
  5201. const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
  5202. if (documentResult) {
  5203. return documentResult;
  5204. }
  5205. // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we
  5206. // have to traverse the DOM manually and do the lookup through the shadow roots.
  5207. if (typeof document.createTreeWalker === 'function' && document.body &&
  5208. typeof document.body.attachShadow === 'function') {
  5209. const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
  5210. let currentNode = treeWalker.currentNode;
  5211. while (currentNode) {
  5212. const shadowRoot = currentNode.shadowRoot;
  5213. if (shadowRoot) {
  5214. // Note that `ShadowRoot` doesn't support `getElementsByName`
  5215. // so we have to fall back to `querySelector`.
  5216. const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
  5217. if (result) {
  5218. return result;
  5219. }
  5220. }
  5221. currentNode = treeWalker.nextNode();
  5222. }
  5223. }
  5224. return null;
  5225. }
  5226. /**
  5227. * Provides an empty implementation of the viewport scroller.
  5228. */
  5229. class NullViewportScroller {
  5230. /**
  5231. * Empty implementation
  5232. */
  5233. setOffset(offset) { }
  5234. /**
  5235. * Empty implementation
  5236. */
  5237. getScrollPosition() {
  5238. return [0, 0];
  5239. }
  5240. /**
  5241. * Empty implementation
  5242. */
  5243. scrollToPosition(position) { }
  5244. /**
  5245. * Empty implementation
  5246. */
  5247. scrollToAnchor(anchor) { }
  5248. /**
  5249. * Empty implementation
  5250. */
  5251. setHistoryScrollRestoration(scrollRestoration) { }
  5252. }
  5253. /**
  5254. * A wrapper around the `XMLHttpRequest` constructor.
  5255. *
  5256. * @publicApi
  5257. */
  5258. class XhrFactory {
  5259. }
  5260. // Converts a string that represents a URL into a URL class instance.
  5261. function getUrl(src, win) {
  5262. // Don't use a base URL is the URL is absolute.
  5263. return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href);
  5264. }
  5265. // Checks whether a URL is absolute (i.e. starts with `http://` or `https://`).
  5266. function isAbsoluteUrl(src) {
  5267. return /^https?:\/\//.test(src);
  5268. }
  5269. // Given a URL, extract the hostname part.
  5270. // If a URL is a relative one - the URL is returned as is.
  5271. function extractHostname(url) {
  5272. return isAbsoluteUrl(url) ? (new URL(url)).hostname : url;
  5273. }
  5274. function isValidPath(path) {
  5275. const isString = typeof path === 'string';
  5276. if (!isString || path.trim() === '') {
  5277. return false;
  5278. }
  5279. // Calling new URL() will throw if the path string is malformed
  5280. try {
  5281. const url = new URL(path);
  5282. return true;
  5283. }
  5284. catch {
  5285. return false;
  5286. }
  5287. }
  5288. function normalizePath(path) {
  5289. return path.endsWith('/') ? path.slice(0, -1) : path;
  5290. }
  5291. function normalizeSrc(src) {
  5292. return src.startsWith('/') ? src.slice(1) : src;
  5293. }
  5294. /**
  5295. * Noop image loader that does no transformation to the original src and just returns it as is.
  5296. * This loader is used as a default one if more specific logic is not provided in an app config.
  5297. *
  5298. * @see {@link ImageLoader}
  5299. * @see {@link NgOptimizedImage}
  5300. */
  5301. const noopImageLoader = (config) => config.src;
  5302. /**
  5303. * Injection token that configures the image loader function.
  5304. *
  5305. * @see {@link ImageLoader}
  5306. * @see {@link NgOptimizedImage}
  5307. * @publicApi
  5308. */
  5309. const IMAGE_LOADER = new InjectionToken('ImageLoader', {
  5310. providedIn: 'root',
  5311. factory: () => noopImageLoader,
  5312. });
  5313. /**
  5314. * Internal helper function that makes it easier to introduce custom image loaders for the
  5315. * `NgOptimizedImage` directive. It is enough to specify a URL builder function to obtain full DI
  5316. * configuration for a given loader: a DI token corresponding to the actual loader function, plus DI
  5317. * tokens managing preconnect check functionality.
  5318. * @param buildUrlFn a function returning a full URL based on loader's configuration
  5319. * @param exampleUrls example of full URLs for a given loader (used in error messages)
  5320. * @returns a set of DI providers corresponding to the configured image loader
  5321. */
  5322. function createImageLoader(buildUrlFn, exampleUrls) {
  5323. return function provideImageLoader(path) {
  5324. if (!isValidPath(path)) {
  5325. throwInvalidPathError(path, exampleUrls || []);
  5326. }
  5327. // The trailing / is stripped (if provided) to make URL construction (concatenation) easier in
  5328. // the individual loader functions.
  5329. path = normalizePath(path);
  5330. const loaderFn = (config) => {
  5331. if (isAbsoluteUrl(config.src)) {
  5332. // Image loader functions expect an image file name (e.g. `my-image.png`)
  5333. // or a relative path + a file name (e.g. `/a/b/c/my-image.png`) as an input,
  5334. // so the final absolute URL can be constructed.
  5335. // When an absolute URL is provided instead - the loader can not
  5336. // build a final URL, thus the error is thrown to indicate that.
  5337. throwUnexpectedAbsoluteUrlError(path, config.src);
  5338. }
  5339. return buildUrlFn(path, { ...config, src: normalizeSrc(config.src) });
  5340. };
  5341. const providers = [{ provide: IMAGE_LOADER, useValue: loaderFn }];
  5342. return providers;
  5343. };
  5344. }
  5345. function throwInvalidPathError(path, exampleUrls) {
  5346. throw new ɵRuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
  5347. `Image loader has detected an invalid path (\`${path}\`). ` +
  5348. `To fix this, supply a path using one of the following formats: ${exampleUrls.join(' or ')}`);
  5349. }
  5350. function throwUnexpectedAbsoluteUrlError(path, url) {
  5351. throw new ɵRuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
  5352. `Image loader has detected a \`<img>\` tag with an invalid \`ngSrc\` attribute: ${url}. ` +
  5353. `This image loader expects \`ngSrc\` to be a relative URL - ` +
  5354. `however the provided value is an absolute URL. ` +
  5355. `To fix this, provide \`ngSrc\` as a path relative to the base URL ` +
  5356. `configured for this loader (\`${path}\`).`);
  5357. }
  5358. /**
  5359. * Function that generates an ImageLoader for [Cloudflare Image
  5360. * Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular
  5361. * provider. Note: Cloudflare has multiple image products - this provider is specifically for
  5362. * Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish.
  5363. *
  5364. * @param path Your domain name, e.g. https://mysite.com
  5365. * @returns Provider that provides an ImageLoader function
  5366. *
  5367. * @publicApi
  5368. */
  5369. const provideCloudflareLoader = createImageLoader(createCloudflareUrl, ngDevMode ? ['https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>'] : undefined);
  5370. function createCloudflareUrl(path, config) {
  5371. let params = `format=auto`;
  5372. if (config.width) {
  5373. params += `,width=${config.width}`;
  5374. }
  5375. // Cloudflare image URLs format:
  5376. // https://developers.cloudflare.com/images/image-resizing/url-format/
  5377. return `${path}/cdn-cgi/image/${params}/${config.src}`;
  5378. }
  5379. /**
  5380. * Name and URL tester for Cloudinary.
  5381. */
  5382. const cloudinaryLoaderInfo = {
  5383. name: 'Cloudinary',
  5384. testUrl: isCloudinaryUrl
  5385. };
  5386. const CLOUDINARY_LOADER_REGEX = /https?\:\/\/[^\/]+\.cloudinary\.com\/.+/;
  5387. /**
  5388. * Tests whether a URL is from Cloudinary CDN.
  5389. */
  5390. function isCloudinaryUrl(url) {
  5391. return CLOUDINARY_LOADER_REGEX.test(url);
  5392. }
  5393. /**
  5394. * Function that generates an ImageLoader for Cloudinary and turns it into an Angular provider.
  5395. *
  5396. * @param path Base URL of your Cloudinary images
  5397. * This URL should match one of the following formats:
  5398. * https://res.cloudinary.com/mysite
  5399. * https://mysite.cloudinary.com
  5400. * https://subdomain.mysite.com
  5401. * @returns Set of providers to configure the Cloudinary loader.
  5402. *
  5403. * @publicApi
  5404. */
  5405. const provideCloudinaryLoader = createImageLoader(createCloudinaryUrl, ngDevMode ?
  5406. [
  5407. 'https://res.cloudinary.com/mysite', 'https://mysite.cloudinary.com',
  5408. 'https://subdomain.mysite.com'
  5409. ] :
  5410. undefined);
  5411. function createCloudinaryUrl(path, config) {
  5412. // Cloudinary image URLformat:
  5413. // https://cloudinary.com/documentation/image_transformations#transformation_url_structure
  5414. // Example of a Cloudinary image URL:
  5415. // https://res.cloudinary.com/mysite/image/upload/c_scale,f_auto,q_auto,w_600/marketing/tile-topics-m.png
  5416. let params = `f_auto,q_auto`; // sets image format and quality to "auto"
  5417. if (config.width) {
  5418. params += `,w_${config.width}`;
  5419. }
  5420. return `${path}/image/upload/${params}/${config.src}`;
  5421. }
  5422. /**
  5423. * Name and URL tester for ImageKit.
  5424. */
  5425. const imageKitLoaderInfo = {
  5426. name: 'ImageKit',
  5427. testUrl: isImageKitUrl,
  5428. };
  5429. const IMAGE_KIT_LOADER_REGEX = /https?\:\/\/[^\/]+\.imagekit\.io\/.+/;
  5430. /**
  5431. * Tests whether a URL is from ImageKit CDN.
  5432. */
  5433. function isImageKitUrl(url) {
  5434. return IMAGE_KIT_LOADER_REGEX.test(url);
  5435. }
  5436. /**
  5437. * Function that generates an ImageLoader for ImageKit and turns it into an Angular provider.
  5438. *
  5439. * @param path Base URL of your ImageKit images
  5440. * This URL should match one of the following formats:
  5441. * https://ik.imagekit.io/myaccount
  5442. * https://subdomain.mysite.com
  5443. * @returns Set of providers to configure the ImageKit loader.
  5444. *
  5445. * @publicApi
  5446. */
  5447. const provideImageKitLoader = createImageLoader(createImagekitUrl, ngDevMode ? ['https://ik.imagekit.io/mysite', 'https://subdomain.mysite.com'] : undefined);
  5448. function createImagekitUrl(path, config) {
  5449. // Example of an ImageKit image URL:
  5450. // https://ik.imagekit.io/demo/tr:w-300,h-300/medium_cafe_B1iTdD0C.jpg
  5451. const { src, width } = config;
  5452. let urlSegments;
  5453. if (width) {
  5454. const params = `tr:w-${width}`;
  5455. urlSegments = [path, params, src];
  5456. }
  5457. else {
  5458. urlSegments = [path, src];
  5459. }
  5460. return urlSegments.join('/');
  5461. }
  5462. /**
  5463. * Name and URL tester for Imgix.
  5464. */
  5465. const imgixLoaderInfo = {
  5466. name: 'Imgix',
  5467. testUrl: isImgixUrl
  5468. };
  5469. const IMGIX_LOADER_REGEX = /https?\:\/\/[^\/]+\.imgix\.net\/.+/;
  5470. /**
  5471. * Tests whether a URL is from Imgix CDN.
  5472. */
  5473. function isImgixUrl(url) {
  5474. return IMGIX_LOADER_REGEX.test(url);
  5475. }
  5476. /**
  5477. * Function that generates an ImageLoader for Imgix and turns it into an Angular provider.
  5478. *
  5479. * @param path path to the desired Imgix origin,
  5480. * e.g. https://somepath.imgix.net or https://images.mysite.com
  5481. * @returns Set of providers to configure the Imgix loader.
  5482. *
  5483. * @publicApi
  5484. */
  5485. const provideImgixLoader = createImageLoader(createImgixUrl, ngDevMode ? ['https://somepath.imgix.net/'] : undefined);
  5486. function createImgixUrl(path, config) {
  5487. const url = new URL(`${path}/${config.src}`);
  5488. // This setting ensures the smallest allowable format is set.
  5489. url.searchParams.set('auto', 'format');
  5490. if (config.width) {
  5491. url.searchParams.set('w', config.width.toString());
  5492. }
  5493. return url.href;
  5494. }
  5495. // Assembles directive details string, useful for error messages.
  5496. function imgDirectiveDetails(ngSrc, includeNgSrc = true) {
  5497. const ngSrcInfo = includeNgSrc ? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) ` : '';
  5498. return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;
  5499. }
  5500. /**
  5501. * Asserts that the application is in development mode. Throws an error if the application is in
  5502. * production mode. This assert can be used to make sure that there is no dev-mode code invoked in
  5503. * the prod mode accidentally.
  5504. */
  5505. function assertDevMode(checkName) {
  5506. if (!ngDevMode) {
  5507. throw new ɵRuntimeError(2958 /* RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE */, `Unexpected invocation of the ${checkName} in the prod mode. ` +
  5508. `Please make sure that the prod mode is enabled for production builds.`);
  5509. }
  5510. }
  5511. /**
  5512. * Observer that detects whether an image with `NgOptimizedImage`
  5513. * is treated as a Largest Contentful Paint (LCP) element. If so,
  5514. * asserts that the image has the `priority` attribute.
  5515. *
  5516. * Note: this is a dev-mode only class and it does not appear in prod bundles,
  5517. * thus there is no `ngDevMode` use in the code.
  5518. *
  5519. * Based on https://web.dev/lcp/#measure-lcp-in-javascript.
  5520. */
  5521. class LCPImageObserver {
  5522. constructor() {
  5523. // Map of full image URLs -> original `ngSrc` values.
  5524. this.images = new Map();
  5525. this.window = null;
  5526. this.observer = null;
  5527. assertDevMode('LCP checker');
  5528. const win = inject(DOCUMENT).defaultView;
  5529. if (typeof win !== 'undefined' && typeof PerformanceObserver !== 'undefined') {
  5530. this.window = win;
  5531. this.observer = this.initPerformanceObserver();
  5532. }
  5533. }
  5534. /**
  5535. * Inits PerformanceObserver and subscribes to LCP events.
  5536. * Based on https://web.dev/lcp/#measure-lcp-in-javascript
  5537. */
  5538. initPerformanceObserver() {
  5539. const observer = new PerformanceObserver((entryList) => {
  5540. const entries = entryList.getEntries();
  5541. if (entries.length === 0)
  5542. return;
  5543. // We use the latest entry produced by the `PerformanceObserver` as the best
  5544. // signal on which element is actually an LCP one. As an example, the first image to load on
  5545. // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
  5546. // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
  5547. const lcpElement = entries[entries.length - 1];
  5548. // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
  5549. // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
  5550. const imgSrc = lcpElement.element?.src ?? '';
  5551. // Exclude `data:` and `blob:` URLs, since they are not supported by the directive.
  5552. if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))
  5553. return;
  5554. const img = this.images.get(imgSrc);
  5555. if (!img)
  5556. return;
  5557. if (!img.priority && !img.alreadyWarnedPriority) {
  5558. img.alreadyWarnedPriority = true;
  5559. logMissingPriorityWarning(imgSrc);
  5560. }
  5561. if (img.modified && !img.alreadyWarnedModified) {
  5562. img.alreadyWarnedModified = true;
  5563. logModifiedWarning(imgSrc);
  5564. }
  5565. });
  5566. observer.observe({ type: 'largest-contentful-paint', buffered: true });
  5567. return observer;
  5568. }
  5569. registerImage(rewrittenSrc, originalNgSrc, isPriority) {
  5570. if (!this.observer)
  5571. return;
  5572. const newObservedImageState = {
  5573. priority: isPriority,
  5574. modified: false,
  5575. alreadyWarnedModified: false,
  5576. alreadyWarnedPriority: false
  5577. };
  5578. this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);
  5579. }
  5580. unregisterImage(rewrittenSrc) {
  5581. if (!this.observer)
  5582. return;
  5583. this.images.delete(getUrl(rewrittenSrc, this.window).href);
  5584. }
  5585. updateImage(originalSrc, newSrc) {
  5586. const originalUrl = getUrl(originalSrc, this.window).href;
  5587. const img = this.images.get(originalUrl);
  5588. if (img) {
  5589. img.modified = true;
  5590. this.images.set(getUrl(newSrc, this.window).href, img);
  5591. this.images.delete(originalUrl);
  5592. }
  5593. }
  5594. ngOnDestroy() {
  5595. if (!this.observer)
  5596. return;
  5597. this.observer.disconnect();
  5598. this.images.clear();
  5599. }
  5600. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LCPImageObserver, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5601. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LCPImageObserver, providedIn: 'root' }); }
  5602. }
  5603. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: LCPImageObserver, decorators: [{
  5604. type: Injectable,
  5605. args: [{ providedIn: 'root' }]
  5606. }], ctorParameters: function () { return []; } });
  5607. function logMissingPriorityWarning(ngSrc) {
  5608. const directiveDetails = imgDirectiveDetails(ngSrc);
  5609. console.warn(ɵformatRuntimeError(2955 /* RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +
  5610. `element but was not marked "priority". This image should be marked ` +
  5611. `"priority" in order to prioritize its loading. ` +
  5612. `To fix this, add the "priority" attribute.`));
  5613. }
  5614. function logModifiedWarning(ngSrc) {
  5615. const directiveDetails = imgDirectiveDetails(ngSrc);
  5616. console.warn(ɵformatRuntimeError(2964 /* RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +
  5617. `element and has had its "ngSrc" attribute modified. This can cause ` +
  5618. `slower loading performance. It is recommended not to modify the "ngSrc" ` +
  5619. `property on any image which could be the LCP element.`));
  5620. }
  5621. // Set of origins that are always excluded from the preconnect checks.
  5622. const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0']);
  5623. /**
  5624. * Injection token to configure which origins should be excluded
  5625. * from the preconnect checks. It can either be a single string or an array of strings
  5626. * to represent a group of origins, for example:
  5627. *
  5628. * ```typescript
  5629. * {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}
  5630. * ```
  5631. *
  5632. * or:
  5633. *
  5634. * ```typescript
  5635. * {provide: PRECONNECT_CHECK_BLOCKLIST,
  5636. * useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']}
  5637. * ```
  5638. *
  5639. * @publicApi
  5640. */
  5641. const PRECONNECT_CHECK_BLOCKLIST = new InjectionToken('PRECONNECT_CHECK_BLOCKLIST');
  5642. /**
  5643. * Contains the logic to detect whether an image, marked with the "priority" attribute
  5644. * has a corresponding `<link rel="preconnect">` tag in the `document.head`.
  5645. *
  5646. * Note: this is a dev-mode only class, which should not appear in prod bundles,
  5647. * thus there is no `ngDevMode` use in the code.
  5648. */
  5649. class PreconnectLinkChecker {
  5650. constructor() {
  5651. this.document = inject(DOCUMENT);
  5652. /**
  5653. * Set of <link rel="preconnect"> tags found on this page.
  5654. * The `null` value indicates that there was no DOM query operation performed.
  5655. */
  5656. this.preconnectLinks = null;
  5657. /*
  5658. * Keep track of all already seen origin URLs to avoid repeating the same check.
  5659. */
  5660. this.alreadySeen = new Set();
  5661. this.window = null;
  5662. this.blocklist = new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST);
  5663. assertDevMode('preconnect link checker');
  5664. const win = this.document.defaultView;
  5665. if (typeof win !== 'undefined') {
  5666. this.window = win;
  5667. }
  5668. const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, { optional: true });
  5669. if (blocklist) {
  5670. this.populateBlocklist(blocklist);
  5671. }
  5672. }
  5673. populateBlocklist(origins) {
  5674. if (Array.isArray(origins)) {
  5675. deepForEach(origins, origin => {
  5676. this.blocklist.add(extractHostname(origin));
  5677. });
  5678. }
  5679. else {
  5680. this.blocklist.add(extractHostname(origins));
  5681. }
  5682. }
  5683. /**
  5684. * Checks that a preconnect resource hint exists in the head for the
  5685. * given src.
  5686. *
  5687. * @param rewrittenSrc src formatted with loader
  5688. * @param originalNgSrc ngSrc value
  5689. */
  5690. assertPreconnect(rewrittenSrc, originalNgSrc) {
  5691. if (!this.window)
  5692. return;
  5693. const imgUrl = getUrl(rewrittenSrc, this.window);
  5694. if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin))
  5695. return;
  5696. // Register this origin as seen, so we don't check it again later.
  5697. this.alreadySeen.add(imgUrl.origin);
  5698. if (!this.preconnectLinks) {
  5699. // Note: we query for preconnect links only *once* and cache the results
  5700. // for the entire lifespan of an application, since it's unlikely that the
  5701. // list would change frequently. This allows to make sure there are no
  5702. // performance implications of making extra DOM lookups for each image.
  5703. this.preconnectLinks = this.queryPreconnectLinks();
  5704. }
  5705. if (!this.preconnectLinks.has(imgUrl.origin)) {
  5706. console.warn(ɵformatRuntimeError(2956 /* RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG */, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` +
  5707. `image. Preconnecting to the origin(s) that serve priority images ensures that these ` +
  5708. `images are delivered as soon as possible. To fix this, please add the following ` +
  5709. `element into the <head> of the document:\n` +
  5710. ` <link rel="preconnect" href="${imgUrl.origin}">`));
  5711. }
  5712. }
  5713. queryPreconnectLinks() {
  5714. const preconnectUrls = new Set();
  5715. const selector = 'link[rel=preconnect]';
  5716. const links = Array.from(this.document.querySelectorAll(selector));
  5717. for (let link of links) {
  5718. const url = getUrl(link.href, this.window);
  5719. preconnectUrls.add(url.origin);
  5720. }
  5721. return preconnectUrls;
  5722. }
  5723. ngOnDestroy() {
  5724. this.preconnectLinks?.clear();
  5725. this.alreadySeen.clear();
  5726. }
  5727. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreconnectLinkChecker, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5728. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreconnectLinkChecker, providedIn: 'root' }); }
  5729. }
  5730. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreconnectLinkChecker, decorators: [{
  5731. type: Injectable,
  5732. args: [{ providedIn: 'root' }]
  5733. }], ctorParameters: function () { return []; } });
  5734. /**
  5735. * Invokes a callback for each element in the array. Also invokes a callback
  5736. * recursively for each nested array.
  5737. */
  5738. function deepForEach(input, fn) {
  5739. for (let value of input) {
  5740. Array.isArray(value) ? deepForEach(value, fn) : fn(value);
  5741. }
  5742. }
  5743. /**
  5744. * In SSR scenarios, a preload `<link>` element is generated for priority images.
  5745. * Having a large number of preload tags may negatively affect the performance,
  5746. * so we warn developers (by throwing an error) if the number of preloaded images
  5747. * is above a certain threshold. This const specifies this threshold.
  5748. */
  5749. const DEFAULT_PRELOADED_IMAGES_LIMIT = 5;
  5750. /**
  5751. * Helps to keep track of priority images that already have a corresponding
  5752. * preload tag (to avoid generating multiple preload tags with the same URL).
  5753. *
  5754. * This Set tracks the original src passed into the `ngSrc` input not the src after it has been
  5755. * run through the specified `IMAGE_LOADER`.
  5756. */
  5757. const PRELOADED_IMAGES = new InjectionToken('NG_OPTIMIZED_PRELOADED_IMAGES', { providedIn: 'root', factory: () => new Set() });
  5758. /**
  5759. * @description Contains the logic needed to track and add preload link tags to the `<head>` tag. It
  5760. * will also track what images have already had preload link tags added so as to not duplicate link
  5761. * tags.
  5762. *
  5763. * In dev mode this service will validate that the number of preloaded images does not exceed the
  5764. * configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}.
  5765. */
  5766. class PreloadLinkCreator {
  5767. constructor() {
  5768. this.preloadedImages = inject(PRELOADED_IMAGES);
  5769. this.document = inject(DOCUMENT);
  5770. }
  5771. /**
  5772. * @description Add a preload `<link>` to the `<head>` of the `index.html` that is served from the
  5773. * server while using Angular Universal and SSR to kick off image loads for high priority images.
  5774. *
  5775. * The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`)
  5776. * properties used to set the corresponding attributes, `imagesizes` and `imagesrcset`
  5777. * respectively, on the preload `<link>` tag so that the correctly sized image is preloaded from
  5778. * the CDN.
  5779. *
  5780. * {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes}
  5781. *
  5782. * @param renderer The `Renderer2` passed in from the directive
  5783. * @param src The original src of the image that is set on the `ngSrc` input.
  5784. * @param srcset The parsed and formatted srcset created from the `ngSrcset` input
  5785. * @param sizes The value of the `sizes` attribute passed in to the `<img>` tag
  5786. */
  5787. createPreloadLinkTag(renderer, src, srcset, sizes) {
  5788. if (ngDevMode) {
  5789. if (this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
  5790. throw new ɵRuntimeError(2961 /* RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES */, ngDevMode &&
  5791. `The \`NgOptimizedImage\` directive has detected that more than ` +
  5792. `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` +
  5793. `This might negatively affect an overall performance of the page. ` +
  5794. `To fix this, remove the "priority" attribute from images with less priority.`);
  5795. }
  5796. }
  5797. if (this.preloadedImages.has(src)) {
  5798. return;
  5799. }
  5800. this.preloadedImages.add(src);
  5801. const preload = renderer.createElement('link');
  5802. renderer.setAttribute(preload, 'as', 'image');
  5803. renderer.setAttribute(preload, 'href', src);
  5804. renderer.setAttribute(preload, 'rel', 'preload');
  5805. renderer.setAttribute(preload, 'fetchpriority', 'high');
  5806. if (sizes) {
  5807. renderer.setAttribute(preload, 'imageSizes', sizes);
  5808. }
  5809. if (srcset) {
  5810. renderer.setAttribute(preload, 'imageSrcset', srcset);
  5811. }
  5812. renderer.appendChild(this.document.head, preload);
  5813. }
  5814. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreloadLinkCreator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5815. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreloadLinkCreator, providedIn: 'root' }); }
  5816. }
  5817. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: PreloadLinkCreator, decorators: [{
  5818. type: Injectable,
  5819. args: [{ providedIn: 'root' }]
  5820. }] });
  5821. /**
  5822. * When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,
  5823. * an error is thrown. The image content (as a string) might be very long, thus making
  5824. * it hard to read an error message if the entire string is included. This const defines
  5825. * the number of characters that should be included into the error message. The rest
  5826. * of the content is truncated.
  5827. */
  5828. const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;
  5829. /**
  5830. * RegExpr to determine whether a src in a srcset is using width descriptors.
  5831. * Should match something like: "100w, 200w".
  5832. */
  5833. const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/;
  5834. /**
  5835. * RegExpr to determine whether a src in a srcset is using density descriptors.
  5836. * Should match something like: "1x, 2x, 50x". Also supports decimals like "1.5x, 1.50x".
  5837. */
  5838. const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d+(\.\d+)?x\s*(,|$)){1,})$/;
  5839. /**
  5840. * Srcset values with a density descriptor higher than this value will actively
  5841. * throw an error. Such densities are not permitted as they cause image sizes
  5842. * to be unreasonably large and slow down LCP.
  5843. */
  5844. const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
  5845. /**
  5846. * Used only in error message text to communicate best practices, as we will
  5847. * only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.
  5848. */
  5849. const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
  5850. /**
  5851. * Used in generating automatic density-based srcsets
  5852. */
  5853. const DENSITY_SRCSET_MULTIPLIERS = [1, 2];
  5854. /**
  5855. * Used to determine which breakpoints to use on full-width images
  5856. */
  5857. const VIEWPORT_BREAKPOINT_CUTOFF = 640;
  5858. /**
  5859. * Used to determine whether two aspect ratios are similar in value.
  5860. */
  5861. const ASPECT_RATIO_TOLERANCE = .1;
  5862. /**
  5863. * Used to determine whether the image has been requested at an overly
  5864. * large size compared to the actual rendered image size (after taking
  5865. * into account a typical device pixel ratio). In pixels.
  5866. */
  5867. const OVERSIZED_IMAGE_TOLERANCE = 1000;
  5868. /**
  5869. * Used to limit automatic srcset generation of very large sources for
  5870. * fixed-size images. In pixels.
  5871. */
  5872. const FIXED_SRCSET_WIDTH_LIMIT = 1920;
  5873. const FIXED_SRCSET_HEIGHT_LIMIT = 1080;
  5874. /** Info about built-in loaders we can test for. */
  5875. const BUILT_IN_LOADERS = [imgixLoaderInfo, imageKitLoaderInfo, cloudinaryLoaderInfo];
  5876. const defaultConfig = {
  5877. breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  5878. };
  5879. /**
  5880. * Injection token that configures the image optimized image functionality.
  5881. *
  5882. * @see {@link NgOptimizedImage}
  5883. * @publicApi
  5884. */
  5885. const IMAGE_CONFIG = new InjectionToken('ImageConfig', { providedIn: 'root', factory: () => defaultConfig });
  5886. /**
  5887. * Directive that improves image loading performance by enforcing best practices.
  5888. *
  5889. * `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is
  5890. * prioritized by:
  5891. * - Automatically setting the `fetchpriority` attribute on the `<img>` tag
  5892. * - Lazy loading non-priority images by default
  5893. * - Asserting that there is a corresponding preconnect link tag in the document head
  5894. *
  5895. * In addition, the directive:
  5896. * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided
  5897. * - Automatically generates a srcset
  5898. * - Requires that `width` and `height` are set
  5899. * - Warns if `width` or `height` have been set incorrectly
  5900. * - Warns if the image will be visually distorted when rendered
  5901. *
  5902. * @usageNotes
  5903. * The `NgOptimizedImage` directive is marked as [standalone](guide/standalone-components) and can
  5904. * be imported directly.
  5905. *
  5906. * Follow the steps below to enable and use the directive:
  5907. * 1. Import it into the necessary NgModule or a standalone Component.
  5908. * 2. Optionally provide an `ImageLoader` if you use an image hosting service.
  5909. * 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `ngSrc`.
  5910. * Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image
  5911. * download.
  5912. *
  5913. * Step 1: import the `NgOptimizedImage` directive.
  5914. *
  5915. * ```typescript
  5916. * import { NgOptimizedImage } from '@angular/common';
  5917. *
  5918. * // Include it into the necessary NgModule
  5919. * @NgModule({
  5920. * imports: [NgOptimizedImage],
  5921. * })
  5922. * class AppModule {}
  5923. *
  5924. * // ... or a standalone Component
  5925. * @Component({
  5926. * standalone: true
  5927. * imports: [NgOptimizedImage],
  5928. * })
  5929. * class MyStandaloneComponent {}
  5930. * ```
  5931. *
  5932. * Step 2: configure a loader.
  5933. *
  5934. * To use the **default loader**: no additional code changes are necessary. The URL returned by the
  5935. * generic loader will always match the value of "src". In other words, this loader applies no
  5936. * transformations to the resource URL and the value of the `ngSrc` attribute will be used as is.
  5937. *
  5938. * To use an existing loader for a **third-party image service**: add the provider factory for your
  5939. * chosen service to the `providers` array. In the example below, the Imgix loader is used:
  5940. *
  5941. * ```typescript
  5942. * import {provideImgixLoader} from '@angular/common';
  5943. *
  5944. * // Call the function and add the result to the `providers` array:
  5945. * providers: [
  5946. * provideImgixLoader("https://my.base.url/"),
  5947. * ],
  5948. * ```
  5949. *
  5950. * The `NgOptimizedImage` directive provides the following functions:
  5951. * - `provideCloudflareLoader`
  5952. * - `provideCloudinaryLoader`
  5953. * - `provideImageKitLoader`
  5954. * - `provideImgixLoader`
  5955. *
  5956. * If you use a different image provider, you can create a custom loader function as described
  5957. * below.
  5958. *
  5959. * To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI
  5960. * token.
  5961. *
  5962. * ```typescript
  5963. * import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';
  5964. *
  5965. * // Configure the loader using the `IMAGE_LOADER` token.
  5966. * providers: [
  5967. * {
  5968. * provide: IMAGE_LOADER,
  5969. * useValue: (config: ImageLoaderConfig) => {
  5970. * return `https://example.com/${config.src}-${config.width}.jpg}`;
  5971. * }
  5972. * },
  5973. * ],
  5974. * ```
  5975. *
  5976. * Step 3: update `<img>` tags in templates to use `ngSrc` instead of `src`.
  5977. *
  5978. * ```
  5979. * <img ngSrc="logo.png" width="200" height="100">
  5980. * ```
  5981. *
  5982. * @publicApi
  5983. */
  5984. class NgOptimizedImage {
  5985. constructor() {
  5986. this.imageLoader = inject(IMAGE_LOADER);
  5987. this.config = processConfig(inject(IMAGE_CONFIG));
  5988. this.renderer = inject(Renderer2);
  5989. this.imgElement = inject(ElementRef).nativeElement;
  5990. this.injector = inject(Injector);
  5991. this.isServer = isPlatformServer(inject(PLATFORM_ID));
  5992. this.preloadLinkCreator = inject(PreloadLinkCreator);
  5993. // a LCP image observer - should be injected only in the dev mode
  5994. this.lcpObserver = ngDevMode ? this.injector.get(LCPImageObserver) : null;
  5995. /**
  5996. * Calculate the rewritten `src` once and store it.
  5997. * This is needed to avoid repetitive calculations and make sure the directive cleanup in the
  5998. * `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
  5999. * instance that might be already destroyed).
  6000. */
  6001. this._renderedSrc = null;
  6002. /**
  6003. * Indicates whether this image should have a high priority.
  6004. */
  6005. this.priority = false;
  6006. /**
  6007. * Disables automatic srcset generation for this image.
  6008. */
  6009. this.disableOptimizedSrcset = false;
  6010. /**
  6011. * Sets the image to "fill mode", which eliminates the height/width requirement and adds
  6012. * styles such that the image fills its containing element.
  6013. */
  6014. this.fill = false;
  6015. }
  6016. /** @nodoc */
  6017. ngOnInit() {
  6018. if (ngDevMode) {
  6019. const ngZone = this.injector.get(NgZone);
  6020. assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
  6021. assertValidNgSrcset(this, this.ngSrcset);
  6022. assertNoConflictingSrc(this);
  6023. if (this.ngSrcset) {
  6024. assertNoConflictingSrcset(this);
  6025. }
  6026. assertNotBase64Image(this);
  6027. assertNotBlobUrl(this);
  6028. if (this.fill) {
  6029. assertEmptyWidthAndHeight(this);
  6030. // This leaves the Angular zone to avoid triggering unnecessary change detection cycles when
  6031. // `load` tasks are invoked on images.
  6032. ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));
  6033. }
  6034. else {
  6035. assertNonEmptyWidthAndHeight(this);
  6036. if (this.height !== undefined) {
  6037. assertGreaterThanZero(this, this.height, 'height');
  6038. }
  6039. if (this.width !== undefined) {
  6040. assertGreaterThanZero(this, this.width, 'width');
  6041. }
  6042. // Only check for distorted images when not in fill mode, where
  6043. // images may be intentionally stretched, cropped or letterboxed.
  6044. ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));
  6045. }
  6046. assertValidLoadingInput(this);
  6047. if (!this.ngSrcset) {
  6048. assertNoComplexSizes(this);
  6049. }
  6050. assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
  6051. assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
  6052. assertNoLoaderParamsWithoutLoader(this, this.imageLoader);
  6053. if (this.lcpObserver !== null) {
  6054. const ngZone = this.injector.get(NgZone);
  6055. ngZone.runOutsideAngular(() => {
  6056. this.lcpObserver.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);
  6057. });
  6058. }
  6059. if (this.priority) {
  6060. const checker = this.injector.get(PreconnectLinkChecker);
  6061. checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
  6062. }
  6063. }
  6064. this.setHostAttributes();
  6065. }
  6066. setHostAttributes() {
  6067. // Must set width/height explicitly in case they are bound (in which case they will
  6068. // only be reflected and not found by the browser)
  6069. if (this.fill) {
  6070. if (!this.sizes) {
  6071. this.sizes = '100vw';
  6072. }
  6073. }
  6074. else {
  6075. this.setHostAttribute('width', this.width.toString());
  6076. this.setHostAttribute('height', this.height.toString());
  6077. }
  6078. this.setHostAttribute('loading', this.getLoadingBehavior());
  6079. this.setHostAttribute('fetchpriority', this.getFetchPriority());
  6080. // The `data-ng-img` attribute flags an image as using the directive, to allow
  6081. // for analysis of the directive's performance.
  6082. this.setHostAttribute('ng-img', 'true');
  6083. // The `src` and `srcset` attributes should be set last since other attributes
  6084. // could affect the image's loading behavior.
  6085. const rewrittenSrcset = this.updateSrcAndSrcset();
  6086. if (this.sizes) {
  6087. this.setHostAttribute('sizes', this.sizes);
  6088. }
  6089. if (this.isServer && this.priority) {
  6090. this.preloadLinkCreator.createPreloadLinkTag(this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes);
  6091. }
  6092. }
  6093. /** @nodoc */
  6094. ngOnChanges(changes) {
  6095. if (ngDevMode) {
  6096. assertNoPostInitInputChange(this, changes, [
  6097. 'ngSrcset',
  6098. 'width',
  6099. 'height',
  6100. 'priority',
  6101. 'fill',
  6102. 'loading',
  6103. 'sizes',
  6104. 'loaderParams',
  6105. 'disableOptimizedSrcset',
  6106. ]);
  6107. }
  6108. if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) {
  6109. const oldSrc = this._renderedSrc;
  6110. this.updateSrcAndSrcset(true);
  6111. const newSrc = this._renderedSrc;
  6112. if (this.lcpObserver !== null && oldSrc && newSrc && oldSrc !== newSrc) {
  6113. const ngZone = this.injector.get(NgZone);
  6114. ngZone.runOutsideAngular(() => {
  6115. this.lcpObserver?.updateImage(oldSrc, newSrc);
  6116. });
  6117. }
  6118. }
  6119. }
  6120. callImageLoader(configWithoutCustomParams) {
  6121. let augmentedConfig = configWithoutCustomParams;
  6122. if (this.loaderParams) {
  6123. augmentedConfig.loaderParams = this.loaderParams;
  6124. }
  6125. return this.imageLoader(augmentedConfig);
  6126. }
  6127. getLoadingBehavior() {
  6128. if (!this.priority && this.loading !== undefined) {
  6129. return this.loading;
  6130. }
  6131. return this.priority ? 'eager' : 'lazy';
  6132. }
  6133. getFetchPriority() {
  6134. return this.priority ? 'high' : 'auto';
  6135. }
  6136. getRewrittenSrc() {
  6137. // ImageLoaderConfig supports setting a width property. However, we're not setting width here
  6138. // because if the developer uses rendered width instead of intrinsic width in the HTML width
  6139. // attribute, the image requested may be too small for 2x+ screens.
  6140. if (!this._renderedSrc) {
  6141. const imgConfig = { src: this.ngSrc };
  6142. // Cache calculated image src to reuse it later in the code.
  6143. this._renderedSrc = this.callImageLoader(imgConfig);
  6144. }
  6145. return this._renderedSrc;
  6146. }
  6147. getRewrittenSrcset() {
  6148. const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset);
  6149. const finalSrcs = this.ngSrcset.split(',').filter(src => src !== '').map(srcStr => {
  6150. srcStr = srcStr.trim();
  6151. const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width;
  6152. return `${this.callImageLoader({ src: this.ngSrc, width })} ${srcStr}`;
  6153. });
  6154. return finalSrcs.join(', ');
  6155. }
  6156. getAutomaticSrcset() {
  6157. if (this.sizes) {
  6158. return this.getResponsiveSrcset();
  6159. }
  6160. else {
  6161. return this.getFixedSrcset();
  6162. }
  6163. }
  6164. getResponsiveSrcset() {
  6165. const { breakpoints } = this.config;
  6166. let filteredBreakpoints = breakpoints;
  6167. if (this.sizes?.trim() === '100vw') {
  6168. // Since this is a full-screen-width image, our srcset only needs to include
  6169. // breakpoints with full viewport widths.
  6170. filteredBreakpoints = breakpoints.filter(bp => bp >= VIEWPORT_BREAKPOINT_CUTOFF);
  6171. }
  6172. const finalSrcs = filteredBreakpoints.map(bp => `${this.callImageLoader({ src: this.ngSrc, width: bp })} ${bp}w`);
  6173. return finalSrcs.join(', ');
  6174. }
  6175. updateSrcAndSrcset(forceSrcRecalc = false) {
  6176. if (forceSrcRecalc) {
  6177. // Reset cached value, so that the followup `getRewrittenSrc()` call
  6178. // will recalculate it and update the cache.
  6179. this._renderedSrc = null;
  6180. }
  6181. const rewrittenSrc = this.getRewrittenSrc();
  6182. this.setHostAttribute('src', rewrittenSrc);
  6183. let rewrittenSrcset = undefined;
  6184. if (this.ngSrcset) {
  6185. rewrittenSrcset = this.getRewrittenSrcset();
  6186. }
  6187. else if (this.shouldGenerateAutomaticSrcset()) {
  6188. rewrittenSrcset = this.getAutomaticSrcset();
  6189. }
  6190. if (rewrittenSrcset) {
  6191. this.setHostAttribute('srcset', rewrittenSrcset);
  6192. }
  6193. return rewrittenSrcset;
  6194. }
  6195. getFixedSrcset() {
  6196. const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map(multiplier => `${this.callImageLoader({
  6197. src: this.ngSrc,
  6198. width: this.width * multiplier
  6199. })} ${multiplier}x`);
  6200. return finalSrcs.join(', ');
  6201. }
  6202. shouldGenerateAutomaticSrcset() {
  6203. return !this.disableOptimizedSrcset && !this.srcset && this.imageLoader !== noopImageLoader &&
  6204. !(this.width > FIXED_SRCSET_WIDTH_LIMIT || this.height > FIXED_SRCSET_HEIGHT_LIMIT);
  6205. }
  6206. /** @nodoc */
  6207. ngOnDestroy() {
  6208. if (ngDevMode) {
  6209. if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) {
  6210. this.lcpObserver.unregisterImage(this._renderedSrc);
  6211. }
  6212. }
  6213. }
  6214. setHostAttribute(name, value) {
  6215. this.renderer.setAttribute(this.imgElement, name, value);
  6216. }
  6217. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgOptimizedImage, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
  6218. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "16.1.0", version: "16.2.9", type: NgOptimizedImage, isStandalone: true, selector: "img[ngSrc]", inputs: { ngSrc: ["ngSrc", "ngSrc", unwrapSafeUrl], ngSrcset: "ngSrcset", sizes: "sizes", width: ["width", "width", numberAttribute], height: ["height", "height", numberAttribute], loading: "loading", priority: ["priority", "priority", booleanAttribute], loaderParams: "loaderParams", disableOptimizedSrcset: ["disableOptimizedSrcset", "disableOptimizedSrcset", booleanAttribute], fill: ["fill", "fill", booleanAttribute], src: "src", srcset: "srcset" }, host: { properties: { "style.position": "fill ? \"absolute\" : null", "style.width": "fill ? \"100%\" : null", "style.height": "fill ? \"100%\" : null", "style.inset": "fill ? \"0px\" : null" } }, usesOnChanges: true, ngImport: i0 }); }
  6219. }
  6220. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.9", ngImport: i0, type: NgOptimizedImage, decorators: [{
  6221. type: Directive,
  6222. args: [{
  6223. standalone: true,
  6224. selector: 'img[ngSrc]',
  6225. host: {
  6226. '[style.position]': 'fill ? "absolute" : null',
  6227. '[style.width]': 'fill ? "100%" : null',
  6228. '[style.height]': 'fill ? "100%" : null',
  6229. '[style.inset]': 'fill ? "0px" : null'
  6230. }
  6231. }]
  6232. }], propDecorators: { ngSrc: [{
  6233. type: Input,
  6234. args: [{ required: true, transform: unwrapSafeUrl }]
  6235. }], ngSrcset: [{
  6236. type: Input
  6237. }], sizes: [{
  6238. type: Input
  6239. }], width: [{
  6240. type: Input,
  6241. args: [{ transform: numberAttribute }]
  6242. }], height: [{
  6243. type: Input,
  6244. args: [{ transform: numberAttribute }]
  6245. }], loading: [{
  6246. type: Input
  6247. }], priority: [{
  6248. type: Input,
  6249. args: [{ transform: booleanAttribute }]
  6250. }], loaderParams: [{
  6251. type: Input
  6252. }], disableOptimizedSrcset: [{
  6253. type: Input,
  6254. args: [{ transform: booleanAttribute }]
  6255. }], fill: [{
  6256. type: Input,
  6257. args: [{ transform: booleanAttribute }]
  6258. }], src: [{
  6259. type: Input
  6260. }], srcset: [{
  6261. type: Input
  6262. }] } });
  6263. /***** Helpers *****/
  6264. /**
  6265. * Sorts provided config breakpoints and uses defaults.
  6266. */
  6267. function processConfig(config) {
  6268. let sortedBreakpoints = {};
  6269. if (config.breakpoints) {
  6270. sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);
  6271. }
  6272. return Object.assign({}, defaultConfig, config, sortedBreakpoints);
  6273. }
  6274. /***** Assert functions *****/
  6275. /**
  6276. * Verifies that there is no `src` set on a host element.
  6277. */
  6278. function assertNoConflictingSrc(dir) {
  6279. if (dir.src) {
  6280. throw new ɵRuntimeError(2950 /* RuntimeErrorCode.UNEXPECTED_SRC_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`src\` and \`ngSrc\` have been set. ` +
  6281. `Supplying both of these attributes breaks lazy loading. ` +
  6282. `The NgOptimizedImage directive sets \`src\` itself based on the value of \`ngSrc\`. ` +
  6283. `To fix this, please remove the \`src\` attribute.`);
  6284. }
  6285. }
  6286. /**
  6287. * Verifies that there is no `srcset` set on a host element.
  6288. */
  6289. function assertNoConflictingSrcset(dir) {
  6290. if (dir.srcset) {
  6291. throw new ɵRuntimeError(2951 /* RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`srcset\` and \`ngSrcset\` have been set. ` +
  6292. `Supplying both of these attributes breaks lazy loading. ` +
  6293. `The NgOptimizedImage directive sets \`srcset\` itself based on the value of ` +
  6294. `\`ngSrcset\`. To fix this, please remove the \`srcset\` attribute.`);
  6295. }
  6296. }
  6297. /**
  6298. * Verifies that the `ngSrc` is not a Base64-encoded image.
  6299. */
  6300. function assertNotBase64Image(dir) {
  6301. let ngSrc = dir.ngSrc.trim();
  6302. if (ngSrc.startsWith('data:')) {
  6303. if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {
  6304. ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';
  6305. }
  6306. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`ngSrc\` is a Base64-encoded string ` +
  6307. `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` +
  6308. `To fix this, disable the NgOptimizedImage directive for this element ` +
  6309. `by removing \`ngSrc\` and using a standard \`src\` attribute instead.`);
  6310. }
  6311. }
  6312. /**
  6313. * Verifies that the 'sizes' only includes responsive values.
  6314. */
  6315. function assertNoComplexSizes(dir) {
  6316. let sizes = dir.sizes;
  6317. if (sizes?.match(/((\)|,)\s|^)\d+px/)) {
  6318. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` +
  6319. `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` +
  6320. `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` +
  6321. `To fix this, modify the \`sizes\` attribute, or provide your own \`ngSrcset\` value directly.`);
  6322. }
  6323. }
  6324. /**
  6325. * Verifies that the `ngSrc` is not a Blob URL.
  6326. */
  6327. function assertNotBlobUrl(dir) {
  6328. const ngSrc = dir.ngSrc.trim();
  6329. if (ngSrc.startsWith('blob:')) {
  6330. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrc\` was set to a blob URL (${ngSrc}). ` +
  6331. `Blob URLs are not supported by the NgOptimizedImage directive. ` +
  6332. `To fix this, disable the NgOptimizedImage directive for this element ` +
  6333. `by removing \`ngSrc\` and using a regular \`src\` attribute instead.`);
  6334. }
  6335. }
  6336. /**
  6337. * Verifies that the input is set to a non-empty string.
  6338. */
  6339. function assertNonEmptyInput(dir, name, value) {
  6340. const isString = typeof value === 'string';
  6341. const isEmptyString = isString && value.trim() === '';
  6342. if (!isString || isEmptyString) {
  6343. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${name}\` has an invalid value ` +
  6344. `(\`${value}\`). To fix this, change the value to a non-empty string.`);
  6345. }
  6346. }
  6347. /**
  6348. * Verifies that the `ngSrcset` is in a valid format, e.g. "100w, 200w" or "1x, 2x".
  6349. */
  6350. function assertValidNgSrcset(dir, value) {
  6351. if (value == null)
  6352. return;
  6353. assertNonEmptyInput(dir, 'ngSrcset', value);
  6354. const stringVal = value;
  6355. const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);
  6356. const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);
  6357. if (isValidDensityDescriptor) {
  6358. assertUnderDensityCap(dir, stringVal);
  6359. }
  6360. const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;
  6361. if (!isValidSrcset) {
  6362. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrcset\` has an invalid value (\`${value}\`). ` +
  6363. `To fix this, supply \`ngSrcset\` using a comma-separated list of one or more width ` +
  6364. `descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`);
  6365. }
  6366. }
  6367. function assertUnderDensityCap(dir, value) {
  6368. const underDensityCap = value.split(',').every(num => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);
  6369. if (!underDensityCap) {
  6370. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` contains an unsupported image density:` +
  6371. `\`${value}\`. NgOptimizedImage generally recommends a max image density of ` +
  6372. `${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` +
  6373. `${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` +
  6374. `greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` +
  6375. `most use cases. Images that will be pinch-zoomed are typically the primary use case for ` +
  6376. `${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`);
  6377. }
  6378. }
  6379. /**
  6380. * Creates a `RuntimeError` instance to represent a situation when an input is set after
  6381. * the directive has initialized.
  6382. */
  6383. function postInitInputChangeError(dir, inputName) {
  6384. let reason;
  6385. if (inputName === 'width' || inputName === 'height') {
  6386. reason = `Changing \`${inputName}\` may result in different attribute value ` +
  6387. `applied to the underlying image element and cause layout shifts on a page.`;
  6388. }
  6389. else {
  6390. reason = `Changing the \`${inputName}\` would have no effect on the underlying ` +
  6391. `image element, because the resource loading has already occurred.`;
  6392. }
  6393. return new ɵRuntimeError(2953 /* RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` was updated after initialization. ` +
  6394. `The NgOptimizedImage directive will not react to this input change. ${reason} ` +
  6395. `To fix this, either switch \`${inputName}\` to a static value ` +
  6396. `or wrap the image element in an *ngIf that is gated on the necessary value.`);
  6397. }
  6398. /**
  6399. * Verify that none of the listed inputs has changed.
  6400. */
  6401. function assertNoPostInitInputChange(dir, changes, inputs) {
  6402. inputs.forEach(input => {
  6403. const isUpdated = changes.hasOwnProperty(input);
  6404. if (isUpdated && !changes[input].isFirstChange()) {
  6405. if (input === 'ngSrc') {
  6406. // When the `ngSrc` input changes, we detect that only in the
  6407. // `ngOnChanges` hook, thus the `ngSrc` is already set. We use
  6408. // `ngSrc` in the error message, so we use a previous value, but
  6409. // not the updated one in it.
  6410. dir = { ngSrc: changes[input].previousValue };
  6411. }
  6412. throw postInitInputChangeError(dir, input);
  6413. }
  6414. });
  6415. }
  6416. /**
  6417. * Verifies that a specified input is a number greater than 0.
  6418. */
  6419. function assertGreaterThanZero(dir, inputValue, inputName) {
  6420. const validNumber = typeof inputValue === 'number' && inputValue > 0;
  6421. const validString = typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;
  6422. if (!validNumber && !validString) {
  6423. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` has an invalid value. ` +
  6424. `To fix this, provide \`${inputName}\` as a number greater than 0.`);
  6425. }
  6426. }
  6427. /**
  6428. * Verifies that the rendered image is not visually distorted. Effectively this is checking:
  6429. * - Whether the "width" and "height" attributes reflect the actual dimensions of the image.
  6430. * - Whether image styling is "correct" (see below for a longer explanation).
  6431. */
  6432. function assertNoImageDistortion(dir, img, renderer) {
  6433. const removeListenerFn = renderer.listen(img, 'load', () => {
  6434. removeListenerFn();
  6435. const computedStyle = window.getComputedStyle(img);
  6436. let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
  6437. let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
  6438. const boxSizing = computedStyle.getPropertyValue('box-sizing');
  6439. if (boxSizing === 'border-box') {
  6440. const paddingTop = computedStyle.getPropertyValue('padding-top');
  6441. const paddingRight = computedStyle.getPropertyValue('padding-right');
  6442. const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
  6443. const paddingLeft = computedStyle.getPropertyValue('padding-left');
  6444. renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
  6445. renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
  6446. }
  6447. const renderedAspectRatio = renderedWidth / renderedHeight;
  6448. const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;
  6449. const intrinsicWidth = img.naturalWidth;
  6450. const intrinsicHeight = img.naturalHeight;
  6451. const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;
  6452. const suppliedWidth = dir.width;
  6453. const suppliedHeight = dir.height;
  6454. const suppliedAspectRatio = suppliedWidth / suppliedHeight;
  6455. // Tolerance is used to account for the impact of subpixel rendering.
  6456. // Due to subpixel rendering, the rendered, intrinsic, and supplied
  6457. // aspect ratios of a correctly configured image may not exactly match.
  6458. // For example, a `width=4030 height=3020` image might have a rendered
  6459. // size of "1062w, 796.48h". (An aspect ratio of 1.334... vs. 1.333...)
  6460. const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;
  6461. const stylingDistortion = nonZeroRenderedDimensions &&
  6462. Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;
  6463. if (inaccurateDimensions) {
  6464. console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` +
  6465. `the aspect ratio indicated by the width and height attributes. ` +
  6466. `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
  6467. `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nSupplied width and height attributes: ` +
  6468. `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round(suppliedAspectRatio)}). ` +
  6469. `\nTo fix this, update the width and height attributes.`));
  6470. }
  6471. else if (stylingDistortion) {
  6472. console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` +
  6473. `does not match the image's intrinsic aspect ratio. ` +
  6474. `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
  6475. `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nRendered image size: ` +
  6476. `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` +
  6477. `${round(renderedAspectRatio)}). \nThis issue can occur if "width" and "height" ` +
  6478. `attributes are added to an image without updating the corresponding ` +
  6479. `image styling. To fix this, adjust image styling. In most cases, ` +
  6480. `adding "height: auto" or "width: auto" to the image styling will fix ` +
  6481. `this issue.`));
  6482. }
  6483. else if (!dir.ngSrcset && nonZeroRenderedDimensions) {
  6484. // If `ngSrcset` hasn't been set, sanity check the intrinsic size.
  6485. const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth;
  6486. const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight;
  6487. const oversizedWidth = (intrinsicWidth - recommendedWidth) >= OVERSIZED_IMAGE_TOLERANCE;
  6488. const oversizedHeight = (intrinsicHeight - recommendedHeight) >= OVERSIZED_IMAGE_TOLERANCE;
  6489. if (oversizedWidth || oversizedHeight) {
  6490. console.warn(ɵformatRuntimeError(2960 /* RuntimeErrorCode.OVERSIZED_IMAGE */, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` +
  6491. `larger than necessary. ` +
  6492. `\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` +
  6493. `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` +
  6494. `\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` +
  6495. `\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` +
  6496. `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` +
  6497. `or consider using the "ngSrcset" and "sizes" attributes.`));
  6498. }
  6499. }
  6500. });
  6501. }
  6502. /**
  6503. * Verifies that a specified input is set.
  6504. */
  6505. function assertNonEmptyWidthAndHeight(dir) {
  6506. let missingAttributes = [];
  6507. if (dir.width === undefined)
  6508. missingAttributes.push('width');
  6509. if (dir.height === undefined)
  6510. missingAttributes.push('height');
  6511. if (missingAttributes.length > 0) {
  6512. throw new ɵRuntimeError(2954 /* RuntimeErrorCode.REQUIRED_INPUT_MISSING */, `${imgDirectiveDetails(dir.ngSrc)} these required attributes ` +
  6513. `are missing: ${missingAttributes.map(attr => `"${attr}"`).join(', ')}. ` +
  6514. `Including "width" and "height" attributes will prevent image-related layout shifts. ` +
  6515. `To fix this, include "width" and "height" attributes on the image tag or turn on ` +
  6516. `"fill" mode with the \`fill\` attribute.`);
  6517. }
  6518. }
  6519. /**
  6520. * Verifies that width and height are not set. Used in fill mode, where those attributes don't make
  6521. * sense.
  6522. */
  6523. function assertEmptyWidthAndHeight(dir) {
  6524. if (dir.width || dir.height) {
  6525. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the attributes \`height\` and/or \`width\` are present ` +
  6526. `along with the \`fill\` attribute. Because \`fill\` mode causes an image to fill its containing ` +
  6527. `element, the size attributes have no effect and should be removed.`);
  6528. }
  6529. }
  6530. /**
  6531. * Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides
  6532. * guidance that this can be caused by the containing element's CSS position property.
  6533. */
  6534. function assertNonZeroRenderedHeight(dir, img, renderer) {
  6535. const removeListenerFn = renderer.listen(img, 'load', () => {
  6536. removeListenerFn();
  6537. const renderedHeight = img.clientHeight;
  6538. if (dir.fill && renderedHeight === 0) {
  6539. console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` +
  6540. `This is likely because the containing element does not have the CSS 'position' ` +
  6541. `property set to one of the following: "relative", "fixed", or "absolute". ` +
  6542. `To fix this problem, make sure the container element has the CSS 'position' ` +
  6543. `property defined and the height of the element is not zero.`));
  6544. }
  6545. });
  6546. }
  6547. /**
  6548. * Verifies that the `loading` attribute is set to a valid input &
  6549. * is not used on priority images.
  6550. */
  6551. function assertValidLoadingInput(dir) {
  6552. if (dir.loading && dir.priority) {
  6553. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` +
  6554. `was used on an image that was marked "priority". ` +
  6555. `Setting \`loading\` on priority images is not allowed ` +
  6556. `because these images will always be eagerly loaded. ` +
  6557. `To fix this, remove the “loading” attribute from the priority image.`);
  6558. }
  6559. const validInputs = ['auto', 'eager', 'lazy'];
  6560. if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {
  6561. throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` +
  6562. `has an invalid value (\`${dir.loading}\`). ` +
  6563. `To fix this, provide a valid value ("lazy", "eager", or "auto").`);
  6564. }
  6565. }
  6566. /**
  6567. * Warns if NOT using a loader (falling back to the generic loader) and
  6568. * the image appears to be hosted on one of the image CDNs for which
  6569. * we do have a built-in image loader. Suggests switching to the
  6570. * built-in loader.
  6571. *
  6572. * @param ngSrc Value of the ngSrc attribute
  6573. * @param imageLoader ImageLoader provided
  6574. */
  6575. function assertNotMissingBuiltInLoader(ngSrc, imageLoader) {
  6576. if (imageLoader === noopImageLoader) {
  6577. let builtInLoaderName = '';
  6578. for (const loader of BUILT_IN_LOADERS) {
  6579. if (loader.testUrl(ngSrc)) {
  6580. builtInLoaderName = loader.name;
  6581. break;
  6582. }
  6583. }
  6584. if (builtInLoaderName) {
  6585. console.warn(ɵformatRuntimeError(2962 /* RuntimeErrorCode.MISSING_BUILTIN_LOADER */, `NgOptimizedImage: It looks like your images may be hosted on the ` +
  6586. `${builtInLoaderName} CDN, but your app is not using Angular's ` +
  6587. `built-in loader for that CDN. We recommend switching to use ` +
  6588. `the built-in by calling \`provide${builtInLoaderName}Loader()\` ` +
  6589. `in your \`providers\` and passing it your instance's base URL. ` +
  6590. `If you don't want to use the built-in loader, define a custom ` +
  6591. `loader function using IMAGE_LOADER to silence this warning.`));
  6592. }
  6593. }
  6594. }
  6595. /**
  6596. * Warns if ngSrcset is present and no loader is configured (i.e. the default one is being used).
  6597. */
  6598. function assertNoNgSrcsetWithoutLoader(dir, imageLoader) {
  6599. if (dir.ngSrcset && imageLoader === noopImageLoader) {
  6600. console.warn(ɵformatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` attribute is present but ` +
  6601. `no image loader is configured (i.e. the default one is being used), ` +
  6602. `which would result in the same image being used for all configured sizes. ` +
  6603. `To fix this, provide a loader or remove the \`ngSrcset\` attribute from the image.`));
  6604. }
  6605. }
  6606. /**
  6607. * Warns if loaderParams is present and no loader is configured (i.e. the default one is being
  6608. * used).
  6609. */
  6610. function assertNoLoaderParamsWithoutLoader(dir, imageLoader) {
  6611. if (dir.loaderParams && imageLoader === noopImageLoader) {
  6612. console.warn(ɵformatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`loaderParams\` attribute is present but ` +
  6613. `no image loader is configured (i.e. the default one is being used), ` +
  6614. `which means that the loaderParams data will not be consumed and will not affect the URL. ` +
  6615. `To fix this, provide a custom loader or remove the \`loaderParams\` attribute from the image.`));
  6616. }
  6617. }
  6618. function round(input) {
  6619. return Number.isInteger(input) ? input : input.toFixed(2);
  6620. }
  6621. // Transform function to handle SafeValue input for ngSrc. This doesn't do any sanitization,
  6622. // as that is not needed for img.src and img.srcset. This transform is purely for compatibility.
  6623. function unwrapSafeUrl(value) {
  6624. if (typeof value === 'string') {
  6625. return value;
  6626. }
  6627. return ɵunwrapSafeValue(value);
  6628. }
  6629. // These exports represent the set of symbols exposed as a public API.
  6630. /**
  6631. * @module
  6632. * @description
  6633. * Entry point for all public APIs of the common package.
  6634. */
  6635. /**
  6636. * @module
  6637. * @description
  6638. * Entry point for all public APIs of this package.
  6639. */
  6640. // This file only reexports content of the `src` folder. Keep it that way.
  6641. // This file is not used to build this module. It is only used during editing
  6642. /**
  6643. * Generated bundle index. Do not edit.
  6644. */
  6645. export { APP_BASE_HREF, AsyncPipe, BrowserPlatformLocation, CommonModule, CurrencyPipe, DATE_PIPE_DEFAULT_OPTIONS, DATE_PIPE_DEFAULT_TIMEZONE, DOCUMENT, DatePipe, DecimalPipe, FormStyle, FormatWidth, HashLocationStrategy, I18nPluralPipe, I18nSelectPipe, IMAGE_CONFIG, IMAGE_LOADER, JsonPipe, KeyValuePipe, LOCATION_INITIALIZED, Location, LocationStrategy, LowerCasePipe, NgClass, NgComponentOutlet, NgForOf as NgFor, NgForOf, NgForOfContext, NgIf, NgIfContext, NgLocaleLocalization, NgLocalization, NgOptimizedImage, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NumberFormatStyle, NumberSymbol, PRECONNECT_CHECK_BLOCKLIST, PathLocationStrategy, PercentPipe, PlatformLocation, Plural, SlicePipe, TitleCasePipe, TranslationWidth, UpperCasePipe, VERSION, ViewportScroller, WeekDay, XhrFactory, formatCurrency, formatDate, formatNumber, formatPercent, getCurrencySymbol, getLocaleCurrencyCode, getLocaleCurrencyName, getLocaleCurrencySymbol, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleDirection, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleFirstDayOfWeek, getLocaleId, getLocaleMonthNames, getLocaleNumberFormat, getLocaleNumberSymbol, getLocalePluralCase, getLocaleTimeFormat, getLocaleWeekEndRange, getNumberOfCurrencyDigits, isPlatformBrowser, isPlatformServer, isPlatformWorkerApp, isPlatformWorkerUi, provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, provideImgixLoader, registerLocaleData, DomAdapter as ɵDomAdapter, NullViewportScroller as ɵNullViewportScroller, PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID, PLATFORM_WORKER_APP_ID as ɵPLATFORM_WORKER_APP_ID, PLATFORM_WORKER_UI_ID as ɵPLATFORM_WORKER_UI_ID, getDOM as ɵgetDOM, parseCookieValue as ɵparseCookieValue, setRootDomAdapter as ɵsetRootDomAdapter };
  6646. //# sourceMappingURL=common.mjs.map