common.mjs 311 KB

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